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