stdin.c: btr preparations.
[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         stat_task->current_audio_format_num = -1;
316 }
317
318 static void kill_all_decoders(int error)
319 {
320         int i;
321
322         FOR_EACH_SLOT(i) {
323                 struct slot_info *s = &slot[i];
324                 if (s->wng && s->wng->task.error >= 0) {
325                         PARA_INFO_LOG("deactivating wng in slot %d\n",
326                                 i);
327                         s->wng->task.error = error;
328                 }
329                 if (s->fc && s->fc->task.error >= 0) {
330                         PARA_INFO_LOG("deactivatimg filter chain in slot %d\n", i);
331                         s->fc->task.error = error;
332                 }
333                 if (s->receiver_node && s->receiver_node->task.error >= 0) {
334                         PARA_INFO_LOG("deactivating receiver_node in slot %d\n", i);
335                         s->receiver_node->task.error = error;
336                 }
337         }
338 }
339
340 static int get_empty_slot(void)
341 {
342         int i;
343         struct slot_info *s;
344
345         FOR_EACH_SLOT(i) {
346                 s = &slot[i];
347                 if (s->format < 0) {
348                         clear_slot(i);
349                         return i;
350                 }
351                 if (s->wng || s->receiver_node || s->fc)
352                         continue;
353                 clear_slot(i);
354                 return i;
355         }
356         return -E_NO_MORE_SLOTS;
357 }
358
359 /**
360  * get the number of filters
361  *
362  * \param audio_format_num the number identifying the audio format
363  *
364  * \return the number of filters for the given audio format
365  *
366  * \sa struct filter;
367  */
368 int num_filters(int audio_format_num)
369 {
370         return afi[audio_format_num].num_filters;
371 }
372
373 static void open_filters(int slot_num)
374 {
375         struct slot_info *s = &slot[slot_num];
376         struct audio_format_info *a = &afi[s->format];
377         struct filter_node *fn;
378         int nf = a->num_filters;
379         int i;
380
381         s->fc = NULL;
382         if (!nf)
383                 return;
384         PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
385         s->fc = para_calloc(sizeof(struct filter_chain));
386         s->fc->filter_nodes = para_malloc(nf * sizeof(struct filter_node));
387         s->fc->inbufp = &s->receiver_node->buf;
388         s->fc->in_loaded = &s->receiver_node->loaded;
389         s->fc->input_error = &s->receiver_node->task.error;
390         s->fc->task.pre_select = NULL;
391         s->fc->task.post_select = filter_post_select;
392         s->fc->task.error = 0;
393         s->fc->num_filters = nf;
394
395         s->receiver_node->output_error = &s->fc->task.error;
396         sprintf(s->fc->task.status, "filter chain");
397         FOR_EACH_FILTER_NODE(fn, s->fc, i) {
398                 struct filter *f = filters + a->filter_nums[i];
399                 fn->filter_num = a->filter_nums[i];
400                 fn->conf = a->filter_conf[i];
401                 fn->fc = s->fc;
402                 fn->loaded = 0;
403                 INIT_LIST_HEAD(&fn->callbacks);
404                 f->open(fn);
405                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
406                         audio_formats[s->format], i,  nf, f->name, slot_num);
407                 s->fc->outbufp = &fn->buf;
408                 s->fc->out_loaded = &fn->loaded;
409         }
410         register_task(&s->fc->task);
411 }
412
413 static void open_writers(int slot_num)
414 {
415         int ret, i;
416         struct slot_info *s = &slot[slot_num];
417         struct audio_format_info *a = &afi[s->format];
418
419         PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
420         if (!a->num_writers)
421                 s->wng = setup_default_wng();
422         else
423                 s->wng = wng_new(a->num_writers);
424         if (s->fc) {
425                 s->wng->bufp = s->fc->outbufp;
426                 s->wng->loaded = s->fc->out_loaded;
427                 s->wng->input_error = &s->fc->task.error;
428                 s->wng->channels = &s->fc->channels;
429                 s->wng->samplerate = &s->fc->samplerate;
430                 s->fc->output_error = &s->wng->task.error;
431                 PARA_INFO_LOG("samplerate: %d\n", *s->wng->samplerate);
432         } else {
433                 s->wng->bufp = &s->receiver_node->buf;
434                 s->wng->loaded = &s->receiver_node->loaded;
435                 s->wng->input_error = &s->receiver_node->task.error;
436         }
437         for (i = 0; i < a->num_writers; i++) {
438                 s->wng->writer_nodes[i].conf = a->writer_conf[i];
439                 s->wng->writer_nodes[i].writer_num = a->writer_nums[i];
440         }
441         ret = wng_open(s->wng);
442         if (ret < 0)
443                 return;
444         s->wstime = *now;
445         s->server_stream_start = stat_task->server_stream_start.tv_sec?
446                 stat_task->server_stream_start : *now;
447         s->offset_seconds = stat_task->offset_seconds;
448         s->seconds_total = stat_task->length_seconds;
449         activate_inactive_grab_clients(s->format, s->fc);
450 }
451
452 static int open_receiver(int format)
453 {
454         struct audio_format_info *a = &afi[format];
455         struct slot_info *s;
456         int ret, slot_num;
457         struct receiver_node *rn;
458         const struct timeval restart_delay = {2, 0};
459
460         ret = get_empty_slot();
461         if (ret < 0)
462                 goto err;
463         slot_num = ret;
464         s = &slot[slot_num];
465         s->format = format;
466         s->receiver_node = para_calloc(sizeof(struct receiver_node));
467         rn = s->receiver_node;
468         rn->receiver = a->receiver;
469         rn->conf = a->receiver_conf;
470         ret = a->receiver->open(s->receiver_node);
471         if (ret < 0) {
472                 free(s->receiver_node);
473                 s->receiver_node = NULL;
474                 goto err;
475         }
476         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
477                 audio_formats[s->format], a->receiver->name, slot_num);
478         rn->task.pre_select = a->receiver->pre_select;
479         rn->task.post_select = a->receiver->post_select;
480         s->rstime = *now;
481         sprintf(rn->task.status, "%s receiver node", rn->receiver->name);
482         register_task(&rn->task);
483         ret = 1;
484 err:
485         if (ret < 0)
486                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
487         tv_add(now, &restart_delay, &afi[format].restart_barrier);
488         return ret;
489 }
490
491 /* return: 0: Not running, 1: Running, -1: Running but eof (or error) */
492 static int receiver_running(int format)
493 {
494         int i, ret = 0;
495
496         FOR_EACH_SLOT(i) {
497                 struct slot_info *s = &slot[i];
498                 if (s->format != format)
499                         continue;
500                 if (!s->receiver_node)
501                         continue;
502                 if (s->receiver_node->task.error >= 0)
503                         return 1;
504                 ret = -1;
505         }
506         return ret;
507 }
508
509 static void open_current_receiver(struct sched *s)
510 {
511         struct timeval diff;
512         int ret, cafn = stat_task->current_audio_format_num;
513
514         if (cafn < 0 || !stat_task->ct)
515                 return;
516         /* Do nothing if the 'N' flag is set or the 'P' flag is unset */
517         if (stat_task->vss_status != VSS_STATUS_FLAG_PLAYING)
518                 return;
519         ret = receiver_running(cafn);
520         if (ret > 0) /* already running and not eof */
521                 return;
522         if (ret < 0) { /* eof */
523                 /*
524                  * para_server uses a zero start time during the announcement
525                  * period, i.e. before it sends the first chunk. Wait until
526                  * this period begins to avoid restarting the receiver that
527                  * belongs to the file just completed.
528                  */
529                 if (stat_task->server_stream_start.tv_sec)
530                         return;
531         }
532         if (tv_diff(now, &afi[cafn].restart_barrier, &diff) < 0) {
533                 /* avoid busy loop */
534                 s->timeout = diff;
535                 return;
536         }
537         /* start a new receiver */
538         open_receiver(cafn);
539 }
540
541 static unsigned compute_time_diff(const struct timeval *status_time)
542 {
543         struct timeval tmp, diff;
544         static unsigned count;
545         int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
546         const struct timeval max_deviation = {0, 500 * 1000};
547         const int time_smooth = 5;
548
549         if (!status_time)
550                 return count;
551         sign = tv_diff(status_time, now, &diff);
552 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
553 //                      sign, sa_time_diff_sign);
554         if (!count) {
555                 sa_time_diff_sign = sign;
556                 stat_task->sa_time_diff = diff;
557                 count++;
558                 goto out;
559         }
560         if (count > 5) {
561                 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
562                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
563                         PARA_WARNING_LOG("time diff jump: %lims\n",
564                                 s * tv2ms(&tmp));
565         }
566         count++;
567         sa_time_diff_sign = tv_convex_combination(
568                 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
569                 count > 10? sign : sign * time_smooth, &diff,
570                 &tmp);
571         stat_task->sa_time_diff = tmp;
572         PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
573                 sign > 0? "+" : "-",
574                 tv2ms(&diff),
575                 sa_time_diff_sign ? "+" : "-",
576                 tv2ms(&stat_task->sa_time_diff)
577         );
578 out:
579         stat_task->sa_time_diff_sign = sa_time_diff_sign;
580         return count;
581 }
582
583 static int update_item(int itemnum, char *buf)
584 {
585         long unsigned sec, usec;
586
587         if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
588                 return 1;
589         free(stat_item_values[itemnum]);
590         stat_item_values[itemnum] = para_strdup(buf);
591         stat_client_write_item(itemnum);
592         switch (itemnum) {
593         case SI_STATUS_FLAGS:
594                 stat_task->vss_status = 0;
595                 if (strchr(buf, 'N'))
596                         stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
597                 if (strchr(buf, 'P'))
598                         stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
599                 break;
600         case SI_OFFSET:
601                 stat_task->offset_seconds = atoi(buf);
602                 break;
603         case SI_SECONDS_TOTAL:
604                 stat_task->length_seconds = atoi(buf);
605                 break;
606         case SI_STREAM_START:
607                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
608                         struct timeval a_start, delay;
609                         delay.tv_sec = conf.stream_delay_arg / 1000;
610                         delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
611                         stat_task->server_stream_start.tv_sec = sec;
612                         stat_task->server_stream_start.tv_usec = usec;
613                         if (compute_time_diff(NULL) > 2) {
614                                 if (stat_task->sa_time_diff_sign < 0)
615                                         tv_add(&stat_task->server_stream_start,
616                                                 &stat_task->sa_time_diff, &a_start);
617                                 else
618                                         tv_diff(&stat_task->server_stream_start,
619                                                 &stat_task->sa_time_diff, &a_start);
620                                 tv_add(&a_start, &delay, &initial_delay_barrier);
621                         }
622                 }
623                 break;
624         case SI_CURRENT_TIME:
625                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
626                         struct timeval tv = {sec, usec};
627                         compute_time_diff(&tv);
628                 }
629                 break;
630         case SI_FORMAT:
631                 stat_task->current_audio_format_num
632                         = get_audio_format_num(buf);
633         }
634         return 1;
635 }
636
637 static int parse_stream_command(const char *txt, char **cmd)
638 {
639         char *p = strchr(txt, ':');
640         int i;
641
642         if (!p)
643                 return -E_MISSING_COLON;
644         p++;
645         FOR_EACH_AUDIO_FORMAT(i) {
646                 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
647                         continue;
648                 *cmd = p;
649                 return i;
650         }
651         return -E_UNSUPPORTED_AUDIO_FORMAT;
652 }
653
654 static int add_filter(int format, char *cmdline)
655 {
656         struct audio_format_info *a = &afi[format];
657         int filter_num, nf = a->num_filters;
658
659         filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
660         if (filter_num < 0)
661                 return filter_num;
662         a->filter_nums[nf] = filter_num;
663         a->num_filters++;
664         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
665                 filters[filter_num].name);
666         return filter_num;
667 }
668
669 static int parse_writer_args(void)
670 {
671         int i, ret, nw;
672         char *cmd;
673         struct audio_format_info *a;
674
675         nw = PARA_MAX(1U, conf.writer_given);
676         PARA_INFO_LOG("maximal number of writers: %d\n", nw);
677         FOR_EACH_AUDIO_FORMAT(i) {
678                 a = &afi[i];
679                 a->writer_conf = para_malloc(nw * sizeof(void *));
680                 a->writer_nums = para_malloc(nw * sizeof(int));
681                 a->num_writers = 0;
682         }
683         for (i = 0; i < conf.writer_given; i++) {
684                 void *wconf;
685                 int writer_num;
686                 ret = parse_stream_command(conf.writer_arg[i], &cmd);
687                 if (ret < 0)
688                         goto out;
689                 a = &afi[ret];
690                 nw = a->num_writers;
691                 wconf = check_writer_arg(cmd, &writer_num);
692                 if (!wconf) {
693                         ret = writer_num;
694                         goto out;
695                 }
696                 a->writer_nums[nw] = writer_num;
697                 a->writer_conf[nw] = wconf;
698                 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
699                         nw, writer_names[writer_num]);
700                 a->num_writers++;
701         }
702         ret = 1;
703 out:
704         return ret;
705 }
706
707 static int parse_receiver_args(void)
708 {
709         int i, ret, receiver_num;
710         char *cmd = NULL;
711         struct audio_format_info *a;
712
713         for (i = conf.receiver_given - 1; i >= 0; i--) {
714                 char *arg = conf.receiver_arg[i];
715                 char *recv_arg = strchr(arg, ':');
716                 ret = -E_MISSING_COLON;
717                 if (!recv_arg)
718                         goto out;
719                 *recv_arg = '\0';
720                 recv_arg++;
721                 ret = get_audio_format_num(arg);
722                 if (ret < 0)
723                         goto out;
724                 afi[ret].receiver_conf = check_receiver_arg(recv_arg, &receiver_num);
725                 if (!afi[ret].receiver_conf) {
726                         ret = -E_RECV_SYNTAX;
727                         goto out;
728                 }
729                 afi[ret].receiver = &receivers[receiver_num];
730         }
731         /* use the first available receiver with no arguments
732          * for those audio formats for which no receiver
733          * was specified
734          */
735         cmd = para_strdup(receivers[0].name);
736         FOR_EACH_AUDIO_FORMAT(i) {
737                 a = &afi[i];
738                 if (a->receiver_conf)
739                         continue;
740                 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
741                 if (!a->receiver_conf)
742                         return -E_RECV_SYNTAX;
743                 a->receiver = &receivers[receiver_num];
744         }
745         ret = 1;
746 out:
747         free(cmd);
748         return ret;
749 }
750
751 static int init_default_filters(void)
752 {
753         int i, ret = 1;
754
755         FOR_EACH_AUDIO_FORMAT(i) {
756                 struct audio_format_info *a = &afi[i];
757                 char *tmp;
758                 int j;
759
760                 if (a->num_filters)
761                         continue; /* no default -- nothing to to */
762                 /* add "dec" to audio format name */
763                 tmp = make_message("%sdec", audio_formats[i]);
764                 for (j = 0; filters[j].name; j++)
765                         if (!strcmp(tmp, filters[j].name))
766                                 break;
767                 free(tmp);
768                 ret = -E_UNSUPPORTED_FILTER;
769                 if (!filters[j].name)
770                         goto out;
771                 tmp = para_strdup(filters[j].name);
772                 ret = add_filter(i, tmp);
773                 free(tmp);
774                 if (ret < 0)
775                         goto out;
776                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
777                         filters[j].name);
778         }
779 out:
780         return ret;
781 }
782
783 static int parse_filter_args(void)
784 {
785         int i, ret, nf;
786
787         nf = PARA_MAX(1U, conf.filter_given);
788         PARA_INFO_LOG("maximal number of filters: %d\n", nf);
789         FOR_EACH_AUDIO_FORMAT(i) {
790                 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
791                 afi[i].filter_nums = para_malloc(nf * sizeof(unsigned));
792         }
793         if (!conf.no_default_filters_given)
794                 return init_default_filters();
795         for (i = 0; i < conf.filter_given; i++) {
796                 char *arg = conf.filter_arg[i];
797                 char *filter_name = strchr(arg, ':');
798                 ret = -E_MISSING_COLON;
799                 if (!filter_name)
800                         goto out;
801                 *filter_name = '\0';
802                 filter_name++;
803                 ret = get_audio_format_num(arg);
804                 if (ret < 0)
805                         goto out;
806                 ret = add_filter(ret, filter_name);
807                 if (ret < 0)
808                         goto out;
809         }
810         ret = init_default_filters(); /* use default values for the rest */
811 out:
812         return ret;
813 }
814
815 static int parse_stream_args(void)
816 {
817         int ret;
818
819         ret = parse_receiver_args();
820         if (ret < 0)
821                 return ret;
822         ret = parse_filter_args();
823         if (ret < 0)
824                 return ret;
825         ret = parse_writer_args();
826         if (ret < 0)
827                 return ret;
828         return 1;
829 }
830
831 /* does not unlink socket on errors */
832 static int audiod_get_socket(void)
833 {
834         struct sockaddr_un unix_addr;
835         int ret, fd;
836
837         if (conf.socket_given)
838                 socket_name = para_strdup(conf.socket_arg);
839         else {
840                 char *hn = para_hostname();
841                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
842                         hn);
843                 free(hn);
844         }
845         PARA_NOTICE_LOG("local socket: %s\n", socket_name);
846         if (conf.force_given)
847                 unlink(socket_name);
848         ret = create_local_socket(socket_name, &unix_addr,
849                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
850         if (ret < 0)
851                 goto err;
852         fd = ret;
853         if (listen(fd , 5) < 0) {
854                 ret = -ERRNO_TO_PARA_ERROR(errno);
855                 goto err;
856         }
857         ret = mark_fd_nonblocking(fd);
858         if (ret < 0)
859                 goto err;
860         return fd;
861 err:
862         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
863         exit(EXIT_FAILURE);
864 }
865
866 static void signal_pre_select(struct sched *s, struct task *t)
867 {
868         struct signal_task *st = container_of(t, struct signal_task, task);
869         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
870 }
871
872 static void signal_post_select(struct sched *s, struct task *t)
873 {
874         struct signal_task *st = container_of(t, struct signal_task, task);
875
876         if (!FD_ISSET(st->fd, &s->rfds))
877                 return;
878
879         st->signum = para_next_signal();
880         switch (st->signum) {
881         case SIGINT:
882         case SIGTERM:
883         case SIGHUP:
884                 PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
885                 clean_exit(EXIT_FAILURE, "caught deadly signal");
886         }
887 }
888
889 static void signal_setup_default(struct signal_task *st)
890 {
891         st->task.pre_select = signal_pre_select;
892         st->task.post_select = signal_post_select;
893         sprintf(st->task.status, "signal task");
894 }
895
896 static void command_pre_select(struct sched *s, struct task *t)
897 {
898         struct command_task *ct = container_of(t, struct command_task, task);
899         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
900 }
901
902 static void command_post_select(struct sched *s, struct task *t)
903 {
904         int ret;
905         struct command_task *ct = container_of(t, struct command_task, task);
906         static struct timeval last_status_dump;
907         struct timeval tmp;
908
909         tv_add(&last_status_dump, &(struct timeval){0, 500 * 1000}, &tmp);
910         if (tv_diff(&tmp, now, NULL) < 0) {
911                 audiod_status_dump();
912                 last_status_dump = *now;
913         }
914
915         if (!FD_ISSET(ct->fd, &s->rfds))
916                 return;
917         ret = handle_connect(ct->fd);
918         if (ret < 0)
919                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
920 }
921
922 static void init_command_task(struct command_task *ct)
923 {
924         ct->task.pre_select = command_pre_select;
925         ct->task.post_select = command_post_select;
926         ct->task.error = 0;
927         ct->fd = audiod_get_socket(); /* doesn't return on errors */
928         sprintf(ct->task.status, "command task");
929 }
930
931 static void close_stat_pipe(void)
932 {
933         if (!stat_task->ct)
934                 return;
935         client_close(stat_task->ct);
936         stat_task->ct = NULL;
937         clear_and_dump_items();
938         stat_task->length_seconds = 0;
939         stat_task->offset_seconds = 0;
940         stat_task->vss_status = 0;
941         stat_task->current_audio_format_num = -1;
942         audiod_status_dump();
943 }
944
945 /**
946  * close the connection to para_server and exit
947  *
948  * \param status the exit status which is passed to exit(3)
949  * \param msg the log message
950  *
951  * Log \a msg with loglevel \p EMERG, close the connection to para_server if
952  * open, and call \p exit(status). \a status should be either EXIT_SUCCESS or
953  * EXIT_FAILURE.
954  *
955  * \sa exit(3)
956  */
957 void __noreturn clean_exit(int status, const char *msg)
958 {
959         PARA_EMERG_LOG("%s\n", msg);
960         if (socket_name)
961                 unlink(socket_name);
962         close_stat_pipe();
963         exit(status);
964 }
965
966 /* avoid busy loop if server is down */
967 static void set_stat_task_restart_barrier(unsigned seconds)
968 {
969         struct timeval delay = {seconds, 0};
970         tv_add(now, &delay, &stat_task->restart_barrier);
971 }
972
973 static void try_to_close_slot(int slot_num)
974 {
975         struct slot_info *s = &slot[slot_num];
976
977         if (s->format < 0)
978                 return;
979         if (s->receiver_node && s->receiver_node->task.error != -E_TASK_UNREGISTERED)
980                 return;
981         if (s->fc && s->fc->task.error != -E_TASK_UNREGISTERED)
982                 return;
983         if (s->wng && s->wng->task.error != -E_TASK_UNREGISTERED)
984                 return;
985         PARA_INFO_LOG("closing slot %d\n", slot_num);
986         wng_close(s->wng);
987         close_filters(s->fc);
988         free(s->fc);
989         close_receiver(slot_num);
990         clear_slot(slot_num);
991 }
992
993 /*
994  * Check if any receivers/filters/writers need to be started and do so if
995  * necessary.
996  */
997 static void start_stop_decoders(struct sched *s)
998 {
999         int i;
1000
1001         FOR_EACH_SLOT(i)
1002                 try_to_close_slot(i);
1003         if (audiod_status != AUDIOD_ON ||
1004                         !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1005                 return kill_all_decoders(-E_NOT_PLAYING);
1006         open_current_receiver(s);
1007         FOR_EACH_SLOT(i) {
1008                 struct slot_info *sl = &slot[i];
1009                 struct audio_format_info *a;
1010                 struct timeval diff;
1011
1012                 if (sl->format < 0)
1013                         continue;
1014                 a = &afi[sl->format];
1015                 if (!sl->receiver_node)
1016                         continue;
1017                 if ((!a->num_filters || sl->fc) && sl->wng)
1018                         continue; /* everything already started */
1019                 if (!a->num_filters) {
1020                         if (sl->receiver_node->loaded && !sl->wng) {
1021                                 open_writers(i);
1022                         }
1023                         continue;
1024                 }
1025                 if (sl->receiver_node->loaded && !sl->fc) {
1026                         open_filters(i);
1027                         continue;
1028                 }
1029                 if (sl->wng || !sl->fc || !*sl->fc->out_loaded)
1030                         continue;
1031                 if (tv_diff(now, &initial_delay_barrier, &diff) > 0) {
1032                         open_writers(i);
1033                         continue;
1034                 }
1035                 PARA_INFO_LOG("initial delay: %lu ms left\n", tv2ms(&diff));
1036                 if (tv_diff(&s->timeout, &diff, NULL) > 0) {
1037                         s->timeout = diff;
1038                 }
1039         }
1040 }
1041
1042
1043 /* restart the client task if necessary */
1044 static void status_pre_select(struct sched *s, struct task *t)
1045 {
1046         struct status_task *st = container_of(t, struct status_task, task);
1047
1048         if (audiod_status == AUDIOD_OFF) {
1049                 if (!st->ct)
1050                         goto out;
1051                 if (st->ct->task.error >= 0) {
1052                         st->ct->task.error = -E_AUDIOD_OFF;
1053                         goto out;
1054                 }
1055                 if (st->ct->task.error != -E_TASK_UNREGISTERED)
1056                         goto out;
1057                 close_stat_pipe();
1058                 st->clock_diff_count = conf.clock_diff_count_arg;
1059                 goto out;
1060         }
1061         if (st->ct) {
1062                 int ret;
1063                 if (st->ct->task.error < 0) {
1064                         if (st->ct->task.error != -E_TASK_UNREGISTERED)
1065                                 goto out;
1066                         close_stat_pipe();
1067                         goto out;
1068                 }
1069                 if (st->ct->status != CL_RECEIVING)
1070                         goto out;
1071                 ret = for_each_stat_item(st->ct->buf, st->ct->loaded,
1072                         update_item);
1073                 if (ret < 0) {
1074                         st->ct->task.error = ret;
1075                         goto out;
1076                 }
1077                 if (st->ct->loaded != ret) {
1078                         st->last_status_read = *now;
1079                         st->ct->loaded = ret;
1080                 } else {
1081                         struct timeval diff;
1082                         tv_diff(now, &st->last_status_read, &diff);
1083                         if (diff.tv_sec > 61)
1084                                 st->ct->task.error = -E_STATUS_TIMEOUT;
1085                 }
1086                 goto out;
1087         }
1088         if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1089                 goto out;
1090         if (st->clock_diff_count) { /* get status only one time */
1091                 char *argv[] = {"audiod", "--", "stat", "-p", "1", NULL};
1092                 int argc = 5;
1093                 PARA_INFO_LOG("clock diff count: %d\n", st->clock_diff_count);
1094                 st->clock_diff_count--;
1095                 client_open(argc, argv, &st->ct, NULL);
1096                 set_stat_task_restart_barrier(2);
1097
1098         } else {
1099                 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1100                 int argc = 4;
1101                 client_open(argc, argv, &st->ct, NULL);
1102                 set_stat_task_restart_barrier(5);
1103         }
1104         free(stat_item_values[SI_BASENAME]);
1105         stat_item_values[SI_BASENAME] = para_strdup(
1106                 "no connection to para_server");
1107         stat_client_write_item(SI_BASENAME);
1108         st->last_status_read = *now;
1109 out:
1110         start_stop_decoders(s);
1111 }
1112
1113 static void init_status_task(struct status_task *st)
1114 {
1115         memset(st, 0, sizeof(struct status_task));
1116         st->task.pre_select = status_pre_select;
1117         st->sa_time_diff_sign = 1;
1118         st->clock_diff_count = conf.clock_diff_count_arg;
1119         st->current_audio_format_num = -1;
1120         sprintf(st->task.status, "status task");
1121 }
1122
1123 static void set_initial_status(void)
1124 {
1125         audiod_status = AUDIOD_ON;
1126         if (!conf.mode_given)
1127                 return;
1128         if (!strcmp(conf.mode_arg, "sb")) {
1129                 audiod_status = AUDIOD_STANDBY;
1130                 return;
1131         }
1132         if (!strcmp(conf.mode_arg, "off")) {
1133                 audiod_status = AUDIOD_OFF;
1134                 return;
1135         }
1136         if (strcmp(conf.mode_arg, "on"))
1137                 PARA_WARNING_LOG("invalid mode\n");
1138 }
1139
1140 __noreturn static void print_help_and_die(void)
1141 {
1142         int d = conf.detailed_help_given;
1143         const char **p = d? audiod_args_info_detailed_help
1144                 : audiod_args_info_help;
1145
1146         printf_or_die("%s\n\n", AUDIOD_CMDLINE_PARSER_PACKAGE "-"
1147                 AUDIOD_CMDLINE_PARSER_VERSION);
1148         printf_or_die("%s\n\n", audiod_args_info_usage);
1149         for (; *p; p++)
1150                 printf_or_die("%s\n", *p);
1151         print_receiver_helps(d);
1152         print_filter_helps(d);
1153         print_writer_helps(d);
1154         exit(0);
1155 }
1156
1157 static void init_colors_or_die(void)
1158 {
1159         int ret, i;
1160
1161         if (!want_colors())
1162                 return;
1163         daemon_set_default_log_colors();
1164         daemon_set_flag(DF_COLOR_LOG);
1165         for (i = 0; i < conf.log_color_given; i++) {
1166                 ret = daemon_set_log_color(conf.log_color_arg[i]);
1167                 if (ret < 0)
1168                         exit(EXIT_FAILURE);
1169         }
1170 }
1171
1172 /**
1173  * the main function of para_audiod
1174  *
1175  * \param argc usual argument count
1176  * \param argv usual argument vector
1177  *
1178  * \return EXIT_SUCCESS or EXIT_FAILURE
1179  *
1180  * \sa para_audiod(1)
1181  * */
1182 int main(int argc, char *argv[])
1183 {
1184         int ret, i;
1185         static struct sched s;
1186         struct command_task command_task_struct, *cmd_task = &command_task_struct;
1187         struct audiod_cmdline_parser_params params = {
1188                 .override = 0,
1189                 .initialize = 1,
1190                 .check_required = 0,
1191                 .check_ambiguity = 0,
1192                 .print_errors = 1
1193         };
1194
1195         valid_fd_012();
1196         if (audiod_cmdline_parser_ext(argc, argv, &conf, &params))
1197                 exit(EXIT_FAILURE);
1198         HANDLE_VERSION_FLAG("audiod", conf);
1199         /* init receivers/filters/writers early to make help work */
1200         recv_init();
1201         filter_init();
1202         writer_init();
1203         if (conf.help_given || conf.detailed_help_given)
1204                 print_help_and_die();
1205         drop_privileges_or_die(conf.user_arg, conf.group_arg);
1206         parse_config_or_die();
1207         init_colors_or_die();
1208         init_random_seed_or_die();
1209         daemon_set_flag(DF_LOG_TIME);
1210         daemon_set_flag(DF_LOG_HOSTNAME);
1211         daemon_set_flag(DF_LOG_LL);
1212         if (conf.log_timing_given)
1213                 daemon_set_flag(DF_LOG_TIMING);
1214         if (conf.logfile_given) {
1215                 daemon_set_logfile(conf.logfile_arg);
1216                 daemon_open_log_or_die();
1217         }
1218         ret = parse_stream_args();
1219         if (ret < 0) {
1220                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1221                 exit(EXIT_FAILURE);
1222         }
1223         log_welcome("para_audiod");
1224         server_uptime(UPTIME_SET);
1225         set_initial_status();
1226         FOR_EACH_SLOT(i)
1227                 clear_slot(i);
1228         init_grabbing();
1229         setup_signal_handling();
1230         signal_setup_default(sig_task);
1231
1232         init_status_task(stat_task);
1233         init_command_task(cmd_task);
1234
1235         if (conf.daemon_given)
1236                 daemonize();
1237
1238         register_task(&sig_task->task);
1239         register_task(&cmd_task->task);
1240         register_task(&stat_task->task);
1241         s.default_timeout.tv_sec = 0;
1242         s.default_timeout.tv_usec = 999 * 1000;
1243         ret = schedule(&s);
1244
1245         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1246         return EXIT_FAILURE;
1247 }