audiod.c: Fix stat task restarting.
[paraslash.git] / audiod.c
1 /*
2  * Copyright (C) 2005-2008 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file audiod.c the paraslash's audio daemon */
8 #include <sys/types.h>
9 #include <dirent.h>
10
11 #include "para.h"
12 #include "error.h"
13 #include "audiod.cmdline.h"
14 #include "list.h"
15 #include "sched.h"
16 #include "recv.h"
17 #include "filter.h"
18 #include "grab_client.cmdline.h"
19 #include "grab_client.h"
20 #include "client.cmdline.h"
21 #include "client.h"
22 #include "audiod.h"
23 #include "net.h"
24 #include "daemon.h"
25 #include "string.h"
26 #include "fd.h"
27 #include "write.h"
28 #include "write_common.h"
29 #include "signal.h"
30
31 /** define the array of error lists needed by para_audiod */
32 INIT_AUDIOD_ERRLISTS;
33 /** define the array containing all supported audio formats */
34 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
35
36 /** Defines how audiod handles one supported audio format. */
37 struct audio_format_info {
38         /** pointer to the receiver for this audio format */
39         struct receiver *receiver;
40         /** the receiver configuration */
41         void *receiver_conf;
42         /** the number of filters that should be activated for this audio format */
43         unsigned int num_filters;
44         /** pointer to the array of filters to be activated */
45         struct filter **filters;
46         /** pointer to the array of filter configurations */
47         void **filter_conf;
48         /** the number of filters that should be activated for this audio format */
49         unsigned int num_writers;
50         /** pointer to the array of writers to be activated */
51         struct writer **writers;
52         /** pointer to the array of writer configurations */
53         void **writer_conf;
54         /** do not start receiver/filters/writer before this time */
55         struct timeval restart_barrier;
56 };
57
58 /**
59  * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
60  * be associated with a receiver/filter/writer triple. This array holds all
61  * information on the status of these slots.
62  *
63  * \sa struct slot_info
64  * */
65 struct slot_info slot[MAX_STREAM_SLOTS];
66
67
68 /**
69  * the current mode of operation of which can be changed by the on/off/cycle
70  * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
71  */
72 int audiod_status = AUDIOD_ON;
73
74 /**
75  * the gengetopt args_info struct that holds information on all command line
76  * arguments
77  */
78 struct audiod_args_info conf;
79
80 static char *socket_name;
81 static FILE *logfile;
82 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
83
84 static struct signal_task signal_task_struct, *sig_task = &signal_task_struct;
85
86 static struct status_task status_task_struct;
87
88 /**
89  * the task that calls the status command of para_server
90  *
91  * \sa struct status_task
92  */
93 struct status_task *stat_task = &status_task_struct;
94 static struct timeval initial_delay_barrier;
95
96 /**
97  * the task for handling audiod commands
98  *
99  * \sa struct task, struct sched
100  */
101 struct command_task {
102         /** the local listening socket */
103         int fd;
104         /** the associated task structure */
105         struct task task;
106 };
107
108 /** iterate over all supported audio formats */
109 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
110
111 /**
112  * get the audio format number
113  * \param name the name of the audio format
114  *
115  * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
116  * \a name is not a supported audio format.
117  */
118 int get_audio_format_num(char *name)
119 {
120         int i;
121
122         while (para_isspace(*name))
123                 name++;
124         FOR_EACH_AUDIO_FORMAT(i)
125                 if (!strcmp(name, audio_formats[i]))
126                         return i;
127         return -E_UNSUPPORTED_AUDIO_FORMAT;
128 }
129
130 /**
131  * the log function of para_audiod
132  *
133  * \param ll loglevel
134  * \param fmt the format string
135  */
136 void para_log(int ll, const char* fmt,...)
137 {
138         va_list argp;
139         FILE *outfd;
140         struct tm *tm;
141         time_t t1;
142         char str[MAXLINE] = "";
143         static char *hostname;
144
145         if (ll < conf.loglevel_arg)
146                 return;
147         if (!logfile && conf.daemon_given)
148                 return;
149         if (!hostname)
150                 hostname = para_hostname();
151         outfd = logfile? logfile : stderr;
152         time(&t1);
153         tm = localtime(&t1);
154         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
155         fprintf(outfd, "%s %s ", str, hostname);
156         if (conf.loglevel_arg <= INFO)
157                 fprintf(outfd, "%i ", ll);
158         va_start(argp, fmt);
159         vfprintf(outfd, fmt, argp);
160         va_end(argp);
161 }
162
163 static char *configfile_exists(void)
164 {
165         char *home = para_homedir();
166         char *config_file = make_message("%s/.paraslash/audiod.conf",
167                 home);
168         free(home);
169         if (file_exists(config_file))
170                 return config_file;
171         free(config_file);
172         return NULL;
173 }
174
175 static void setup_signal_handling(void)
176 {
177         sig_task->fd = para_signal_init();
178         PARA_INFO_LOG("signal pipe: fd %d\n", sig_task->fd);
179         para_install_sighandler(SIGINT);
180         para_install_sighandler(SIGTERM);
181         para_install_sighandler(SIGHUP);
182         signal(SIGPIPE, SIG_IGN);
183 }
184
185 static void clear_slot(int slot_num)
186 {
187         struct slot_info *s = &slot[slot_num];
188
189         PARA_INFO_LOG("clearing slot %d\n", slot_num);
190         memset(s, 0, sizeof(struct slot_info));
191         s->format = -1;
192 }
193
194 static void close_receiver(int slot_num)
195 {
196         struct slot_info *s = &slot[slot_num];
197         struct audio_format_info *a;
198
199         if (s->format < 0 || !s->receiver_node)
200                 return;
201         a = &afi[s->format];
202         PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
203                 audio_formats[s->format], slot_num);
204         a->receiver->close(s->receiver_node);
205         free(s->receiver_node);
206         s->receiver_node = NULL;
207 }
208
209 static void kill_all_decoders(int error)
210 {
211         int i;
212
213         FOR_EACH_SLOT(i) {
214                 struct slot_info *s = &slot[i];
215                 if (s->wng && !s->wng->task.error) {
216                         PARA_INFO_LOG("unregistering writer node group in slot %d\n",
217                                 i);
218                         wng_unregister(s->wng);
219                         s->wng->task.error = error;
220                 }
221                 if (s->fc && !s->fc->task.error) {
222                         PARA_INFO_LOG("unregistering filter chain in slot %d\n", i);
223                         unregister_task(&s->fc->task);
224                         s->fc->task.error = error;
225                 }
226                 if (s->receiver_node && !s->receiver_node->task.error) {
227                         PARA_INFO_LOG("unregistering receiver_node in slot %d\n", i);
228                         unregister_task(&s->receiver_node->task);
229                         s->receiver_node->task.error = error;
230                 }
231         }
232 }
233
234 static int get_empty_slot(void)
235 {
236         int i;
237         struct slot_info *s;
238
239         FOR_EACH_SLOT(i) {
240                 s = &slot[i];
241                 if (s->format < 0) {
242                         clear_slot(i);
243                         return i;
244                 }
245                 if (s->wng || s->receiver_node || s->fc)
246                         continue;
247                 clear_slot(i);
248                 return i;
249         }
250         return -E_NO_MORE_SLOTS;
251 }
252
253 /**
254  * get the number of filters
255  *
256  * \param audio_format_num the number identifying the audio format
257  *
258  * \return the number of filters for the given audio format
259  *
260  * \sa struct filter;
261  */
262 int num_filters(int audio_format_num)
263 {
264         return afi[audio_format_num].num_filters;
265 }
266
267 static void open_filters(int slot_num)
268 {
269         struct slot_info *s = &slot[slot_num];
270         struct audio_format_info *a = &afi[s->format];
271         int nf = a->num_filters;
272         int i;
273
274         s->fc = NULL;
275         if (!nf)
276                 return;
277         PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
278         s->fc = para_calloc(sizeof(struct filter_chain));
279         INIT_LIST_HEAD(&s->fc->filters);
280         s->fc->inbuf = s->receiver_node->buf;
281         s->fc->in_loaded = &s->receiver_node->loaded;
282         s->fc->input_error = &s->receiver_node->task.error;
283         s->fc->task.pre_select = filter_pre_select;
284         s->fc->task.error = 0;
285
286         s->receiver_node->output_error = &s->fc->task.error;
287         sprintf(s->fc->task.status, "filter chain");
288         for (i = 0; i < nf; i++) {
289                 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
290                 fn->conf = a->filter_conf[i];
291                 fn->fc = s->fc;
292                 fn->filter = a->filters[i];
293                 INIT_LIST_HEAD(&fn->callbacks);
294                 list_add_tail(&fn->node, &s->fc->filters);
295                 fn->filter->open(fn);
296                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
297                         audio_formats[s->format], i + 1,  nf,
298                         fn->filter->name, slot_num);
299                 s->fc->outbuf = fn->buf;
300                 s->fc->out_loaded = &fn->loaded;
301         }
302         register_task(&s->fc->task);
303 }
304
305 static void open_writers(int slot_num)
306 {
307         int ret, i;
308         struct slot_info *s = &slot[slot_num];
309         struct audio_format_info *a = &afi[s->format];
310
311         PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
312         if (!a->num_writers)
313                 s->wng = setup_default_wng();
314         else
315                 s->wng = wng_new(a->num_writers);
316         if (s->fc) {
317                 s->wng->buf = s->fc->outbuf;
318                 s->wng->loaded = s->fc->out_loaded;
319                 s->wng->input_error = &s->fc->task.error;
320                 s->wng->channels = &s->fc->channels;
321                 s->wng->samplerate = &s->fc->samplerate;
322                 s->fc->output_error = &s->wng->task.error;
323                 PARA_INFO_LOG("samplerate: %d\n", *s->wng->samplerate);
324         } else {
325                 s->wng->buf = s->receiver_node->buf;
326                 s->wng->loaded = &s->receiver_node->loaded;
327                 s->wng->input_error = &s->receiver_node->task.error;
328         }
329         for (i = 0; i < a->num_writers; i++) {
330                 s->wng->writer_nodes[i].conf = a->writer_conf[i];
331                 s->wng->writer_nodes[i].writer = a->writers[i];
332         }
333         ret = wng_open(s->wng);
334         if (ret < 0) {
335                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
336                 return;
337         }
338         s->wstime = *now;
339         activate_inactive_grab_clients(slot_num, s->format, &s->fc->filters);
340 }
341
342 #if 0
343 static void rn_event_handler(struct task *t)
344 {
345         struct receiver_node *rn = t->private_data;
346         int i;
347
348         PARA_NOTICE_LOG("%s\n", para_strerror(-t->ret));
349         unregister_task(t);
350         rn->error = t->ret;
351         /* set restart barrier */
352         FOR_EACH_SLOT(i) {
353                 struct timeval restart_delay = {0, 10 * 1000};
354                 if (slot[i].receiver_node != rn)
355                         continue;
356                 if (rn->error != -E_RECV_EOF)
357                         /* don't reconnect immediately on errors */
358                         restart_delay.tv_sec = 5;
359                 tv_add(now, &restart_delay, &afi[slot[i].format].restart_barrier);
360         }
361 }
362 #endif
363
364 static int open_receiver(int format)
365 {
366         struct audio_format_info *a = &afi[format];
367         struct slot_info *s;
368         int ret, slot_num;
369         struct receiver_node *rn;
370         const struct timeval restart_delay = {1, 0};
371
372         ret = get_empty_slot();
373         if (ret < 0)
374                 goto err;
375         slot_num = ret;
376         s = &slot[slot_num];
377         s->format = format;
378         s->receiver_node = para_calloc(sizeof(struct receiver_node));
379         rn = s->receiver_node;
380         rn->receiver = a->receiver;
381         rn->conf = a->receiver_conf;
382         ret = a->receiver->open(s->receiver_node);
383         if (ret < 0) {
384                 free(s->receiver_node);
385                 s->receiver_node = NULL;
386                 goto err;
387         }
388         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
389                 audio_formats[s->format], a->receiver->name, slot_num);
390         rn->task.pre_select = a->receiver->pre_select;
391         rn->task.post_select = a->receiver->post_select;
392         sprintf(rn->task.status, "%s receiver node", rn->receiver->name);
393         register_task(&rn->task);
394         return 1;
395 err:
396         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
397         tv_add(now, &restart_delay, &afi[format].restart_barrier);
398         return ret;
399 }
400
401 static int receiver_running(int format)
402 {
403         int i;
404
405         FOR_EACH_SLOT(i) {
406                 struct slot_info *s = &slot[i];
407                 if (s->format == format && s->receiver_node
408                                 && s->receiver_node->task.error >= 0)
409                         return 1;
410         }
411         return 0;
412 }
413
414 static int open_current_receiver(struct sched *s)
415 {
416         struct timeval diff;
417         int cafn = stat_task->current_audio_format_num;
418
419         if (cafn < 0 || !stat_task->ct)
420                 return 0;
421         if (receiver_running(cafn))
422                 return 0;
423         if (tv_diff(now, &afi[cafn].restart_barrier, &diff) < 0) {
424                 s->timeout = diff;
425                 return 0;
426         }
427         return open_receiver(cafn) < 0? 0 : 1;
428 }
429
430 static unsigned compute_time_diff(const struct timeval *status_time)
431 {
432         struct timeval tmp, diff;
433         static unsigned count;
434         int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
435         const struct timeval max_deviation = {0, 500 * 1000};
436         const int time_smooth = 5;
437
438         if (!status_time)
439                 return count;
440         sign = tv_diff(status_time, now, &diff);
441 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
442 //                      sign, sa_time_diff_sign);
443         if (!count) {
444                 sa_time_diff_sign = sign;
445                 stat_task->sa_time_diff = diff;
446                 count++;
447                 goto out;
448         }
449         if (count > 5) {
450                 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
451                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
452                         PARA_WARNING_LOG("time diff jump: %lims\n",
453                                 s * tv2ms(&tmp));
454         }
455         count++;
456         sa_time_diff_sign = tv_convex_combination(
457                 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
458                 count > 10? sign : sign * time_smooth, &diff,
459                 &tmp);
460         stat_task->sa_time_diff = tmp;
461         PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
462                 sign > 0? "+" : "-",
463                 tv2ms(&diff),
464                 sa_time_diff_sign ? "+" : "-",
465                 tv2ms(&stat_task->sa_time_diff)
466         );
467 out:
468         stat_task->sa_time_diff_sign = sa_time_diff_sign;
469         return count;
470 }
471
472 static int check_stat_line(char *line, __a_unused void *data)
473 {
474         int itemnum;
475         size_t ilen = 0;
476         long unsigned sec, usec;
477         char *tmp;
478
479         //PARA_INFO_LOG("line: %s\n", line);
480         if (!line)
481                 return 1;
482         itemnum = stat_line_valid(line);
483         if (itemnum < 0) {
484                 PARA_WARNING_LOG("invalid status line: %s\n", line);
485                 return 1;
486         }
487         if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
488                 return 1;
489         tmp = make_message("%s\n", line);
490         stat_client_write(tmp, itemnum);
491         free(tmp);
492         free(stat_task->stat_item_values[itemnum]);
493         stat_task->stat_item_values[itemnum] = para_strdup(line);
494         ilen = strlen(status_item_list[itemnum]);
495         switch (itemnum) {
496         case SI_STATUS:
497                 stat_task->playing = strstr(line, "playing")? 1 : 0;
498                 PARA_INFO_LOG("stat task playing: %d\n", stat_task->playing);
499                 break;
500         case SI_OFFSET:
501                 stat_task->offset_seconds = atoi(line + ilen + 1);
502                 break;
503         case SI_SECONDS_TOTAL:
504                 stat_task->length_seconds = atoi(line + ilen + 1);
505                 break;
506         case SI_STREAM_START:
507                 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
508                         struct timeval a_start, delay;
509                         delay.tv_sec = conf.stream_delay_arg / 1000;
510                         delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
511                         stat_task->server_stream_start.tv_sec = sec;
512                         stat_task->server_stream_start.tv_usec = usec;
513                         if (compute_time_diff(NULL) > 2) {
514                                 if (stat_task->sa_time_diff_sign < 0)
515                                         tv_add(&stat_task->server_stream_start,
516                                                 &stat_task->sa_time_diff, &a_start);
517                                 else
518                                         tv_diff(&stat_task->server_stream_start,
519                                                 &stat_task->sa_time_diff, &a_start);
520                                 tv_add(&a_start, &delay, &initial_delay_barrier);
521                         }
522                 }
523                 break;
524         case SI_CURRENT_TIME:
525                 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
526                         struct timeval tv = {sec, usec};
527                         compute_time_diff(&tv);
528                 }
529                 if (stat_task->clock_diff_count)
530                         stat_task->clock_diff_count--;
531                 break;
532         case SI_FORMAT:
533                 stat_task->current_audio_format_num = get_audio_format_num(
534                         line + ilen + 1);
535         }
536         return 1;
537 }
538
539 static void try_to_close_slot(int slot_num)
540 {
541         struct slot_info *s = &slot[slot_num];
542
543         if (s->format < 0)
544                 return;
545         if (s->receiver_node && s->receiver_node->task.error >= 0)
546                 return;
547         if (s->fc && s->fc->task.error >= 0)
548                 return;
549         if (s->wng && s->wng->task.error >= 0)
550                 return;
551         PARA_INFO_LOG("closing slot %d\n", slot_num);
552         wng_close(s->wng);
553         close_filters(s->fc);
554         free(s->fc);
555         close_receiver(slot_num);
556         clear_slot(slot_num);
557 }
558
559 /*
560  * Check if any receivers/filters/writers need to be started and do so if
561  * necessary.  Since the pre_select function didn't have a chance yet to put
562  * file descriptors into the fd sets given by s, make the upcoming select()
563  * return immediately to avoid a long timeout in case we started something.
564  */
565 static void audiod_pre_select(struct sched *s, __a_unused struct task *t)
566 {
567         int i;
568         struct timeval min_delay = {0, 1};
569
570         if (audiod_status != AUDIOD_ON || !stat_task->playing)
571                 return kill_all_decoders(-E_NOT_PLAYING);
572         if (open_current_receiver(s))
573                 s->timeout = min_delay;
574         FOR_EACH_SLOT(i) {
575                 struct slot_info *sl = &slot[i];
576                 struct audio_format_info *a;
577                 struct timeval diff;
578
579                 if (sl->format < 0)
580                         continue;
581                 a = &afi[sl->format];
582                 if (!sl->receiver_node)
583                         continue;
584                 if ((!a->num_filters || sl->fc) && sl->wng)
585                         continue; /* everything already started */
586                 if (!a->num_filters) {
587                         if (sl->receiver_node->loaded && !sl->wng) {
588                                 open_writers(i);
589                                 s->timeout = min_delay;
590                         }
591                         continue;
592                 }
593                 if (sl->receiver_node->loaded && !sl->fc) {
594                         open_filters(i);
595                         s->timeout = min_delay;
596                         continue;
597                 }
598                 if (sl->wng || !sl->fc || !*sl->fc->out_loaded)
599                         continue;
600                 if (tv_diff(now, &initial_delay_barrier, &diff) > 0) {
601                         open_writers(i);
602                         s->timeout = min_delay;
603                         continue;
604                 }
605                 PARA_INFO_LOG("initial delay: %lu ms left\n", tv2ms(&diff));
606                 if (tv_diff(&s->timeout, &diff, NULL) > 0) {
607                         s->timeout = diff;
608                 }
609         }
610 }
611
612 static void audiod_post_select(__a_unused struct sched *s,
613         __a_unused struct task *t)
614 {
615         int i;
616
617         FOR_EACH_SLOT(i)
618                 try_to_close_slot(i);
619 }
620
621 static void init_audiod_task(struct task *t)
622 {
623         t->pre_select = audiod_pre_select;
624         t->post_select = audiod_post_select;
625         t->error = 0;
626         sprintf(t->status, "audiod task");
627 }
628
629 static int parse_stream_command(const char *txt, char **cmd)
630 {
631         char *p = strchr(txt, ':');
632         int i;
633
634         if (!p)
635                 return -E_MISSING_COLON;
636         p++;
637         FOR_EACH_AUDIO_FORMAT(i) {
638                 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
639                         continue;
640                 *cmd = p;
641                 return i;
642         }
643         return -E_UNSUPPORTED_AUDIO_FORMAT;
644 }
645
646 static int add_filter(int format, char *cmdline)
647 {
648         struct audio_format_info *a = &afi[format];
649         int filter_num, nf = a->num_filters;
650
651         filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
652         if (filter_num < 0)
653                 return filter_num;
654         a->filters[nf] = &filters[filter_num];
655         a->num_filters++;
656         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
657                 a->filters[nf]->name);
658         return filter_num;
659 }
660
661 static int init_writers(void)
662 {
663         int i, ret, nw;
664         char *cmd;
665         struct audio_format_info *a;
666
667         init_supported_writers();
668         nw = PARA_MAX(1, conf.writer_given);
669         PARA_INFO_LOG("maximal number of writers: %d\n", nw);
670         FOR_EACH_AUDIO_FORMAT(i) {
671                 a = &afi[i];
672                 a->writer_conf = para_malloc(nw * sizeof(void *));
673                 a->writers = para_malloc(nw * sizeof(struct writer *));
674                 a->num_writers = 0;
675         }
676         for (i = 0; i < conf.writer_given; i++) {
677                 void *wconf;
678                 int writer_num;
679                 ret = parse_stream_command(conf.writer_arg[i], &cmd);
680                 if (ret < 0)
681                         goto out;
682                 a = &afi[ret];
683                 nw = a->num_writers;
684                 wconf = check_writer_arg(cmd, &writer_num);
685                 if (!wconf) {
686                         ret = writer_num;
687                         goto out;
688                 }
689                 a->writers[nw] = &writers[writer_num];
690                 a->writer_conf[nw] = wconf;
691                 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
692                         nw, writer_names[writer_num]);
693                 a->num_writers++;
694         }
695         ret = 1;
696 out:
697         return ret;
698 }
699
700 static int init_receivers(void)
701 {
702         int i, ret, receiver_num;
703         char *cmd = NULL;
704         struct audio_format_info *a;
705
706         for (i = 0; receivers[i].name; i++) {
707                 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
708                 receivers[i].init(&receivers[i]);
709         }
710         for (i = conf.receiver_given - 1; i >= 0; i--) {
711                 char *arg = conf.receiver_arg[i];
712                 char *recv_arg = strchr(arg, ':');
713                 ret = -E_MISSING_COLON;
714                 if (!recv_arg)
715                         goto out;
716                 *recv_arg = '\0';
717                 recv_arg++;
718                 ret = get_audio_format_num(arg);
719                 if (ret < 0)
720                         goto out;
721                 afi[ret].receiver_conf = check_receiver_arg(recv_arg, &receiver_num);
722                 if (!afi[ret].receiver_conf) {
723                         ret = -E_RECV_SYNTAX;
724                         goto out;
725                 }
726                 afi[ret].receiver = &receivers[receiver_num];
727         }
728         /* use the first available receiver with no arguments
729          * for those audio formats for which no receiver
730          * was specified
731          */
732         cmd = para_strdup(receivers[0].name);
733         FOR_EACH_AUDIO_FORMAT(i) {
734                 a = &afi[i];
735                 if (a->receiver_conf)
736                         continue;
737                 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
738                 if (!a->receiver_conf)
739                         return -E_RECV_SYNTAX;
740                 a->receiver = &receivers[receiver_num];
741         }
742         ret = 1;
743 out:
744         free(cmd);
745         return ret;
746 }
747
748 static int init_default_filters(void)
749 {
750         int i, ret = 1;
751
752         FOR_EACH_AUDIO_FORMAT(i) {
753                 struct audio_format_info *a = &afi[i];
754                 char *tmp;
755                 int j;
756
757                 if (a->num_filters)
758                         continue; /* no default -- nothing to to */
759                 /* add "dec" to audio format name */
760                 tmp = make_message("%sdec", audio_formats[i]);
761                 for (j = 0; filters[j].name; j++)
762                         if (!strcmp(tmp, filters[j].name))
763                                 break;
764                 free(tmp);
765                 ret = -E_UNSUPPORTED_FILTER;
766                 if (!filters[j].name)
767                         goto out;
768                 tmp = para_strdup(filters[j].name);
769                 ret = add_filter(i, tmp);
770                 free(tmp);
771                 if (ret < 0)
772                         goto out;
773                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
774                         filters[j].name);
775         }
776 out:
777         return ret;
778 }
779
780 static int init_filters(void)
781 {
782         int i, ret, nf;
783
784         filter_init(filters);
785         nf = PARA_MAX(1,  conf.filter_given);
786         PARA_INFO_LOG("maximal number of filters: %d\n", nf);
787         FOR_EACH_AUDIO_FORMAT(i) {
788                 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
789                 afi[i].filters = para_malloc(nf * sizeof(struct filter *));
790         }
791         if (!conf.no_default_filters_given)
792                 return init_default_filters();
793         for (i = 0; i < conf.filter_given; i++) {
794                 char *arg = conf.filter_arg[i];
795                 char *filter_name = strchr(arg, ':');
796                 ret = -E_MISSING_COLON;
797                 if (!filter_name)
798                         goto out;
799                 *filter_name = '\0';
800                 filter_name++;
801                 ret = get_audio_format_num(arg);
802                 if (ret < 0)
803                         goto out;
804                 ret = add_filter(ret, filter_name);
805                 if (ret < 0)
806                         goto out;
807         }
808         ret = init_default_filters(); /* use default values for the rest */
809 out:
810         return ret;
811 }
812
813 static int init_stream_io(void)
814 {
815         int ret;
816
817         ret = init_writers();
818         if (ret < 0)
819                 return ret;
820         ret = init_receivers();
821         if (ret < 0)
822                 return ret;
823         ret = init_filters();
824         if (ret < 0)
825                 return ret;
826         return 1;
827 }
828
829 /* does not unlink socket on errors */
830 static int audiod_get_socket(void)
831 {
832         struct sockaddr_un unix_addr;
833         int ret, fd;
834
835         if (conf.socket_given)
836                 socket_name = para_strdup(conf.socket_arg);
837         else {
838                 char *hn = para_hostname();
839                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
840                         hn);
841                 free(hn);
842         }
843         PARA_NOTICE_LOG("local socket: %s\n", socket_name);
844         if (conf.force_given)
845                 unlink(socket_name);
846         ret = create_local_socket(socket_name, &unix_addr,
847                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
848         if (ret < 0)
849                 goto err;
850         fd = ret;
851         if (listen(fd , 5) < 0) {
852                 ret = -ERRNO_TO_PARA_ERROR(errno);
853                 goto err;
854         }
855         ret = mark_fd_nonblocking(fd);
856         if (ret < 0)
857                 goto err;
858         return fd;
859 err:
860         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
861         exit(EXIT_FAILURE);
862 }
863
864 static void signal_pre_select(struct sched *s, struct task *t)
865 {
866         struct signal_task *st = container_of(t, struct signal_task, task);
867         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
868 }
869
870 static void signal_post_select(struct sched *s, struct task *t)
871 {
872         struct signal_task *st = container_of(t, struct signal_task, task);
873         int signum;
874
875         if (!FD_ISSET(st->fd, &s->rfds))
876                 return;
877
878         signum = para_next_signal();
879         switch (signum) {
880         case SIGINT:
881         case SIGTERM:
882         case SIGHUP:
883                 PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
884                 clean_exit(EXIT_FAILURE, "caught deadly signal");
885         }
886 }
887
888 static void signal_setup_default(struct signal_task *st)
889 {
890         st->task.pre_select = signal_pre_select;
891         st->task.post_select = signal_post_select;
892         sprintf(st->task.status, "signal task");
893 }
894
895 static void command_pre_select(struct sched *s, struct task *t)
896 {
897         struct command_task *ct = container_of(t, struct command_task, task);
898         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
899 }
900
901 static void command_post_select(struct sched *s, struct task *t)
902 {
903         int ret;
904         struct command_task *ct = container_of(t, struct command_task, task);
905
906         audiod_status_dump();
907         if (!FD_ISSET(ct->fd, &s->rfds))
908                 return;
909         ret = handle_connect(ct->fd);
910         if (ret < 0)
911                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
912 }
913
914 static void init_command_task(struct command_task *ct)
915 {
916         ct->task.pre_select = command_pre_select;
917         ct->task.post_select = command_post_select;
918         ct->task.error = 0;
919         ct->fd = audiod_get_socket(); /* doesn't return on errors */
920         sprintf(ct->task.status, "command task");
921 }
922
923 static void close_stat_pipe(void)
924 {
925         int i;
926
927         if (!stat_task->ct)
928                 return;
929         client_close(stat_task->ct);
930         stat_task->ct = NULL;
931         FOR_EACH_STATUS_ITEM(i) {
932                 free(stat_task->stat_item_values[i]);
933                 stat_task->stat_item_values[i] = NULL;
934         }
935         dump_empty_status();
936         stat_task->length_seconds = 0;
937         stat_task->offset_seconds = 0;
938         audiod_status_dump();
939         stat_task->playing = 0;
940         stat_task->stat_item_values[SI_BASENAME] = make_message(
941                 "%s: no connection to para_server\n",
942                 status_item_list[SI_BASENAME]);
943         stat_client_write(stat_task->stat_item_values[SI_BASENAME],
944                 SI_BASENAME);
945         if (stat_task->clock_diff_count) {
946                 stat_task->clock_diff_barrier.tv_sec = now->tv_sec + 1;
947                 stat_task->clock_diff_barrier.tv_usec = now->tv_usec;
948         }
949 }
950
951 /**
952  * close the connection to para_server and exit
953  *
954  * \param status the exit status which is passed to exit(3)
955  * \param msg the log message
956  *
957  * Log \a msg with loglevel \p EMERG, close the connection to para_server if
958  * open, and call \p exit(status). \a status should be either EXIT_SUCCESS or
959  * EXIT_FAILURE.
960  *
961  * \sa exit(3)
962  */
963 void __noreturn clean_exit(int status, const char *msg)
964 {
965         PARA_EMERG_LOG("%s\n", msg);
966         if (socket_name)
967                 unlink(socket_name);
968         close_stat_pipe();
969         exit(status);
970 }
971
972 /* avoid busy loop if server is down */
973 static void set_stat_task_restart_barrier(void)
974 {
975         struct timeval delay = {5, 0};
976         tv_add(now, &delay, &stat_task->restart_barrier);
977 }
978
979 /* restart the client task if necessary */
980 static void status_pre_select(struct sched *s, struct task *t)
981 {
982         struct status_task *st = container_of(t, struct status_task, task);
983         int ret;
984
985         if (st->ct || audiod_status == AUDIOD_OFF) /* no need to restart */
986                 return;
987         if (!st->clock_diff_count && tv_diff(now, &st->restart_barrier, NULL)
988                         < 0)
989                 return;
990         if (st->clock_diff_count) { /* get status only one time */
991                 char *argv[] = {"audiod", "stat", "1", NULL};
992                 int argc = 3;
993                 if (tv_diff(now, &st->clock_diff_barrier, NULL) < 0)
994                         return;
995                 PARA_INFO_LOG("clock diff count: %d\n", st->clock_diff_count);
996                 ret = client_open(argc, argv, &st->ct);
997
998         } else {
999                 char *argv[] = {"audiod", "stat", NULL};
1000                 int argc = 2;
1001                 ret = client_open(argc, argv, &st->ct);
1002         }
1003         set_stat_task_restart_barrier();
1004         if (ret < 0)
1005                 return;
1006         s->timeout.tv_sec = 0;
1007         s->timeout.tv_usec = 1;
1008 }
1009
1010 static void status_post_select(__a_unused struct sched *s, struct task *t)
1011 {
1012         struct status_task *st = container_of(t, struct status_task, task);
1013         unsigned bytes_left;
1014
1015         if (!st->ct || st->ct->status != CL_RECEIVING)
1016                 return;
1017         if (audiod_status == AUDIOD_OFF || st->ct->task.error < 0) {
1018                 if (st->ct->task.error >= 0)
1019                         unregister_task(&st->ct->task);
1020                 if (audiod_status == AUDIOD_OFF)
1021                         st->clock_diff_count = conf.clock_diff_count_arg;
1022                 close_stat_pipe();
1023                 return;
1024         }
1025         bytes_left = for_each_line(st->ct->buf, st->ct->loaded,
1026                 &check_stat_line, NULL);
1027         if (st->ct->loaded != bytes_left) {
1028                 st->last_status_read = *now;
1029                 st->ct->loaded = bytes_left;
1030         } else {
1031                 struct timeval diff;
1032                 tv_diff(now, &st->last_status_read, &diff);
1033                 if (diff.tv_sec > 61)
1034                         close_stat_pipe();
1035         }
1036 }
1037
1038 static void init_status_task(struct status_task *st)
1039 {
1040         memset(st, 0, sizeof(struct status_task));
1041         st->task.pre_select = status_pre_select;
1042         st->task.post_select = status_post_select;
1043         st->sa_time_diff_sign = 1;
1044         st->clock_diff_count = conf.clock_diff_count_arg;
1045         st->current_audio_format_num = -1;
1046         sprintf(st->task.status, "status task");
1047 }
1048
1049 static void set_initial_status(void)
1050 {
1051         audiod_status = AUDIOD_ON;
1052         if (!conf.mode_given)
1053                 return;
1054         if (!strcmp(conf.mode_arg, "sb")) {
1055                 audiod_status = AUDIOD_STANDBY;
1056                 return;
1057         }
1058         if (!strcmp(conf.mode_arg, "off")) {
1059                 audiod_status = AUDIOD_OFF;
1060                 return;
1061         }
1062         if (strcmp(conf.mode_arg, "on"))
1063                 PARA_WARNING_LOG("invalid mode\n");
1064 }
1065
1066 /**
1067  * the main function of para_audiod
1068  *
1069  * \param argc usual argument count
1070  * \param argv usual argument vector
1071  *
1072  * \return EXIT_SUCCESS or EXIT_FAILURE
1073  *
1074  * \sa para_audiod(1)
1075  * */
1076 int main(int argc, char *argv[])
1077 {
1078         char *config_file;
1079         int ret, i;
1080         struct sched s;
1081         struct command_task command_task_struct, *cmd_task = &command_task_struct;
1082         struct task audiod_task_struct, *audiod_task = &audiod_task_struct;
1083
1084         valid_fd_012();
1085         audiod_cmdline_parser(argc, argv, &conf);
1086         HANDLE_VERSION_FLAG("audiod", conf);
1087         para_drop_privileges(conf.user_arg, conf.group_arg);
1088         config_file = configfile_exists();
1089         if (config_file) {
1090                 struct audiod_cmdline_parser_params params = {
1091                         .override = 0,
1092                         .initialize = 0,
1093                         .check_required = 0,
1094                         .check_ambiguity = 0
1095
1096                 };
1097                 if (audiod_cmdline_parser_config_file(config_file, &conf, &params)) {
1098                         PARA_EMERG_LOG("parse error in config file\n");
1099                         exit(EXIT_FAILURE);
1100                 }
1101                 free(config_file);
1102         }
1103         if (conf.logfile_given)
1104                 logfile = open_log(conf.logfile_arg);
1105         log_welcome("para_audiod", conf.loglevel_arg);
1106         i = init_stream_io();
1107         if (i < 0) {
1108                 PARA_EMERG_LOG("init stream io error: %s\n", para_strerror(-i));
1109                 exit(EXIT_FAILURE);
1110         }
1111         server_uptime(UPTIME_SET);
1112         set_initial_status();
1113         FOR_EACH_SLOT(i)
1114                 clear_slot(i);
1115         init_grabbing();
1116         setup_signal_handling();
1117         signal_setup_default(sig_task);
1118
1119         init_status_task(stat_task);
1120         init_command_task(cmd_task);
1121         init_audiod_task(audiod_task);
1122
1123         if (conf.daemon_given)
1124                 daemon_init();
1125
1126         register_task(&sig_task->task);
1127         register_task(&cmd_task->task);
1128         register_task(&stat_task->task);
1129         register_task(audiod_task);
1130         s.default_timeout.tv_sec = 0;
1131         s.default_timeout.tv_usec = 99 * 1000;
1132         ret = schedule(&s);
1133
1134         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1135         return EXIT_FAILURE;
1136 }