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