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