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