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