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