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