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