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