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