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