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