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