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