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