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