btr support for the wmadec filter.
[paraslash.git] / audiod.c
1 /*
2  * Copyright (C) 2005-2009 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 <dirent.h>
11 #include <signal.h>
12 #include <openssl/rc4.h>
13 #include <stdbool.h>
14
15 #include "para.h"
16 #include "error.h"
17 #include "crypt.h"
18 #include "audiod.cmdline.h"
19 #include "list.h"
20 #include "sched.h"
21 #include "ggo.h"
22 #include "recv.h"
23 #include "buffer_tree.h"
24 #include "filter.h"
25 #include "grab_client.h"
26 #include "client.cmdline.h"
27 #include "client.h"
28 #include "audiod.h"
29 #include "net.h"
30 #include "daemon.h"
31 #include "string.h"
32 #include "fd.h"
33 #include "write.h"
34 #include "write_common.h"
35 #include "signal.h"
36
37 /** define the array of error lists needed by para_audiod */
38 INIT_AUDIOD_ERRLISTS;
39 /** define the array containing all supported audio formats */
40 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
41
42 /** Defines how audiod handles one supported audio format. */
43 struct audio_format_info {
44         /** pointer to the receiver for this audio format */
45         struct receiver *receiver;
46         /** the receiver configuration */
47         void *receiver_conf;
48         /** the number of filters that should be activated for this audio format */
49         unsigned int num_filters;
50         /** Array of filter numbers to be activated. */
51         unsigned *filter_nums;
52         /** Pointer to the array of filter configurations. */
53         void **filter_conf;
54         /** the number of filters that should be activated for this audio format */
55         unsigned int num_writers;
56         /** Array of writer numbers to be activated. */
57         int *writer_nums;
58         /** pointer to the array of writer configurations */
59         void **writer_conf;
60         /** do not start receiver/filters/writer before this time */
61         struct timeval restart_barrier;
62 };
63
64 /**
65  * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
66  * be associated with a receiver/filter/writer triple. This array holds all
67  * information on the status of these slots.
68  *
69  * \sa struct slot_info
70  * */
71 struct slot_info slot[MAX_STREAM_SLOTS];
72
73 /** The vss status flags audiod is interested in. */
74 enum vss_status_flags {
75         /** Whether the 'N' flag is set. */
76         VSS_STATUS_FLAG_NEXT = 1,
77         /** The 'P' flag is set. */
78         VSS_STATUS_FLAG_PLAYING = 2,
79 };
80
81 /**
82  * The task for obtaining para_server's status (para_client stat).
83  *
84  * \sa struct task, struct sched.
85  */
86 struct status_task {
87         /** The associated task structure of audiod. */
88         struct task task;
89         /** Client data associated with the stat task. */
90         struct client_task *ct;
91         /** Do not restart client command until this time. */
92         struct timeval restart_barrier;
93         /** Last time we received status data from para_server. */
94         struct timeval last_status_read;
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 };
114
115 /** The array of status items sent by para_server. */
116 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
117
118 /**
119  * the current mode of operation of which can be changed by the on/off/cycle
120  * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
121  */
122 int audiod_status = AUDIOD_ON;
123
124 /**
125  * the gengetopt args_info struct that holds information on all command line
126  * arguments
127  */
128 struct audiod_args_info conf;
129
130 static char *socket_name;
131 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
132
133 static struct signal_task signal_task_struct, *sig_task = &signal_task_struct;
134
135 static struct status_task status_task_struct;
136
137 /**
138  * the task that calls the status command of para_server
139  *
140  * \sa struct status_task
141  */
142 static struct status_task *stat_task = &status_task_struct;
143 static struct timeval initial_delay_barrier;
144
145 /**
146  * the task for handling audiod commands
147  *
148  * \sa struct task, struct sched
149  */
150 struct command_task {
151         /** the local listening socket */
152         int fd;
153         /** the associated task structure */
154         struct task task;
155 };
156
157 /** iterate over all supported audio formats */
158 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
159
160 /**
161  * get the audio format number
162  * \param name the name of the audio format
163  *
164  * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
165  * \a name is not a supported audio format.
166  */
167 int get_audio_format_num(const char *name)
168 {
169         int i;
170
171         while (para_isspace(*name))
172                 name++;
173         FOR_EACH_AUDIO_FORMAT(i)
174                 if (!strcmp(name, audio_formats[i]))
175                         return i;
176         return -E_UNSUPPORTED_AUDIO_FORMAT;
177 }
178
179 char *get_time_string(int slot_num)
180 {
181         int ret, seconds = 0, length;
182         struct timeval *tmp, sum, sss, /* server stream start */
183                 wtime, /* now - writer start */
184                 rskip; /* receiver start - sss */
185         struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
186
187         if (audiod_status == AUDIOD_OFF)
188                 goto empty;
189         if (!(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)) {
190                 if (stat_task->length_seconds) /* paused */
191                         return NULL;
192                 goto empty; /* stopped */
193         }
194         if (audiod_status == AUDIOD_ON && !s)
195                 goto empty;
196         /* valid status items and playing */
197         if (s) { /* writer active in this slot */
198                 length = s->seconds_total;
199                 tmp = &s->server_stream_start;
200         } else { /* standby mode, rely on status items */
201                 length = stat_task->length_seconds;
202                 tmp = &stat_task->server_stream_start;
203         }
204         if (stat_task->sa_time_diff_sign > 0)
205                 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
206         else
207                 tv_add(tmp, &stat_task->sa_time_diff, &sss);
208         if (!s) {
209                 struct timeval diff;
210                 tv_diff(now, &sss, &diff);
211                 seconds = diff.tv_sec + stat_task->offset_seconds;
212                 goto out;
213         }
214         tv_diff(now, &s->wstime, &wtime);
215         seconds = s->offset_seconds;
216         ret = tv_diff(&s->rstime, &sss, &rskip);
217         if (ret > 0) { /* audiod was started in the middle of the stream */
218                 tv_add(&wtime, &rskip, &sum);
219                 seconds += sum.tv_sec;
220         } else
221                 seconds += wtime.tv_sec;
222 out:
223         seconds = PARA_MIN(seconds, length);
224         seconds = PARA_MAX(seconds, 0);
225         return make_message(
226                 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
227                 s? "" : "~",
228                 seconds / 60,
229                 seconds % 60,
230                 (length - seconds) / 60,
231                 (length - seconds) % 60,
232                 length? (seconds * 100 + length / 2) / length : 0,
233                 length / 60,
234                 length % 60
235         );
236 empty:
237         return para_strdup(NULL);
238 }
239
240 static int want_colors(void)
241 {
242         if (conf.color_arg == color_arg_no)
243                 return 0;
244         if (conf.color_arg == color_arg_yes)
245                 return 1;
246         if (conf.logfile_given)
247                 return 0;
248         return isatty(STDERR_FILENO);
249 }
250
251 static void parse_config_or_die(void)
252 {
253         int ret;
254         char *config_file;
255         struct audiod_cmdline_parser_params params = {
256                 .override = 0,
257                 .initialize = 0,
258                 .check_required = 1,
259                 .check_ambiguity = 0,
260                 .print_errors = 1
261         };
262
263         if (conf.config_file_given)
264                 config_file = para_strdup(conf.config_file_arg);
265         else {
266                 char *home = para_homedir();
267                 config_file = make_message("%s/.paraslash/audiod.conf", home);
268                 free(home);
269         }
270         ret = file_exists(config_file);
271         if (conf.config_file_given && !ret) {
272                 PARA_EMERG_LOG("can not read config file %s\n", config_file);
273                 goto err;
274         }
275         if (ret)
276                 audiod_cmdline_parser_config_file(config_file, &conf, &params);
277         free(config_file);
278         daemon_set_loglevel(conf.loglevel_arg);
279         return;
280 err:
281         free(config_file);
282         exit(EXIT_FAILURE);
283 }
284
285 static void setup_signal_handling(void)
286 {
287         sig_task->fd = para_signal_init();
288         PARA_INFO_LOG("signal pipe: fd %d\n", sig_task->fd);
289         para_install_sighandler(SIGINT);
290         para_install_sighandler(SIGTERM);
291         para_install_sighandler(SIGHUP);
292         para_sigaction(SIGPIPE, SIG_IGN);
293 }
294
295 static void clear_slot(int slot_num)
296 {
297         struct slot_info *s = &slot[slot_num];
298
299         PARA_INFO_LOG("clearing slot %d\n", slot_num);
300         memset(s, 0, sizeof(struct slot_info));
301         s->format = -1;
302 }
303
304 static void close_receiver(int slot_num)
305 {
306         struct slot_info *s = &slot[slot_num];
307         struct audio_format_info *a;
308
309         if (s->format < 0 || !s->receiver_node)
310                 return;
311         a = &afi[s->format];
312         PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
313                 audio_formats[s->format], slot_num);
314         a->receiver->close(s->receiver_node);
315         free(s->receiver_node);
316         s->receiver_node = NULL;
317         stat_task->current_audio_format_num = -1;
318 }
319
320 static void kill_all_decoders(int error)
321 {
322         int i;
323
324         FOR_EACH_SLOT(i) {
325                 struct slot_info *s = &slot[i];
326                 if (s->wng && s->wng->task.error >= 0) {
327                         PARA_INFO_LOG("deactivating wng in slot %d\n",
328                                 i);
329                         s->wng->task.error = error;
330                 }
331                 if (s->fc && s->fc->task.error >= 0) {
332                         PARA_INFO_LOG("deactivatimg filter chain in slot %d\n", i);
333                         s->fc->task.error = error;
334                 }
335                 if (s->receiver_node && s->receiver_node->task.error >= 0) {
336                         PARA_INFO_LOG("deactivating receiver_node in slot %d\n", i);
337                         s->receiver_node->task.error = error;
338                 }
339         }
340 }
341
342 static int get_empty_slot(void)
343 {
344         int i;
345         struct slot_info *s;
346
347         FOR_EACH_SLOT(i) {
348                 s = &slot[i];
349                 if (s->format < 0) {
350                         clear_slot(i);
351                         return i;
352                 }
353                 if (s->wng || s->receiver_node || s->fc)
354                         continue;
355                 clear_slot(i);
356                 return i;
357         }
358         return -E_NO_MORE_SLOTS;
359 }
360
361 /**
362  * get the number of filters
363  *
364  * \param audio_format_num the number identifying the audio format
365  *
366  * \return the number of filters for the given audio format
367  *
368  * \sa struct filter;
369  */
370 int num_filters(int audio_format_num)
371 {
372         return afi[audio_format_num].num_filters;
373 }
374
375 static void open_filters(int slot_num)
376 {
377         struct slot_info *s = &slot[slot_num];
378         struct audio_format_info *a = &afi[s->format];
379         struct filter_node *fn;
380         int nf = a->num_filters;
381         int i;
382
383         s->fc = NULL;
384         if (!nf)
385                 return;
386         PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
387         s->fc = para_calloc(sizeof(struct filter_chain));
388         s->fc->filter_nodes = para_malloc(nf * sizeof(struct filter_node));
389         s->fc->inbufp = &s->receiver_node->buf;
390         s->fc->in_loaded = &s->receiver_node->loaded;
391         s->fc->input_error = &s->receiver_node->task.error;
392         s->fc->task.pre_select = NULL;
393         s->fc->task.post_select = filter_post_select;
394         s->fc->task.error = 0;
395         s->fc->num_filters = nf;
396
397         s->receiver_node->output_error = &s->fc->task.error;
398         sprintf(s->fc->task.status, "filter chain");
399         FOR_EACH_FILTER_NODE(fn, s->fc, i) {
400                 struct filter *f = filters + a->filter_nums[i];
401                 fn->filter_num = a->filter_nums[i];
402                 fn->conf = a->filter_conf[i];
403                 fn->fc = s->fc;
404                 fn->loaded = 0;
405                 INIT_LIST_HEAD(&fn->callbacks);
406                 f->open(fn);
407                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
408                         audio_formats[s->format], i,  nf, f->name, slot_num);
409                 s->fc->outbufp = &fn->buf;
410                 s->fc->out_loaded = &fn->loaded;
411         }
412         register_task(&s->fc->task);
413 }
414
415 static void open_writers(int slot_num)
416 {
417         int ret, i;
418         struct slot_info *s = &slot[slot_num];
419         struct audio_format_info *a = &afi[s->format];
420
421         PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
422         if (!a->num_writers)
423                 s->wng = setup_default_wng();
424         else
425                 s->wng = wng_new(a->num_writers);
426         if (s->fc) {
427                 s->wng->bufp = s->fc->outbufp;
428                 s->wng->loaded = s->fc->out_loaded;
429                 s->wng->input_error = &s->fc->task.error;
430                 s->wng->channels = &s->fc->channels;
431                 s->wng->samplerate = &s->fc->samplerate;
432                 s->fc->output_error = &s->wng->task.error;
433                 PARA_INFO_LOG("samplerate: %d\n", *s->wng->samplerate);
434         } else {
435                 s->wng->bufp = &s->receiver_node->buf;
436                 s->wng->loaded = &s->receiver_node->loaded;
437                 s->wng->input_error = &s->receiver_node->task.error;
438         }
439         for (i = 0; i < a->num_writers; i++) {
440                 s->wng->writer_nodes[i].conf = a->writer_conf[i];
441                 s->wng->writer_nodes[i].writer_num = a->writer_nums[i];
442         }
443         ret = wng_open(s->wng);
444         if (ret < 0)
445                 return;
446         s->wstime = *now;
447         s->server_stream_start = stat_task->server_stream_start.tv_sec?
448                 stat_task->server_stream_start : *now;
449         s->offset_seconds = stat_task->offset_seconds;
450         s->seconds_total = stat_task->length_seconds;
451         activate_inactive_grab_clients(s->format, s->fc);
452 }
453
454 static int open_receiver(int format)
455 {
456         struct audio_format_info *a = &afi[format];
457         struct slot_info *s;
458         int ret, slot_num;
459         struct receiver_node *rn;
460         const struct timeval restart_delay = {2, 0};
461
462         ret = get_empty_slot();
463         if (ret < 0)
464                 goto err;
465         slot_num = ret;
466         s = &slot[slot_num];
467         s->format = format;
468         s->receiver_node = para_calloc(sizeof(struct receiver_node));
469         rn = s->receiver_node;
470         rn->receiver = a->receiver;
471         rn->conf = a->receiver_conf;
472         ret = a->receiver->open(s->receiver_node);
473         if (ret < 0) {
474                 free(s->receiver_node);
475                 s->receiver_node = NULL;
476                 goto err;
477         }
478         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
479                 audio_formats[s->format], a->receiver->name, slot_num);
480         rn->task.pre_select = a->receiver->pre_select;
481         rn->task.post_select = a->receiver->post_select;
482         s->rstime = *now;
483         sprintf(rn->task.status, "%s receiver node", rn->receiver->name);
484         register_task(&rn->task);
485         ret = 1;
486 err:
487         if (ret < 0)
488                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
489         tv_add(now, &restart_delay, &afi[format].restart_barrier);
490         return ret;
491 }
492
493 /* return: 0: Not running, 1: Running, -1: Running but eof (or error) */
494 static int receiver_running(int format)
495 {
496         int i, ret = 0;
497
498         FOR_EACH_SLOT(i) {
499                 struct slot_info *s = &slot[i];
500                 if (s->format != format)
501                         continue;
502                 if (!s->receiver_node)
503                         continue;
504                 if (s->receiver_node->task.error >= 0)
505                         return 1;
506                 ret = -1;
507         }
508         return ret;
509 }
510
511 static void open_current_receiver(struct sched *s)
512 {
513         struct timeval diff;
514         int ret, cafn = stat_task->current_audio_format_num;
515
516         if (cafn < 0 || !stat_task->ct)
517                 return;
518         /* Do nothing if the 'N' flag is set or the 'P' flag is unset */
519         if (stat_task->vss_status != VSS_STATUS_FLAG_PLAYING)
520                 return;
521         ret = receiver_running(cafn);
522         if (ret > 0) /* already running and not eof */
523                 return;
524         if (ret < 0) { /* eof */
525                 /*
526                  * para_server uses a zero start time during the announcement
527                  * period, i.e. before it sends the first chunk. Wait until
528                  * this period begins to avoid restarting the receiver that
529                  * belongs to the file just completed.
530                  */
531                 if (stat_task->server_stream_start.tv_sec)
532                         return;
533         }
534         if (tv_diff(now, &afi[cafn].restart_barrier, &diff) < 0) {
535                 /* avoid busy loop */
536                 s->timeout = diff;
537                 return;
538         }
539         /* start a new receiver */
540         open_receiver(cafn);
541 }
542
543 static unsigned compute_time_diff(const struct timeval *status_time)
544 {
545         struct timeval tmp, diff;
546         static unsigned count;
547         int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
548         const struct timeval max_deviation = {0, 500 * 1000};
549         const int time_smooth = 5;
550
551         if (!status_time)
552                 return count;
553         sign = tv_diff(status_time, now, &diff);
554 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
555 //                      sign, sa_time_diff_sign);
556         if (!count) {
557                 sa_time_diff_sign = sign;
558                 stat_task->sa_time_diff = diff;
559                 count++;
560                 goto out;
561         }
562         if (count > 5) {
563                 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
564                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
565                         PARA_WARNING_LOG("time diff jump: %lims\n",
566                                 s * tv2ms(&tmp));
567         }
568         count++;
569         sa_time_diff_sign = tv_convex_combination(
570                 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
571                 count > 10? sign : sign * time_smooth, &diff,
572                 &tmp);
573         stat_task->sa_time_diff = tmp;
574         PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
575                 sign > 0? "+" : "-",
576                 tv2ms(&diff),
577                 sa_time_diff_sign ? "+" : "-",
578                 tv2ms(&stat_task->sa_time_diff)
579         );
580 out:
581         stat_task->sa_time_diff_sign = sa_time_diff_sign;
582         return count;
583 }
584
585 static int update_item(int itemnum, char *buf)
586 {
587         long unsigned sec, usec;
588
589         if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
590                 return 1;
591         free(stat_item_values[itemnum]);
592         stat_item_values[itemnum] = para_strdup(buf);
593         stat_client_write_item(itemnum);
594         switch (itemnum) {
595         case SI_STATUS_FLAGS:
596                 stat_task->vss_status = 0;
597                 if (strchr(buf, 'N'))
598                         stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
599                 if (strchr(buf, 'P'))
600                         stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
601                 break;
602         case SI_OFFSET:
603                 stat_task->offset_seconds = atoi(buf);
604                 break;
605         case SI_SECONDS_TOTAL:
606                 stat_task->length_seconds = atoi(buf);
607                 break;
608         case SI_STREAM_START:
609                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
610                         struct timeval a_start, delay;
611                         delay.tv_sec = conf.stream_delay_arg / 1000;
612                         delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
613                         stat_task->server_stream_start.tv_sec = sec;
614                         stat_task->server_stream_start.tv_usec = usec;
615                         if (compute_time_diff(NULL) > 2) {
616                                 if (stat_task->sa_time_diff_sign < 0)
617                                         tv_add(&stat_task->server_stream_start,
618                                                 &stat_task->sa_time_diff, &a_start);
619                                 else
620                                         tv_diff(&stat_task->server_stream_start,
621                                                 &stat_task->sa_time_diff, &a_start);
622                                 tv_add(&a_start, &delay, &initial_delay_barrier);
623                         }
624                 }
625                 break;
626         case SI_CURRENT_TIME:
627                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
628                         struct timeval tv = {sec, usec};
629                         compute_time_diff(&tv);
630                 }
631                 break;
632         case SI_FORMAT:
633                 stat_task->current_audio_format_num
634                         = get_audio_format_num(buf);
635         }
636         return 1;
637 }
638
639 static int parse_stream_command(const char *txt, char **cmd)
640 {
641         char *p = strchr(txt, ':');
642         int i;
643
644         if (!p)
645                 return -E_MISSING_COLON;
646         p++;
647         FOR_EACH_AUDIO_FORMAT(i) {
648                 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
649                         continue;
650                 *cmd = p;
651                 return i;
652         }
653         return -E_UNSUPPORTED_AUDIO_FORMAT;
654 }
655
656 static int add_filter(int format, char *cmdline)
657 {
658         struct audio_format_info *a = &afi[format];
659         int filter_num, nf = a->num_filters;
660
661         filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
662         if (filter_num < 0)
663                 return filter_num;
664         a->filter_nums[nf] = filter_num;
665         a->num_filters++;
666         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
667                 filters[filter_num].name);
668         return filter_num;
669 }
670
671 static int parse_writer_args(void)
672 {
673         int i, ret, nw;
674         char *cmd;
675         struct audio_format_info *a;
676
677         nw = PARA_MAX(1U, conf.writer_given);
678         PARA_INFO_LOG("maximal number of writers: %d\n", nw);
679         FOR_EACH_AUDIO_FORMAT(i) {
680                 a = &afi[i];
681                 a->writer_conf = para_malloc(nw * sizeof(void *));
682                 a->writer_nums = para_malloc(nw * sizeof(int));
683                 a->num_writers = 0;
684         }
685         for (i = 0; i < conf.writer_given; i++) {
686                 void *wconf;
687                 int writer_num;
688                 ret = parse_stream_command(conf.writer_arg[i], &cmd);
689                 if (ret < 0)
690                         goto out;
691                 a = &afi[ret];
692                 nw = a->num_writers;
693                 wconf = check_writer_arg(cmd, &writer_num);
694                 if (!wconf) {
695                         ret = writer_num;
696                         goto out;
697                 }
698                 a->writer_nums[nw] = writer_num;
699                 a->writer_conf[nw] = wconf;
700                 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
701                         nw, writer_names[writer_num]);
702                 a->num_writers++;
703         }
704         ret = 1;
705 out:
706         return ret;
707 }
708
709 static int parse_receiver_args(void)
710 {
711         int i, ret, receiver_num;
712         char *cmd = NULL;
713         struct audio_format_info *a;
714
715         for (i = conf.receiver_given - 1; i >= 0; i--) {
716                 char *arg = conf.receiver_arg[i];
717                 char *recv_arg = strchr(arg, ':');
718                 ret = -E_MISSING_COLON;
719                 if (!recv_arg)
720                         goto out;
721                 *recv_arg = '\0';
722                 recv_arg++;
723                 ret = get_audio_format_num(arg);
724                 if (ret < 0)
725                         goto out;
726                 afi[ret].receiver_conf = check_receiver_arg(recv_arg, &receiver_num);
727                 if (!afi[ret].receiver_conf) {
728                         ret = -E_RECV_SYNTAX;
729                         goto out;
730                 }
731                 afi[ret].receiver = &receivers[receiver_num];
732         }
733         /* use the first available receiver with no arguments
734          * for those audio formats for which no receiver
735          * was specified
736          */
737         cmd = para_strdup(receivers[0].name);
738         FOR_EACH_AUDIO_FORMAT(i) {
739                 a = &afi[i];
740                 if (a->receiver_conf)
741                         continue;
742                 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
743                 if (!a->receiver_conf)
744                         return -E_RECV_SYNTAX;
745                 a->receiver = &receivers[receiver_num];
746         }
747         ret = 1;
748 out:
749         free(cmd);
750         return ret;
751 }
752
753 static int init_default_filters(void)
754 {
755         int i, ret = 1;
756
757         FOR_EACH_AUDIO_FORMAT(i) {
758                 struct audio_format_info *a = &afi[i];
759                 char *tmp;
760                 int j;
761
762                 if (a->num_filters)
763                         continue; /* no default -- nothing to to */
764                 /* add "dec" to audio format name */
765                 tmp = make_message("%sdec", audio_formats[i]);
766                 for (j = 0; filters[j].name; j++)
767                         if (!strcmp(tmp, filters[j].name))
768                                 break;
769                 free(tmp);
770                 ret = -E_UNSUPPORTED_FILTER;
771                 if (!filters[j].name)
772                         goto out;
773                 tmp = para_strdup(filters[j].name);
774                 ret = add_filter(i, tmp);
775                 free(tmp);
776                 if (ret < 0)
777                         goto out;
778                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
779                         filters[j].name);
780         }
781 out:
782         return ret;
783 }
784
785 static int parse_filter_args(void)
786 {
787         int i, ret, nf;
788
789         nf = PARA_MAX(1U, conf.filter_given);
790         PARA_INFO_LOG("maximal number of filters: %d\n", nf);
791         FOR_EACH_AUDIO_FORMAT(i) {
792                 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
793                 afi[i].filter_nums = para_malloc(nf * sizeof(unsigned));
794         }
795         if (!conf.no_default_filters_given)
796                 return init_default_filters();
797         for (i = 0; i < conf.filter_given; i++) {
798                 char *arg = conf.filter_arg[i];
799                 char *filter_name = strchr(arg, ':');
800                 ret = -E_MISSING_COLON;
801                 if (!filter_name)
802                         goto out;
803                 *filter_name = '\0';
804                 filter_name++;
805                 ret = get_audio_format_num(arg);
806                 if (ret < 0)
807                         goto out;
808                 ret = add_filter(ret, filter_name);
809                 if (ret < 0)
810                         goto out;
811         }
812         ret = init_default_filters(); /* use default values for the rest */
813 out:
814         return ret;
815 }
816
817 static int parse_stream_args(void)
818 {
819         int ret;
820
821         ret = parse_receiver_args();
822         if (ret < 0)
823                 return ret;
824         ret = parse_filter_args();
825         if (ret < 0)
826                 return ret;
827         ret = parse_writer_args();
828         if (ret < 0)
829                 return ret;
830         return 1;
831 }
832
833 /* does not unlink socket on errors */
834 static int audiod_get_socket(void)
835 {
836         struct sockaddr_un unix_addr;
837         int ret, fd;
838
839         if (conf.socket_given)
840                 socket_name = para_strdup(conf.socket_arg);
841         else {
842                 char *hn = para_hostname();
843                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
844                         hn);
845                 free(hn);
846         }
847         PARA_NOTICE_LOG("local socket: %s\n", socket_name);
848         if (conf.force_given)
849                 unlink(socket_name);
850         ret = create_local_socket(socket_name, &unix_addr,
851                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
852         if (ret < 0)
853                 goto err;
854         fd = ret;
855         if (listen(fd , 5) < 0) {
856                 ret = -ERRNO_TO_PARA_ERROR(errno);
857                 goto err;
858         }
859         ret = mark_fd_nonblocking(fd);
860         if (ret < 0)
861                 goto err;
862         return fd;
863 err:
864         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
865         exit(EXIT_FAILURE);
866 }
867
868 static void signal_pre_select(struct sched *s, struct task *t)
869 {
870         struct signal_task *st = container_of(t, struct signal_task, task);
871         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
872 }
873
874 static void signal_post_select(struct sched *s, struct task *t)
875 {
876         struct signal_task *st = container_of(t, struct signal_task, task);
877
878         if (!FD_ISSET(st->fd, &s->rfds))
879                 return;
880
881         st->signum = para_next_signal();
882         switch (st->signum) {
883         case SIGINT:
884         case SIGTERM:
885         case SIGHUP:
886                 PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
887                 clean_exit(EXIT_FAILURE, "caught deadly signal");
888         }
889 }
890
891 static void signal_setup_default(struct signal_task *st)
892 {
893         st->task.pre_select = signal_pre_select;
894         st->task.post_select = signal_post_select;
895         sprintf(st->task.status, "signal task");
896 }
897
898 static void command_pre_select(struct sched *s, struct task *t)
899 {
900         struct command_task *ct = container_of(t, struct command_task, task);
901         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
902 }
903
904 static void command_post_select(struct sched *s, struct task *t)
905 {
906         int ret;
907         struct command_task *ct = container_of(t, struct command_task, task);
908         static struct timeval last_status_dump;
909         struct timeval tmp;
910
911         tv_add(&last_status_dump, &(struct timeval){0, 500 * 1000}, &tmp);
912         if (tv_diff(&tmp, now, NULL) < 0) {
913                 audiod_status_dump();
914                 last_status_dump = *now;
915         }
916
917         if (!FD_ISSET(ct->fd, &s->rfds))
918                 return;
919         ret = handle_connect(ct->fd);
920         if (ret < 0)
921                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
922 }
923
924 static void init_command_task(struct command_task *ct)
925 {
926         ct->task.pre_select = command_pre_select;
927         ct->task.post_select = command_post_select;
928         ct->task.error = 0;
929         ct->fd = audiod_get_socket(); /* doesn't return on errors */
930         sprintf(ct->task.status, "command task");
931 }
932
933 static void close_stat_pipe(void)
934 {
935         if (!stat_task->ct)
936                 return;
937         client_close(stat_task->ct);
938         stat_task->ct = NULL;
939         clear_and_dump_items();
940         stat_task->length_seconds = 0;
941         stat_task->offset_seconds = 0;
942         stat_task->vss_status = 0;
943         stat_task->current_audio_format_num = -1;
944         audiod_status_dump();
945 }
946
947 /**
948  * close the connection to para_server and exit
949  *
950  * \param status the exit status which is passed to exit(3)
951  * \param msg the log message
952  *
953  * Log \a msg with loglevel \p EMERG, close the connection to para_server if
954  * open, and call \p exit(status). \a status should be either EXIT_SUCCESS or
955  * EXIT_FAILURE.
956  *
957  * \sa exit(3)
958  */
959 void __noreturn clean_exit(int status, const char *msg)
960 {
961         PARA_EMERG_LOG("%s\n", msg);
962         if (socket_name)
963                 unlink(socket_name);
964         close_stat_pipe();
965         exit(status);
966 }
967
968 /* avoid busy loop if server is down */
969 static void set_stat_task_restart_barrier(unsigned seconds)
970 {
971         struct timeval delay = {seconds, 0};
972         tv_add(now, &delay, &stat_task->restart_barrier);
973 }
974
975 static void try_to_close_slot(int slot_num)
976 {
977         struct slot_info *s = &slot[slot_num];
978
979         if (s->format < 0)
980                 return;
981         if (s->receiver_node && s->receiver_node->task.error != -E_TASK_UNREGISTERED)
982                 return;
983         if (s->fc && s->fc->task.error != -E_TASK_UNREGISTERED)
984                 return;
985         if (s->wng && s->wng->task.error != -E_TASK_UNREGISTERED)
986                 return;
987         PARA_INFO_LOG("closing slot %d\n", slot_num);
988         wng_close(s->wng);
989         close_filters(s->fc);
990         free(s->fc);
991         close_receiver(slot_num);
992         clear_slot(slot_num);
993 }
994
995 /*
996  * Check if any receivers/filters/writers need to be started and do so if
997  * necessary.
998  */
999 static void start_stop_decoders(struct sched *s)
1000 {
1001         int i;
1002
1003         FOR_EACH_SLOT(i)
1004                 try_to_close_slot(i);
1005         if (audiod_status != AUDIOD_ON ||
1006                         !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1007                 return kill_all_decoders(-E_NOT_PLAYING);
1008         open_current_receiver(s);
1009         FOR_EACH_SLOT(i) {
1010                 struct slot_info *sl = &slot[i];
1011                 struct audio_format_info *a;
1012                 struct timeval diff;
1013
1014                 if (sl->format < 0)
1015                         continue;
1016                 a = &afi[sl->format];
1017                 if (!sl->receiver_node)
1018                         continue;
1019                 if ((!a->num_filters || sl->fc) && sl->wng)
1020                         continue; /* everything already started */
1021                 if (!a->num_filters) {
1022                         if (sl->receiver_node->loaded && !sl->wng) {
1023                                 open_writers(i);
1024                         }
1025                         continue;
1026                 }
1027                 if (sl->receiver_node->loaded && !sl->fc) {
1028                         open_filters(i);
1029                         continue;
1030                 }
1031                 if (sl->wng || !sl->fc || !*sl->fc->out_loaded)
1032                         continue;
1033                 if (tv_diff(now, &initial_delay_barrier, &diff) > 0) {
1034                         open_writers(i);
1035                         continue;
1036                 }
1037                 PARA_INFO_LOG("initial delay: %lu ms left\n", tv2ms(&diff));
1038                 if (tv_diff(&s->timeout, &diff, NULL) > 0) {
1039                         s->timeout = diff;
1040                 }
1041         }
1042 }
1043
1044
1045 /* restart the client task if necessary */
1046 static void status_pre_select(struct sched *s, struct task *t)
1047 {
1048         struct status_task *st = container_of(t, struct status_task, task);
1049
1050         if (audiod_status == AUDIOD_OFF) {
1051                 if (!st->ct)
1052                         goto out;
1053                 if (st->ct->task.error >= 0) {
1054                         st->ct->task.error = -E_AUDIOD_OFF;
1055                         goto out;
1056                 }
1057                 if (st->ct->task.error != -E_TASK_UNREGISTERED)
1058                         goto out;
1059                 close_stat_pipe();
1060                 st->clock_diff_count = conf.clock_diff_count_arg;
1061                 goto out;
1062         }
1063         if (st->ct) {
1064                 int ret;
1065                 if (st->ct->task.error < 0) {
1066                         if (st->ct->task.error != -E_TASK_UNREGISTERED)
1067                                 goto out;
1068                         close_stat_pipe();
1069                         goto out;
1070                 }
1071                 if (st->ct->status != CL_RECEIVING)
1072                         goto out;
1073                 ret = for_each_stat_item(st->ct->buf, st->ct->loaded,
1074                         update_item);
1075                 if (ret < 0) {
1076                         st->ct->task.error = ret;
1077                         goto out;
1078                 }
1079                 if (st->ct->loaded != ret) {
1080                         st->last_status_read = *now;
1081                         st->ct->loaded = ret;
1082                 } else {
1083                         struct timeval diff;
1084                         tv_diff(now, &st->last_status_read, &diff);
1085                         if (diff.tv_sec > 61)
1086                                 st->ct->task.error = -E_STATUS_TIMEOUT;
1087                 }
1088                 goto out;
1089         }
1090         if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1091                 goto out;
1092         if (st->clock_diff_count) { /* get status only one time */
1093                 char *argv[] = {"audiod", "--", "stat", "-p", "1", NULL};
1094                 int argc = 5;
1095                 PARA_INFO_LOG("clock diff count: %d\n", st->clock_diff_count);
1096                 st->clock_diff_count--;
1097                 client_open(argc, argv, &st->ct, NULL);
1098                 set_stat_task_restart_barrier(2);
1099
1100         } else {
1101                 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1102                 int argc = 4;
1103                 client_open(argc, argv, &st->ct, NULL);
1104                 set_stat_task_restart_barrier(5);
1105         }
1106         free(stat_item_values[SI_BASENAME]);
1107         stat_item_values[SI_BASENAME] = para_strdup(
1108                 "no connection to para_server");
1109         stat_client_write_item(SI_BASENAME);
1110         st->last_status_read = *now;
1111 out:
1112         start_stop_decoders(s);
1113 }
1114
1115 static void init_status_task(struct status_task *st)
1116 {
1117         memset(st, 0, sizeof(struct status_task));
1118         st->task.pre_select = status_pre_select;
1119         st->sa_time_diff_sign = 1;
1120         st->clock_diff_count = conf.clock_diff_count_arg;
1121         st->current_audio_format_num = -1;
1122         sprintf(st->task.status, "status task");
1123 }
1124
1125 static void set_initial_status(void)
1126 {
1127         audiod_status = AUDIOD_ON;
1128         if (!conf.mode_given)
1129                 return;
1130         if (!strcmp(conf.mode_arg, "sb")) {
1131                 audiod_status = AUDIOD_STANDBY;
1132                 return;
1133         }
1134         if (!strcmp(conf.mode_arg, "off")) {
1135                 audiod_status = AUDIOD_OFF;
1136                 return;
1137         }
1138         if (strcmp(conf.mode_arg, "on"))
1139                 PARA_WARNING_LOG("invalid mode\n");
1140 }
1141
1142 __noreturn static void print_help_and_die(void)
1143 {
1144         int d = conf.detailed_help_given;
1145         const char **p = d? audiod_args_info_detailed_help
1146                 : audiod_args_info_help;
1147
1148         printf_or_die("%s\n\n", AUDIOD_CMDLINE_PARSER_PACKAGE "-"
1149                 AUDIOD_CMDLINE_PARSER_VERSION);
1150         printf_or_die("%s\n\n", audiod_args_info_usage);
1151         for (; *p; p++)
1152                 printf_or_die("%s\n", *p);
1153         print_receiver_helps(d);
1154         print_filter_helps(d);
1155         print_writer_helps(d);
1156         exit(0);
1157 }
1158
1159 static void init_colors_or_die(void)
1160 {
1161         int ret, i;
1162
1163         if (!want_colors())
1164                 return;
1165         daemon_set_default_log_colors();
1166         daemon_set_flag(DF_COLOR_LOG);
1167         for (i = 0; i < conf.log_color_given; i++) {
1168                 ret = daemon_set_log_color(conf.log_color_arg[i]);
1169                 if (ret < 0)
1170                         exit(EXIT_FAILURE);
1171         }
1172 }
1173
1174 /**
1175  * the main function of para_audiod
1176  *
1177  * \param argc usual argument count
1178  * \param argv usual argument vector
1179  *
1180  * \return EXIT_SUCCESS or EXIT_FAILURE
1181  *
1182  * \sa para_audiod(1)
1183  * */
1184 int main(int argc, char *argv[])
1185 {
1186         int ret, i;
1187         static struct sched s;
1188         struct command_task command_task_struct, *cmd_task = &command_task_struct;
1189         struct audiod_cmdline_parser_params params = {
1190                 .override = 0,
1191                 .initialize = 1,
1192                 .check_required = 0,
1193                 .check_ambiguity = 0,
1194                 .print_errors = 1
1195         };
1196
1197         valid_fd_012();
1198         if (audiod_cmdline_parser_ext(argc, argv, &conf, &params))
1199                 exit(EXIT_FAILURE);
1200         HANDLE_VERSION_FLAG("audiod", conf);
1201         /* init receivers/filters/writers early to make help work */
1202         recv_init();
1203         filter_init();
1204         writer_init();
1205         if (conf.help_given || conf.detailed_help_given)
1206                 print_help_and_die();
1207         drop_privileges_or_die(conf.user_arg, conf.group_arg);
1208         parse_config_or_die();
1209         init_colors_or_die();
1210         init_random_seed_or_die();
1211         daemon_set_flag(DF_LOG_TIME);
1212         daemon_set_flag(DF_LOG_HOSTNAME);
1213         daemon_set_flag(DF_LOG_LL);
1214         if (conf.log_timing_given)
1215                 daemon_set_flag(DF_LOG_TIMING);
1216         if (conf.logfile_given) {
1217                 daemon_set_logfile(conf.logfile_arg);
1218                 daemon_open_log_or_die();
1219         }
1220         ret = parse_stream_args();
1221         if (ret < 0) {
1222                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1223                 exit(EXIT_FAILURE);
1224         }
1225         log_welcome("para_audiod");
1226         server_uptime(UPTIME_SET);
1227         set_initial_status();
1228         FOR_EACH_SLOT(i)
1229                 clear_slot(i);
1230         init_grabbing();
1231         setup_signal_handling();
1232         signal_setup_default(sig_task);
1233
1234         init_status_task(stat_task);
1235         init_command_task(cmd_task);
1236
1237         if (conf.daemon_given)
1238                 daemonize();
1239
1240         register_task(&sig_task->task);
1241         register_task(&cmd_task->task);
1242         register_task(&stat_task->task);
1243         s.default_timeout.tv_sec = 0;
1244         s.default_timeout.tv_usec = 999 * 1000;
1245         ret = schedule(&s);
1246
1247         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1248         return EXIT_FAILURE;
1249 }