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