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