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