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