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