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