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