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