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