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