integrate writers into para_audiod
[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 static void close_writer(int slot_num)
498 {
499         struct slot_info *s = &slot[slot_num];
500         if (s->wng) {
501                 PARA_INFO_LOG("slot %d: closing writer node group\n",
502                         slot_num);
503                 wng_close(s->wng);
504                 s->wng = NULL;
505         }
506         if (s->fc)
507                 *s->fc->output_eof = 1; /* FIXME */
508 }
509
510
511 static void kill_all_decoders(void)
512 {
513         int i;
514
515         FOR_EACH_SLOT(i)
516                 close_writer(i);
517 }
518
519 static void check_sigchld(void)
520 {
521         pid_t pid;
522         struct timeval now;
523         gettimeofday(&now, NULL);
524
525 reap_next_child:
526         pid = para_reap_child();
527         if (pid <= 0)
528                 return;
529         PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
530         goto reap_next_child;
531 }
532
533 static int get_empty_slot(void)
534 {
535         int i;
536         struct slot_info *s;
537
538         FOR_EACH_SLOT(i) {
539                 s = &slot[i];
540                 if (s->format < 0) {
541                         clear_slot(i);
542                         return i;
543                 }
544                 if (s->wng)
545                         continue;
546                 if (s->receiver_node)
547                         continue;
548                 if (s->fc)
549                         continue;
550                 clear_slot(i);
551                 return i;
552         }
553         return -E_NO_MORE_SLOTS;
554 }
555
556 static int decoder_running(int format)
557 {
558         int i, ret = 0;
559         struct slot_info *s;
560
561         FOR_EACH_SLOT(i) {
562                 s = &slot[i];
563                 if (s->format == format && s->receiver_node)
564                         ret |= 1;
565                 if (s->format == format && s->wng)
566                         ret |= 2;
567         }
568         return ret;
569 }
570
571 static void close_stat_pipe(void)
572 {
573         int i;
574
575         if (stat_task->fd < 0)
576                 return;
577         PARA_NOTICE_LOG("%s", "closing status pipe\n");
578         close(stat_task->fd);
579         del_close_on_fork_list(stat_task->fd);
580         stat_task->fd = -1;
581         kill_all_decoders();
582         for (i = 0; i < NUM_STAT_ITEMS; i++) {
583                 free(stat_item_values[i]);
584                 stat_item_values[i] = NULL;
585         }
586         dump_empty_status();
587         length_seconds = 0;
588         offset_seconds = 0;
589         audiod_status_dump();
590         playing = 0;
591         stat_item_values[SI_STATUS_BAR] = make_message("%s:no connection to para_server\n",
592                 status_item_list[SI_STATUS_BAR]);
593         stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
594 }
595
596 static void __noreturn clean_exit(int status, const char *msg)
597 {
598         PARA_EMERG_LOG("%s\n", msg);
599         kill_all_decoders();
600         if (socket_name)
601                 unlink(socket_name);
602         if (stat_task->fd >= 0)
603                 close_stat_pipe();
604         exit(status);
605 }
606
607 #if 0
608 __malloc static char *glob_cmd(char *cmd)
609 {
610         char *ret, *replacement;
611         struct timeval tmp, delay, rss; /* real stream start */
612
613         delay.tv_sec = conf.stream_delay_arg / 1000;
614         delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
615 //      PARA_INFO_LOG("delay: %lu:%lu\n", delay.tv_sec, delay.tv_usec);
616         if (sa_time_diff_sign < 0)
617                 tv_add(&server_stream_start, &sa_time_diff, &rss);
618         else
619                 tv_diff(&server_stream_start, &sa_time_diff, &rss);
620         tv_add(&rss, &delay, &tmp);
621         replacement = make_message("%lu:%lu",
622                 (long unsigned)tmp.tv_sec,
623                 (long unsigned)tmp.tv_usec);
624         ret = s_a_r(cmd, "STREAM_START", replacement);
625         free(replacement);
626         if (!ret)
627                 goto out;
628         PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
629 out:
630         return ret;
631 }
632 #endif
633
634 /** get the number of filters for the given audio format */
635 int num_filters(int audio_format_num)
636 {
637         return afi[audio_format_num].num_filters;
638 }
639
640 void filter_event_handler(struct task *t)
641 {
642         PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
643         unregister_task(t);
644 }
645
646 static void open_filters(int slot_num)
647 {
648         struct slot_info *s = &slot[slot_num];
649         struct audio_format_info *a = &afi[s->format];
650         int nf = a->num_filters;
651         int i;
652
653         s->fc = NULL;
654         if (!nf)
655                 return;
656         s->fc = para_calloc(sizeof(struct filter_chain));
657         INIT_LIST_HEAD(&s->fc->filters);
658         s->fc->inbuf = s->receiver_node->buf;
659         s->fc->in_loaded = &s->receiver_node->loaded;
660         s->fc->input_eof = &s->receiver_node->eof;
661
662         s->fc->task.pre_select = filter_pre_select;
663         s->fc->task.event_handler = filter_event_handler;
664         s->fc->task.private_data = s->fc;
665         s->fc->task.flags = 0;
666         s->fc->eof = 0;
667         sprintf(s->fc->task.status, "filter chain");
668         for (i = 0; i < nf; i++) {
669                 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
670                 fn->conf = a->filter_conf[i];
671                 fn->fc = s->fc;
672                 fn->filter = a->filters[i];
673                 INIT_LIST_HEAD(&fn->callbacks);
674                 list_add_tail(&fn->node, &s->fc->filters);
675                 fn->filter->open(fn);
676                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
677                         audio_formats[s->format], i + 1,  nf,
678                         fn->filter->name, slot_num);
679                 s->fc->outbuf = fn->buf;
680                 s->fc->out_loaded = &fn->loaded;
681         }
682         register_task(&s->fc->task);
683 //      PARA_DEBUG_LOG("output loaded for filter chain %p: %p\n", s->fc,
684 //              s->fc->out_loaded);
685 }
686
687 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
688 {
689         struct filter_node *fn;
690         int i, j;
691
692         FOR_EACH_SLOT(i) {
693                 struct slot_info *s = &slot[i];
694                 if (s->format < 0 || !s->fc)
695                         continue;
696                 if (slot_num >= 0 && slot_num != i)
697                         continue;
698                 if (format >= 0 && s->format != format)
699                         continue;
700                 if (num_filters(i) < filternum)
701                         continue;
702                 /* success */
703                 j = 1;
704                 list_for_each_entry(fn, &s->fc->filters, node)
705                         if (filternum <= 0 || j++ == filternum)
706                                 break;
707                 return fn;
708         }
709         return NULL;
710 }
711
712 static void wng_event_handler(struct task *t)
713 {
714         struct writer_node_group *g = t->private_data;
715         int i;
716
717         PARA_INFO_LOG("%s\n", PARA_STRERROR(-t->ret));
718         unregister_task(t);
719         FOR_EACH_SLOT(i) {
720                 if (slot[i].wng != g)
721                         continue;
722                 wng_close(g);
723                 wng_destroy(g);
724                 slot[i].wng = NULL;
725         }
726 }
727
728 static void start_stream_writer(int slot_num, struct timeval *now)
729 {
730         int ret, i;
731         struct slot_info *s = &slot[slot_num];
732         struct audio_format_info *a = &afi[s->format];
733
734         PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
735         open_filters(slot_num);
736         PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
737         if (!a->num_writers)
738                 s->wng = setup_default_wng();
739         else
740                 s->wng = wng_new(a->num_writers);
741         if (s->fc) {
742                 s->wng->buf = s->fc->outbuf;
743                 s->wng->loaded = s->fc->out_loaded;
744                 s->wng->input_eof = &s->fc->eof;
745                 s->fc->output_eof = &s->wng->eof;
746         } else {
747                 s->wng->buf = s->receiver_node->buf;
748                 s->wng->loaded = &s->receiver_node->loaded;
749                 s->wng->input_eof = &s->receiver_node->eof;
750         }
751         s->wng->task.event_handler = wng_event_handler;
752         for (i = 0; i < a->num_writers; i++) {
753                 s->wng->writer_nodes[i].conf = a->writer_conf[i];
754                 s->wng->writer_nodes[i].writer = a->writers[i];
755                 sprintf(s->wng->writer_nodes[i].task.status, "writer_ node");
756         }
757         ret = wng_open(s->wng);
758         s->wstime = *now;
759         current_decoder = slot_num;
760         activate_inactive_grab_clients(slot_num, s->format, &s->fc->filters);
761 }
762
763 void rn_event_handler(struct task *t)
764 {
765 //      struct receiver_node *rn = t->private_data;
766         PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
767         unregister_task(t);
768 }
769 static void open_receiver(int format)
770 {
771         struct audio_format_info *a = &afi[format];
772         struct slot_info *s;
773         int ret, slot_num;
774         struct receiver_node *rn;
775
776         slot_num = get_empty_slot();
777         if (slot_num < 0)
778                 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
779         s = &slot[slot_num];
780         s->format = format;
781         gettimeofday(&s->rtime, NULL);
782         s->wtime = s->rtime;
783         s->receiver_node = para_calloc(sizeof(struct receiver_node));
784         rn = s->receiver_node;
785         rn->receiver = a->receiver;
786         rn->conf = a->receiver_conf;
787         ret = a->receiver->open(s->receiver_node);
788         if (ret < 0) {
789                 PARA_ERROR_LOG("failed to open receiver (%s)\n",
790                         PARA_STRERROR(-ret));
791                 free(s->receiver_node);
792                 s->receiver_node = NULL;
793                 return;
794         }
795         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
796                 audio_formats[s->format], a->receiver->name, slot_num);
797         rn->task.private_data = s->receiver_node;
798         PARA_NOTICE_LOG("rn = %p\n", rn->task.private_data);
799         rn->task.pre_select = a->receiver->pre_select;
800         rn->task.post_select = a->receiver->post_select;
801         rn->task.event_handler = rn_event_handler;
802         rn->task.flags = 0;
803         sprintf(rn->task.status, "receiver node");
804         register_task(&rn->task);
805 }
806
807 static int is_frozen(int format)
808 {
809         struct timeval now;
810         struct audio_format_info *a = &afi[format];
811
812         gettimeofday(&now, NULL);
813         return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
814 }
815
816 static void start_current_receiver(void)
817 {
818         int i;
819
820         if (!af_status)
821                 return;
822         i = get_audio_format_num(af_status);
823         if (i < 0)
824                 return;
825         if ((decoder_running(i) & 1) || is_frozen(i))
826                 return;
827         open_receiver(i);
828 }
829
830 static void compute_time_diff(const struct timeval *status_time)
831 {
832         struct timeval now, tmp, diff;
833         static int count;
834         int sign;
835         const struct timeval max_deviation = {0, 500 * 1000};
836         const int time_smooth = 5;
837
838         gettimeofday(&now, NULL);
839         sign = tv_diff(status_time, &now, &diff);
840 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
841 //                      sign, sa_time_diff_sign);
842         if (!count) {
843                 sa_time_diff_sign = sign;
844                 sa_time_diff = diff;
845                 count++;
846                 return;
847         }
848         if (count > 5) {
849                 int s = tv_diff(&diff, &sa_time_diff, &tmp);
850                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
851                         PARA_WARNING_LOG("time diff jump: %lims\n",
852                                 s * tv2ms(&tmp));
853         }
854         count++;
855         sa_time_diff_sign = tv_convex_combination(
856                 sa_time_diff_sign * time_smooth, &sa_time_diff,
857                 count > 10? sign : sign * time_smooth, &diff,
858                 &tmp);
859         sa_time_diff = tmp;
860         PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
861                 sign > 0? "+" : "-",
862                 tv2ms(&diff),
863                 sa_time_diff_sign ? "+" : "-",
864                 tv2ms(&sa_time_diff)
865         );
866 }
867
868 static void check_stat_line(char *line)
869 {
870         int itemnum;
871         size_t ilen = 0;
872         long unsigned sec, usec;
873         char *tmp;
874
875 //      PARA_INFO_LOG("line: %s\n", line);
876         if (!line)
877                 return;
878         itemnum = stat_line_valid(line);
879         if (itemnum < 0) {
880                 PARA_WARNING_LOG("invalid status line: %s\n", line);
881                 return;
882         }
883         tmp = make_message("%s\n", line);
884         stat_client_write(tmp, itemnum);
885         free(tmp);
886         free(stat_item_values[itemnum]);
887         stat_item_values[itemnum] = para_strdup(line);
888         ilen = strlen(status_item_list[itemnum]);
889         switch (itemnum) {
890         case SI_STATUS:
891                 playing = strstr(line, "playing")? 1 : 0;
892                 break;
893         case SI_FORMAT:
894                 free(af_status);
895                 af_status = para_strdup(line + ilen + 1);
896                 break;
897         case SI_OFFSET:
898                 offset_seconds = atoi(line + ilen + 1);
899                 break;
900         case SI_LENGTH:
901                 length_seconds = atoi(line + ilen + 1);
902                 break;
903         case SI_STREAM_START:
904                 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
905                         server_stream_start.tv_sec = sec;
906                         server_stream_start.tv_usec = usec;
907                 }
908                 break;
909         case SI_CURRENT_TIME:
910                 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
911                         struct timeval tv = {sec, usec};
912                         compute_time_diff(&tv);
913                 }
914                 break;
915         }
916 }
917
918 static void handle_signal(int sig)
919 {
920         switch (sig) {
921         case SIGCHLD:
922                 return check_sigchld();
923         case SIGINT:
924         case SIGTERM:
925         case SIGHUP:
926                 PARA_EMERG_LOG("terminating on signal %d\n", sig);
927                 clean_exit(EXIT_FAILURE, "caught deadly signal");
928                 return;
929         }
930 }
931
932 static void check_timeouts(void)
933 {
934         struct timeval now;
935         int slot_num, timeout = conf.stream_timeout_arg;
936
937         gettimeofday(&now, NULL);
938         FOR_EACH_SLOT(slot_num) {
939                 struct slot_info *s = &slot[slot_num];
940                 if (s->format < 0)
941                         continue;
942                 /* check read time */
943                 if (s->receiver_node &&
944                         now.tv_sec > s->rtime.tv_sec + timeout) {
945                         PARA_INFO_LOG("%s stream (slot %d) not ready\n",
946                                 audio_formats[s->format], slot_num);
947                         s->receiver_node->eof = 1;
948                 }
949         }
950 }
951
952 static void close_decoder_if_idle(int slot_num)
953 {
954         struct slot_info *s = &slot[slot_num];
955
956         if (s->format < 0)
957                 return;
958         if (!s->fc)
959                 return;
960         if (s->wng)
961                 return;
962         PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
963                 slot_num, s->fc);
964         close_filters(s->fc);
965         free(s->fc);
966         close_receiver(slot_num);
967         clear_slot(slot_num);
968 }
969
970 static void audiod_pre_select(__a_unused struct sched *s, __a_unused struct task *t)
971 {
972         int i;
973
974         if (audiod_status != AUDIOD_ON)
975                 kill_all_decoders();
976         else if (playing)
977                 start_current_receiver();
978         check_timeouts();
979         FOR_EACH_SLOT(i) {
980                 struct receiver_node *rn;
981
982                 close_decoder_if_idle(i);
983                 if (slot[i].format < 0)
984                         continue;
985                 rn = slot[i].receiver_node;
986                 if (rn && rn->loaded && !slot[i].wng) {
987                         PARA_INFO_LOG("no writer in slot %d\n", i);
988                         start_stream_writer(i, &s->now);
989                 }
990         }
991 }
992
993 #if 0
994 static int write_audio_data(int slot_num)
995 {
996         struct slot_info *s = &slot[slot_num];
997         struct audio_format_info *a = &afi[s->format];
998         struct receiver_node *rn = s->receiver_node;
999         int ret;
1000         char **buf;
1001         size_t *len;
1002
1003         if (a->num_filters) {
1004                 buf = &s->fc->outbuf;
1005                 len = s->fc->out_loaded;
1006         } else {
1007                 buf = &rn->buf;
1008                 len = &rn->loaded;
1009         }
1010         PARA_DEBUG_LOG("writing %p (%zd bytes)\n", *buf, *len);
1011         ret = write(s->write_fd, *buf, *len);
1012         PARA_DEBUG_LOG("wrote %d/%zd\n", ret, *len);
1013         if (ret < 0) {
1014                 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
1015                         slot_num, s->write_fd, strerror(errno));
1016                 *len = 0;
1017                 close_writer(slot_num);
1018 //              s->fc->error = E_WRITE_AUDIO_DATA;
1019         } else if (ret != *len) {
1020                 PARA_DEBUG_LOG("partial %s write (%i/%zd) for slot %d\n",
1021                         audio_formats[s->format], ret, *len, slot_num);
1022                 *len -= ret;
1023                 memmove(*buf, *buf + ret, *len);
1024         } else
1025                 *len = 0;
1026         if (ret > 0)
1027                 gettimeofday(&s->wtime, NULL);
1028         return ret;
1029 }
1030 #endif
1031
1032
1033 static void audiod_post_select(struct sched *s, __a_unused struct task *t)
1034 {
1035         int i;
1036
1037         FOR_EACH_SLOT(i) {
1038                 struct receiver_node *rn = slot[i].receiver_node;
1039
1040                 if (rn && rn->loaded)
1041                         slot[i].rtime = s->now;
1042 //              if (slot[i].write_fd <= 0 || !slot[i].wcheck
1043 //                      || !FD_ISSET(slot[i].write_fd, &s->wfds))
1044 //                      continue;
1045 //              ret = write_audio_data(i);
1046         }
1047 }
1048
1049 static void init_audiod_task(struct audiod_task *at)
1050 {
1051         at->task.pre_select = audiod_pre_select;
1052         at->task.post_select = audiod_post_select;
1053         at->task.private_data = at;
1054         at->task.flags = 0;
1055         sprintf(at->task.status, "audiod task");
1056 }
1057
1058 static int parse_stream_command(const char *txt, char **cmd)
1059 {
1060         char *p = strchr(txt, ':');
1061         int i;
1062
1063         if (!p)
1064                 return -E_MISSING_COLON;
1065         p++;
1066         FOR_EACH_AUDIO_FORMAT(i) {
1067                 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1068                         continue;
1069                 *cmd = p;
1070                 return i;
1071         }
1072         return -E_UNSUPPORTED_AUDIO_FORMAT;
1073 }
1074
1075 static int add_filter(int format, char *cmdline)
1076 {
1077         struct audio_format_info *a = &afi[format];
1078         int filter_num, nf = a->num_filters;
1079
1080         filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1081         if (filter_num < 0)
1082                 return filter_num;
1083         a->filters[nf] = &filters[filter_num];
1084         a->num_filters++;
1085         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1086                 a->filters[nf]->name);
1087         return filter_num;
1088 }
1089
1090 static int setup_default_filters(void)
1091 {
1092         int i, ret = 1;
1093
1094         FOR_EACH_AUDIO_FORMAT(i) {
1095                 struct audio_format_info *a = &afi[i];
1096                 char *tmp;
1097                 int j;
1098                 if (a->num_filters)
1099                         continue;
1100                 /* add "dec" to audio format name */
1101                 tmp = make_message("%sdec", audio_formats[i]);
1102                 for (j = 0; filters[j].name; j++)
1103                         if (!strcmp(tmp, filters[j].name))
1104                                 break;
1105                 free(tmp);
1106                 ret = -E_UNSUPPORTED_FILTER;
1107                 if (!filters[j].name)
1108                         goto out;
1109                 tmp = para_strdup(filters[j].name);
1110                 ret = add_filter(i, tmp);
1111                 free(tmp);
1112                 if (ret < 0)
1113                         goto out;
1114                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1115                         filters[j].name);
1116                 ret = add_filter(i, "wav");
1117                 if (ret < 0)
1118                         goto out;
1119                 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1120         }
1121 out:
1122         return ret;
1123 }
1124
1125 static int init_stream_io(void)
1126 {
1127         int i, ret, receiver_num, nf, nw;
1128         char *cmd;
1129         struct audio_format_info *a;
1130
1131         init_supported_writers();
1132         nw = PARA_MAX(1, conf.writer_given);
1133         PARA_INFO_LOG("allocating space for %d writers\n", nw);
1134         FOR_EACH_AUDIO_FORMAT(i) {
1135                 a = &afi[i];
1136                 a->writer_conf = para_malloc(nw * sizeof(void *));
1137                 a->writers = para_malloc(nw * sizeof(struct writer *));
1138                 a->num_writers = 0;
1139         }
1140         for (i = 0; i < conf.writer_given; i++) {
1141                 void *wconf;
1142                 int writer_num;
1143                 ret = parse_stream_command(conf.writer_arg[i], &cmd);
1144                 if (ret < 0)
1145                         goto out;
1146                 a = &afi[ret];
1147                 nw = a->num_writers;
1148                 wconf = check_writer_arg(cmd, &writer_num);
1149                 if (!wconf) {
1150                         ret = writer_num;
1151                         goto out;
1152                 }
1153                 a->writers[nw] = &writers[ret];
1154                 a->writer_conf[nw] = wconf;
1155                 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
1156                         nw, writer_names[writer_num]);
1157                 a->num_writers++;
1158         }
1159         for (i = 0; receivers[i].name; i++) {
1160                 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1161                 receivers[i].init(&receivers[i]);
1162         }
1163         for (i = 0; i < conf.receiver_given; i++) {
1164                 char *arg = conf.receiver_arg[i];
1165                 char *recv = strchr(arg, ':');
1166                 ret = -E_MISSING_COLON;
1167                 if (!recv)
1168                         goto out;
1169                 *recv = '\0';
1170                 recv++;
1171                 ret = get_audio_format_num(arg);
1172                 if (ret < 0)
1173                         goto out;
1174                 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1175                 if (!afi[ret].receiver_conf) {
1176                         ret = -E_RECV_SYNTAX;
1177                         goto out;
1178                 }
1179                 afi[ret].receiver = &receivers[receiver_num];
1180         }
1181         /* use the first available receiver with no arguments
1182          * for those audio formats for which no receiver
1183          * was specified
1184          */
1185         cmd = para_strdup(receivers[0].name);
1186         FOR_EACH_AUDIO_FORMAT(i) {
1187                 a = &afi[i];
1188                 if (a->receiver_conf)
1189                         continue;
1190                 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1191                 if (!a->receiver_conf)
1192                         return -E_RECV_SYNTAX;
1193                 a->receiver = &receivers[receiver_num];
1194         }
1195         free(cmd);
1196         /* filters */
1197         filter_init(filters);
1198         nf = PARA_MAX(2,  conf.filter_given) + 1;
1199         PARA_INFO_LOG("allocating space for %d filters\n", nf);
1200         FOR_EACH_AUDIO_FORMAT(i) {
1201                 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
1202                 afi[i].filters = para_malloc(nf * sizeof(struct filter *));
1203         }
1204         if (!conf.no_default_filters_given)
1205                 return setup_default_filters();
1206         for (i = 0; i < conf.filter_given; i++) {
1207                 char *arg = conf.filter_arg[i];
1208                 char *filter_name = strchr(arg, ':');
1209                 ret = -E_MISSING_COLON;
1210                 if (!filter_name)
1211                         goto out;
1212                 *filter_name = '\0';
1213                 filter_name++;
1214                 ret = get_audio_format_num(arg);
1215                 if (ret < 0)
1216                         goto out;
1217                 ret = add_filter(ret, filter_name);
1218                 if (ret < 0)
1219                         goto out;
1220         }
1221         ret = 1;
1222 out:
1223         return ret;
1224 }
1225
1226 static int dump_commands(int fd)
1227 {
1228         char *buf = para_strdup(""), *tmp = NULL;
1229         int i;
1230         ssize_t ret;
1231
1232         FOR_EACH_COMMAND(i) {
1233                 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1234                         cmds[i].description);
1235                 free(buf);
1236                 buf = tmp;
1237         }
1238         ret = client_write(fd, buf);
1239         free(buf);
1240         return ret;
1241 }
1242
1243 /*
1244  * command handlers don't close their fd on errors (ret < 0) so that
1245  * its caller can send an error message. Otherwise (ret >= 0) it's up
1246  * to each individual command to close the fd if necessary.
1247  */
1248
1249 static int com_help(int fd, int argc, char **argv)
1250 {
1251         int i, ret;
1252         char *buf;
1253         const char *dflt = "No such command. Available commands:\n";
1254
1255         if (argc < 2) {
1256                 ret = dump_commands(fd);
1257                 goto out;
1258         }
1259         FOR_EACH_COMMAND(i) {
1260                 if (strcmp(cmds[i].name, argv[1]))
1261                         continue;
1262                 buf = make_message(
1263                         "NAME\n\t%s -- %s\n"
1264                         "SYNOPSIS\n\tpara_audioc %s\n"
1265                         "DESCRIPTION\n%s\n",
1266                         argv[1],
1267                         cmds[i].description,
1268                         cmds[i].synopsis,
1269                         cmds[i].help
1270                 );
1271                 ret = client_write(fd, buf);
1272                 free(buf);
1273                 goto out;
1274         }
1275         ret = client_write(fd, dflt);
1276         if (ret > 0)
1277                 ret = dump_commands(fd);
1278 out:
1279         if (ret >= 0)
1280                 close(fd);
1281         return ret;
1282 }
1283
1284 static int com_stat(int fd, __a_unused int argc, __a_unused char **argv)
1285 {
1286         int i, ret;
1287         char *buf = NULL;
1288         long unsigned mask = ~0LU;
1289
1290         if (argc > 1) {
1291                 mask = 0;
1292                 for (i = 1; i < argc; i++) {
1293                         ret = stat_item_valid(argv[i]);
1294                         if (ret < 0)
1295                                 return ret;
1296                         mask |= (1 << ret);
1297                 }
1298         }
1299         PARA_INFO_LOG("mask: 0x%lx\n", mask);
1300         if (mask & (1 << SI_PLAY_TIME)) {
1301                 struct timeval *t = wstime();
1302                 char *ts = get_time_string(t);
1303                 if (ts) {
1304                         ret = client_write(fd, ts);
1305                         if (ret < 0)
1306                                 goto out;
1307                         free(ts);
1308                 }
1309         }
1310         if (mask & (1 << SI_AUDIOD_UPTIME)) {
1311                 char *tmp, *us = uptime_str();
1312                 tmp = make_message("%s:%s\n",
1313                         status_item_list[SI_AUDIOD_UPTIME], us);
1314                 free(us);
1315                 ret = client_write(fd, tmp);
1316                 if (ret < 0)
1317                         goto out;
1318                 free(tmp);
1319         }
1320         if (mask & (1 << SI_AUDIOD_STATUS)) {
1321                 char *s = audiod_status_string();
1322                 ret = client_write(fd, s);
1323                 if (ret < 0)
1324                         goto out;
1325                 free(s);
1326         }
1327         if (mask & (1 << SI_DECODER_FLAGS)) {
1328                 char *df =decoder_flags();
1329                 ret = client_write(fd, df);
1330                 if (ret < 0)
1331                         goto out;
1332                 free(df);
1333         }
1334
1335         for (i = 0; i < NUM_STAT_ITEMS; i++) {
1336                 char *tmp, *v;
1337                 if (!((1 << i) & mask))
1338                         continue;
1339                 v = stat_item_values[i];
1340                 tmp = make_message("%s%s%s", buf? buf: "",
1341                         v? v : "", v? "\n" : "");
1342                 free(buf);
1343                 buf = tmp;
1344         }
1345         ret = client_write(fd, buf);
1346 out:
1347         if (ret > 0)
1348                 ret = stat_client_add(fd, mask);
1349         free(buf);
1350         return ret;
1351 }
1352
1353 #if 0
1354 static char *list_filters(void)
1355 {
1356         int i, j;
1357         char *tmp, *msg = make_message("format\tnum\tcmd\n");
1358
1359         FOR_EACH_AUDIO_FORMAT(i) {
1360                 for (j = 0; j < afi[i].num_filters; j++) {
1361                         tmp = make_message("%s\t%i\t%s\n",
1362                                 afi[i].name, j, afi[i].filter_cmds[j]);
1363                         msg = para_strcat(msg, tmp);
1364                         free(tmp);
1365                 }
1366                 tmp = make_message("%s\t%i\t%s\n", afi[i].name,
1367                         j, afi[i].write_cmd);
1368                 msg = para_strcat(msg, tmp);
1369                 free(tmp);
1370         }
1371         return msg;
1372 }
1373 #endif
1374
1375
1376 static int com_grab(int fd, char *cmdline)
1377 {
1378         struct grab_client *gc;
1379         struct filter_node *fn;
1380         int i, err;
1381         char *msg;
1382
1383         gc = grab_client_new(fd, cmdline, &err);
1384         if (!gc)
1385                 goto err_out;
1386         fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1387         if (fn)
1388                 activate_grab_client(gc, fn);
1389         return 1;
1390 err_out:
1391         if (err != -E_GC_HELP_GIVEN && err != -E_GC_VERSION_GIVEN)
1392                 return err;
1393         if (err == -E_GC_HELP_GIVEN) {
1394                 msg = make_message("%s\n\n", grab_client_args_info_usage);
1395                 for (i = 0; grab_client_args_info_help[i]; i++) {
1396                         char *tmp = make_message("%s%s\n", msg,
1397                                 grab_client_args_info_help[i]);
1398                         free(msg);
1399                         msg = tmp;
1400                 }
1401         } else
1402                 msg = make_message("%s %s\n",
1403                         GRAB_CLIENT_CMDLINE_PARSER_PACKAGE,
1404                         GRAB_CLIENT_CMDLINE_PARSER_VERSION);
1405         err = client_write(fd, msg);
1406         free(msg);
1407         if (err < 0)
1408                 return err;
1409         close(fd);
1410         return 1;
1411 }
1412
1413 static int __noreturn com_term(int fd, __a_unused int argc, __a_unused char **argv)
1414 {
1415         close(fd);
1416         clean_exit(EXIT_SUCCESS, "terminating on user request");
1417 }
1418
1419 static int com_on(int fd, __a_unused int argc, __a_unused char **argv)
1420 {
1421         audiod_status = AUDIOD_ON;
1422         close(fd);
1423         return 1;
1424 }
1425
1426 static int com_off(int fd, __a_unused int argc, __a_unused char **argv)
1427 {
1428         audiod_status = AUDIOD_OFF;
1429         close(fd);
1430         return 1;
1431 }
1432
1433 static int com_sb(int fd, __a_unused int argc, __a_unused char **argv)
1434 {
1435         audiod_status = AUDIOD_STANDBY;
1436         close(fd);
1437         return 1;
1438 }
1439
1440 static int com_cycle(int fd, int argc, char **argv)
1441 {
1442         switch (audiod_status) {
1443                 case  AUDIOD_ON:
1444                         return com_sb(fd, argc, argv);
1445                         break;
1446                 case  AUDIOD_OFF:
1447                         return com_on(fd, argc, argv);
1448                         break;
1449                 case  AUDIOD_STANDBY:
1450                         return com_off(fd, argc, argv);
1451                         break;
1452         }
1453         close(fd);
1454         return 1;
1455 }
1456
1457 static int check_perms(uid_t uid)
1458 {
1459         int i;
1460
1461         if (!conf.user_allow_given)
1462                 return 1;
1463         for (i = 0; i < conf.user_allow_given; i++)
1464                 if (uid == conf.user_allow_arg[i])
1465                         return 1;
1466         return -E_UCRED_PERM;
1467 }
1468
1469 static int handle_connect(void)
1470 {
1471         int i, argc, ret, clifd = -1;
1472         char *cmd = NULL, *p, *buf = para_calloc(MAXLINE), **argv = NULL;
1473         struct sockaddr_un unix_addr;
1474
1475         ret = para_accept(cmd_task->fd, &unix_addr, sizeof(struct sockaddr_un));
1476         if (ret < 0)
1477                 goto out;
1478         clifd = ret;
1479         ret = recv_cred_buffer(clifd, buf, MAXLINE - 1);
1480         if (ret < 0)
1481                 goto out;
1482         PARA_INFO_LOG("connection from user %i, buf: %s\n",  ret, buf);
1483         ret = check_perms(ret);
1484         if (ret < 0)
1485                 goto out;
1486         ret = -E_INVALID_AUDIOD_CMD;
1487         cmd = para_strdup(buf);
1488         p = strchr(cmd, '\n');
1489         if (!p)
1490                 p = "";
1491         else {
1492                 *p = '\0';
1493                 p++;
1494         }
1495         for (i = 0; cmds[i].name; i++) {
1496                 int j;
1497                 if (strcmp(cmds[i].name, cmd))
1498                         continue;
1499                 if (cmds[i].handler) {
1500                         argc = split_args(buf, &argv, "\n");
1501                         PARA_INFO_LOG("argv[0]: %s, argc= %d\n", argv[0], argc);
1502                         ret = cmds[i].handler(clifd, argc, argv);
1503                         goto out;
1504                 }
1505                 for (j = 0; p[j]; j++)
1506                         if (p[j] == '\n')
1507                                 p[j] = ' ';
1508                 PARA_INFO_LOG("cmd: %s, options: %s\n", cmd, p);
1509                 ret = cmds[i].line_handler(clifd, p);
1510                 goto out;
1511         }
1512         ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1513 out:
1514         free(cmd);
1515         free(buf);
1516         free(argv);
1517         if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1518                 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1519                 client_write(clifd, tmp);
1520                 free(tmp);
1521                 close(clifd);
1522         }
1523         return ret;
1524 }
1525
1526 static void audiod_get_socket(void)
1527 {
1528         struct sockaddr_un unix_addr;
1529
1530         if (conf.socket_given)
1531                 socket_name = para_strdup(conf.socket_arg);
1532         else {
1533                 char *hn = para_hostname();
1534                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1535                         hn);
1536                 free(hn);
1537         }
1538         PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1539         if (conf.force_given)
1540                 unlink(socket_name);
1541         cmd_task->fd = create_pf_socket(socket_name, &unix_addr,
1542                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1543         if (cmd_task->fd < 0) {
1544                 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1545                 exit(EXIT_FAILURE); /* do not unlink socket */
1546         }
1547         if (listen(cmd_task->fd , 5) < 0) {
1548                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1549                 exit(EXIT_FAILURE); /* do not unlink socket */
1550         }
1551         add_close_on_fork_list(cmd_task->fd);
1552 }
1553
1554 static int open_stat_pipe(void)
1555 {
1556         int ret, fd[3] = {-1, 1, 0};
1557         pid_t pid;
1558         ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1559         if (ret >= 0) {
1560                 ret = fd[1];
1561                 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1562                 add_close_on_fork_list(ret);
1563         } else
1564                 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1565         return ret;
1566 }
1567
1568 void signal_event_handler(struct task *t)
1569 {
1570         struct signal_task *st = t->private_data;
1571         handle_signal(st->signum);
1572 }
1573
1574 void signal_pre_select(struct sched *s, struct task *t)
1575 {
1576         struct signal_task *st = t->private_data;
1577         t->ret = 1;
1578         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1579 }
1580
1581 void signal_post_select(struct sched *s, struct task *t)
1582 {
1583         struct signal_task *st = t->private_data;
1584         t->ret = 1;
1585         if (!FD_ISSET(st->fd, &s->rfds))
1586                 return;
1587         t->ret = -E_SIGNAL_CAUGHT;
1588         st->signum = para_next_signal();
1589 }
1590
1591 void signal_setup_default(struct signal_task *st)
1592 {
1593         st->task.pre_select = signal_pre_select;
1594         st->task.post_select = signal_post_select;
1595         st->task.private_data = st;
1596         st->task.flags = 0;
1597         sprintf(st->task.status, "signal task");
1598 }
1599
1600 static void command_pre_select(struct sched *s, struct task *t)
1601 {
1602         struct command_task *ct = t->private_data;
1603         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
1604
1605 }
1606
1607 static void command_post_select(struct sched *s, struct task *t)
1608 {
1609         int ret;
1610         struct command_task *ct = t->private_data;
1611
1612         if (audiod_status != AUDIOD_OFF)
1613                 audiod_status_dump();
1614         t->ret = 1; /* always successful */
1615         if (!FD_ISSET(ct->fd, &s->rfds))
1616                 return;
1617         ret = handle_connect();
1618         if (ret < 0)
1619                 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1620 }
1621
1622 void init_command_task(struct command_task *ct)
1623 {
1624         ct->task.pre_select = command_pre_select;
1625         ct->task.post_select = command_post_select;
1626         ct->task.private_data = ct;
1627         ct->task.flags = 0;
1628         sprintf(ct->task.status, "command task");
1629 }
1630
1631 static void status_pre_select(struct sched *s, struct task *t)
1632 {
1633         struct status_task *st = t->private_data;
1634         t->ret = 1;
1635         if (st->fd >= 0 && audiod_status == AUDIOD_OFF)
1636                 close_stat_pipe();
1637         if (st->fd < 0 && audiod_status != AUDIOD_OFF) {
1638                 st->fd = open_stat_pipe();
1639                 st->loaded = 0;
1640                 st->buf[0] = '\0';
1641         }
1642         if (st->fd >= 0 && audiod_status != AUDIOD_OFF)
1643                 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1644 }
1645
1646 static void status_post_select(struct sched *s, struct task *t)
1647 {
1648         struct status_task *st = t->private_data;
1649         int ret;
1650
1651         t->ret = 1;
1652         if (st->fd < 0 || !FD_ISSET(st->fd, &s->rfds))
1653                 return;
1654         ret = read(st->fd, st->buf + st->loaded,
1655                 STRINGSIZE - 1 - st->loaded);
1656         if (ret <= 0) {
1657                 close_stat_pipe();
1658                 /* avoid busy loop if server is down */
1659                 while (sleep(1) > 0)
1660                         ; /* try again*/
1661         } else {
1662                 st->buf[ret + st->loaded] = '\0';
1663                 st->loaded = for_each_line(st->buf, ret + st->loaded,
1664                         &check_stat_line);
1665         }
1666 }
1667
1668 static void init_status_task(struct status_task *st)
1669 {
1670         st->task.pre_select = status_pre_select;
1671         st->task.post_select = status_post_select;
1672         st->task.private_data = st;
1673         st->task.flags = 0;
1674         st->loaded = 0;
1675         st->fd = -1;
1676         st->buf[0] = '\0';
1677         sprintf(st->task.status, "status task");
1678 }
1679
1680
1681
1682 #if 0
1683 /* TODO: move everything before the select call to pre_select() */
1684 static void __noreturn audiod_mainloop(void)
1685 {
1686         fd_set rfds, wfds;
1687         int ret, max_fileno, sbo = 0;
1688         char status_buf[STRINGSIZE] = "";
1689         struct timeval tv;
1690
1691
1692
1693 repeat:
1694         FD_ZERO(&wfds);
1695         FD_ZERO(&rfds);
1696         max_fileno = -1;
1697         /* always check signal pipe and the local socket */
1698         para_fd_set(signal_pipe, &rfds, &max_fileno);
1699         para_fd_set(audiod_socket, &rfds, &max_fileno);
1700
1701         if (audiod_status != AUDIOD_ON)
1702                 kill_all_decoders();
1703         else if (playing)
1704                 start_current_receiver();
1705
1706         set_stream_fds(&wfds, &max_fileno);
1707         /* status pipe */
1708         if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1709                 close_stat_pipe();
1710         if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1711                 stat_pipe = open_stat_pipe();
1712                 sbo = 0;
1713                 status_buf[0] = '\0';
1714         }
1715         if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF)
1716                 para_fd_set(stat_pipe, &rfds, &max_fileno);
1717         /* local socket */
1718         tv.tv_sec = 0;
1719         tv.tv_usec = 200 * 1000;
1720         audiod_pre_select(&rfds, &wfds, &tv, &max_fileno);
1721         ret = para_select(max_fileno + 1, &rfds, &wfds, &tv);
1722         if (ret < 0)
1723                 goto repeat;
1724         if (audiod_status != AUDIOD_OFF)
1725                 audiod_status_dump();
1726         audiod_post_select(ret, &rfds, &wfds);
1727         /* read status pipe */
1728         if (stat_pipe >=0 && FD_ISSET(stat_pipe, &rfds)) {
1729                 ret = read(stat_pipe, status_buf + sbo, STRINGSIZE - 1 - sbo);
1730                 if (ret <= 0) {
1731                         close_stat_pipe();
1732                         /* avoid busy loop if server is down */
1733                         while (sleep(1) > 0)
1734                                 ; /* try again*/
1735                 } else {
1736                         status_buf[ret + sbo] = '\0';
1737                         sbo = for_each_line(status_buf, ret + sbo,
1738                                 &check_stat_line);
1739                 }
1740         }
1741         slot_io(&wfds);
1742         if (FD_ISSET(audiod_socket, &rfds)) {
1743                 ret = handle_connect();
1744                 if (ret < 0) {
1745                         PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1746                 }
1747         }
1748         /* signals */
1749         if (FD_ISSET(signal_pipe, &rfds)) {
1750                 int sig_nr = para_next_signal();
1751                 if (sig_nr > 0)
1752                         handle_signal(sig_nr);
1753         }
1754         goto repeat;
1755 }
1756 #endif
1757
1758 static void set_initial_status(void)
1759 {
1760         audiod_status = AUDIOD_ON;
1761         if (!conf.mode_given)
1762                 return;
1763         if (!strcmp(conf.mode_arg, "sb")) {
1764                 audiod_status = AUDIOD_STANDBY;
1765                 return;
1766         }
1767         if (!strcmp(conf.mode_arg, "off")) {
1768                 audiod_status = AUDIOD_OFF;
1769                 return;
1770         }
1771         if (strcmp(conf.mode_arg, "on"))
1772                 PARA_WARNING_LOG("%s", "invalid mode\n");
1773 }
1774
1775 int main(int argc, char *argv[])
1776 {
1777         char *cf;
1778         int ret, i;
1779         struct sched s;
1780
1781         init_sched();
1782
1783         valid_fd_012();
1784         hostname = para_hostname();
1785         cmdline_parser(argc, argv, &conf);
1786         para_drop_privileges(conf.user_arg, conf.group_arg);
1787         cf = configfile_exists();
1788         if (cf) {
1789                 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1790                         PARA_EMERG_LOG("%s", "parse error in config file\n");
1791                         exit(EXIT_FAILURE);
1792                 }
1793         }
1794         if (conf.logfile_given)
1795                 logfile = open_log(conf.logfile_arg);
1796         log_welcome("para_audiod", conf.loglevel_arg);
1797         i = init_stream_io();
1798         if (i < 0) {
1799                 PARA_EMERG_LOG("init stream io error: %s\n", PARA_STRERROR(-i));
1800                 exit(EXIT_FAILURE);
1801         }
1802 //      return 0;
1803         server_uptime(UPTIME_SET);
1804         set_initial_status();
1805         FOR_EACH_SLOT(i)
1806                 clear_slot(i);
1807         init_grabbing();
1808         setup_signal_handling();
1809         if (conf.daemon_given)
1810                 daemon_init();
1811         audiod_get_socket(); /* doesn't return on errors */
1812
1813         signal_setup_default(sig_task);
1814         sig_task->task.event_handler = signal_event_handler;
1815
1816         init_status_task(stat_task);
1817         init_command_task(cmd_task);
1818         init_audiod_task(at);
1819
1820         register_task(&sig_task->task);
1821         register_task(&cmd_task->task);
1822         register_task(&stat_task->task);
1823         register_task(&at->task);
1824         s.default_timeout.tv_sec = 0;
1825         s.default_timeout.tv_usec = 99 * 1000;
1826         ret = sched(&s);
1827
1828         PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
1829         return EXIT_FAILURE;
1830 }