]> git.tuebingen.mpg.de Git - paraslash.git/blob - audiod.c
audiod: use set_restart_barrier() instead of duplicating it.
[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 set_restart_barrier(int format, struct timeval *now)
452 {
453         struct timeval tmp;
454
455         if (now)
456                 tmp = *now;
457         else
458                 gettimeofday(&tmp, NULL);
459         tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
460 }
461
462 static void close_receiver(int slot_num)
463 {
464         struct slot_info *s = &slot[slot_num];
465         struct audio_format_info *a;
466         struct timeval now;
467
468         if (s->format < 0 || !s->receiver_node)
469                 return;
470         a = &afi[s->format];
471         PARA_NOTICE_LOG("closing %s recevier in slot %d\n",
472                 audio_formats[s->format] , slot_num);
473         a->receiver->close(s->receiver_node);
474         free(s->receiver_node);
475         s->receiver_node = NULL;
476         set_restart_barrier(s->format, NULL);
477 }
478
479 static void kill_all_decoders(void)
480 {
481         int i;
482
483         FOR_EACH_SLOT(i)
484                 if (slot[i].format >= 0) {
485                         PARA_INFO_LOG("stopping decoder in slot %d\n", i);
486                         kill_stream_writer(i);
487                 }
488 }
489
490 static void check_sigchld(void)
491 {
492         pid_t pid;
493         int i;
494         struct timeval now;
495         gettimeofday(&now, NULL);
496
497 reap_next_child:
498         pid = para_reap_child();
499         if (pid <= 0)
500                 return;
501         FOR_EACH_SLOT(i) {
502                 struct slot_info *s = &slot[i];
503                 long lifetime;
504                 if (s->format < 0)
505                         continue;
506                 if (pid == s->wpid) {
507                         s->wpid = -1;
508                         lifetime = now.tv_sec - s->wstime.tv_sec;
509                         PARA_INFO_LOG("%s stream writer in slot %d died "
510                                 "after %li secs\n",
511                                 audio_formats[s->format], i, lifetime);
512                         set_restart_barrier(s->format, &now);
513                         goto reap_next_child;
514                 }
515         }
516         PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
517         goto reap_next_child;
518 }
519
520 static int get_empty_slot(void)
521 {
522         int i;
523         struct slot_info *s;
524
525         FOR_EACH_SLOT(i) {
526                 s = &slot[i];
527                 if (s->format < 0) {
528                         clear_slot(i);
529                         return i;
530                 }
531                 if (s->write_fd > 0 || s->wpid > 0)
532                         continue;
533                 if (s->receiver_node)
534                         continue;
535                 if (s->fci)
536                         continue;
537                 clear_slot(i);
538                 return i;
539         }
540         return -E_NO_MORE_SLOTS;
541 }
542
543 static int decoder_running(int format)
544 {
545         int i, ret = 0;
546         struct slot_info *s;
547
548         FOR_EACH_SLOT(i) {
549                 s = &slot[i];
550                 if (s->format == format && s->receiver_node)
551                         ret |= 1;
552                 if (s->format == format && s->wpid > 0)
553                         ret |= 2;
554         }
555         return ret;
556 }
557
558 static void close_stat_pipe(void)
559 {
560         char *msg;
561         int i;
562
563         if (stat_pipe < 0)
564                 return;
565         PARA_NOTICE_LOG("%s", "closing status pipe\n");
566         close(stat_pipe);
567         del_close_on_fork_list(stat_pipe);
568         stat_pipe = -1;
569         kill_all_decoders();
570         for (i = 0; i < RINGBUFFER_SIZE; i++)
571                 free(ringbuffer_add(stat_item_ringbuf, para_strdup(NULL)));
572         dump_empty_status();
573         length_seconds = 0;
574         offset_seconds = 0;
575         audiod_status_dump();
576         playing = 0;
577         msg = make_message("%s:no connection to para_server\n",
578                 status_item_list[SI_STATUS_BAR]);
579         free(ringbuffer_add(stat_item_ringbuf, msg));
580         stat_client_write(msg);
581 }
582
583 static void __noreturn clean_exit(int status, const char *msg)
584 {
585         PARA_EMERG_LOG("%s\n", msg);
586         kill_all_decoders();
587         if (socket_name)
588                 unlink(socket_name);
589         if (stat_pipe >= 0)
590                 close_stat_pipe();
591         exit(status);
592 }
593
594 static char *glob_cmd(char *cmd)
595 {
596         char *ret, *replacement;
597         struct timeval tmp, delay, rss; /* real stream start */
598
599         delay.tv_sec = conf.stream_delay_arg / 1000;
600         delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
601 //      PARA_INFO_LOG("delay: %lu:%lu\n", delay.tv_sec, delay.tv_usec);
602         if (sa_time_diff_sign < 0)
603                 tv_add(&server_stream_start, &sa_time_diff, &rss);
604         else
605                 tv_diff(&server_stream_start, &sa_time_diff, &rss);
606         tv_add(&rss, &delay, &tmp);
607         replacement = make_message("%lu:%lu", tmp.tv_sec, tmp.tv_usec);
608         ret = s_a_r(cmd, "STREAM_START", replacement);
609         free(replacement);
610         if (!ret)
611                 goto out;
612         PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
613         {
614         struct timeval now;
615         gettimeofday(&now, NULL);
616         PARA_INFO_LOG("now: %lu:%lu\n", now.tv_sec, now.tv_usec);
617         }
618 out:
619         return ret;
620 }
621
622 /** get the number of filters for the given audio format */
623 int num_filters(int audio_format_num)
624 {
625         return afi[audio_format_num].num_filters;
626 }
627
628 static void open_filters(int slot_num)
629 {
630         struct slot_info *s = &slot[slot_num];
631         struct audio_format_info *a = &afi[s->format];
632         int nf = a->num_filters;
633         int i;
634
635         s->fci = para_calloc(sizeof(struct filter_chain_info));
636         INIT_LIST_HEAD(&s->fci->filters);
637         if (!nf)
638                 return;
639         s->fci->inbuf = s->receiver_node->buf;
640         s->fci->in_loaded = &s->receiver_node->loaded;
641         s->fci->outbuf = s->receiver_node->buf;
642         s->fci->out_loaded = &s->receiver_node->loaded;
643         s->fci->eof = &s->receiver_node->eof;
644         for (i = 0; i < nf; i++) {
645                 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
646                 fn->conf = a->filter_conf[i];
647                 fn->fci = s->fci;
648                 fn->filter = a->filters[i];
649                 INIT_LIST_HEAD(&fn->callbacks);
650                 list_add_tail(&fn->node, &s->fci->filters);
651                 fn->filter->open(fn);
652                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
653                         audio_formats[s->format], i + 1,  nf,
654                         fn->filter->name, slot_num);
655                 s->fci->outbuf = fn->buf;
656                 s->fci->out_loaded = &fn->loaded;
657         }
658         PARA_DEBUG_LOG("output buffer for filter chain %p: %p\n", s->fci,
659                 s->fci->outbuf);
660 }
661
662 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
663 {
664         struct filter_node *fn;
665         int i, j;
666
667         FOR_EACH_SLOT(i) {
668                 struct slot_info *s = &slot[i];
669                 if (s->format < 0 || !s->fci)
670                         continue;
671                 if (slot_num >= 0 && slot_num != i)
672                         continue;
673                 if (format >= 0 && s->format != format)
674                         continue;
675                 if (num_filters(i) < filternum)
676                         continue;
677                 /* success */
678                 j = 1;
679                 list_for_each_entry(fn, &s->fci->filters, node)
680                         if (filternum <= 0 || j++ == filternum)
681                                 break;
682                 return fn;
683         }
684         return NULL;
685 }
686
687 static void start_stream_writer(int slot_num)
688 {
689         int ret, fds[3] = {1, -1, -1};
690         struct slot_info *s = &slot[slot_num];
691         struct audio_format_info *a = &afi[s->format];
692         char *glob = glob_cmd(a->write_cmd);
693
694         PARA_INFO_LOG("starting stream writer: %s\n", glob? glob : a->write_cmd);
695         open_filters(slot_num);
696
697         ret = para_exec_cmdline_pid(&s->wpid, glob? glob : a->write_cmd, fds);
698         free(glob);
699         if (ret < 0) {
700                 PARA_ERROR_LOG("exec failed (%d)\n", ret);
701                 return;
702         }
703         s->write_fd = fds[0];
704         add_close_on_fork_list(s->write_fd);
705         /* we write to this fd in do_select, so we need non-blocking */
706         fcntl(s->write_fd, F_SETFL, O_NONBLOCK);
707         gettimeofday(&s->wstime, NULL);
708         current_decoder = slot_num;
709         activate_inactive_grab_clients(slot_num, s->format, &s->fci->filters);
710 }
711
712 static void open_receiver(int format)
713 {
714         struct audio_format_info *a = &afi[format];
715         struct slot_info *s;
716         int ret, slot_num;
717
718         slot_num = get_empty_slot();
719         if (slot_num < 0)
720                 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
721         s = &slot[slot_num];
722         s->format = format;
723         gettimeofday(&s->rtime, NULL);
724         s->wtime = s->rtime;
725         s->receiver_node = para_calloc(sizeof(struct receiver_node));
726         s->receiver_node->conf = a->receiver_conf;
727         ret = a->receiver->open(s->receiver_node);
728         if (ret < 0) {
729                 PARA_ERROR_LOG("failed to open receiver (%s)\n",
730                         PARA_STRERROR(-ret));
731                 free(s->receiver_node);
732                 s->receiver_node = NULL;
733                 return;
734         }
735         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
736                 audio_formats[s->format], a->receiver->name, slot_num);
737 }
738
739 static int is_frozen(int format)
740 {
741         struct timeval now;
742         struct audio_format_info *a = &afi[format];
743
744         gettimeofday(&now, NULL);
745         return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
746 }
747
748 static void start_current_receiver(void)
749 {
750         int i;
751
752         if (!af_status)
753                 return;
754         i = get_audio_format_num(af_status);
755         if (i < 0)
756                 return;
757         if ((decoder_running(i) & 1) || is_frozen(i))
758                 return;
759         open_receiver(i);
760 }
761
762 static void compute_time_diff(const struct timeval *status_time)
763 {
764         struct timeval now, tmp, diff;
765         static int count;
766         int sign;
767         const struct timeval max_deviation = {0, 500 * 1000};
768         const int time_smooth = 5;
769
770         gettimeofday(&now, NULL);
771         sign = tv_diff(status_time, &now, &diff);
772 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
773 //                      sign, sa_time_diff_sign);
774         if (!count) {
775                 sa_time_diff_sign = sign;
776                 sa_time_diff = diff;
777                 count++;
778                 return;
779         }
780         if (count > 5) {
781                 int s = tv_diff(&diff, &sa_time_diff, &tmp);
782                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
783                         PARA_WARNING_LOG("time diff jump: %lims\n",
784                                 s * tv2ms(&tmp));
785         }
786         count++;
787         sa_time_diff_sign = tv_convex_combination(
788                 sa_time_diff_sign * time_smooth, &sa_time_diff,
789                 count > 10? sign : sign * time_smooth, &diff,
790                 &tmp);
791         sa_time_diff = tmp;
792         PARA_INFO_LOG("time diff (cur/avg): "
793                 "%li:%lu/%li:%lu\n",
794                 sign * diff.tv_sec, (diff.tv_usec + 500) / 1000,
795                 sa_time_diff_sign * sa_time_diff.tv_sec,
796                 (sa_time_diff.tv_usec + 500)/ 1000);
797 }
798
799 static void check_stat_line(char *line)
800 {
801         int itemnum;
802         size_t ilen = 0;
803         struct timeval tv;
804
805         if (!line)
806                 return;
807         free(ringbuffer_add(stat_item_ringbuf, para_strdup(line)));
808         stat_client_write(line);
809         itemnum = stat_line_valid(line);
810         if (itemnum < 0)
811                 return;
812         ilen = strlen(status_item_list[itemnum]);
813         switch (itemnum) {
814         case SI_STATUS:
815                 playing = strstr(line, "playing")? 1 : 0;
816                 break;
817         case SI_FORMAT:
818                 free(af_status);
819                 af_status = para_strdup(line + ilen + 1);
820                 break;
821         case SI_OFFSET:
822                 offset_seconds = atoi(line + ilen + 1);
823                 break;
824         case SI_LENGTH:
825                 length_seconds = atoi(line + ilen + 1);
826                 break;
827         case SI_STREAM_START:
828                 if (sscanf(line + ilen + 1, "%lu.%lu",
829                                 &tv.tv_sec, &tv.tv_usec) == 2)
830                         server_stream_start = tv;
831                 break;
832         case SI_CURRENT_TIME:
833                 if (sscanf(line + ilen + 1, "%lu.%lu", &tv.tv_sec,
834                                 &tv.tv_usec) == 2)
835                         compute_time_diff(&tv);
836                 break;
837         }
838 }
839
840 static void handle_signal(int sig)
841 {
842         switch (sig) {
843         case SIGCHLD:
844                 return check_sigchld();
845         case SIGINT:
846         case SIGTERM:
847         case SIGHUP:
848                 PARA_EMERG_LOG("terminating on signal %d\n", sig);
849                 clean_exit(EXIT_FAILURE, "caught deadly signal");
850                 return;
851         }
852 }
853
854 static void check_timeouts(void)
855 {
856         struct timeval now;
857         int slot_num, timeout = conf.stream_timeout_arg;
858
859         gettimeofday(&now, NULL);
860         FOR_EACH_SLOT(slot_num) {
861                 struct slot_info *s = &slot[slot_num];
862                 if (s->format < 0)
863                         continue;
864                 /* check read time */
865                 if (s->receiver_node &&
866                         now.tv_sec > s->rtime.tv_sec + timeout) {
867                         PARA_INFO_LOG("%s input buffer (slot %d) not ready\n",
868                                 audio_formats[s->format], slot_num);
869                         if (s->fci)
870                                 s->fci->error = 42;
871                         else
872                                 close_receiver(slot_num);
873                 }
874                 /* check write time */
875                 if (s->wpid > 0 && !s->wkilled &&
876                         now.tv_sec > s->wtime.tv_sec + timeout) {
877                         PARA_INFO_LOG("%s output buffer (slot %d) not ready\n",
878                                 audio_formats[s->format], slot_num);
879                         if (s->fci)
880                                 s->fci->error = 42;
881                 }
882         }
883 }
884
885 static size_t get_loaded_bytes(int slot_num)
886 {
887         size_t loaded = 0;
888         struct slot_info *s = &slot[slot_num];
889         struct receiver_node *rn = s->receiver_node;
890
891         if (s->format < 0)
892                 goto out;
893
894         if (afi[s->format].num_filters) {
895                 if (s->fci)
896                         loaded = *s->fci->out_loaded;
897         } else {
898                 if (rn)
899                         loaded = rn->loaded;
900         }
901 out:
902         return loaded;
903 }
904
905
906 static void close_decoder_if_idle(int slot_num)
907 {
908         struct slot_info *s = &slot[slot_num];
909         struct receiver_node *rn = s->receiver_node;
910
911         if (s->format < 0)
912                 return;
913         if (!s->fci)
914                 return;
915         if (!rn->eof && !s->fci->error && s->wpid > 0)
916                 return;
917         if (!s->fci->error && s->wpid > 0) { /* eof */
918                 if (filter_io(s->fci) > 0)
919                         return;
920                 if (get_loaded_bytes(slot_num))
921                         return;
922         }
923         if (s->write_fd > 0) {
924                 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
925                         s->write_fd);
926                 close(s->write_fd);
927                 del_close_on_fork_list(s->write_fd);
928                 s->write_fd = -1;
929         }
930         if (s->wpid > 0)
931                 return; /* wait until writer dies before closing filters */
932         PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
933                 slot_num, s->fci);
934         close_filters(s->fci);
935         free(s->fci);
936         close_receiver(slot_num);
937         clear_slot(slot_num);
938 }
939
940 static int set_stream_fds(fd_set *wfds)
941 {
942         int i, max_fileno = -1;
943
944         check_timeouts();
945         FOR_EACH_SLOT(i) {
946                 struct slot_info *s = &slot[i];
947                 struct audio_format_info *a;
948                 struct receiver_node *rn;
949
950                 close_decoder_if_idle(i);
951                 s->wcheck = 0;
952                 if (s->format < 0)
953                         continue;
954                 a = &afi[s->format];
955                 rn = s->receiver_node;
956                 if (rn && rn->loaded && !s->wpid) {
957                         PARA_INFO_LOG("no writer in slot %d\n", i);
958                         start_stream_writer(i);
959                 }
960                 if (s->write_fd <= 0)
961                         continue;
962                 if (!get_loaded_bytes(i))
963                         continue;
964                 FD_SET(s->write_fd, wfds);
965                 s->wcheck = 1;
966                 max_fileno = MAX(s->write_fd, max_fileno);
967         }
968 //      PARA_INFO_LOG("return %d\n", max_fileno);
969         return max_fileno;
970 }
971
972 static int write_audio_data(int slot_num)
973 {
974         struct slot_info *s = &slot[slot_num];
975         struct audio_format_info *a = &afi[s->format];
976         struct receiver_node *rn = s->receiver_node;
977         int rv;
978         char **buf;
979         size_t *len;
980
981         if (a->num_filters) {
982                 buf = &s->fci->outbuf;
983                 len = s->fci->out_loaded;
984         } else {
985                 buf = &rn->buf;
986                 len = &rn->loaded;
987         }
988         PARA_DEBUG_LOG("writing %p (%zd bytes)\n", *buf, *len);
989         rv = write(s->write_fd, *buf, *len);
990         PARA_DEBUG_LOG("wrote %d/%zd\n", rv, *len);
991         if (rv < 0) {
992                 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
993                         slot_num, s->write_fd, strerror(errno));
994                 *len = 0;
995                 s->fci->error = E_WRITE_AUDIO_DATA;
996         } else if (rv != *len) {
997                 PARA_DEBUG_LOG("partial %s write (%i/%zd) for slot %d\n",
998                         audio_formats[s->format], rv, *len, slot_num);
999                 *len -= rv;
1000                 memmove(*buf, *buf + rv, *len);
1001         } else
1002                 *len = 0;
1003         if (rv > 0)
1004                 gettimeofday(&s->wtime, NULL);
1005         return rv;
1006 }
1007
1008 static void slot_io(fd_set *wfds)
1009 {
1010         int ret, i;
1011
1012         FOR_EACH_SLOT(i) {
1013                 struct slot_info *s = &slot[i];
1014                 struct receiver_node *rn = s->receiver_node;
1015
1016                 if (rn && rn->loaded)
1017                         gettimeofday(&s->rtime, NULL);
1018                 if (s->format >= 0 && s->write_fd > 0 && s->fci) {
1019                         ret = filter_io(s->fci);
1020                         if (ret < 0)
1021                                 s->fci->error = -ret;
1022 //                      PARA_DEBUG_LOG("slot %d, filter io %d bytes, check write: %d, loaded: %d/%d, eof: %d\n",
1023 //                               i, ret, s->wcheck, rn->loaded, *s->fci->out_loaded, rn->eof);
1024                 }
1025                 if (s->write_fd <= 0 || !s->wcheck || !FD_ISSET(s->write_fd, wfds))
1026                         continue;
1027                 write_audio_data(i);
1028         }
1029 }
1030
1031 static int parse_stream_command(const char *txt, char **cmd)
1032 {
1033         char *p = strchr(txt, ':');
1034         int i;
1035
1036         if (!p)
1037                 return -E_MISSING_COLON;
1038         p++;
1039         FOR_EACH_AUDIO_FORMAT(i) {
1040                 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1041                         continue;
1042                 *cmd = p;
1043                 return i;
1044         }
1045         return -E_UNSUPPORTED_AUDIO_FORMAT;
1046 }
1047
1048 static int add_filter(int format, char *cmdline)
1049 {
1050         struct audio_format_info *a = &afi[format];
1051         int filter_num, nf = a->num_filters;
1052
1053         filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1054         if (filter_num < 0)
1055                 return filter_num;
1056         a->filters[nf] = &filters[filter_num];
1057         a->num_filters++;
1058         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1059                 a->filters[nf]->name);
1060         return filter_num;
1061 }
1062
1063 static int setup_default_filters(void)
1064 {
1065         int i, ret = 1;
1066
1067         FOR_EACH_AUDIO_FORMAT(i) {
1068                 struct audio_format_info *a = &afi[i];
1069                 char *tmp;
1070                 int j;
1071                 if (a->num_filters)
1072                         continue;
1073                 /* add "dec" to audio format name */
1074                 tmp = make_message("%sdec", audio_formats[i]);
1075                 for (j = 0; filters[j].name; j++)
1076                         if (!strcmp(tmp, filters[j].name))
1077                                 break;
1078                 free(tmp);
1079                 ret = -E_UNSUPPORTED_FILTER;
1080                 if (!filters[j].name)
1081                         goto out;
1082                 tmp = para_strdup(filters[j].name);
1083                 ret = add_filter(i, tmp);
1084                 free(tmp);
1085                 if (ret < 0)
1086                         goto out;
1087                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i], filters[j].name);
1088                 ret = add_filter(i, "wav");
1089                 if (ret < 0)
1090                         goto out;
1091                 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1092         }
1093 out:
1094         return ret;
1095 }
1096
1097 static int init_stream_io(void)
1098 {
1099         int i, ret, receiver_num;
1100         char *cmd;
1101
1102         for (i = 0; i < conf.stream_write_cmd_given; i++) {
1103                 ret = parse_stream_command(conf.stream_write_cmd_arg[i], &cmd);
1104                 if (ret < 0)
1105                         goto out;
1106                 afi[ret].write_cmd = para_strdup(cmd);
1107                 PARA_INFO_LOG("%s write command: %s\n", audio_formats[ret], afi[ret].write_cmd);
1108         }
1109         for (i = 0; receivers[i].name; i++) {
1110                 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1111                 receivers[i].init(&receivers[i]);
1112         }
1113         for (i = 0; i < conf.receiver_given; i++) {
1114                 char *arg = conf.receiver_arg[i];
1115                 char *recv = strchr(arg, ':');
1116                 ret = -E_MISSING_COLON;
1117                 if (!recv)
1118                         goto out;
1119                 *recv = '\0';
1120                 recv++;
1121                 ret = get_audio_format_num(arg);
1122                 if (ret < 0)
1123                         goto out;
1124                 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1125                 if (!afi[ret].receiver_conf) {
1126                         ret = -E_RECV_SYNTAX;
1127                         goto out;
1128                 }
1129                 afi[ret].receiver = &receivers[receiver_num];
1130         }
1131         /* use the first available receiver with no arguments
1132          * for those audio formats for which no receiver
1133          * was specified
1134          */
1135         cmd = para_strdup(receivers[0].name);
1136         FOR_EACH_AUDIO_FORMAT(i) {
1137                 struct audio_format_info *a = &afi[i];
1138                 if (a->receiver_conf)
1139                         continue;
1140                 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1141                 if (!a->receiver_conf)
1142                         return -E_RECV_SYNTAX;
1143                 a->receiver = &receivers[receiver_num];
1144         }
1145         free(cmd);
1146         /* filters */
1147         filter_init(filters);
1148         FOR_EACH_AUDIO_FORMAT(i) {
1149                 afi[i].filter_conf = para_malloc((conf.filter_given + 1) * sizeof(char *));
1150                 afi[i].filters = para_malloc((conf.filter_given + 1) * sizeof(struct filter *));
1151         }
1152         if (!conf.no_default_filters_given)
1153                 return setup_default_filters();
1154         for (i = 0; i < conf.filter_given; i++) {
1155                 char *arg = conf.filter_arg[i];
1156                 char *filter_name = strchr(arg, ':');
1157                 ret = -E_MISSING_COLON;
1158                 if (!filter_name)
1159                         goto out;
1160                 *filter_name = '\0';
1161                 filter_name++;
1162                 ret = get_audio_format_num(arg);
1163                 if (ret < 0)
1164                         goto out;
1165                 ret = add_filter(ret, filter_name);
1166                 if (ret < 0)
1167                         goto out;
1168         }
1169         ret = 1;
1170 out:
1171         return ret;
1172 }
1173
1174 static int dump_commands(int fd)
1175 {
1176         char *buf = para_strdup(""), *tmp = NULL;
1177         int i;
1178         ssize_t ret;
1179
1180         FOR_EACH_COMMAND(i) {
1181                 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1182                         cmds[i].description);
1183                 free(buf);
1184                 buf = tmp;
1185         }
1186         ret = client_write(fd, buf);
1187         free(buf);
1188         return ret;
1189 }
1190
1191 /*
1192  * command handlers don't close their fd on errors (ret < 0) so that
1193  * its caller can send an error message. Otherwise (ret >= 0) it's up
1194  * to each individual command to close the fd if necessary.  
1195  */
1196
1197 static int com_help(int fd, int argc, char **argv)
1198 {
1199         int i, ret;
1200         char *buf;
1201         const char *dflt = "No such command. Available commands:\n";
1202
1203         if (argc < 2) {
1204                 ret = dump_commands(fd);
1205                 goto out;
1206         }
1207         FOR_EACH_COMMAND(i) {
1208                 if (strcmp(cmds[i].name, argv[1]))
1209                         continue;
1210                 buf = make_message(
1211                         "NAME\n\t%s -- %s\n"
1212                         "SYNOPSIS\n\tpara_audioc %s\n"
1213                         "DESCRIPTION\n%s\n",
1214                         argv[1],
1215                         cmds[i].description,
1216                         cmds[i].synopsis,
1217                         cmds[i].help
1218                 );
1219                 ret = client_write(fd, buf);
1220                 free(buf);
1221                 goto out;
1222         }
1223         ret = client_write(fd, dflt);
1224         if (ret > 0)
1225                 ret = dump_commands(fd);
1226 out:
1227         if (ret >= 0)
1228                 close(fd);
1229         return ret;
1230 }
1231
1232 static int com_stat(int fd, __unused int argc, __unused char **argv)
1233 {
1234         int i, ret;
1235         char *buf = audiod_status_string();
1236
1237         buf = para_strcat(buf, "\n");
1238         for (i = RINGBUFFER_SIZE - 1; i >= 0; i--) {
1239                 char *tmp, *line = ringbuffer_get(stat_item_ringbuf, i);
1240                 if (!line)
1241                         continue;
1242                 tmp = make_message("%s\n", line);
1243                 buf = para_strcat(buf, tmp);
1244                 free(tmp);
1245         }
1246         ret = client_write(fd, buf);
1247         if (ret > 0)
1248                 ret = stat_client_add(fd);
1249         free(buf);
1250         return ret;
1251 }
1252
1253 #if 0
1254 static char *list_filters(void)
1255 {
1256         int i, j;
1257         char *tmp, *msg = make_message("format\tnum\tcmd\n");
1258
1259         FOR_EACH_AUDIO_FORMAT(i) {
1260                 for (j = 0; j < afi[i].num_filters; j++) {
1261                         tmp = make_message("%s\t%i\t%s\n",
1262                                 afi[i].name, j, afi[i].filter_cmds[j]);
1263                         msg = para_strcat(msg, tmp);
1264                         free(tmp);
1265                 }
1266                 tmp = make_message("%s\t%i\t%s\n", afi[i].name,
1267                         j, afi[i].write_cmd);
1268                 msg = para_strcat(msg, tmp);
1269                 free(tmp);
1270         }
1271         return msg;
1272 }
1273 #endif
1274
1275 static int com_grab(int fd, int argc, char **argv)
1276 {
1277         struct grab_client *gc;
1278         struct filter_node *fn;
1279         int err;
1280
1281         PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1282         gc = grab_client_new(fd, argc, argv, &err);
1283         PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1284         if (!gc)
1285                 goto err_out;
1286         fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1287         if (fn)
1288                 activate_grab_client(gc, fn);
1289         return 1;
1290 err_out:
1291         if (err != -E_GC_HELP_GIVEN)
1292                 return err;
1293         err = client_write(fd, "Usage: para_audioc [audioc_options] -- "
1294                 "grab [grab_options]\nAvailable options:\n");
1295         if (err < 0)
1296                 return err;
1297         err = client_write(fd, GRAB_HELP_TXT);
1298         if (err < 0)
1299                 return err;
1300         close(fd);
1301         return 1;
1302 }
1303
1304 static int __noreturn com_term(int fd, __unused int argc, __unused char **argv)
1305 {
1306         close(fd);
1307         clean_exit(EXIT_SUCCESS, "terminating on user request");
1308 }
1309
1310 static int com_on(int fd, __unused int argc, __unused char **argv)
1311 {
1312         audiod_status = AUDIOD_ON;
1313         close(fd);
1314         return 1;
1315 }
1316
1317 static int com_off(int fd, __unused int argc, __unused char **argv)
1318 {
1319         audiod_status = AUDIOD_OFF;
1320         close(fd);
1321         return 1;
1322 }
1323
1324 static int com_sb(int fd, __unused int argc, __unused char **argv)
1325 {
1326         audiod_status = AUDIOD_STANDBY;
1327         close(fd);
1328         return 1;
1329 }
1330
1331 static int com_cycle(int fd, int argc, char **argv)
1332 {
1333         switch (audiod_status) {
1334                 case  AUDIOD_ON:
1335                         return com_sb(fd, argc, argv);
1336                         break;
1337                 case  AUDIOD_OFF:
1338                         return com_on(fd, argc, argv);
1339                         break;
1340                 case  AUDIOD_STANDBY:
1341                         return com_off(fd, argc, argv);
1342                         break;
1343         }
1344         close(fd);
1345         return 1;
1346 }
1347
1348 static int check_perms(struct ucred *c)
1349 {
1350         int i;
1351
1352         if (!conf.user_allow_given)
1353                 return 1;
1354         for (i = 0; i < conf.user_allow_given; i++)
1355                 if (c->uid == conf.user_allow_arg[i])
1356                         return 1;
1357         return -E_UCRED_PERM;
1358 }
1359
1360 static int handle_connect(void)
1361 {
1362         int i, argc, ret, clifd = -1;
1363         struct ucred c;
1364         char *buf = para_malloc(MAXLINE), **argv = NULL;
1365         struct sockaddr_un unix_addr;
1366
1367         ret = para_accept(audiod_socket, &unix_addr, sizeof(struct sockaddr_un));
1368         if (ret < 0)
1369                 goto out;
1370         clifd = ret;
1371         ret = recv_cred_buffer(clifd, buf, MAXLINE - 1, &c);
1372         if (ret < 0)
1373                 goto out;
1374         PARA_INFO_LOG("pid: %i, uid: %i, gid: %i, ret: %i, buf: %s\n", c.pid, c.uid, c.gid, ret, buf);
1375         buf[ret] = '\0';
1376         ret = check_perms(&c);
1377         if (ret < 0)
1378                 goto out;
1379         argc = split_args(buf, &argv, '\n');
1380         PARA_INFO_LOG("argv[0]: %s\n", argv[0]);
1381         for (i = 0; cmds[i].name; i++) {
1382                 if (strcmp(cmds[i].name, argv[0]))
1383                         continue;
1384                 ret = cmds[i].handler(clifd, argc + 1, argv);
1385                 goto out;
1386         }
1387         ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1388 out:
1389         free(buf);
1390         free(argv);
1391         if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1392                 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1393                 client_write(clifd, tmp);
1394                 free(tmp);
1395                 close(clifd);
1396         }
1397         return ret;
1398 }
1399
1400 static void audiod_get_socket(void)
1401 {
1402         struct sockaddr_un unix_addr;
1403
1404         if (conf.socket_given)
1405                 socket_name = para_strdup(conf.socket_arg);
1406         else {
1407                 char *hn = para_hostname();
1408                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1409                         hn);
1410                 free(hn);
1411         }
1412         PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1413         if (conf.force_given)
1414                 unlink(socket_name);
1415         audiod_socket = create_pf_socket(socket_name, &unix_addr,
1416                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1417         if (audiod_socket < 0) {
1418                 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1419                 exit(EXIT_FAILURE); /* do not unlink socket */
1420         }
1421         if (listen(audiod_socket, 5) < 0) {
1422                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1423                 exit(EXIT_FAILURE); /* do not unlink socket */
1424         }
1425         add_close_on_fork_list(audiod_socket);
1426 }
1427
1428 static int open_stat_pipe(void)
1429 {
1430         int ret, fd[3] = {-1, 1, 0};
1431         char *argv[] = {BINDIR "/para_client", "stat", NULL};
1432         pid_t pid;
1433         ret = para_exec(&pid, BINDIR "/para_client",  argv, fd);
1434         if (ret >= 0) {
1435                 ret = fd[1];
1436                 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1437                 add_close_on_fork_list(ret);
1438         } else
1439                 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1440         return ret;
1441 }
1442
1443 static int pre_select(fd_set *rfds, fd_set *wfds, struct timeval *tv)
1444 {
1445         int i, ret, max = -1;
1446
1447         FOR_EACH_SLOT(i) {
1448                 struct slot_info *s = &slot[i];
1449                 struct audio_format_info *a;
1450                 struct receiver_node *rn = s->receiver_node;
1451                 if (s->format < 0 || !rn)
1452                         continue;
1453                 a = &afi[s->format];
1454                 ret = a->receiver->pre_select(rn, rfds, wfds, tv);
1455 //              PARA_NOTICE_LOG("%s preselect: %d\n", a->receiver->name, ret);
1456                 max = MAX(max, ret);
1457         }
1458         return max;
1459
1460 }
1461 static void audiod_post_select(int select_ret, fd_set *rfds, fd_set *wfds)
1462 {
1463         int i, ret;
1464
1465         FOR_EACH_SLOT(i) {
1466                 struct slot_info *s = &slot[i];
1467                 struct audio_format_info *a;
1468                 struct receiver_node *rn = s->receiver_node;
1469                 if (s->format < 0 || !rn || rn->eof)
1470                         continue;
1471                 a = &afi[s->format];
1472                 ret = a->receiver->post_select(rn, select_ret, rfds, wfds);
1473                 if (ret <= 0) {
1474                         if (ret)
1475                                 PARA_ERROR_LOG("%s post select failed: %s (slot %d)\n",
1476                                 a->receiver->name, PARA_STRERROR(-ret), i);
1477                         else
1478                                 PARA_INFO_LOG("eof in slot %d\n", i);
1479                         rn->eof = 1;
1480                 }
1481                 if (ret < 0 && s->fci)
1482                         s->fci->error = ret;
1483         }
1484 }
1485
1486 /* TODO: move everything before the select call to pre_select() */
1487 static void __noreturn audiod_mainloop(void)
1488 {
1489         fd_set rfds, wfds;
1490         int ret, max_fileno, sbo = 0;
1491         char status_buf[STRINGSIZE] = "";
1492         struct timeval tv;
1493 repeat:
1494         FD_ZERO(&rfds);
1495         FD_ZERO(&wfds);
1496         max_fileno = 0;
1497         if (audiod_status != AUDIOD_ON)
1498                 kill_all_decoders();
1499         else if (playing)
1500                 start_current_receiver();
1501         max_fileno = set_stream_fds(&wfds);
1502         /* stat pipe (read) */
1503         if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1504                 close_stat_pipe();
1505         if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1506                 stat_pipe = open_stat_pipe();
1507                 sbo = 0;
1508                 status_buf[0] = '\0';
1509         }
1510         if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF) {
1511                 FD_SET(stat_pipe, &rfds);
1512                 max_fileno = MAX(max_fileno, stat_pipe);
1513         }
1514         /* always check signal pipe */
1515         FD_SET(signal_pipe, &rfds);
1516         max_fileno = MAX(max_fileno, signal_pipe);
1517         /* local socket */
1518         if (audiod_socket < 0)
1519                 audiod_get_socket(); /* doesn't return on errors */
1520         FD_SET(audiod_socket, &rfds);
1521         max_fileno = MAX(max_fileno, audiod_socket);
1522         tv.tv_sec = 0;
1523         tv.tv_usec = 200 * 1000;
1524         ret = pre_select(&rfds, &wfds, &tv);
1525         max_fileno = MAX(max_fileno, ret);
1526         ret = select(max_fileno + 1, &rfds, &wfds, NULL, &tv);
1527         if (ret < 0 && errno != EINTR)
1528                 PARA_ERROR_LOG("select returned %d (%s)\n", ret,
1529                         strerror(errno));
1530         if (audiod_status != AUDIOD_OFF)
1531                 audiod_status_dump();
1532         if (ret < 0)
1533                 goto repeat;
1534         audiod_post_select(ret, &rfds, &wfds);
1535         /* read status pipe */
1536         if (stat_pipe >=0 && FD_ISSET(stat_pipe, &rfds)) {
1537                 ret = read(stat_pipe, status_buf + sbo, STRINGSIZE - 1 - sbo);
1538                 if (ret <= 0) {
1539                         close_stat_pipe();
1540                         /* avoid busy loop if server is down */
1541                         while (sleep(1) > 0)
1542                                 ; /* try again*/
1543                 } else {
1544                         status_buf[ret + sbo] = '\0';
1545                         sbo = for_each_line(status_buf, ret + sbo,
1546                                 &check_stat_line);
1547                 }
1548         }
1549         slot_io(&wfds);
1550         if (FD_ISSET(audiod_socket, &rfds)) {
1551                 ret = handle_connect();
1552                 if (ret < 0) {
1553                         PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1554                 }
1555         }
1556         /* signals */
1557         if (FD_ISSET(signal_pipe, &rfds)) {
1558                 int sig_nr = para_next_signal();
1559                 if (sig_nr > 0)
1560                         handle_signal(sig_nr);
1561         }
1562         goto repeat;
1563 }
1564
1565 static void set_initial_status(void)
1566 {
1567         audiod_status = AUDIOD_ON;
1568         if (!conf.mode_given)
1569                 return;
1570         if (!strcmp(conf.mode_arg, "sb")) {
1571                 audiod_status = AUDIOD_STANDBY;
1572                 return;
1573         }
1574         if (!strcmp(conf.mode_arg, "off")) {
1575                 audiod_status = AUDIOD_OFF;
1576                 return;
1577         }
1578         if (strcmp(conf.mode_arg, "on"))
1579                 PARA_WARNING_LOG("%s", "invalid mode\n");
1580 }
1581
1582 int __noreturn main(int argc, char *argv[])
1583 {
1584         char *cf;
1585         int i;
1586
1587         valid_fd_012();
1588         hostname = para_hostname();
1589         cmdline_parser(argc, argv, &conf);
1590         para_drop_privileges(conf.user_arg);
1591         cf = configfile_exists();
1592         if (cf) {
1593                 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1594                         fprintf(stderr, "parse error in config file\n");
1595                         exit(EXIT_FAILURE);
1596                 }
1597         }
1598         log_welcome("para_audiod", conf.loglevel_arg);
1599         i = init_stream_io();
1600         if (i < 0) {
1601                 fprintf(stderr, "init stream io error: %s\n",
1602                         PARA_STRERROR(-i));
1603                 exit(EXIT_FAILURE);
1604         }
1605         server_uptime(UPTIME_SET);
1606         set_initial_status();
1607         FOR_EACH_SLOT(i)
1608                 clear_slot(i);
1609         stat_item_ringbuf = ringbuffer_new(RINGBUFFER_SIZE);
1610         init_grabbing();
1611         setup_signal_handling();
1612         if (conf.daemon_given)
1613                 daemon_init();
1614         audiod_mainloop();
1615 }