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