0c8ee2875873ef5c86b392448d0c80e6ec6e4540
[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 /**
47  * the possible modes of operation
48  *
49  * - off: disconnect from para_server
50  * - on: receive status information from para_server and play the audio stream
51  * - sb: only receive status information but not the audio stream
52 */
53 enum {AUDIOD_OFF, AUDIOD_ON, AUDIOD_STANDBY};
54
55 /** defines how to handle one supported audio format */
56 struct audio_format_info {
57         /** pointer to the receiver for this audio format */
58         struct receiver *receiver;
59         /** the receiver configuration */
60         void *receiver_conf;
61         /** the number of filters that should be activated for this audio format */
62         unsigned int num_filters;
63         /** pointer to the array of filters to be activated */
64         struct filter **filters;
65         /** pointer to the array of filter configurations */
66         void **filter_conf;
67         /** the number of filters that should be activated for this audio format */
68         unsigned int num_writers;
69         /** pointer to the array of writers to be activated */
70         struct writer **writers;
71         /** pointer to the array of writer configurations */
72         void **writer_conf;
73         /** do not start receiver/filters/writer before this time */
74         struct timeval restart_barrier;
75 };
76
77 /**
78  * describes one instance of a receiver-filter-writer chain
79  *
80  * \sa receier_node, receiver, filter, filter_node, filter_chain, writer,
81  * writer_node, writer_node_group.
82   */
83 struct slot_info {
84         /** number of the audio format in this slot */
85         int format;
86         /** writer start time */
87         struct timeval wstime;
88         /** the receiver info associated with this slot */
89         struct receiver_node *receiver_node;
90         /** the active filter chain */
91         struct filter_chain *fc;
92         /** the active writer node group */
93         struct writer_node_group *wng;
94 };
95 static struct slot_info slot[MAX_STREAM_SLOTS];
96
97 extern const char *status_item_list[NUM_STAT_ITEMS];
98
99 static struct gengetopt_args_info conf;
100 static struct timeval server_stream_start, sa_time_diff;
101 static int playing, current_decoder = -1,
102         audiod_status = AUDIOD_ON, offset_seconds, length_seconds,
103         sa_time_diff_sign = 1;
104 static char *af_status, /* the audio format announced in server status */
105         *socket_name, *hostname;
106 static char *stat_item_values[NUM_STAT_ITEMS];
107 static FILE *logfile;
108 static const struct timeval restart_delay = {0, 300 * 1000};
109 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
110 static struct timeval *now;
111
112 static struct signal_task signal_task_struct, *sig_task = &signal_task_struct;
113
114 /**
115  * the task for handling audiod commands
116  *
117  * \sa struct task, struct sched
118  */
119 struct command_task {
120         /** the local listening socket */
121         int fd;
122         /** the associated task structure */
123         struct task task;
124 };
125
126 /**
127  * the task for audiod's child (para_client stat)
128  *
129  * \sa struct task, struct sched
130  */
131 struct status_task {
132         /** the output of the stat command is read from this fd */
133         int fd;
134         /** stat data is stored here */
135         char buf[STRINGSIZE];
136         /** number of bytes loaded in \a buf */
137         unsigned loaded;
138         /** the associated task structure */
139         struct task task;
140 };
141 static struct status_task status_task_struct, *stat_task = &status_task_struct;
142
143 struct signal_task {
144         int fd;
145         int signum;
146         struct task task;
147 };
148
149 /** defines one command of para_audiod */
150 struct audiod_command {
151         /** the name of the command */
152         const char *name;
153         /** pointer to the function that handles the command */
154         int (*handler)(int, int, char**);
155         /**
156          * if the command prefers to handle the full line (rather than the usual
157          * argv[] array), it stores a pointer to the corresponding line handling
158          * function here. In this case, the above \a handler pointer must be NULL.
159          */
160         int (*line_handler)(int, char*);
161         /** one-line description of the command */
162         const char *description;
163         /** summary of the command line options */
164         const char *synopsis;
165         /** the long help text */
166         const char *help;
167 };
168 static int com_grab(int, char *);
169 static int com_cycle(int, int, char **);
170 static int com_help(int, int, char **);
171 static int com_off(int, int, char **);
172 static int com_on(int, int, char **);
173 static int com_sb(int, int, char **);
174 static int com_stat(int, int, char **);
175 static int com_term(int, int, char **);
176 static struct audiod_command cmds[] = {
177 {
178 .name = "cycle",
179 .handler = com_cycle,
180 .description = "switch to next mode",
181 .synopsis = "cycle",
182 .help =
183
184 "on -> standby -> off -> on\n"
185
186 },
187 {
188 .name = "grab",
189 .line_handler = com_grab,
190 .description = "grab the audio stream",
191 .synopsis = "-- grab [grab_options]",
192 .help =
193
194 "grab ('splice') the audio stream at any position in the filter      \n"
195 "chain and send that data back to the client. Try\n"
196 "\t para_audioc -- grab -h\n"
197 "for the list of available options.\n"
198 },
199
200 {
201 .name = "help",
202 .handler = com_help,
203 .description = "display command list or help for given command",
204 .synopsis = "help [command]",
205 .help =
206
207 "When I was younger, so much younger than today, I never needed\n"
208 "anybody's help in any way. But now these days are gone, I'm not so\n"
209 "self assured. Now I find I've changed my mind and opened up the doors.\n"
210 "\n"
211 "                               -- Beatles: Help\n"
212
213 },
214 {
215 .name = "off",
216 .handler = com_off,
217 .description = "deactivate para_audiod",
218 .synopsis = "off",
219 .help =
220
221 "Close connection to para_server and stop all decoders.\n"
222
223 },
224 {
225 .name = "on",
226 .handler = com_on,
227 .description = "activate para_audiod",
228 .synopsis = "on",
229 .help =
230
231 "Establish connection to para_server, retrieve para_server's current\n"
232 "status. If playing, start corresponding decoder. Otherwise stop\n"
233 "all decoders.\n"
234
235 },
236 {
237 .name = "sb",
238 .handler = com_sb,
239 .description = "enter standby mode",
240 .synopsis = "sb",
241 .help =
242
243 "Stop all decoders but leave connection to para_server open.\n"
244
245 },
246 {
247 .name = "stat",
248 .handler = com_stat,
249 .description = "print status information",
250 .synopsis = "stat [item1 ...]",
251 .help =
252
253 "Dump given status items (all if none given) to stdout.\n"
254
255 },
256 {
257 .name = "term",
258 .handler = com_term,
259 .description = "terminate audiod",
260 .synopsis = "term",
261 .help =
262
263 "Stop all decoders, shut down connection to para_server and exit.\n"
264
265 },
266 {
267 .name = NULL,
268 }
269 };
270
271 /** iterate over all slots */
272 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
273 /** iterate over all supported audio formats */
274 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
275 /** iterate over the array of all audiod commands */
276 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
277
278 /**
279  * get the audio format number
280  * \param name the name of the audio format
281  *
282  * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
283  * \a name is not a supported audio format.
284  */
285 int get_audio_format_num(char *name)
286 {
287         int i;
288         FOR_EACH_AUDIO_FORMAT(i)
289                 if (!strcmp(name, audio_formats[i]))
290                         return i;
291         return -E_UNSUPPORTED_AUDIO_FORMAT;
292 }
293
294 /*
295  * log function. first argument is loglevel.
296  */
297 void para_log(int ll, const char* fmt,...)
298 {
299         va_list argp;
300         FILE *outfd;
301         struct tm *tm;
302         time_t t1;
303         char str[MAXLINE] = "";
304
305         if (ll < conf.loglevel_arg)
306                 return;
307         outfd = logfile? logfile : stderr;
308         time(&t1);
309         tm = localtime(&t1);
310         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
311         fprintf(outfd, "%s %s ", str, hostname);
312         if (conf.loglevel_arg <= INFO)
313                 fprintf(outfd, "%i ", ll);
314         va_start(argp, fmt);
315         vfprintf(outfd, fmt, argp);
316         va_end(argp);
317 }
318
319 static int client_write(int fd, const char *buf)
320 {
321         size_t len = strlen(buf);
322         return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
323 }
324
325 static char *get_time_string(struct timeval *newest_stime)
326 {
327         struct timeval diff, adj_stream_start, tmp;
328         int total = 0, use_server_time = 1;
329
330         if (!playing) {
331                 if (length_seconds)
332                         return NULL;
333                 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
334         }
335         if (audiod_status == AUDIOD_OFF)
336                 goto out;
337         if (sa_time_diff_sign > 0)
338                 tv_diff(&server_stream_start, &sa_time_diff,
339                         &adj_stream_start);
340         else
341                 tv_add(&server_stream_start, &sa_time_diff,
342                         &adj_stream_start);
343         tmp = adj_stream_start;
344         if (newest_stime && audiod_status == AUDIOD_ON) {
345                 tv_diff(newest_stime, &adj_stream_start, &diff);
346                 if (tv2ms(&diff) < 5000) {
347                         tmp = *newest_stime;
348                         use_server_time = 0;
349                 }
350         }
351         tv_diff(now, &tmp, &diff);
352         total = diff.tv_sec + offset_seconds;
353         if (total > length_seconds)
354                 total = length_seconds;
355         if (total < 0)
356                 total = 0;
357 out:
358         return make_message(
359                 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
360                 status_item_list[SI_PLAY_TIME],
361                 use_server_time? "~" : "",
362                 total / 60,
363                 total % 60,
364                 (length_seconds - total) / 60,
365                 (length_seconds - total) % 60,
366                 length_seconds? (total * 100 + length_seconds / 2) /
367                         length_seconds : 0,
368                 length_seconds / 60,
369                 length_seconds % 60
370         );
371 }
372
373 __malloc static char *audiod_status_string(void)
374 {
375         const char *status = (audiod_status == AUDIOD_ON)?
376                 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
377         return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
378 }
379
380 static struct timeval *wstime(void)
381 {
382         int i;
383         struct timeval *max = NULL;
384         FOR_EACH_SLOT(i) {
385                 struct slot_info *s = &slot[i];
386                 if (!s->wng)
387                         continue;
388                 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
389                         continue;
390                 max = &s->wstime;
391         }
392         return max;
393 }
394 __malloc static char *decoder_flags(void)
395 {
396         int i;
397         char decoder_flags[MAX_STREAM_SLOTS + 1];
398
399         FOR_EACH_SLOT(i) {
400                 struct slot_info *s = &slot[i];
401                 char flag = '0';
402                 if (s->receiver_node)
403                         flag += 1;
404                 if (s->wng)
405                         flag += 2;
406                 decoder_flags[i] = flag;
407         }
408         decoder_flags[MAX_STREAM_SLOTS] = '\0';
409         return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
410                 decoder_flags);
411 }
412
413 static char *configfile_exists(void)
414 {
415         static char *config_file;
416
417         if (!config_file) {
418                 char *home = para_homedir();
419                 config_file = make_message("%s/.paraslash/audiod.conf", home);
420                 free(home);
421         }
422         return file_exists(config_file)? config_file : NULL;
423 }
424
425 static void setup_signal_handling(void)
426 {
427         sig_task->fd = para_signal_init();
428         PARA_INFO_LOG("signal pipe: fd %d\n", sig_task->fd);
429         para_install_sighandler(SIGINT);
430         para_install_sighandler(SIGTERM);
431         para_install_sighandler(SIGCHLD);
432         para_install_sighandler(SIGHUP);
433         signal(SIGPIPE, SIG_IGN);
434 }
435
436 static void audiod_status_dump(void)
437 {
438         static char *p_ts, *p_us, *p_as, *p_df;
439         struct timeval *t = wstime();
440         char *us, *tmp = get_time_string(t);
441
442         if (tmp && (!p_ts || strcmp(tmp, p_ts)))
443                 stat_client_write(tmp, SI_PLAY_TIME);
444         free(p_ts);
445         p_ts = tmp;
446
447         us = uptime_str();
448         tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
449         free(us);
450         if (!p_us || strcmp(p_us, tmp))
451                 stat_client_write(tmp, SI_AUDIOD_UPTIME);
452         free(p_us);
453         p_us = tmp;
454
455         tmp = audiod_status_string();
456         if (!p_as || strcmp(p_as, tmp))
457                 stat_client_write(tmp, SI_AUDIOD_STATUS);
458         free(p_as);
459         p_as = tmp;
460
461         tmp = decoder_flags();
462         if (!p_df || strcmp(p_df, tmp))
463                 stat_client_write(tmp, SI_DECODER_FLAGS);
464         free(p_df);
465         p_df = tmp;
466 }
467
468 static void clear_slot(int slot_num)
469 {
470         struct slot_info *s = &slot[slot_num];
471
472         PARA_INFO_LOG("clearing slot %d\n", slot_num);
473         memset(s, 0, sizeof(struct slot_info));
474         s->format = -1;
475 }
476
477 static void close_receiver(int slot_num)
478 {
479         struct slot_info *s = &slot[slot_num];
480         struct audio_format_info *a;
481
482         if (s->format < 0 || !s->receiver_node)
483                 return;
484         a = &afi[s->format];
485         PARA_NOTICE_LOG("closing %s receiver in slot %d (eof = %d)\n",
486                 audio_formats[s->format] , slot_num, s->receiver_node->eof);
487         if (!s->receiver_node->eof)
488                 unregister_task(&s->receiver_node->task);
489         a->receiver->close(s->receiver_node);
490         free(s->receiver_node);
491         s->receiver_node = NULL;
492         /* set restart barrier */
493         tv_add(now, &restart_delay, &afi[s->format].restart_barrier);
494 }
495
496 static void kill_all_decoders(void)
497 {
498         int i;
499
500         FOR_EACH_SLOT(i) {
501                 struct slot_info *s = &slot[i];
502                 if (s->receiver_node)
503                         s->receiver_node->eof = 1;
504         }
505 }
506
507 static int get_empty_slot(void)
508 {
509         int i;
510         struct slot_info *s;
511
512         FOR_EACH_SLOT(i) {
513                 s = &slot[i];
514                 if (s->format < 0) {
515                         clear_slot(i);
516                         return i;
517                 }
518                 if (s->wng || s->receiver_node || s->fc)
519                         continue;
520                 clear_slot(i);
521                 return i;
522         }
523         return -E_NO_MORE_SLOTS;
524 }
525
526 static int decoder_running(int format)
527 {
528         int i, ret = 0;
529         struct slot_info *s;
530
531         FOR_EACH_SLOT(i) {
532                 s = &slot[i];
533                 if (s->format == format && s->receiver_node)
534                         ret |= 1;
535                 if (s->format == format && s->wng)
536                         ret |= 2;
537         }
538         return ret;
539 }
540
541 static void close_stat_pipe(void)
542 {
543         int i;
544
545         if (stat_task->fd < 0)
546                 return;
547         PARA_NOTICE_LOG("%s", "closing status pipe\n");
548         close(stat_task->fd);
549         del_close_on_fork_list(stat_task->fd);
550         stat_task->fd = -1;
551         kill_all_decoders();
552         for (i = 0; i < NUM_STAT_ITEMS; i++) {
553                 free(stat_item_values[i]);
554                 stat_item_values[i] = NULL;
555         }
556         dump_empty_status();
557         length_seconds = 0;
558         offset_seconds = 0;
559         audiod_status_dump();
560         playing = 0;
561         stat_item_values[SI_STATUS_BAR] = make_message(
562                 "%s:no connection to para_server\n",
563                 status_item_list[SI_STATUS_BAR]);
564         stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
565 }
566
567 static void __noreturn clean_exit(int status, const char *msg)
568 {
569         PARA_EMERG_LOG("%s\n", msg);
570         if (socket_name)
571                 unlink(socket_name);
572         if (stat_task->fd >= 0)
573                 close_stat_pipe();
574         exit(status);
575 }
576
577 /**
578  * get the number of filters
579  *
580  * \param audio_format_num the number identifying the audio format
581  *
582  * \return the number of filters for the given audio format
583  *
584  * \sa struct filter;
585  */
586 int num_filters(int audio_format_num)
587 {
588         return afi[audio_format_num].num_filters;
589 }
590
591 static void filter_event_handler(struct task *t)
592 {
593         PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
594         unregister_task(t);
595 }
596
597 static void open_filters(int slot_num)
598 {
599         struct slot_info *s = &slot[slot_num];
600         struct audio_format_info *a = &afi[s->format];
601         int nf = a->num_filters;
602         int i;
603
604         s->fc = NULL;
605         if (!nf)
606                 return;
607         PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
608         s->fc = para_calloc(sizeof(struct filter_chain));
609         INIT_LIST_HEAD(&s->fc->filters);
610         s->fc->inbuf = s->receiver_node->buf;
611         s->fc->in_loaded = &s->receiver_node->loaded;
612         s->fc->input_eof = &s->receiver_node->eof;
613         s->fc->task.pre_select = filter_pre_select;
614         s->fc->task.event_handler = filter_event_handler;
615         s->fc->task.private_data = s->fc;
616         s->fc->task.flags = 0;
617         s->fc->eof = 0;
618
619         s->receiver_node->output_eof = &s->fc->eof;
620         sprintf(s->fc->task.status, "filter chain");
621         for (i = 0; i < nf; i++) {
622                 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
623                 fn->conf = a->filter_conf[i];
624                 fn->fc = s->fc;
625                 fn->filter = a->filters[i];
626                 INIT_LIST_HEAD(&fn->callbacks);
627                 list_add_tail(&fn->node, &s->fc->filters);
628                 fn->filter->open(fn);
629                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
630                         audio_formats[s->format], i + 1,  nf,
631                         fn->filter->name, slot_num);
632                 s->fc->outbuf = fn->buf;
633                 s->fc->out_loaded = &fn->loaded;
634         }
635         register_task(&s->fc->task);
636 }
637
638 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
639 {
640         struct filter_node *fn;
641         int i, j;
642
643         FOR_EACH_SLOT(i) {
644                 struct slot_info *s = &slot[i];
645                 if (s->format < 0 || !s->fc)
646                         continue;
647                 if (slot_num >= 0 && slot_num != i)
648                         continue;
649                 if (format >= 0 && s->format != format)
650                         continue;
651                 if (num_filters(i) < filternum)
652                         continue;
653                 /* success */
654                 j = 1;
655                 list_for_each_entry(fn, &s->fc->filters, node)
656                         if (filternum <= 0 || j++ == filternum)
657                                 break;
658                 return fn;
659         }
660         return NULL;
661 }
662
663 static void wng_event_handler(struct task *t)
664 {
665         struct writer_node_group *wng = t->private_data;
666         int i;
667
668         wng_unregister(wng);
669         FOR_EACH_SLOT(i) {
670                 struct slot_info *s = &slot[i];
671                 if (s->wng != wng)
672                         continue;
673 //              if (s->fc)
674 //                      s->fc->eof = 1;
675 //              if (s->receiver_node)
676 //                      s->receiver_node->eof = 1;
677                 PARA_INFO_LOG("slot %d: %s\n", i, PARA_STRERROR(-t->ret));
678         }
679 }
680
681 static void open_writers(int slot_num)
682 {
683         int ret, i;
684         struct slot_info *s = &slot[slot_num];
685         struct audio_format_info *a = &afi[s->format];
686
687         PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
688         if (!a->num_writers)
689                 s->wng = setup_default_wng();
690         else
691                 s->wng = wng_new(a->num_writers);
692         if (s->fc) {
693                 s->wng->buf = s->fc->outbuf;
694                 s->wng->loaded = s->fc->out_loaded;
695                 s->wng->input_eof = &s->fc->eof;
696                 s->wng->channels = &s->fc->channels;
697                 s->wng->samplerate = &s->fc->samplerate;
698                 s->fc->output_eof = &s->wng->eof;
699                 PARA_INFO_LOG("samplerate: %d\n", *s->wng->samplerate);
700         } else {
701                 s->wng->buf = s->receiver_node->buf;
702                 s->wng->loaded = &s->receiver_node->loaded;
703                 s->wng->input_eof = &s->receiver_node->eof;
704         }
705         s->wng->task.event_handler = wng_event_handler;
706         for (i = 0; i < a->num_writers; i++) {
707                 s->wng->writer_nodes[i].conf = a->writer_conf[i];
708                 s->wng->writer_nodes[i].writer = a->writers[i];
709                 sprintf(s->wng->writer_nodes[i].task.status, "writer_node");
710         }
711         ret = wng_open(s->wng); /* FIXME */
712         s->wstime = *now;
713         current_decoder = slot_num;
714         activate_inactive_grab_clients(slot_num, s->format, &s->fc->filters);
715 }
716
717 static void rn_event_handler(struct task *t)
718 {
719 //      struct receiver_node *rn = t->private_data;
720         PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
721         unregister_task(t);
722 }
723
724 static void open_receiver(int format)
725 {
726         struct audio_format_info *a = &afi[format];
727         struct slot_info *s;
728         int ret, slot_num;
729         struct receiver_node *rn;
730
731         slot_num = get_empty_slot();
732         if (slot_num < 0)
733                 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
734         s = &slot[slot_num];
735         s->format = format;
736         s->receiver_node = para_calloc(sizeof(struct receiver_node));
737         rn = s->receiver_node;
738         rn->receiver = a->receiver;
739         rn->conf = a->receiver_conf;
740         ret = a->receiver->open(s->receiver_node);
741         if (ret < 0) {
742                 PARA_ERROR_LOG("failed to open receiver (%s)\n",
743                         PARA_STRERROR(-ret));
744                 free(s->receiver_node);
745                 s->receiver_node = NULL;
746                 return;
747         }
748         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
749                 audio_formats[s->format], a->receiver->name, slot_num);
750         rn->task.private_data = s->receiver_node;
751         rn->task.pre_select = a->receiver->pre_select;
752         rn->task.post_select = a->receiver->post_select;
753         rn->task.event_handler = rn_event_handler;
754         rn->task.flags = 0;
755         sprintf(rn->task.status, "receiver node");
756         register_task(&rn->task);
757 }
758
759 static int is_frozen(int format)
760 {
761         struct audio_format_info *a = &afi[format];
762
763         return (tv_diff(now, &a->restart_barrier, NULL) > 0)? 0 : 1;
764 }
765
766 static void open_current_receiver(void)
767 {
768         int i;
769
770         if (!af_status)
771                 return;
772         i = get_audio_format_num(af_status);
773         if (i < 0)
774                 return;
775         if (decoder_running(i) || is_frozen(i))
776                 return;
777         open_receiver(i);
778 }
779
780 static void compute_time_diff(const struct timeval *status_time)
781 {
782         struct timeval tmp, diff;
783         static int count;
784         int sign;
785         const struct timeval max_deviation = {0, 500 * 1000};
786         const int time_smooth = 5;
787
788         sign = tv_diff(status_time, now, &diff);
789 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
790 //                      sign, sa_time_diff_sign);
791         if (!count) {
792                 sa_time_diff_sign = sign;
793                 sa_time_diff = diff;
794                 count++;
795                 return;
796         }
797         if (count > 5) {
798                 int s = tv_diff(&diff, &sa_time_diff, &tmp);
799                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
800                         PARA_WARNING_LOG("time diff jump: %lims\n",
801                                 s * tv2ms(&tmp));
802         }
803         count++;
804         sa_time_diff_sign = tv_convex_combination(
805                 sa_time_diff_sign * time_smooth, &sa_time_diff,
806                 count > 10? sign : sign * time_smooth, &diff,
807                 &tmp);
808         sa_time_diff = tmp;
809         PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
810                 sign > 0? "+" : "-",
811                 tv2ms(&diff),
812                 sa_time_diff_sign ? "+" : "-",
813                 tv2ms(&sa_time_diff)
814         );
815 }
816
817 static void check_stat_line(char *line)
818 {
819         int itemnum;
820         size_t ilen = 0;
821         long unsigned sec, usec;
822         char *tmp;
823
824 //      PARA_INFO_LOG("line: %s\n", line);
825         if (!line)
826                 return;
827         itemnum = stat_line_valid(line);
828         if (itemnum < 0) {
829                 PARA_WARNING_LOG("invalid status line: %s\n", line);
830                 return;
831         }
832         tmp = make_message("%s\n", line);
833         stat_client_write(tmp, itemnum);
834         free(tmp);
835         free(stat_item_values[itemnum]);
836         stat_item_values[itemnum] = para_strdup(line);
837         ilen = strlen(status_item_list[itemnum]);
838         switch (itemnum) {
839         case SI_STATUS:
840                 playing = strstr(line, "playing")? 1 : 0;
841                 break;
842         case SI_FORMAT:
843                 free(af_status);
844                 af_status = para_strdup(line + ilen + 1);
845                 break;
846         case SI_OFFSET:
847                 offset_seconds = atoi(line + ilen + 1);
848                 break;
849         case SI_LENGTH:
850                 length_seconds = atoi(line + ilen + 1);
851                 break;
852         case SI_STREAM_START:
853                 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
854                         server_stream_start.tv_sec = sec;
855                         server_stream_start.tv_usec = usec;
856                 }
857                 break;
858         case SI_CURRENT_TIME:
859                 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
860                         struct timeval tv = {sec, usec};
861                         compute_time_diff(&tv);
862                 }
863                 break;
864         }
865 }
866
867 static void handle_signal(int sig)
868 {
869         switch (sig) {
870         case SIGCHLD:
871                 for (;;) {
872                         pid_t pid = para_reap_child();
873                         if (pid <= 0)
874                                 return;
875                         PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
876                 }
877         case SIGINT:
878         case SIGTERM:
879         case SIGHUP:
880                 PARA_EMERG_LOG("terminating on signal %d\n", sig);
881                 clean_exit(EXIT_FAILURE, "caught deadly signal");
882                 return;
883         }
884 }
885
886 static void try_to_close_slot(int slot_num)
887 {
888         struct slot_info *s = &slot[slot_num];
889
890         if (s->format < 0)
891                 return;
892         if (s->receiver_node && !s->receiver_node->eof)
893                 return;
894         if (s->fc && !s->fc->eof)
895                 return;
896         if (s->wng && !s->wng->eof)
897                 return;
898         PARA_INFO_LOG("closing slot %d \n", slot_num);
899         wng_close(s->wng);
900         close_filters(s->fc);
901         free(s->fc);
902         close_receiver(slot_num);
903         clear_slot(slot_num);
904 }
905
906 static void audiod_pre_select(struct sched *s, __a_unused struct task *t)
907 {
908         int i;
909
910         t->ret = 1;
911         now = &s->now;
912         if (audiod_status != AUDIOD_ON)
913                 kill_all_decoders();
914         else if (playing)
915                 open_current_receiver();
916         FOR_EACH_SLOT(i) {
917                 struct slot_info *s = &slot[i];
918                 struct audio_format_info *a;
919
920                 try_to_close_slot(i);
921                 if (s->format < 0)
922                         continue;
923                 a = &afi[s->format];
924                 if (!s->receiver_node)
925                         continue;
926                 if (!a->num_filters) {
927                         if (s->receiver_node->loaded && !s->wng)
928                                 open_writers(i);
929                         continue;
930                 }
931                 if (s->receiver_node->loaded && !s->fc) {
932                         open_filters(i);
933                         continue;
934                 }
935                 if (s->fc && *s->fc->out_loaded && !s->wng)
936                         open_writers(i);
937         }
938 }
939
940 static void audiod_post_select(struct sched *s, __a_unused struct task *t)
941 {
942         /* only save away the current time for other users */
943         now = &s->now;
944         t->ret = 1;
945 }
946
947 static void init_audiod_task(struct task *t)
948 {
949         t->pre_select = audiod_pre_select;
950         t->post_select = audiod_post_select;
951         t->event_handler = NULL;
952         t->private_data = t;
953         t->flags = 0;
954         sprintf(t->status, "audiod task");
955 }
956
957 static int parse_stream_command(const char *txt, char **cmd)
958 {
959         char *p = strchr(txt, ':');
960         int i;
961
962         if (!p)
963                 return -E_MISSING_COLON;
964         p++;
965         FOR_EACH_AUDIO_FORMAT(i) {
966                 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
967                         continue;
968                 *cmd = p;
969                 return i;
970         }
971         return -E_UNSUPPORTED_AUDIO_FORMAT;
972 }
973
974 static int add_filter(int format, char *cmdline)
975 {
976         struct audio_format_info *a = &afi[format];
977         int filter_num, nf = a->num_filters;
978
979         filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
980         if (filter_num < 0)
981                 return filter_num;
982         a->filters[nf] = &filters[filter_num];
983         a->num_filters++;
984         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
985                 a->filters[nf]->name);
986         return filter_num;
987 }
988
989 static int init_writers(void)
990 {
991         int i, ret, nw;
992         char *cmd;
993         struct audio_format_info *a;
994
995         init_supported_writers();
996         nw = PARA_MAX(1, conf.writer_given);
997         PARA_INFO_LOG("maximal number of writers: %d\n", nw);
998         FOR_EACH_AUDIO_FORMAT(i) {
999                 a = &afi[i];
1000                 a->writer_conf = para_malloc(nw * sizeof(void *));
1001                 a->writers = para_malloc(nw * sizeof(struct writer *));
1002                 a->num_writers = 0;
1003         }
1004         for (i = 0; i < conf.writer_given; i++) {
1005                 void *wconf;
1006                 int writer_num;
1007                 ret = parse_stream_command(conf.writer_arg[i], &cmd);
1008                 if (ret < 0)
1009                         goto out;
1010                 a = &afi[ret];
1011                 nw = a->num_writers;
1012                 wconf = check_writer_arg(cmd, &writer_num);
1013                 if (!wconf) {
1014                         ret = writer_num;
1015                         goto out;
1016                 }
1017                 a->writers[nw] = &writers[writer_num];
1018                 a->writer_conf[nw] = wconf;
1019                 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
1020                         nw, writer_names[writer_num]);
1021                 a->num_writers++;
1022         }
1023         ret = 1;
1024 out:
1025         return ret;
1026 }
1027
1028 static int init_receivers(void)
1029 {
1030         int i, ret, receiver_num;
1031         char *cmd = NULL;
1032         struct audio_format_info *a;
1033
1034         for (i = 0; receivers[i].name; i++) {
1035                 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1036                 receivers[i].init(&receivers[i]);
1037         }
1038         for (i = 0; i < conf.receiver_given; i++) {
1039                 char *arg = conf.receiver_arg[i];
1040                 char *recv = strchr(arg, ':');
1041                 ret = -E_MISSING_COLON;
1042                 if (!recv)
1043                         goto out;
1044                 *recv = '\0';
1045                 recv++;
1046                 ret = get_audio_format_num(arg);
1047                 if (ret < 0)
1048                         goto out;
1049                 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1050                 if (!afi[ret].receiver_conf) {
1051                         ret = -E_RECV_SYNTAX;
1052                         goto out;
1053                 }
1054                 afi[ret].receiver = &receivers[receiver_num];
1055         }
1056         /* use the first available receiver with no arguments
1057          * for those audio formats for which no receiver
1058          * was specified
1059          */
1060         cmd = para_strdup(receivers[0].name);
1061         FOR_EACH_AUDIO_FORMAT(i) {
1062                 a = &afi[i];
1063                 if (a->receiver_conf)
1064                         continue;
1065                 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1066                 if (!a->receiver_conf)
1067                         return -E_RECV_SYNTAX;
1068                 a->receiver = &receivers[receiver_num];
1069         }
1070         ret = 1;
1071 out:
1072         free(cmd);
1073         return ret;
1074 }
1075
1076 static int init_default_filters(void)
1077 {
1078         int i, ret = 1;
1079
1080         FOR_EACH_AUDIO_FORMAT(i) {
1081                 struct audio_format_info *a = &afi[i];
1082                 char *tmp;
1083                 int j;
1084
1085                 if (a->num_filters)
1086                         continue; /* no default -- nothing to to */
1087                 /* add "dec" to audio format name */
1088                 tmp = make_message("%sdec", audio_formats[i]);
1089                 for (j = 0; filters[j].name; j++)
1090                         if (!strcmp(tmp, filters[j].name))
1091                                 break;
1092                 free(tmp);
1093                 ret = -E_UNSUPPORTED_FILTER;
1094                 if (!filters[j].name)
1095                         goto out;
1096                 tmp = para_strdup(filters[j].name);
1097                 ret = add_filter(i, tmp);
1098                 free(tmp);
1099                 if (ret < 0)
1100                         goto out;
1101                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1102                         filters[j].name);
1103         }
1104 out:
1105         return ret;
1106 }
1107
1108 static int init_filters(void)
1109 {
1110         int i, ret, nf;
1111
1112         filter_init(filters);
1113         nf = PARA_MAX(1,  conf.filter_given);
1114         PARA_INFO_LOG("maximal number of filters: %d\n", nf);
1115         FOR_EACH_AUDIO_FORMAT(i) {
1116                 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
1117                 afi[i].filters = para_malloc(nf * sizeof(struct filter *));
1118         }
1119         if (!conf.no_default_filters_given)
1120                 return init_default_filters();
1121         for (i = 0; i < conf.filter_given; i++) {
1122                 char *arg = conf.filter_arg[i];
1123                 char *filter_name = strchr(arg, ':');
1124                 ret = -E_MISSING_COLON;
1125                 if (!filter_name)
1126                         goto out;
1127                 *filter_name = '\0';
1128                 filter_name++;
1129                 ret = get_audio_format_num(arg);
1130                 if (ret < 0)
1131                         goto out;
1132                 ret = add_filter(ret, filter_name);
1133                 if (ret < 0)
1134                         goto out;
1135         }
1136         ret = init_default_filters(); /* use default values for the rest */
1137 out:
1138         return ret;
1139 }
1140
1141 static int init_stream_io(void)
1142 {
1143         int ret;
1144
1145         ret = init_writers();
1146         if (ret < 0)
1147                 return ret;
1148         ret = init_receivers();
1149         if (ret < 0)
1150                 return ret;
1151         ret = init_filters();
1152         if (ret < 0)
1153                 return ret;
1154         return 1;
1155 }
1156
1157 static int dump_commands(int fd)
1158 {
1159         char *buf = para_strdup(""), *tmp = NULL;
1160         int i;
1161         ssize_t ret;
1162
1163         FOR_EACH_COMMAND(i) {
1164                 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1165                         cmds[i].description);
1166                 free(buf);
1167                 buf = tmp;
1168         }
1169         ret = client_write(fd, buf);
1170         free(buf);
1171         return ret;
1172 }
1173
1174 /*
1175  * command handlers don't close their fd on errors (ret < 0) so that
1176  * its caller can send an error message. Otherwise (ret >= 0) it's up
1177  * to each individual command to close the fd if necessary.
1178  */
1179
1180 static int com_help(int fd, int argc, char **argv)
1181 {
1182         int i, ret;
1183         char *buf;
1184         const char *dflt = "No such command. Available commands:\n";
1185
1186         if (argc < 2) {
1187                 ret = dump_commands(fd);
1188                 goto out;
1189         }
1190         FOR_EACH_COMMAND(i) {
1191                 if (strcmp(cmds[i].name, argv[1]))
1192                         continue;
1193                 buf = make_message(
1194                         "NAME\n\t%s -- %s\n"
1195                         "SYNOPSIS\n\tpara_audioc %s\n"
1196                         "DESCRIPTION\n%s\n",
1197                         argv[1],
1198                         cmds[i].description,
1199                         cmds[i].synopsis,
1200                         cmds[i].help
1201                 );
1202                 ret = client_write(fd, buf);
1203                 free(buf);
1204                 goto out;
1205         }
1206         ret = client_write(fd, dflt);
1207         if (ret > 0)
1208                 ret = dump_commands(fd);
1209 out:
1210         if (ret >= 0)
1211                 close(fd);
1212         return ret;
1213 }
1214
1215 static int com_stat(int fd, __a_unused int argc, __a_unused char **argv)
1216 {
1217         int i, ret;
1218         char *buf = NULL;
1219         long unsigned mask = ~0LU;
1220
1221         if (argc > 1) {
1222                 mask = 0;
1223                 for (i = 1; i < argc; i++) {
1224                         ret = stat_item_valid(argv[i]);
1225                         if (ret < 0)
1226                                 return ret;
1227                         mask |= (1 << ret);
1228                 }
1229         }
1230         PARA_INFO_LOG("mask: 0x%lx\n", mask);
1231         if (mask & (1 << SI_PLAY_TIME)) {
1232                 struct timeval *t = wstime();
1233                 char *ts = get_time_string(t);
1234                 if (ts) {
1235                         ret = client_write(fd, ts);
1236                         if (ret < 0)
1237                                 goto out;
1238                         free(ts);
1239                 }
1240         }
1241         if (mask & (1 << SI_AUDIOD_UPTIME)) {
1242                 char *tmp, *us = uptime_str();
1243                 tmp = make_message("%s:%s\n",
1244                         status_item_list[SI_AUDIOD_UPTIME], us);
1245                 free(us);
1246                 ret = client_write(fd, tmp);
1247                 if (ret < 0)
1248                         goto out;
1249                 free(tmp);
1250         }
1251         if (mask & (1 << SI_AUDIOD_STATUS)) {
1252                 char *s = audiod_status_string();
1253                 ret = client_write(fd, s);
1254                 if (ret < 0)
1255                         goto out;
1256                 free(s);
1257         }
1258         if (mask & (1 << SI_DECODER_FLAGS)) {
1259                 char *df =decoder_flags();
1260                 ret = client_write(fd, df);
1261                 if (ret < 0)
1262                         goto out;
1263                 free(df);
1264         }
1265
1266         for (i = 0; i < NUM_STAT_ITEMS; i++) {
1267                 char *tmp, *v;
1268                 if (!((1 << i) & mask))
1269                         continue;
1270                 v = stat_item_values[i];
1271                 tmp = make_message("%s%s%s", buf? buf: "",
1272                         v? v : "", v? "\n" : "");
1273                 free(buf);
1274                 buf = tmp;
1275         }
1276         ret = client_write(fd, buf);
1277 out:
1278         if (ret > 0)
1279                 ret = stat_client_add(fd, mask);
1280         free(buf);
1281         return ret;
1282 }
1283
1284 static int com_grab(int fd, char *cmdline)
1285 {
1286         struct grab_client *gc;
1287         struct filter_node *fn;
1288         int i, err;
1289         char *msg;
1290
1291         gc = grab_client_new(fd, cmdline, &err);
1292         if (!gc)
1293                 goto err_out;
1294         fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1295         if (fn)
1296                 activate_grab_client(gc, fn);
1297         return 1;
1298 err_out:
1299         if (err != -E_GC_HELP_GIVEN && err != -E_GC_VERSION_GIVEN)
1300                 return err;
1301         if (err == -E_GC_HELP_GIVEN) {
1302                 msg = make_message("%s\n\n", grab_client_args_info_usage);
1303                 for (i = 0; grab_client_args_info_help[i]; i++) {
1304                         char *tmp = make_message("%s%s\n", msg,
1305                                 grab_client_args_info_help[i]);
1306                         free(msg);
1307                         msg = tmp;
1308                 }
1309         } else
1310                 msg = make_message("%s %s\n",
1311                         GRAB_CLIENT_CMDLINE_PARSER_PACKAGE,
1312                         GRAB_CLIENT_CMDLINE_PARSER_VERSION);
1313         err = client_write(fd, msg);
1314         free(msg);
1315         if (err < 0)
1316                 return err;
1317         close(fd);
1318         return 1;
1319 }
1320
1321 static int __noreturn com_term(int fd, __a_unused int argc, __a_unused char **argv)
1322 {
1323         close(fd);
1324         clean_exit(EXIT_SUCCESS, "terminating on user request");
1325 }
1326
1327 static int com_on(int fd, __a_unused int argc, __a_unused char **argv)
1328 {
1329         audiod_status = AUDIOD_ON;
1330         close(fd);
1331         return 1;
1332 }
1333
1334 static int com_off(int fd, __a_unused int argc, __a_unused char **argv)
1335 {
1336         audiod_status = AUDIOD_OFF;
1337         close(fd);
1338         return 1;
1339 }
1340
1341 static int com_sb(int fd, __a_unused int argc, __a_unused char **argv)
1342 {
1343         audiod_status = AUDIOD_STANDBY;
1344         close(fd);
1345         return 1;
1346 }
1347
1348 static int com_cycle(int fd, int argc, char **argv)
1349 {
1350         switch (audiod_status) {
1351                 case  AUDIOD_ON:
1352                         return com_sb(fd, argc, argv);
1353                         break;
1354                 case  AUDIOD_OFF:
1355                         return com_on(fd, argc, argv);
1356                         break;
1357                 case  AUDIOD_STANDBY:
1358                         return com_off(fd, argc, argv);
1359                         break;
1360         }
1361         close(fd);
1362         return 1;
1363 }
1364
1365 static int check_perms(uid_t uid)
1366 {
1367         int i;
1368
1369         if (!conf.user_allow_given)
1370                 return 1;
1371         for (i = 0; i < conf.user_allow_given; i++)
1372                 if (uid == conf.user_allow_arg[i])
1373                         return 1;
1374         return -E_UCRED_PERM;
1375 }
1376
1377 static int handle_connect(int accept_fd)
1378 {
1379         int i, argc, ret, clifd = -1;
1380         char *cmd = NULL, *p, *buf = para_calloc(MAXLINE), **argv = NULL;
1381         struct sockaddr_un unix_addr;
1382
1383         ret = para_accept(accept_fd, &unix_addr, sizeof(struct sockaddr_un));
1384         if (ret < 0)
1385                 goto out;
1386         clifd = ret;
1387         ret = recv_cred_buffer(clifd, buf, MAXLINE - 1);
1388         if (ret < 0)
1389                 goto out;
1390         PARA_INFO_LOG("connection from user %i, buf: %s\n",  ret, buf);
1391         ret = check_perms(ret);
1392         if (ret < 0)
1393                 goto out;
1394         ret = -E_INVALID_AUDIOD_CMD;
1395         cmd = para_strdup(buf);
1396         p = strchr(cmd, '\n');
1397         if (!p)
1398                 p = "";
1399         else {
1400                 *p = '\0';
1401                 p++;
1402         }
1403         for (i = 0; cmds[i].name; i++) {
1404                 int j;
1405                 if (strcmp(cmds[i].name, cmd))
1406                         continue;
1407                 if (cmds[i].handler) {
1408                         argc = split_args(buf, &argv, "\n");
1409                         PARA_INFO_LOG("argv[0]: %s, argc= %d\n", argv[0], argc);
1410                         ret = cmds[i].handler(clifd, argc, argv);
1411                         goto out;
1412                 }
1413                 for (j = 0; p[j]; j++)
1414                         if (p[j] == '\n')
1415                                 p[j] = ' ';
1416                 PARA_INFO_LOG("cmd: %s, options: %s\n", cmd, p);
1417                 ret = cmds[i].line_handler(clifd, p);
1418                 goto out;
1419         }
1420         ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1421 out:
1422         free(cmd);
1423         free(buf);
1424         free(argv);
1425         if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1426                 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1427                 client_write(clifd, tmp);
1428                 free(tmp);
1429                 close(clifd);
1430         }
1431         return ret;
1432 }
1433
1434 static int audiod_get_socket(void)
1435 {
1436         struct sockaddr_un unix_addr;
1437         int fd;
1438
1439         if (conf.socket_given)
1440                 socket_name = para_strdup(conf.socket_arg);
1441         else {
1442                 char *hn = para_hostname();
1443                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1444                         hn);
1445                 free(hn);
1446         }
1447         PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1448         if (conf.force_given)
1449                 unlink(socket_name);
1450         fd = create_pf_socket(socket_name, &unix_addr,
1451                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1452         if (fd < 0) {
1453                 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1454                 exit(EXIT_FAILURE); /* do not unlink socket */
1455         }
1456         if (listen(fd , 5) < 0) {
1457                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1458                 exit(EXIT_FAILURE); /* do not unlink socket */
1459         }
1460         add_close_on_fork_list(fd);
1461         return fd;
1462 }
1463
1464 static int open_stat_pipe(void)
1465 {
1466         int ret, fd[3] = {-1, 1, 0};
1467         pid_t pid;
1468         ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1469         if (ret >= 0) {
1470                 ret = fd[1];
1471                 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1472                 add_close_on_fork_list(ret);
1473         } else
1474                 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1475         return ret;
1476 }
1477
1478 void signal_event_handler(struct task *t)
1479 {
1480         struct signal_task *st = t->private_data;
1481         handle_signal(st->signum);
1482 }
1483
1484 void signal_pre_select(struct sched *s, struct task *t)
1485 {
1486         struct signal_task *st = t->private_data;
1487         t->ret = 1;
1488         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1489 }
1490
1491 void signal_post_select(struct sched *s, struct task *t)
1492 {
1493         struct signal_task *st = t->private_data;
1494         t->ret = 1;
1495         if (!FD_ISSET(st->fd, &s->rfds))
1496                 return;
1497         t->ret = -E_SIGNAL_CAUGHT;
1498         st->signum = para_next_signal();
1499 }
1500
1501 void signal_setup_default(struct signal_task *st)
1502 {
1503         st->task.pre_select = signal_pre_select;
1504         st->task.post_select = signal_post_select;
1505         st->task.private_data = st;
1506         st->task.flags = 0;
1507         sprintf(st->task.status, "signal task");
1508 }
1509
1510 static void command_pre_select(struct sched *s, struct task *t)
1511 {
1512         struct command_task *ct = t->private_data;
1513         t->ret = 1;
1514         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
1515
1516 }
1517
1518 static void command_post_select(struct sched *s, struct task *t)
1519 {
1520         int ret;
1521         struct command_task *ct = t->private_data;
1522
1523         t->ret = 1; /* always successful */
1524         if (audiod_status != AUDIOD_OFF)
1525                 audiod_status_dump();
1526         if (!FD_ISSET(ct->fd, &s->rfds))
1527                 return;
1528         ret = handle_connect(ct->fd);
1529         if (ret < 0)
1530                 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1531 }
1532
1533 static void init_command_task(struct command_task *ct)
1534 {
1535         ct->task.pre_select = command_pre_select;
1536         ct->task.post_select = command_post_select;
1537         ct->task.event_handler = NULL;
1538         ct->task.private_data = ct;
1539         ct->task.flags = 0;
1540         ct->fd = audiod_get_socket(); /* doesn't return on errors */
1541         sprintf(ct->task.status, "command task");
1542 }
1543
1544 static void status_pre_select(struct sched *s, struct task *t)
1545 {
1546         struct status_task *st = t->private_data;
1547         t->ret = 1;
1548         if (st->fd >= 0 && audiod_status == AUDIOD_OFF)
1549                 close_stat_pipe();
1550         if (st->fd < 0 && audiod_status != AUDIOD_OFF) {
1551                 st->fd = open_stat_pipe();
1552                 st->loaded = 0;
1553                 st->buf[0] = '\0';
1554         }
1555         if (st->fd >= 0 && audiod_status != AUDIOD_OFF)
1556                 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1557 }
1558
1559 static void status_post_select(struct sched *s, struct task *t)
1560 {
1561         struct status_task *st = t->private_data;
1562         int ret;
1563
1564         t->ret = 1;
1565         if (st->fd < 0 || !FD_ISSET(st->fd, &s->rfds))
1566                 return;
1567         ret = read(st->fd, st->buf + st->loaded,
1568                 STRINGSIZE - 1 - st->loaded);
1569         if (ret <= 0) {
1570                 close_stat_pipe();
1571                 /* avoid busy loop if server is down */
1572                 while (sleep(1) > 0) /* FIXME */
1573                         ; /* try again*/
1574         } else {
1575                 st->buf[ret + st->loaded] = '\0';
1576                 st->loaded = for_each_line(st->buf, ret + st->loaded,
1577                         &check_stat_line);
1578         }
1579 }
1580
1581 static void init_status_task(struct status_task *st)
1582 {
1583         st->task.pre_select = status_pre_select;
1584         st->task.post_select = status_post_select;
1585         st->task.private_data = st;
1586         st->task.flags = 0;
1587         st->loaded = 0;
1588         st->fd = -1;
1589         st->buf[0] = '\0';
1590         sprintf(st->task.status, "status task");
1591 }
1592
1593 static void set_initial_status(void)
1594 {
1595         audiod_status = AUDIOD_ON;
1596         if (!conf.mode_given)
1597                 return;
1598         if (!strcmp(conf.mode_arg, "sb")) {
1599                 audiod_status = AUDIOD_STANDBY;
1600                 return;
1601         }
1602         if (!strcmp(conf.mode_arg, "off")) {
1603                 audiod_status = AUDIOD_OFF;
1604                 return;
1605         }
1606         if (strcmp(conf.mode_arg, "on"))
1607                 PARA_WARNING_LOG("%s", "invalid mode\n");
1608 }
1609
1610 int main(int argc, char *argv[])
1611 {
1612         char *cf;
1613         int ret, i;
1614         struct sched s;
1615         struct command_task command_task_struct, *cmd_task = &command_task_struct;
1616         struct task audiod_task_struct, *audiod_task = &audiod_task_struct;
1617
1618         init_sched();
1619
1620         valid_fd_012();
1621         hostname = para_hostname();
1622         cmdline_parser(argc, argv, &conf);
1623         para_drop_privileges(conf.user_arg, conf.group_arg);
1624         cf = configfile_exists();
1625         if (cf) {
1626                 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1627                         PARA_EMERG_LOG("%s", "parse error in config file\n");
1628                         exit(EXIT_FAILURE);
1629                 }
1630         }
1631         if (conf.logfile_given)
1632                 logfile = open_log(conf.logfile_arg);
1633         log_welcome("para_audiod", conf.loglevel_arg);
1634         i = init_stream_io();
1635         if (i < 0) {
1636                 PARA_EMERG_LOG("init stream io error: %s\n", PARA_STRERROR(-i));
1637                 exit(EXIT_FAILURE);
1638         }
1639         server_uptime(UPTIME_SET);
1640         set_initial_status();
1641         FOR_EACH_SLOT(i)
1642                 clear_slot(i);
1643         init_grabbing();
1644         setup_signal_handling();
1645         signal_setup_default(sig_task);
1646         sig_task->task.event_handler = signal_event_handler;
1647
1648         init_status_task(stat_task);
1649         init_command_task(cmd_task);
1650         init_audiod_task(audiod_task);
1651
1652         if (conf.daemon_given)
1653                 daemon_init();
1654
1655         register_task(&sig_task->task);
1656         register_task(&cmd_task->task);
1657         register_task(&stat_task->task);
1658         register_task(audiod_task);
1659         s.default_timeout.tv_sec = 0;
1660         s.default_timeout.tv_usec = 99 * 1000;
1661         ret = sched(&s);
1662
1663         PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
1664         return EXIT_FAILURE;
1665 }