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