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