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