wmadec: Properly handle empty outputs.
[paraslash.git] / audiod.c
1 /*
2  * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file audiod.c The paraslash's audio daemon. */
8
9 #include <netinet/in.h>
10 #include <sys/socket.h>
11 #include <regex.h>
12 #include <sys/types.h>
13 #include <arpa/inet.h>
14 #include <sys/un.h>
15 #include <netdb.h>
16 #include <signal.h>
17 #include <pwd.h>
18
19 #include "para.h"
20 #include "error.h"
21 #include "crypt.h"
22 #include "audiod.cmdline.h"
23 #include "list.h"
24 #include "sched.h"
25 #include "ggo.h"
26 #include "buffer_tree.h"
27 #include "recv.h"
28 #include "filter.h"
29 #include "grab_client.h"
30 #include "client.cmdline.h"
31 #include "client.h"
32 #include "audiod.h"
33 #include "net.h"
34 #include "daemon.h"
35 #include "string.h"
36 #include "fd.h"
37 #include "write.h"
38 #include "write_common.h"
39 #include "signal.h"
40 #include "version.h"
41
42 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
43 /** define the array of error lists needed by para_audiod */
44 INIT_AUDIOD_ERRLISTS;
45 /** define the array containing all supported audio formats */
46 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
47
48 DEFINE_RECEIVER_ARRAY;
49
50 /** Defines how audiod handles one supported audio format. */
51 struct audio_format_info {
52         /** pointer to the receiver for this audio format */
53         struct receiver *receiver;
54         /** the receiver configuration */
55         void *receiver_conf;
56         /** the number of filters that should be activated for this audio format */
57         unsigned int num_filters;
58         /** Array of filter numbers to be activated. */
59         unsigned *filter_nums;
60         /** Pointer to the array of filter configurations. */
61         void **filter_conf;
62         /** the number of filters that should be activated for this audio format */
63         unsigned int num_writers;
64         /** Array of writer numbers to be activated. */
65         int *writer_nums;
66         /** pointer to the array of writer configurations */
67         void **writer_conf;
68         /** do not start receiver/filters/writer before this time */
69         struct timeval restart_barrier;
70 };
71
72 /* Describes one instance of a receiver-filter-writer chain. */
73 struct slot_info {
74         /* Number of the audio format in this slot. */
75         int format;
76         /* The stream_start status item announced by para_server.  */
77         struct timeval server_stream_start;
78         /* The offset status item announced by para_server. */
79         unsigned offset_seconds;
80         /* The seconds_total status item announced by para_server. */
81         unsigned seconds_total;
82         /* The receiver info associated with this slot. */
83         struct receiver_node *receiver_node;
84         /* The array of filter nodes. */
85         struct filter_node *fns;
86         /* The array of writers attached to the last filter. */
87         struct writer_node *wns;
88 };
89
90 /** Maximal number of simultaneous instances. */
91 #define MAX_STREAM_SLOTS 5
92
93 /** Iterate over all slots. */
94 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
95
96 /**
97  * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
98  * be associated with a receiver/filter/writer triple. This array holds all
99  * information on the status of these slots.
100  *
101  * \sa struct slot_info
102  * */
103 struct slot_info slot[MAX_STREAM_SLOTS];
104
105 /** The vss status flags audiod is interested in. */
106 enum vss_status_flags {
107         /** Whether the 'N' flag is set. */
108         VSS_STATUS_FLAG_NEXT = 1,
109         /** The 'P' flag is set. */
110         VSS_STATUS_FLAG_PLAYING = 2,
111 };
112
113 /**
114  * The scheduler instance of para_audiod.
115  *
116  * This is needed also in audiod_command.c (for the tasks command), so it can
117  * not be made static.
118  */
119 struct sched sched = {.max_fileno = 0};
120
121 /* The task for obtaining para_server's status (para_client stat). */
122 struct status_task {
123         /** The associated task structure of audiod. */
124         struct task *task;
125         /** Client data associated with the stat task. */
126         struct client_task *ct;
127         /** Do not restart client command until this time. */
128         struct timeval restart_barrier;
129         /** Last time we received status data from para_server. */
130         struct timeval last_status_read;
131         size_t min_iqs;
132         /** The offset value announced by para_server. */
133         int offset_seconds;
134         /** The length of the current audio file as announced by para_server. */
135         int length_seconds;
136         /** The start of the current stream from the view of para_server. */
137         struct timeval server_stream_start;
138         /** The average time deviation between para_server and para_audiod. */
139         struct timeval sa_time_diff;
140         /** Whether client time is ahead of server time. */
141         int sa_time_diff_sign;
142         /** The 'P' and the 'N' flags as announced by para_server. */
143         enum vss_status_flags vss_status;
144         /** Number of times the clock difference is to be checked. */
145         unsigned clock_diff_count;
146         /** When to start the next check for clock difference. */
147         struct timeval clock_diff_barrier;
148         /** Number of the audio format as announced by para_server. */
149         int current_audio_format_num;
150         /* The status task btrn is the child of the client task. */
151         struct btr_node *btrn;
152 };
153
154 /** The array of status items sent by para_server. */
155 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
156
157 /**
158  * the current mode of operation of which can be changed by the on/off/cycle
159  * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
160  */
161 int audiod_status = AUDIOD_ON;
162
163 /**
164  * the gengetopt args_info struct that holds information on all command line
165  * arguments
166  */
167 static struct audiod_args_info conf;
168
169 static char *socket_name;
170 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
171
172 static struct signal_task *signal_task;
173
174 static struct status_task status_task_struct;
175
176 static uid_t *uid_whitelist;
177
178 /**
179  * the task that calls the status command of para_server
180  *
181  * \sa struct status_task
182  */
183 static struct status_task *stat_task = &status_task_struct;
184
185 /*
186  * The task for handling audiod commands.
187  *
188  * We need two listening sockets for backward compability: on Linux systems
189  * fd[0] is an abstract socket (more precisely, a socket bound to an address in
190  * the abstract namespace), and fd[1] is the usual pathname socket. On other
191  * systems, fd[0] is negative, and only the pathname socket is used.
192  *
193  * For 0.5.x we accept connections on both sockets to make sure that old
194  * para_audioc versions can still connect. New versions use only the abstract
195  * socket. Hence after v0.6.0 we can go back to a single socket, either an
196  * abstract one (Linux) or a pathname socket (all other systems).
197  */
198 struct command_task {
199         /** The local listening sockets. */
200         int fd[2];
201         /** the associated task structure */
202         struct task *task;
203 };
204
205 /** iterate over all supported audio formats */
206 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
207
208 /**
209  * Get the audio format number.
210  *
211  * \param name The name of the audio format.
212  *
213  * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
214  * \a name is not a supported audio format.
215  */
216 static int get_audio_format_num(const char *name)
217 {
218         int i;
219
220         while (para_isspace(*name))
221                 name++;
222         FOR_EACH_AUDIO_FORMAT(i)
223                 if (!strcmp(name, audio_formats[i]))
224                         return i;
225         return -E_UNSUPPORTED_AUDIO_FORMAT;
226 }
227
228 /**
229  * Return the flags for the \a decoder_flags status item.
230  *
231  * Allocates a string which contains one octal digit per slot.  Bit zero (value
232  * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
233  * have the analogous meaning for filter and writer, respectively.
234  *
235  * \return String that must be freed by the caller.
236  */
237 __malloc char *audiod_get_decoder_flags(void)
238 {
239         int i;
240         char flags[MAX_STREAM_SLOTS + 1];
241
242         FOR_EACH_SLOT(i) {
243                 struct slot_info *s = &slot[i];
244                 char flag = '0';
245                 if (s->receiver_node)
246                         flag += 1;
247                 if (s->fns)
248                         flag += 2;
249                 if (s->wns)
250                         flag += 4;
251                 flags[i] = flag;
252         }
253         flags[MAX_STREAM_SLOTS] = '\0';
254         return para_strdup(flags);
255 }
256
257 static int get_matching_audio_format_nums(const char *re)
258 {
259         int i, ret;
260         regex_t preg;
261
262         ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
263         if (ret < 0)
264                 return ret;
265         ret = 0;
266         FOR_EACH_AUDIO_FORMAT(i)
267                 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
268                         ret |= (1 << i);
269         regfree(&preg);
270         return ret;
271 }
272
273 static int get_play_time_slot_num(void)
274 {
275         int i, oldest_slot = -1;
276         struct timeval oldest_wstime = {0, 0};
277
278         FOR_EACH_SLOT(i) {
279                 struct slot_info *s = &slot[i];
280                 struct timeval wstime;
281                 if (!s->wns || !s->wns[0].btrn)
282                         continue;
283                 btr_get_node_start(s->wns[0].btrn, &wstime);
284                 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
285                         continue;
286                 oldest_wstime = wstime;
287                 oldest_slot = i;
288         }
289         return oldest_slot;
290 }
291
292 /**
293  * Compute the play time based on information of the current slot.
294  *
295  * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
296  * from the status items received from para_server and the start time of the
297  * (first) writer of the current slot.
298  *
299  * It has to take into account that the stream was probably not started at
300  * the beginning of the file, that the clock between the server and the client
301  * host may differ and that playback of the stream was delayed, e.g. because
302  * the prebuffer filter is used in the filter configuration.
303  *
304  * If no writer is active, for example because para_audiod runs in standby
305  * mode, an approximation based only on the status items is computed and the
306  * returned string is prefixed with "~".
307  *
308  * \return A string that must be freed by the caller.
309  */
310 char *get_time_string(void)
311 {
312         int ret, seconds = 0, length = stat_task->length_seconds;
313         struct timeval *tmp, sum, sss, /* server stream start */
314                 rstime, /* receiver start time */
315                 wstime, /* writer start time */
316                 wtime, /* now - writer start */
317                 rskip; /* receiver start - sss */
318         int slot_num = get_play_time_slot_num();
319         struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
320         char *msg;
321
322         if (audiod_status == AUDIOD_OFF)
323                 goto empty;
324         if (stat_task->server_stream_start.tv_sec == 0) {
325                 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
326                         goto out; /* server is about to change file */
327                 if (length > 0) /* paused */
328                         return NULL;
329                 goto empty; /* stopped */
330         }
331         /*
332          * Valid status items and playing, set length and tmp to the stream
333          * start. We use the slot info and fall back to the info from current
334          * status items if no slot info is available.
335          */
336         tmp = &stat_task->server_stream_start;
337         if (s && s->wns && s->wns[0].btrn) { /* writer active in this slot */
338                 btr_get_node_start(s->wns[0].btrn, &wstime);
339                 if (wstime.tv_sec != 0) { /* writer wrote something */
340                         if (s->server_stream_start.tv_sec == 0) {
341                                 /* copy status info to slot */
342                                 s->server_stream_start = stat_task->server_stream_start;
343                                 s->offset_seconds = stat_task->offset_seconds;
344                                 s->seconds_total = stat_task->length_seconds;
345                         }
346                         length = s->seconds_total;
347                         tmp = &s->server_stream_start;
348                 }
349         }
350         if (stat_task->sa_time_diff_sign > 0)
351                 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
352         else
353                 tv_add(tmp, &stat_task->sa_time_diff, &sss);
354         if (!s || !s->wns || !s->wns[0].btrn || wstime.tv_sec == 0) {
355                 struct timeval diff;
356                 tv_diff(now, &sss, &diff);
357                 seconds = diff.tv_sec + stat_task->offset_seconds;
358                 goto out;
359         }
360         tv_diff(now, &wstime, &wtime);
361         //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
362         seconds = s->offset_seconds;
363         if (s->receiver_node->btrn) {
364                 btr_get_node_start(s->receiver_node->btrn, &rstime);
365                 ret = tv_diff(&rstime, &sss, &rskip);
366                 if (ret > 0 && rskip.tv_sec > 2) {
367                         /* audiod was started in the middle of the stream */
368                         tv_add(&wtime, &rskip, &sum);
369                         seconds += sum.tv_sec;
370                 } else
371                         seconds += wtime.tv_sec;
372         } else
373                 seconds += wtime.tv_sec;
374 out:
375         seconds = PARA_MIN(seconds, length);
376         seconds = PARA_MAX(seconds, 0);
377         msg = make_message(
378                 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
379                 s? "" : "~",
380                 seconds / 60,
381                 seconds % 60,
382                 (length - seconds) / 60,
383                 (length - seconds) % 60,
384                 length? (seconds * 100 + length / 2) / length : 0,
385                 length / 60,
386                 length % 60
387         );
388         //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
389         return msg;
390 empty:
391         return para_strdup(NULL);
392 }
393
394 static void parse_config_or_die(void)
395 {
396         int ret, i;
397         char *config_file;
398         struct audiod_cmdline_parser_params params = {
399                 .override = 0,
400                 .initialize = 0,
401                 .check_required = 1,
402                 .check_ambiguity = 0,
403                 .print_errors = 1
404         };
405
406         if (conf.config_file_given)
407                 config_file = para_strdup(conf.config_file_arg);
408         else {
409                 char *home = para_homedir();
410                 config_file = make_message("%s/.paraslash/audiod.conf", home);
411                 free(home);
412         }
413         ret = file_exists(config_file);
414         if (conf.config_file_given && !ret) {
415                 PARA_EMERG_LOG("can not read config file %s\n", config_file);
416                 free(config_file);
417                 goto err;
418         }
419         if (ret) {
420                 audiod_cmdline_parser_config_file(config_file, &conf, &params);
421                 daemon_set_loglevel(conf.loglevel_arg);
422         }
423         free(config_file);
424         if (conf.user_allow_given > 0) {
425                 uid_whitelist = para_malloc(conf.user_allow_given
426                         * sizeof(uid_t));
427                 for (i = 0; i < conf.user_allow_given; i++) {
428                         int32_t val;
429                         struct passwd *pw;
430                         ret = para_atoi32(conf.user_allow_arg[i], &val);
431                         if (ret >= 0) {
432                                 uid_whitelist[i] = val;
433                                 continue;
434                         }
435                         errno = 0; /* see getpwnam(3) */
436                         pw = getpwnam(conf.user_allow_arg[i]);
437                         if (!pw) {
438                                 PARA_EMERG_LOG("invalid username: %s\n",
439                                         conf.user_allow_arg[i]);
440                                 goto err;
441                         }
442                         uid_whitelist[i] = pw->pw_uid;
443                 }
444         }
445         return;
446 err:
447         exit(EXIT_FAILURE);
448 }
449
450 static void setup_signal_handling(void)
451 {
452         signal_task = signal_init_or_die();
453         para_install_sighandler(SIGINT);
454         para_install_sighandler(SIGTERM);
455         para_install_sighandler(SIGHUP);
456         para_sigaction(SIGPIPE, SIG_IGN);
457 }
458
459 static void clear_slot(int slot_num)
460 {
461         struct slot_info *s = &slot[slot_num];
462
463         PARA_INFO_LOG("clearing slot %d\n", slot_num);
464         memset(s, 0, sizeof(struct slot_info));
465         s->format = -1;
466 }
467
468 static void close_receiver(int slot_num)
469 {
470         struct slot_info *s = &slot[slot_num];
471         struct audio_format_info *a;
472
473         if (s->format < 0 || !s->receiver_node)
474                 return;
475         a = &afi[s->format];
476         PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
477                 audio_formats[s->format], slot_num);
478         a->receiver->close(s->receiver_node);
479         btr_remove_node(&s->receiver_node->btrn);
480         task_reap(&s->receiver_node->task);
481         free(s->receiver_node);
482         s->receiver_node = NULL;
483         stat_task->current_audio_format_num = -1;
484         tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
485                 &a->restart_barrier);
486 }
487
488 static void writer_cleanup(struct writer_node *wn)
489 {
490         struct writer *w;
491
492         if (!wn)
493                 return;
494         w = writers + wn->writer_num;
495         PARA_INFO_LOG("closing %s\n", writer_names[wn->writer_num]);
496         w->close(wn);
497         btr_remove_node(&wn->btrn);
498         task_reap(&wn->task);
499 }
500
501 static void close_writers(struct slot_info *s)
502 {
503         struct audio_format_info *a;
504         int i;
505
506         if (s->format < 0)
507                 return;
508         assert(s->wns);
509         a = afi + s->format;
510         if (a->num_writers == 0)
511                 writer_cleanup(s->wns);
512         else {
513                 for (i = 0; i < a->num_writers; i++)
514                         writer_cleanup(s->wns + i);
515         }
516         free(s->wns);
517         s->wns = NULL;
518 }
519
520 static void close_filters(struct slot_info *s)
521 {
522         int i;
523         struct audio_format_info *a = afi + s->format;
524         if (a->num_filters == 0)
525                 return;
526         for (i = a->num_filters - 1; i >= 0; i--) {
527                 struct filter_node *fn = s->fns + i;
528                 const struct filter *f;
529
530                 if (!fn)
531                         continue;
532                 f = filter_get(fn->filter_num);
533                 if (f->close)
534                         f->close(fn);
535                 btr_remove_node(&fn->btrn);
536                 task_reap(&fn->task);
537         }
538         free(s->fns);
539         s->fns = NULL;
540 }
541
542 static void notify_receivers(int error)
543 {
544         int i;
545
546         FOR_EACH_SLOT(i) {
547                 struct slot_info *s = slot + i;
548                 if (s->format < 0)
549                         continue;
550                 if (!s->receiver_node)
551                         continue;
552                 task_notify(s->receiver_node->task, error);
553         }
554 }
555
556 static int get_empty_slot(void)
557 {
558         int i;
559         struct slot_info *s;
560
561         FOR_EACH_SLOT(i) {
562                 s = &slot[i];
563                 if (s->format < 0) {
564                         clear_slot(i);
565                         return i;
566                 }
567                 if (s->wns || s->receiver_node || s->fns)
568                         continue;
569                 clear_slot(i);
570                 return i;
571         }
572         return -E_NO_MORE_SLOTS;
573 }
574
575 static void open_filters(struct slot_info *s)
576 {
577         struct audio_format_info *a = afi + s->format;
578         struct filter_node *fn;
579         int nf = a->num_filters;
580         struct btr_node *parent;
581         int i;
582
583         if (nf == 0)
584                 return;
585         PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
586         assert(s->fns == NULL);
587         s->fns = para_calloc(nf * sizeof(struct filter_node));
588         parent = s->receiver_node->btrn;
589         for (i = 0; i < nf; i++) {
590                 char buf[20];
591                 const struct filter *f = filter_get(a->filter_nums[i]);
592                 fn = s->fns + i;
593                 fn->filter_num = a->filter_nums[i];
594                 fn->conf = a->filter_conf[i];
595                 fn->btrn = btr_new_node(&(struct btr_node_description)
596                         EMBRACE(.name = f->name, .parent = parent,
597                                 .handler = f->execute, .context = fn));
598
599                 if (f->open)
600                         f->open(fn);
601                 sprintf(buf, "%s (slot %d)", f->name, (int)(s - slot));
602                 fn->task = task_register(&(struct task_info) {
603                         .name = buf,
604                         .pre_select = f->pre_select,
605                         .post_select = f->post_select,
606                         .context = fn,
607                 }, &sched);
608                 parent = fn->btrn;
609                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
610                         audio_formats[s->format], i,  nf, f->name, (int)(s - slot));
611         }
612 }
613
614 static void open_writers(struct slot_info *s)
615 {
616         int i;
617         struct audio_format_info *a = afi + s->format;
618         struct writer_node *wn;
619         struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
620
621         assert(s->wns == NULL);
622         s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
623                 * sizeof(struct writer_node));
624         for (i = 0; i < a->num_writers; i++) {
625                 wn = s->wns + i;
626                 wn->conf = a->writer_conf[i];
627                 wn->writer_num = a->writer_nums[i];
628                 register_writer_node(wn, parent, &sched);
629                 PARA_NOTICE_LOG("%s writer started in slot %d\n",
630                         writer_names[a->writer_nums[i]], (int)(s - slot));
631         }
632 }
633
634 /* returns slot num on success */
635 static int open_receiver(int format)
636 {
637         struct audio_format_info *a = &afi[format];
638         struct slot_info *s;
639         int ret, slot_num;
640         struct receiver *r = a->receiver;
641         struct receiver_node *rn;
642
643         tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
644         ret = get_empty_slot();
645         if (ret < 0)
646                 return ret;
647         slot_num = ret;
648         rn = para_calloc(sizeof(*rn));
649         rn->receiver = r;
650         rn->conf = a->receiver_conf;
651         rn->btrn = btr_new_node(&(struct btr_node_description)
652                 EMBRACE(.name = r->name, .context = rn));
653         ret = r->open(rn);
654         if (ret < 0) {
655                 btr_remove_node(&rn->btrn);
656                 free(rn);
657                 return ret;
658         }
659         s = &slot[slot_num];
660         s->format = format;
661         s->receiver_node = rn;
662         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
663                 audio_formats[format], r->name, slot_num);
664         rn->task = task_register(&(struct task_info) {
665                 .name = r->name,
666                 .pre_select = r->pre_select,
667                 .post_select = r->post_select,
668                 .context = rn,
669         }, &sched);
670         return slot_num;
671 }
672
673 static bool receiver_running(void)
674 {
675         int i;
676         long unsigned ss1 = stat_task->server_stream_start.tv_sec;
677
678         FOR_EACH_SLOT(i) {
679                 struct slot_info *s = &slot[i];
680                 long unsigned ss2 = s->server_stream_start.tv_sec;
681
682                 if (!s->receiver_node)
683                         continue;
684                 if (task_status(s->receiver_node->task) >= 0)
685                         return true;
686                 if (ss1 == ss2)
687                         return true;
688         }
689         return false;
690 }
691
692 /**
693  * Return the root node of the current buffer tree.
694  *
695  * This is only used for stream grabbing.
696  *
697  * \return \p NULL if no slot is currently active. If more than one buffer tree
698  * exists, the node corresponding to the most recently started receiver is
699  * returned.
700  */
701 struct btr_node *audiod_get_btr_root(void)
702 {
703         int i, newest_slot = -1;
704         struct timeval newest_rstime = {0, 0};
705
706         FOR_EACH_SLOT(i) {
707                 struct slot_info *s = &slot[i];
708                 struct timeval rstime;
709                 if (!s->receiver_node)
710                         continue;
711                 if (task_status(s->receiver_node->task) < 0)
712                         continue;
713                 btr_get_node_start(s->receiver_node->btrn, &rstime);
714                 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
715                         continue;
716                 newest_rstime = rstime;
717                 newest_slot = i;
718         }
719         if (newest_slot == -1)
720                 return NULL;
721         return slot[newest_slot].receiver_node->btrn;
722 }
723
724 /* whether a new instance of a decoder should be started. */
725 static bool must_start_decoder(void)
726 {
727         int cafn = stat_task->current_audio_format_num;
728         unsigned vs = stat_task->vss_status;
729
730         if (audiod_status != AUDIOD_ON)
731                 return false;
732         if (cafn < 0)
733                 return false;
734         if (!stat_task->ct)
735                 return false;
736         if (vs & VSS_STATUS_FLAG_NEXT)
737                 return false;
738         if (!(vs & VSS_STATUS_FLAG_PLAYING))
739                 return false;
740         if (receiver_running())
741                 return false;
742         if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
743                 return false;
744         return true;
745 }
746
747 static void compute_time_diff(const struct timeval *status_time)
748 {
749         struct timeval tmp, diff;
750         static unsigned count;
751         int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
752         const struct timeval max_deviation = {0, 500 * 1000};
753         const int time_smooth = 5;
754
755         sign = tv_diff(status_time, now, &diff);
756 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
757 //                      sign, sa_time_diff_sign);
758         if (!count) {
759                 sa_time_diff_sign = sign;
760                 stat_task->sa_time_diff = diff;
761                 count++;
762                 goto out;
763         }
764         if (count > 5) {
765                 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
766                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
767                         PARA_WARNING_LOG("time diff jump: %lims\n",
768                                 s * tv2ms(&tmp));
769         }
770         count++;
771         sa_time_diff_sign = tv_convex_combination(
772                 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
773                 count > 10? sign : sign * time_smooth, &diff,
774                 &tmp);
775         stat_task->sa_time_diff = tmp;
776         PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
777                 sign < 0? "-" : "+",
778                 tv2ms(&diff),
779                 sa_time_diff_sign < 0? "-" : "+",
780                 tv2ms(&stat_task->sa_time_diff)
781         );
782 out:
783         stat_task->sa_time_diff_sign = sa_time_diff_sign;
784 }
785
786 static int update_item(int itemnum, char *buf)
787 {
788         long unsigned sec, usec;
789
790         if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
791                 return 1;
792         free(stat_item_values[itemnum]);
793         stat_item_values[itemnum] = para_strdup(buf);
794         stat_client_write_item(itemnum);
795         switch (itemnum) {
796         case SI_STATUS_FLAGS:
797                 stat_task->vss_status = 0;
798                 if (strchr(buf, 'N'))
799                         stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
800                 if (strchr(buf, 'P'))
801                         stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
802                 break;
803         case SI_OFFSET:
804                 stat_task->offset_seconds = atoi(buf);
805                 break;
806         case SI_SECONDS_TOTAL:
807                 stat_task->length_seconds = atoi(buf);
808                 break;
809         case SI_STREAM_START:
810                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
811                         stat_task->server_stream_start.tv_sec = sec;
812                         stat_task->server_stream_start.tv_usec = usec;
813                 }
814                 break;
815         case SI_CURRENT_TIME:
816                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
817                         struct timeval tv = {sec, usec};
818                         compute_time_diff(&tv);
819                 }
820                 break;
821         case SI_FORMAT:
822                 stat_task->current_audio_format_num
823                         = get_audio_format_num(buf);
824         }
825         return 1;
826 }
827
828 static int parse_stream_command(const char *txt, char **cmd)
829 {
830         int ret, len;
831         char *re, *p = strchr(txt, ':');
832
833         if (!p)
834                 return -E_MISSING_COLON;
835         *cmd = p + 1;
836         len = p - txt;
837         re = malloc(len + 1);
838         strncpy(re, txt, len);
839         re[len] = '\0';
840         ret = get_matching_audio_format_nums(re);
841         free(re);
842         return ret;
843 }
844
845 static int add_filter(int format, char *cmdline)
846 {
847         struct audio_format_info *a = &afi[format];
848         int filter_num, nf = a->num_filters;
849         void *cfg;
850
851         filter_num = check_filter_arg(cmdline, &cfg);
852         if (filter_num < 0)
853                 return filter_num;
854         a->filter_conf = para_realloc(a->filter_conf,
855                 (nf + 1) * sizeof(void *));
856         a->filter_nums = para_realloc(a->filter_nums,
857                 (nf + 1) * sizeof(unsigned));
858         a->filter_nums[nf] = filter_num;
859         a->filter_conf[nf] = cfg;
860         a->num_filters++;
861         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
862                 filter_get(filter_num)->name);
863         return filter_num;
864 }
865
866 static int parse_writer_args(void)
867 {
868         int i, ret;
869         char *cmd;
870         struct audio_format_info *a;
871
872         for (i = 0; i < conf.writer_given; i++) {
873                 void *wconf;
874                 int j, nw, writer_num, af_mask;
875
876                 ret = parse_stream_command(conf.writer_arg[i], &cmd);
877                 if (ret < 0)
878                         return ret;
879                 af_mask = ret;
880                 FOR_EACH_AUDIO_FORMAT(j) {
881                         a = afi + j;
882                         if ((af_mask & (1 << j)) == 0) /* no match */
883                                 continue;
884                         wconf = check_writer_arg_or_die(cmd, &writer_num);
885                         nw = a->num_writers;
886                         a->writer_nums = para_realloc(a->writer_nums, (nw + 1) * sizeof(int));
887                         a->writer_conf = para_realloc(a->writer_conf, (nw + 1) * sizeof(void *));
888                         a->writer_nums[nw] = writer_num;
889                         a->writer_conf[nw] = wconf;
890                         PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
891                                 nw, writer_names[writer_num]);
892                         a->num_writers++;
893                 }
894         }
895         /* Use default writer for audio formats which are not yet set up. */
896         FOR_EACH_AUDIO_FORMAT(i) {
897                 void *writer_conf;
898                 int writer_num;
899                 a = afi + i;
900                 if (a->num_writers > 0)
901                         continue; /* already set up */
902                 writer_conf = check_writer_arg_or_die(NULL, &writer_num);
903                 a->writer_nums = para_malloc(sizeof(int));
904                 a->writer_nums[0] = writer_num;
905                 a->writer_conf = para_malloc(sizeof(void *));
906                 a->writer_conf[0] = writer_conf;
907                 a->num_writers = 1;
908                 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
909                         writer_names[writer_num]);
910         }
911         return 1;
912 }
913
914 static int parse_receiver_args(void)
915 {
916         int i, ret, receiver_num;
917         char *cmd = NULL;
918         struct audio_format_info *a;
919
920         for (i = conf.receiver_given - 1; i >= 0; i--) {
921                 char *arg;
922                 int j, af_mask;
923
924                 ret = parse_stream_command(conf.receiver_arg[i], &arg);
925                 if (ret < 0)
926                         goto out;
927                 af_mask = ret;
928                 FOR_EACH_AUDIO_FORMAT(j) {
929                         a = afi + j;
930                         if ((af_mask & (1 << j)) == 0) /* no match */
931                                 continue;
932                         /*
933                          * If multiple receivers are given for this audio format, the
934                          * last one wins and we have to free the previous receiver
935                          * config here. Since we are iterating backwards, the winning
936                          * receiver arg is in fact the first one given.
937                          */
938                         if (a->receiver_conf)
939                                 a->receiver->free_config(a->receiver_conf);
940                         a->receiver_conf = check_receiver_arg(arg, &receiver_num);
941                         ret = -E_RECV_SYNTAX;
942                         if (!a->receiver_conf)
943                                 goto out;
944                         a->receiver = receivers + receiver_num;
945                 }
946         }
947         /*
948          * Use the first available receiver with no arguments for those audio
949          * formats for which no receiver was specified.
950          */
951         cmd = para_strdup(receivers[0].name);
952         FOR_EACH_AUDIO_FORMAT(i) {
953                 a = &afi[i];
954                 if (a->receiver_conf)
955                         continue;
956                 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
957                 if (!a->receiver_conf)
958                         return -E_RECV_SYNTAX;
959                 a->receiver = &receivers[receiver_num];
960         }
961         FOR_EACH_AUDIO_FORMAT(i) {
962                 a = afi + i;
963                 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
964                         audio_formats[i], a->receiver->name);
965         }
966         ret = 1;
967 out:
968         free(cmd);
969         return ret;
970 }
971
972 static int init_default_filters(void)
973 {
974         int i, ret = 1;
975
976         FOR_EACH_AUDIO_FORMAT(i) {
977                 struct audio_format_info *a = &afi[i];
978                 char *tmp;
979                 int j;
980
981                 if (a->num_filters)
982                         continue; /* no default -- nothing to to */
983                 /*
984                  * udp and dccp streams are fec-encoded, so add fecdec as the
985                  * first filter.
986                  */
987                 if (strcmp(afi[i].receiver->name, "udp") == 0 ||
988                                 strcmp(afi[i].receiver->name, "dccp") == 0) {
989                         tmp = para_strdup("fecdec");
990                         add_filter(i, tmp);
991                         free(tmp);
992                         if (ret < 0)
993                                 goto out;
994                 }
995                 /* add "dec" to audio format name */
996                 tmp = make_message("%sdec", audio_formats[i]);
997                 for (j = 0; filter_get(j); j++)
998                         if (!strcmp(tmp, filter_get(j)->name))
999                                 break;
1000                 free(tmp);
1001                 ret = -E_UNSUPPORTED_FILTER;
1002                 if (!filter_get(j))
1003                         goto out;
1004                 tmp = para_strdup(filter_get(j)->name);
1005                 ret = add_filter(i, tmp);
1006                 free(tmp);
1007                 if (ret < 0)
1008                         goto out;
1009                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1010                         filter_get(j)->name);
1011         }
1012 out:
1013         return ret;
1014 }
1015
1016 static int parse_filter_args(void)
1017 {
1018         int i, j, ret, af_mask, num_matches;
1019
1020         for (i = 0; i < conf.filter_given; i++) {
1021                 char *arg;
1022                 ret = parse_stream_command(conf.filter_arg[i], &arg);
1023                 if (ret < 0)
1024                         goto out;
1025                 af_mask = ret;
1026                 num_matches = 0;
1027                 FOR_EACH_AUDIO_FORMAT(j) {
1028                         if ((af_mask & (1 << j)) == 0) /* no match */
1029                                 continue;
1030                         ret = add_filter(j, arg);
1031                         if (ret < 0)
1032                                 goto out;
1033                         num_matches++;
1034                 }
1035                 if (num_matches == 0)
1036                         PARA_WARNING_LOG("ignoring filter spec: %s\n",
1037                                 conf.filter_arg[i]);
1038         }
1039         ret = init_default_filters(); /* use default values for the rest */
1040 out:
1041         return ret;
1042 }
1043
1044 static int parse_stream_args(void)
1045 {
1046         int ret;
1047
1048         ret = parse_receiver_args();
1049         if (ret < 0)
1050                 return ret;
1051         ret = parse_filter_args();
1052         if (ret < 0)
1053                 return ret;
1054         ret = parse_writer_args();
1055         if (ret < 0)
1056                 return ret;
1057         return 1;
1058 }
1059
1060 /* does not unlink socket on errors */
1061 static void init_local_sockets(struct command_task *ct)
1062 {
1063         if (conf.socket_given)
1064                 socket_name = para_strdup(conf.socket_arg);
1065         else {
1066                 char *hn = para_hostname();
1067                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1068                         hn);
1069                 free(hn);
1070         }
1071         PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1072         if (conf.force_given)
1073                 unlink(socket_name);
1074         ct->fd[0] = create_local_socket(socket_name, 0);
1075         ct->fd[1] = create_local_socket(socket_name,
1076                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
1077         if (ct->fd[0] >= 0 || ct->fd[1] >= 0)
1078                 return;
1079         PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd[1]));
1080         exit(EXIT_FAILURE);
1081 }
1082
1083 static int signal_post_select(struct sched *s, void *context)
1084 {
1085         struct signal_task *st = context;
1086         int ret, signum;
1087
1088         ret = task_get_notification(st->task);
1089         if (ret < 0)
1090                 return ret;
1091         signum = para_next_signal(&s->rfds);
1092         switch (signum) {
1093         case SIGINT:
1094         case SIGTERM:
1095         case SIGHUP:
1096                 PARA_NOTICE_LOG("received signal %d\n", signum);
1097                 task_notify_all(s, E_AUDIOD_SIGNAL);
1098                 return -E_AUDIOD_SIGNAL;
1099         }
1100         return 0;
1101 }
1102
1103 static void command_pre_select(struct sched *s, void *context)
1104 {
1105         struct command_task *ct = context;
1106         int i;
1107
1108         for (i = 0; i < 2; i++)
1109                 if (ct->fd[i] >= 0)
1110                         para_fd_set(ct->fd[i], &s->rfds, &s->max_fileno);
1111 }
1112
1113 static int command_post_select(struct sched *s, void *context)
1114 {
1115         int ret, i;
1116         struct command_task *ct = context;
1117         static struct timeval last_status_dump;
1118         struct timeval tmp, delay;
1119         bool force = false;
1120
1121         ret = task_get_notification(ct->task);
1122         if (ret < 0)
1123                 return ret;
1124         for (i = 0; i < 2; i++) {
1125                 if (ct->fd[i] < 0)
1126                         continue;
1127                 ret = handle_connect(ct->fd[i], &s->rfds);
1128                 if (ret < 0) {
1129                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1130                         if (ret == -E_AUDIOD_TERM) {
1131                                 task_notify_all(s, -ret);
1132                                 return ret;
1133                         }
1134                 } else if (ret > 0)
1135                         force = true;
1136         }
1137         if (force == true)
1138                 goto dump;
1139
1140         /* if last status dump was less than 500ms ago, do nothing */
1141         delay.tv_sec = 0;
1142         delay.tv_usec = 500 * 1000;
1143         tv_add(&last_status_dump, &delay, &tmp);
1144         if (tv_diff(now, &tmp, NULL) < 0)
1145                 return 0;
1146
1147         /*
1148          * If last status dump was more than 5s ago, force update. Otherwise,
1149          * update only those items that have changed.
1150          */
1151         delay.tv_sec = 5;
1152         delay.tv_usec = 0;
1153         tv_add(&last_status_dump, &delay, &tmp);
1154         if (tv_diff(now, &tmp, NULL) > 0)
1155                 force = true;
1156 dump:
1157         audiod_status_dump(force);
1158         last_status_dump = *now;
1159         return 1;
1160 }
1161
1162 static void init_command_task(struct command_task *ct)
1163 {
1164         init_local_sockets(ct); /* doesn't return on errors */
1165
1166         ct->task = task_register(&(struct task_info) {
1167                 .name = "command",
1168                 .pre_select = command_pre_select,
1169                 .post_select = command_post_select,
1170                 .context = ct,
1171         }, &sched);
1172 }
1173
1174 static void close_stat_pipe(void)
1175 {
1176         if (!stat_task->ct)
1177                 return;
1178         task_reap(&stat_task->ct->task);
1179         client_close(stat_task->ct);
1180         stat_task->ct = NULL;
1181         clear_and_dump_items();
1182         stat_task->length_seconds = 0;
1183         stat_task->offset_seconds = 0;
1184         stat_task->vss_status = 0;
1185         stat_task->current_audio_format_num = -1;
1186         audiod_status_dump(true);
1187 }
1188
1189 /* avoid busy loop if server is down */
1190 static void set_stat_task_restart_barrier(unsigned seconds)
1191 {
1192         struct timeval delay = {seconds, 0};
1193         tv_add(now, &delay, &stat_task->restart_barrier);
1194 }
1195
1196 static bool must_close_slot(int slot_num)
1197 {
1198         struct slot_info *s = &slot[slot_num];
1199         struct audio_format_info *a = afi + s->format;
1200         int i;
1201
1202         if (s->format < 0)
1203                 return false;
1204         if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1205                 return false;
1206         for (i = 0; i < a->num_filters; i++)
1207                 if (s->fns && task_status(s->fns[i].task) >= 0)
1208                         return false;
1209         if (a->num_writers > 0) {
1210                 for (i = 0; i < a->num_writers; i++)
1211                         if (s->wns && task_status(s->wns[i].task) >= 0)
1212                                 return false;
1213         } else {
1214                 if (s->wns && task_status(s->wns[0].task) >= 0)
1215                         return false;
1216         }
1217         return true;
1218 }
1219
1220 static void close_slot(int slot_num)
1221 {
1222         struct slot_info *s = slot + slot_num;
1223
1224         PARA_INFO_LOG("closing slot %d\n", slot_num);
1225         close_writers(s);
1226         close_filters(s);
1227         close_receiver(slot_num);
1228         clear_slot(slot_num);
1229 }
1230
1231 static void close_unused_slots(void)
1232 {
1233         int i;
1234         bool dump = false;
1235
1236         FOR_EACH_SLOT(i)
1237                 if (must_close_slot(i)) {
1238                         close_slot(i);
1239                         dump = true;
1240                 }
1241         if (dump)
1242                 audiod_status_dump(true);
1243 }
1244
1245 /*
1246  * Cleanup all resources.
1247  *
1248  * This performs various cleanups, removes the audiod socket and closes the
1249  * connection to para_server.
1250  */
1251 static void audiod_cleanup(void)
1252 {
1253         if (socket_name)
1254                 unlink(socket_name);
1255         close_stat_pipe();
1256         close_unused_slots();
1257         audiod_cmdline_parser_free(&conf);
1258         close_stat_clients();
1259         free(uid_whitelist);
1260 }
1261
1262 /*
1263  * Check if any receivers/filters/writers need to be started and do so if
1264  * necessary.
1265  */
1266 static void start_stop_decoders(void)
1267 {
1268         int ret;
1269         struct slot_info *sl;
1270
1271         close_unused_slots();
1272         if (audiod_status != AUDIOD_ON ||
1273                         !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1274                 return notify_receivers(E_NOT_PLAYING);
1275         if (!must_start_decoder())
1276                 return;
1277         ret = open_receiver(stat_task->current_audio_format_num);
1278         if (ret < 0) {
1279                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1280                 return;
1281         }
1282         sl = slot + ret;
1283         open_filters(sl);
1284         open_writers(sl);
1285         activate_grab_clients(&sched);
1286         btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1287         audiod_status_dump(true);
1288 }
1289
1290 static void status_pre_select(struct sched *s, void *context)
1291 {
1292         struct status_task *st = context;
1293         int i, ret, cafn = stat_task->current_audio_format_num;
1294
1295         if (must_start_decoder())
1296                 goto min_delay;
1297         FOR_EACH_SLOT(i)
1298                 if (must_close_slot(i))
1299                         goto min_delay;
1300         ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1301         if (ret > 0)
1302                 goto min_delay;
1303         if (st->ct && audiod_status == AUDIOD_OFF)
1304                 goto min_delay;
1305         if (!st->ct && audiod_status != AUDIOD_OFF)
1306                 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1307         if (cafn >= 0)
1308                 sched_request_barrier(&afi[cafn].restart_barrier, s);
1309         /*
1310          * If para_server is playing we'd like to have a smooth time display
1311          * even if we are running in standby mode. So we request a timeout that
1312          * expires at the next full second.
1313          */
1314         if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1315                 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1316         return;
1317 min_delay:
1318         sched_min_delay(s);
1319 }
1320
1321 /* restart the client task if necessary */
1322 static int status_post_select(struct sched *s, void *context)
1323 {
1324         struct status_task *st = context;
1325         int ret;
1326
1327         ret = task_get_notification(st->task);
1328         if (ret < 0)
1329                 return ret;
1330         if (audiod_status == AUDIOD_OFF) {
1331                 if (!st->ct)
1332                         goto out;
1333                 if (task_status(st->ct->task) >= 0) {
1334                         task_notify(st->ct->task, E_AUDIOD_OFF);
1335                         goto out;
1336                 }
1337                 close_stat_pipe();
1338                 st->clock_diff_count = conf.clock_diff_count_arg;
1339                 goto out;
1340         }
1341         if (st->ct) {
1342                 char *buf;
1343                 size_t sz;
1344
1345                 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1346                 if (ret < 0) {
1347                         close_stat_pipe();
1348                         goto out;
1349                 }
1350                 if (st->ct->status != CL_EXECUTING)
1351                         goto out;
1352                 if (ret == 0) {
1353                         struct timeval diff;
1354                         tv_diff(now, &st->last_status_read, &diff);
1355                         if (diff.tv_sec > 61)
1356                                 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1357                         goto out;
1358                 }
1359                 btr_merge(st->btrn, st->min_iqs);
1360                 sz = btr_next_buffer(st->btrn, &buf);
1361                 ret = for_each_stat_item(buf, sz, update_item);
1362                 if (ret < 0) {
1363                         task_notify(st->ct->task, -ret);
1364                         goto out;
1365                 }
1366                 if (sz != ret) {
1367                         btr_consume(st->btrn, sz - ret);
1368                         st->last_status_read = *now;
1369                         st->min_iqs = 0;
1370                 } else /* current status item crosses buffers */
1371                         st->min_iqs = sz + 1;
1372                 goto out;
1373         }
1374         btr_drain(st->btrn);
1375         st->current_audio_format_num = -1;
1376         if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1377                 goto out;
1378         if (st->clock_diff_count) { /* get status only one time */
1379                 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1380                 int argc = 5;
1381                 PARA_INFO_LOG("clock diff count: %d\n", st->clock_diff_count);
1382                 st->clock_diff_count--;
1383                 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1384                 set_stat_task_restart_barrier(2);
1385
1386         } else {
1387                 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1388                 int argc = 4;
1389                 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1390                 set_stat_task_restart_barrier(5);
1391         }
1392         free(stat_item_values[SI_BASENAME]);
1393         stat_item_values[SI_BASENAME] = para_strdup(
1394                 "no connection to para_server");
1395         stat_client_write_item(SI_BASENAME);
1396         st->last_status_read = *now;
1397 out:
1398         start_stop_decoders();
1399         return 0;
1400 }
1401
1402 static void init_status_task(struct status_task *st)
1403 {
1404         memset(st, 0, sizeof(struct status_task));
1405         st->sa_time_diff_sign = 1;
1406         st->clock_diff_count = conf.clock_diff_count_arg;
1407         st->current_audio_format_num = -1;
1408         st->btrn = btr_new_node(&(struct btr_node_description)
1409                 EMBRACE(.name = "stat"));
1410
1411         stat_task->task = task_register(&(struct task_info) {
1412                 .name = "stat",
1413                 .pre_select = status_pre_select,
1414                 .post_select = status_post_select,
1415                 .context = stat_task,
1416         }, &sched);
1417 }
1418
1419 static void set_initial_status(void)
1420 {
1421         audiod_status = AUDIOD_ON;
1422         if (!conf.mode_given)
1423                 return;
1424         if (!strcmp(conf.mode_arg, "sb")) {
1425                 audiod_status = AUDIOD_STANDBY;
1426                 return;
1427         }
1428         if (!strcmp(conf.mode_arg, "off")) {
1429                 audiod_status = AUDIOD_OFF;
1430                 return;
1431         }
1432         if (strcmp(conf.mode_arg, "on"))
1433                 PARA_WARNING_LOG("invalid mode\n");
1434 }
1435
1436 __noreturn static void print_help_and_die(void)
1437 {
1438         struct ggo_help h = DEFINE_GGO_HELP(audiod);
1439         bool d = conf.detailed_help_given;
1440         unsigned flags;
1441
1442         flags = d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
1443         ggo_print_help(&h, flags);
1444
1445         flags = d? GPH_MODULE_FLAGS_DETAILED : GPH_MODULE_FLAGS;
1446         print_receiver_helps(flags);
1447         print_filter_helps(flags);
1448         print_writer_helps(flags);
1449         exit(0);
1450 }
1451
1452 /**
1453  * Lookup the given UID in the whitelist.
1454  *
1455  * The whitelist is the array of arguments to the --user-allow opion. If the
1456  * option was not given, the array is empty, in which case the check succeeds.
1457  *
1458  * \param uid User ID to look up.
1459  *
1460  * \return True if --user-allow was not given, or if uid matches an element of
1461  * the whitelist.
1462  */
1463 bool uid_is_whitelisted(uid_t uid)
1464 {
1465         int i;
1466
1467         if (!conf.user_allow_given)
1468                 return true;
1469         for (i = 0; i < conf.user_allow_given; i++)
1470                 if (uid == uid_whitelist[i])
1471                         return true;
1472         return false;
1473 }
1474
1475 /**
1476  * the main function of para_audiod
1477  *
1478  * \param argc usual argument count
1479  * \param argv usual argument vector
1480  *
1481  * \return EXIT_SUCCESS or EXIT_FAILURE
1482  *
1483  * \sa para_audiod(1)
1484  * */
1485 int main(int argc, char *argv[])
1486 {
1487         int ret, i;
1488         struct command_task command_task_struct, *cmd_task = &command_task_struct;
1489         struct audiod_cmdline_parser_params params = {
1490                 .override = 0,
1491                 .initialize = 1,
1492                 .check_required = 0,
1493                 .check_ambiguity = 0,
1494                 .print_errors = 1
1495         };
1496
1497         valid_fd_012();
1498         audiod_cmdline_parser_ext(argc, argv, &conf, &params);
1499         daemon_set_loglevel(conf.loglevel_arg);
1500         version_handle_flag("audiod", conf.version_given);
1501         /* init receivers/filters/writers early to make help work */
1502         recv_init();
1503         filter_init();
1504         writer_init();
1505         if (conf.help_given || conf.detailed_help_given)
1506                 print_help_and_die();
1507         daemon_set_priority(conf.priority_arg);
1508         daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
1509         parse_config_or_die();
1510         if (daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
1511                 conf.logfile_given)) {
1512                         for (i = 0; i < conf.log_color_given; i++)
1513                                 daemon_set_log_color_or_die(conf.log_color_arg[i]);
1514         }
1515         init_random_seed_or_die();
1516         daemon_set_flag(DF_LOG_TIME);
1517         daemon_set_flag(DF_LOG_HOSTNAME);
1518         daemon_set_flag(DF_LOG_LL);
1519         if (conf.log_timing_given)
1520                 daemon_set_flag(DF_LOG_TIMING);
1521         if (conf.logfile_given) {
1522                 daemon_set_logfile(conf.logfile_arg);
1523                 daemon_open_log_or_die();
1524         }
1525         ret = parse_stream_args();
1526         if (ret < 0) {
1527                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1528                 exit(EXIT_FAILURE);
1529         }
1530         daemon_log_welcome("audiod");
1531         daemon_set_start_time();
1532         set_initial_status();
1533         FOR_EACH_SLOT(i)
1534                 clear_slot(i);
1535         setup_signal_handling();
1536
1537         init_status_task(stat_task);
1538         init_command_task(cmd_task);
1539
1540         if (conf.daemon_given)
1541                 daemonize(false /* parent exits immediately */);
1542
1543         signal_task->task = task_register(&(struct task_info) {
1544                 .name = "signal",
1545                 .pre_select = signal_pre_select,
1546                 .post_select = signal_post_select,
1547                 .context = signal_task,
1548         }, &sched);
1549
1550         sched.default_timeout.tv_sec = 2;
1551         sched.default_timeout.tv_usec = 999 * 1000;
1552         ret = schedule(&sched);
1553         audiod_cleanup();
1554         sched_shutdown(&sched);
1555         signal_shutdown(signal_task);
1556
1557         if (ret < 0)
1558                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1559         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1560 }