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