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