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