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