741bd68b0344c510ecdd750e897aedfa25b9ee48
[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
38 /** define the array of error lists needed by para_audiod */
39 INIT_AUDIOD_ERRLISTS;
40 /** define the array containing all supported audio formats */
41 DEFINE_AUDIO_FORMAT_ARRAY;
42
43 /**
44  * the possible modes of operation
45  *
46  * - off: disconnect from para_server
47  * - on: receive status information from para_server and play the audio stream
48  * - sb: only receive status information but not the audio stream
49 */
50 enum {AUDIOD_OFF, AUDIOD_ON, AUDIOD_STANDBY};
51
52 /** defines how to handle one supported audio format */
53 struct audio_format_info {
54 /** pointer to the receiver for this audio format */
55         struct receiver *receiver;
56 /** the receiver configuration */
57         void *receiver_conf;
58 /** the number of filters that should be activated for this audio format */
59         unsigned int num_filters;
60 /** pointer to the array of filters to be activated */
61         struct filter **filters;
62 /** pointer to the array of filter configurations */
63         void **filter_conf;
64 /** output of the last filter is written to stdin of this command */
65         char *write_cmd;
66 /** do not start receiver/filters/writer before this time */
67         struct timeval restart_barrier;
68 };
69
70 /**
71  * describes one instance of a receiver-filter-writer chain
72  *
73  * \sa receier_node, receiver, filter, filter_node, filter_chain_info
74   */
75 struct slot_info {
76 /** number of the audio format in this slot */
77         int format;
78 /** the file descriptor of the writer */
79         int write_fd;
80 /** the process id of the writer */
81         pid_t wpid;
82 /** time of the last successful read from the receiver */
83         struct timeval rtime;
84 /** time the last write to the write fd happend */
85         struct timeval wtime;
86 /** writer start time */
87         struct timeval wstime;
88 /** did we include \a write_fd in the fdset */
89         int  wcheck;
90 /** set to one if we have sent the TERM signal to \a wpid */
91         int wkilled;
92 /** the receiver info associated with this slot */
93         struct receiver_node *receiver_node;
94 /** the active filter chain */
95         struct filter_chain_info *fci;
96 };
97
98 static struct slot_info slot[MAX_STREAM_SLOTS];
99
100 /** defines one command of para_audiod */
101 struct audiod_command {
102 /** the name of the command */
103 const char *name;
104 /** pointer to the function that handles the command */
105 int (*handler)(int, int, char**);
106 /** one-line description of the command */
107 const char *description;
108 /** summary of the command line options */
109 const char *synopsis;
110 /** the long help text */
111 const char *help;
112 };
113
114 extern const char *status_item_list[NUM_STAT_ITEMS];
115
116 static int com_grab(int, int, char **);
117 static int com_cycle(int, int, char **);
118 static int com_help(int, int, char **);
119 static int com_off(int, int, char **);
120 static int com_on(int, int, char **);
121 static int com_sb(int, int, char **);
122 static int com_stat(int, int, char **);
123 static int com_term(int, int, char **);
124 static int stat_pipe = -1, signal_pipe;
125
126 static struct gengetopt_args_info conf;
127 static struct timeval server_stream_start, sa_time_diff;
128 static int playing, current_decoder = -1,
129         audiod_status = AUDIOD_ON, offset_seconds, length_seconds,
130         sa_time_diff_sign = 1, audiod_socket = -1;
131 static char *af_status, /* the audio format announced in server status */
132         *socket_name, *hostname;
133 static char *stat_item_values[NUM_STAT_ITEMS];
134 static FILE *logfile;
135 static const struct timeval restart_delay = {0, 300 * 1000};
136
137 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
138
139 static struct audiod_command cmds[] = {
140 {
141 .name = "cycle",
142 .handler = com_cycle,
143 .description = "switch to next mode",
144 .synopsis = "cycle",
145 .help =
146
147 "on -> standby -> off -> on\n"
148
149 },
150 {
151 .name = "grab",
152 .handler = com_grab,
153 .description = "grab the audio stream",
154 .synopsis = "-- grab [grab_options]",
155 .help =
156 "grab ('splice') the audio stream at any position in the filter      \n"
157 "chain and send that data back to the client. \n"
158 "Available options:\n\n"
159 GRAB_HELP_TXT
160 },
161 {
162 .name = "help",
163 .handler = com_help,
164 .description = "display command list or help for given command",
165 .synopsis = "help [command]",
166 .help =
167
168 "When I was younger, so much younger than today, I never needed\n"
169 "anybody's help in any way. But now these days are gone, I'm not so\n"
170 "self assured. Now I find I've changed my mind and opened up the doors.\n"
171 "\n"
172 "                               -- Beatles: Help\n"
173
174 },
175 {
176 .name = "off",
177 .handler = com_off,
178 .description = "deactivate para_audiod",
179 .synopsis = "off",
180 .help =
181
182 "Close connection to para_server and stop all decoders.\n"
183
184 },
185 {
186 .name = "on",
187 .handler = com_on,
188 .description = "activate para_audiod",
189 .synopsis = "on",
190 .help =
191
192 "Establish connection to para_server, retrieve para_server's current\n"
193 "status. If playing, start corresponding decoder. Otherwise stop\n"
194 "all decoders.\n"
195
196 },
197 {
198 .name = "sb",
199 .handler = com_sb,
200 .description = "enter standby mode",
201 .synopsis = "sb",
202 .help =
203
204 "Stop all decoders but leave connection to para_server open.\n"
205
206 },
207 {
208 .name = "stat",
209 .handler = com_stat,
210 .description = "print status information",
211 .synopsis = "stat [item1 ...]",
212 .help =
213
214 "Dump given status items (all if none given) to stdout.\n"
215
216 },
217 {
218 .name = "term",
219 .handler = com_term,
220 .description = "terminate audiod",
221 .synopsis = "term",
222 .help =
223
224 "Stop all decoders, shut down connection to para_server and exit.\n"
225
226 },
227 {
228 .name = NULL,
229 }
230 };
231
232 /** iterate over all slots */
233 #define FOR_EACH_SLOT(slot) for (slot = 0; slot < MAX_STREAM_SLOTS; slot++)
234 /** iterate over all supported audio formats */
235 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
236 /** iterate over the array of all audiod commands */
237 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
238
239 /**
240  * get the audio format number
241  * \param name the name of the audio format
242  *
243  * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
244  * \a name is not a supported audio format.
245  */
246 int get_audio_format_num(char *name)
247 {
248         int i;
249         FOR_EACH_AUDIO_FORMAT(i)
250                 if (!strcmp(name, audio_formats[i]))
251                         return i;
252         return -E_UNSUPPORTED_AUDIO_FORMAT;
253 }
254
255 /*
256  * log function. first argument is loglevel.
257  */
258 void para_log(int ll, const char* fmt,...)
259 {
260         va_list argp;
261         FILE *outfd;
262         struct tm *tm;
263         time_t t1;
264         char str[MAXLINE] = "";
265
266         if (ll < conf.loglevel_arg)
267                 return;
268         if (!logfile && conf.logfile_given)
269                 logfile = open_log(conf.logfile_arg);
270         if (!logfile && conf.daemon_given)
271                 return;
272         if (!logfile) {
273                 if (ll < WARNING)
274                         outfd = stdout;
275                 else
276                         outfd = stderr;
277         } else
278                 outfd = logfile;
279         time(&t1);
280         tm = localtime(&t1);
281         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
282         fprintf(outfd, "%s %s ", str, hostname);
283         if (conf.loglevel_arg <= INFO)
284                 fprintf(outfd, "%i ", ll);
285         va_start(argp, fmt);
286         vfprintf(outfd, fmt, argp);
287         va_end(argp);
288 }
289
290 static int client_write(int fd, const char *buf)
291 {
292         size_t len = strlen(buf);
293         return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
294 }
295
296 static char *get_time_string(struct timeval *newest_stime)
297 {
298         struct timeval now, diff, adj_stream_start, tmp;
299         int total = 0, use_server_time = 1;
300
301         if (!playing) {
302                 if (length_seconds)
303                         return NULL;
304                 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
305         }
306         if (audiod_status == AUDIOD_OFF)
307                 goto out;
308         if (sa_time_diff_sign > 0)
309                 tv_diff(&server_stream_start, &sa_time_diff,
310                         &adj_stream_start);
311         else
312                 tv_add(&server_stream_start, &sa_time_diff,
313                         &adj_stream_start);
314         tmp = adj_stream_start;
315         if (newest_stime && audiod_status == AUDIOD_ON) {
316                 tv_diff(newest_stime, &adj_stream_start, &diff);
317                 if (tv2ms(&diff) < 5000) {
318                         tmp = *newest_stime;
319                         use_server_time = 0;
320                 }
321         }
322         gettimeofday(&now, NULL);
323         tv_diff(&now, &tmp, &diff);
324         total = diff.tv_sec + offset_seconds;
325         if (total > length_seconds)
326                 total = length_seconds;
327         if (total < 0)
328                 total = 0;
329 out:
330         return make_message(
331                 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
332                 status_item_list[SI_PLAY_TIME],
333                 use_server_time? "~" : "",
334                 total / 60,
335                 total % 60,
336                 (length_seconds - total) / 60,
337                 (length_seconds - total) % 60,
338                 length_seconds? (total * 100 + length_seconds / 2) /
339                         length_seconds : 0,
340                 length_seconds / 60,
341                 length_seconds % 60
342         );
343 }
344
345 __malloc static char *audiod_status_string(void)
346 {
347         const char *status = (audiod_status == AUDIOD_ON)?
348                 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
349         return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
350 }
351
352 static struct timeval *wstime(void)
353 {
354         int i;
355         struct timeval *max = NULL;
356         FOR_EACH_SLOT(i) {
357                 struct slot_info *s = &slot[i];
358                 if (s->wpid <= 0)
359                         continue;
360                 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
361                         continue;
362                 max = &s->wstime;
363         }
364         return max;
365 }
366 __malloc static char *decoder_flags(void)
367 {
368         int i;
369         char decoder_flags[MAX_STREAM_SLOTS + 1];
370
371         FOR_EACH_SLOT(i) {
372                 struct slot_info *s = &slot[i];
373                 char flag = '0';
374                 if (s->receiver_node)
375                         flag += 1;
376                 if (s->wpid > 0)
377                         flag += 2;
378                 if (flag != '0')
379                         flag += s->format * 4;
380                 decoder_flags[i] = flag;
381         }
382         decoder_flags[MAX_STREAM_SLOTS] = '\0';
383         return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
384                 decoder_flags);
385 }
386
387 static char *configfile_exists(void)
388 {
389         static char *config_file;
390
391         if (!config_file) {
392                 char *home = para_homedir();
393                 config_file = make_message("%s/.paraslash/audiod.conf", home);
394                 free(home);
395         }
396         return file_exists(config_file)? config_file : NULL;
397 }
398
399 static void setup_signal_handling(void)
400 {
401         signal_pipe = para_signal_init();
402         PARA_INFO_LOG("signal pipe: fd %d\n", signal_pipe);
403         para_install_sighandler(SIGINT);
404         para_install_sighandler(SIGTERM);
405         para_install_sighandler(SIGCHLD);
406         para_install_sighandler(SIGHUP);
407         signal(SIGPIPE, SIG_IGN);
408 }
409
410 static void audiod_status_dump(void)
411 {
412         static char *p_ts, *p_us, *p_as, *p_df;
413         struct timeval *t = wstime();
414         char *us, *tmp = get_time_string(t);
415
416         if (tmp && (!p_ts || strcmp(tmp, p_ts)))
417                 stat_client_write(tmp, SI_PLAY_TIME);
418         free(p_ts);
419         p_ts = tmp;
420
421         us = uptime_str();
422         tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
423         free(us);
424         if (!p_us || strcmp(p_us, tmp))
425                 stat_client_write(tmp, SI_AUDIOD_UPTIME);
426         free(p_us);
427         p_us = tmp;
428
429         tmp = audiod_status_string();
430         if (!p_as || strcmp(p_as, tmp))
431                 stat_client_write(tmp, SI_AUDIOD_STATUS);
432         free(p_as);
433         p_as = tmp;
434
435         tmp = decoder_flags();
436         if (!p_df || strcmp(p_df, tmp))
437                 stat_client_write(tmp, SI_DECODER_FLAGS);
438         free(p_df);
439         p_df = tmp;
440 }
441
442 static void clear_slot(int slot_num)
443 {
444         struct slot_info *s = &slot[slot_num];
445
446         PARA_INFO_LOG("clearing slot %d\n", slot_num);
447         memset(s, 0, sizeof(struct slot_info));
448         s->format = -1;
449 }
450
451 static void kill_stream_writer(int slot_num)
452 {
453         struct slot_info *s = &slot[slot_num];
454
455         if (s->format < 0 || s->wkilled || s->wpid <= 0)
456                 return;
457         PARA_DEBUG_LOG("kill -TERM %d (%s stream writer in slot %d)\n",
458                 s->wpid, audio_formats[s->format], slot_num);
459         kill(s->wpid, SIGTERM);
460         s->wkilled = 1;
461         s->fci->error = 1;
462 }
463
464 static void set_restart_barrier(int format, struct timeval *now)
465 {
466         struct timeval tmp;
467
468         if (now)
469                 tmp = *now;
470         else
471                 gettimeofday(&tmp, NULL);
472         tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
473 }
474
475 static void close_receiver(int slot_num)
476 {
477         struct slot_info *s = &slot[slot_num];
478         struct audio_format_info *a;
479
480         if (s->format < 0 || !s->receiver_node)
481                 return;
482         a = &afi[s->format];
483         PARA_NOTICE_LOG("closing %s recevier in slot %d\n",
484                 audio_formats[s->format] , slot_num);
485         a->receiver->close(s->receiver_node);
486         free(s->receiver_node);
487         s->receiver_node = NULL;
488         set_restart_barrier(s->format, NULL);
489 }
490
491 static void kill_all_decoders(void)
492 {
493         int i;
494
495         FOR_EACH_SLOT(i)
496                 if (slot[i].format >= 0) {
497                         PARA_INFO_LOG("stopping decoder in slot %d\n", i);
498                         kill_stream_writer(i);
499                 }
500 }
501
502 static void check_sigchld(void)
503 {
504         pid_t pid;
505         int i;
506         struct timeval now;
507         gettimeofday(&now, NULL);
508
509 reap_next_child:
510         pid = para_reap_child();
511         if (pid <= 0)
512                 return;
513         FOR_EACH_SLOT(i) {
514                 struct slot_info *s = &slot[i];
515                 long lifetime;
516                 if (s->format < 0)
517                         continue;
518                 if (pid == s->wpid) {
519                         s->wpid = -1;
520                         lifetime = now.tv_sec - s->wstime.tv_sec;
521                         PARA_INFO_LOG("%s stream writer in slot %d died "
522                                 "after %li secs\n",
523                                 audio_formats[s->format], i, lifetime);
524                         set_restart_barrier(s->format, &now);
525                         goto reap_next_child;
526                 }
527         }
528         PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
529         goto reap_next_child;
530 }
531
532 static int get_empty_slot(void)
533 {
534         int i;
535         struct slot_info *s;
536
537         FOR_EACH_SLOT(i) {
538                 s = &slot[i];
539                 if (s->format < 0) {
540                         clear_slot(i);
541                         return i;
542                 }
543                 if (s->write_fd > 0 || s->wpid > 0)
544                         continue;
545                 if (s->receiver_node)
546                         continue;
547                 if (s->fci)
548                         continue;
549                 clear_slot(i);
550                 return i;
551         }
552         return -E_NO_MORE_SLOTS;
553 }
554
555 static int decoder_running(int format)
556 {
557         int i, ret = 0;
558         struct slot_info *s;
559
560         FOR_EACH_SLOT(i) {
561                 s = &slot[i];
562                 if (s->format == format && s->receiver_node)
563                         ret |= 1;
564                 if (s->format == format && s->wpid > 0)
565                         ret |= 2;
566         }
567         return ret;
568 }
569
570 static void close_stat_pipe(void)
571 {
572         int i;
573
574         if (stat_pipe < 0)
575                 return;
576         PARA_NOTICE_LOG("%s", "closing status pipe\n");
577         close(stat_pipe);
578         del_close_on_fork_list(stat_pipe);
579         stat_pipe = -1;
580         kill_all_decoders();
581         for (i = 0; i < NUM_STAT_ITEMS; i++) {
582                 free(stat_item_values[i]);
583                 stat_item_values[i] = NULL;
584         }
585         dump_empty_status();
586         length_seconds = 0;
587         offset_seconds = 0;
588         audiod_status_dump();
589         playing = 0;
590         stat_item_values[SI_STATUS_BAR] = make_message("%s:no connection to para_server\n",
591                 status_item_list[SI_STATUS_BAR]);
592         stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
593 }
594
595 static void __noreturn clean_exit(int status, const char *msg)
596 {
597         PARA_EMERG_LOG("%s\n", msg);
598         kill_all_decoders();
599         if (socket_name)
600                 unlink(socket_name);
601         if (stat_pipe >= 0)
602                 close_stat_pipe();
603         exit(status);
604 }
605
606 __malloc static char *glob_cmd(char *cmd)
607 {
608         char *ret, *replacement;
609         struct timeval tmp, delay, rss; /* real stream start */
610
611         delay.tv_sec = conf.stream_delay_arg / 1000;
612         delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
613 //      PARA_INFO_LOG("delay: %lu:%lu\n", delay.tv_sec, delay.tv_usec);
614         if (sa_time_diff_sign < 0)
615                 tv_add(&server_stream_start, &sa_time_diff, &rss);
616         else
617                 tv_diff(&server_stream_start, &sa_time_diff, &rss);
618         tv_add(&rss, &delay, &tmp);
619         replacement = make_message("%lu:%lu", tmp.tv_sec, tmp.tv_usec);
620         ret = s_a_r(cmd, "STREAM_START", replacement);
621         free(replacement);
622         if (!ret)
623                 goto out;
624         PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
625         {
626         struct timeval now;
627         gettimeofday(&now, NULL);
628         PARA_INFO_LOG("now: %lu:%lu\n", now.tv_sec, now.tv_usec);
629         }
630 out:
631         return ret;
632 }
633
634 /** get the number of filters for the given audio format */
635 int num_filters(int audio_format_num)
636 {
637         return afi[audio_format_num].num_filters;
638 }
639
640 static void open_filters(int slot_num)
641 {
642         struct slot_info *s = &slot[slot_num];
643         struct audio_format_info *a = &afi[s->format];
644         int nf = a->num_filters;
645         int i;
646
647         s->fci = para_calloc(sizeof(struct filter_chain_info));
648         INIT_LIST_HEAD(&s->fci->filters);
649         if (!nf)
650                 return;
651         s->fci->inbuf = s->receiver_node->buf;
652         s->fci->in_loaded = &s->receiver_node->loaded;
653         s->fci->outbuf = s->receiver_node->buf;
654         s->fci->out_loaded = &s->receiver_node->loaded;
655         s->fci->eof = &s->receiver_node->eof;
656         for (i = 0; i < nf; i++) {
657                 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
658                 fn->conf = a->filter_conf[i];
659                 fn->fci = s->fci;
660                 fn->filter = a->filters[i];
661                 INIT_LIST_HEAD(&fn->callbacks);
662                 list_add_tail(&fn->node, &s->fci->filters);
663                 fn->filter->open(fn);
664                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
665                         audio_formats[s->format], i + 1,  nf,
666                         fn->filter->name, slot_num);
667                 s->fci->outbuf = fn->buf;
668                 s->fci->out_loaded = &fn->loaded;
669         }
670         PARA_DEBUG_LOG("output buffer for filter chain %p: %p\n", s->fci,
671                 s->fci->outbuf);
672 }
673
674 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
675 {
676         struct filter_node *fn;
677         int i, j;
678
679         FOR_EACH_SLOT(i) {
680                 struct slot_info *s = &slot[i];
681                 if (s->format < 0 || !s->fci)
682                         continue;
683                 if (slot_num >= 0 && slot_num != i)
684                         continue;
685                 if (format >= 0 && s->format != format)
686                         continue;
687                 if (num_filters(i) < filternum)
688                         continue;
689                 /* success */
690                 j = 1;
691                 list_for_each_entry(fn, &s->fci->filters, node)
692                         if (filternum <= 0 || j++ == filternum)
693                                 break;
694                 return fn;
695         }
696         return NULL;
697 }
698
699 static void start_stream_writer(int slot_num)
700 {
701         int ret, fds[3] = {1, -1, -1};
702         struct slot_info *s = &slot[slot_num];
703         struct audio_format_info *a = &afi[s->format];
704         char *glob = NULL;
705
706         if (a->write_cmd)
707                 glob = glob_cmd(a->write_cmd);
708         if (!glob)
709                 glob = para_strdup("para_play");
710         PARA_INFO_LOG("starting stream writer: %s\n", glob);
711         open_filters(slot_num);
712         ret = para_exec_cmdline_pid(&s->wpid, glob, fds);
713         free(glob);
714         if (ret < 0) {
715                 PARA_ERROR_LOG("exec failed (%d)\n", ret);
716                 return;
717         }
718         s->write_fd = fds[0];
719         add_close_on_fork_list(s->write_fd);
720         /* we write to this fd in do_select, so we need non-blocking */
721         fcntl(s->write_fd, F_SETFL, O_NONBLOCK);
722         gettimeofday(&s->wstime, NULL);
723         current_decoder = slot_num;
724         activate_inactive_grab_clients(slot_num, s->format, &s->fci->filters);
725 }
726
727 static void open_receiver(int format)
728 {
729         struct audio_format_info *a = &afi[format];
730         struct slot_info *s;
731         int ret, slot_num;
732
733         slot_num = get_empty_slot();
734         if (slot_num < 0)
735                 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
736         s = &slot[slot_num];
737         s->format = format;
738         gettimeofday(&s->rtime, NULL);
739         s->wtime = s->rtime;
740         s->receiver_node = para_calloc(sizeof(struct receiver_node));
741         s->receiver_node->conf = a->receiver_conf;
742         ret = a->receiver->open(s->receiver_node);
743         if (ret < 0) {
744                 PARA_ERROR_LOG("failed to open receiver (%s)\n",
745                         PARA_STRERROR(-ret));
746                 free(s->receiver_node);
747                 s->receiver_node = NULL;
748                 return;
749         }
750         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
751                 audio_formats[s->format], a->receiver->name, slot_num);
752 }
753
754 static int is_frozen(int format)
755 {
756         struct timeval now;
757         struct audio_format_info *a = &afi[format];
758
759         gettimeofday(&now, NULL);
760         return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
761 }
762
763 static void start_current_receiver(void)
764 {
765         int i;
766
767         if (!af_status)
768                 return;
769         i = get_audio_format_num(af_status);
770         if (i < 0)
771                 return;
772         if ((decoder_running(i) & 1) || is_frozen(i))
773                 return;
774         open_receiver(i);
775 }
776
777 static void compute_time_diff(const struct timeval *status_time)
778 {
779         struct timeval now, tmp, diff;
780         static int count;
781         int sign;
782         const struct timeval max_deviation = {0, 500 * 1000};
783         const int time_smooth = 5;
784
785         gettimeofday(&now, NULL);
786         sign = tv_diff(status_time, &now, &diff);
787 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
788 //                      sign, sa_time_diff_sign);
789         if (!count) {
790                 sa_time_diff_sign = sign;
791                 sa_time_diff = diff;
792                 count++;
793                 return;
794         }
795         if (count > 5) {
796                 int s = tv_diff(&diff, &sa_time_diff, &tmp);
797                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
798                         PARA_WARNING_LOG("time diff jump: %lims\n",
799                                 s * tv2ms(&tmp));
800         }
801         count++;
802         sa_time_diff_sign = tv_convex_combination(
803                 sa_time_diff_sign * time_smooth, &sa_time_diff,
804                 count > 10? sign : sign * time_smooth, &diff,
805                 &tmp);
806         sa_time_diff = tmp;
807         PARA_INFO_LOG("time diff (cur/avg): "
808                 "%li:%lu/%li:%lu\n",
809                 sign * diff.tv_sec, (diff.tv_usec + 500) / 1000,
810                 sa_time_diff_sign * sa_time_diff.tv_sec,
811                 (sa_time_diff.tv_usec + 500)/ 1000);
812 }
813
814 static void check_stat_line(char *line)
815 {
816         int itemnum;
817         size_t ilen = 0;
818         struct timeval tv;
819         char *tmp;
820
821         if (!line)
822                 return;
823         itemnum = stat_line_valid(line);
824         if (itemnum < 0) {
825                 PARA_WARNING_LOG("invalid status line: %s\n", line);
826                 return;
827         }
828         tmp = make_message("%s\n", line);
829         stat_client_write(tmp, itemnum);
830         free(tmp);
831         free(stat_item_values[itemnum]);
832         stat_item_values[itemnum] = para_strdup(line);
833         ilen = strlen(status_item_list[itemnum]);
834         switch (itemnum) {
835         case SI_STATUS:
836                 playing = strstr(line, "playing")? 1 : 0;
837                 break;
838         case SI_FORMAT:
839                 free(af_status);
840                 af_status = para_strdup(line + ilen + 1);
841                 break;
842         case SI_OFFSET:
843                 offset_seconds = atoi(line + ilen + 1);
844                 break;
845         case SI_LENGTH:
846                 length_seconds = atoi(line + ilen + 1);
847                 break;
848         case SI_STREAM_START:
849                 if (sscanf(line + ilen + 1, "%lu.%lu",
850                                 &tv.tv_sec, &tv.tv_usec) == 2)
851                         server_stream_start = tv;
852                 break;
853         case SI_CURRENT_TIME:
854                 if (sscanf(line + ilen + 1, "%lu.%lu", &tv.tv_sec,
855                                 &tv.tv_usec) == 2)
856                         compute_time_diff(&tv);
857                 break;
858         }
859 }
860
861 static void handle_signal(int sig)
862 {
863         switch (sig) {
864         case SIGCHLD:
865                 return check_sigchld();
866         case SIGINT:
867         case SIGTERM:
868         case SIGHUP:
869                 PARA_EMERG_LOG("terminating on signal %d\n", sig);
870                 clean_exit(EXIT_FAILURE, "caught deadly signal");
871                 return;
872         }
873 }
874
875 static void check_timeouts(void)
876 {
877         struct timeval now;
878         int slot_num, timeout = conf.stream_timeout_arg;
879
880         gettimeofday(&now, NULL);
881         FOR_EACH_SLOT(slot_num) {
882                 struct slot_info *s = &slot[slot_num];
883                 if (s->format < 0)
884                         continue;
885                 /* check read time */
886                 if (s->receiver_node &&
887                         now.tv_sec > s->rtime.tv_sec + timeout) {
888                         PARA_INFO_LOG("%s input buffer (slot %d) not ready\n",
889                                 audio_formats[s->format], slot_num);
890                         if (s->fci)
891                                 s->fci->error = 42;
892                         else
893                                 close_receiver(slot_num);
894                 }
895                 /* check write time */
896                 if (s->wpid > 0 && !s->wkilled &&
897                         now.tv_sec > s->wtime.tv_sec + timeout) {
898                         PARA_INFO_LOG("%s output buffer (slot %d) not ready\n",
899                                 audio_formats[s->format], slot_num);
900                         if (s->fci)
901                                 s->fci->error = 42;
902                 }
903         }
904 }
905
906 static size_t get_loaded_bytes(int slot_num)
907 {
908         size_t loaded = 0;
909         struct slot_info *s = &slot[slot_num];
910         struct receiver_node *rn = s->receiver_node;
911
912         if (s->format < 0)
913                 goto out;
914
915         if (afi[s->format].num_filters) {
916                 if (s->fci)
917                         loaded = *s->fci->out_loaded;
918         } else {
919                 if (rn)
920                         loaded = rn->loaded;
921         }
922 out:
923         return loaded;
924 }
925
926
927 static void close_decoder_if_idle(int slot_num)
928 {
929         struct slot_info *s = &slot[slot_num];
930         struct receiver_node *rn = s->receiver_node;
931
932         if (s->format < 0)
933                 return;
934         if (!s->fci)
935                 return;
936         if (!rn->eof && !s->fci->error && s->wpid > 0)
937                 return;
938         if (!s->fci->error && s->wpid > 0) { /* eof */
939                 if (filter_io(s->fci) > 0)
940                         return;
941                 if (get_loaded_bytes(slot_num))
942                         return;
943         }
944         if (s->write_fd > 0) {
945                 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
946                         s->write_fd);
947                 close(s->write_fd);
948                 del_close_on_fork_list(s->write_fd);
949                 s->write_fd = -1;
950         }
951         if (s->wpid > 0)
952                 return; /* wait until writer dies before closing filters */
953         PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
954                 slot_num, s->fci);
955         close_filters(s->fci);
956         free(s->fci);
957         close_receiver(slot_num);
958         clear_slot(slot_num);
959 }
960
961 static int set_stream_fds(fd_set *wfds)
962 {
963         int i, max_fileno = -1;
964
965         check_timeouts();
966         FOR_EACH_SLOT(i) {
967                 struct slot_info *s = &slot[i];
968                 struct audio_format_info *a;
969                 struct receiver_node *rn;
970
971                 close_decoder_if_idle(i);
972                 s->wcheck = 0;
973                 if (s->format < 0)
974                         continue;
975                 a = &afi[s->format];
976                 rn = s->receiver_node;
977                 if (rn && rn->loaded && !s->wpid) {
978                         PARA_INFO_LOG("no writer in slot %d\n", i);
979                         start_stream_writer(i);
980                 }
981                 if (s->write_fd <= 0)
982                         continue;
983                 if (!get_loaded_bytes(i))
984                         continue;
985                 FD_SET(s->write_fd, wfds);
986                 s->wcheck = 1;
987                 max_fileno = MAX(s->write_fd, max_fileno);
988         }
989 //      PARA_INFO_LOG("return %d\n", max_fileno);
990         return max_fileno;
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 err;
1349
1350         PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1351         gc = grab_client_new(fd, argc, argv, &err);
1352         PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1353         if (!gc)
1354                 goto err_out;
1355         fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1356         if (fn)
1357                 activate_grab_client(gc, fn);
1358         return 1;
1359 err_out:
1360         if (err != -E_GC_HELP_GIVEN)
1361                 return err;
1362         err = client_write(fd, "Usage: para_audioc [audioc_options] -- "
1363                 "grab [grab_options]\nAvailable options:\n");
1364         if (err < 0)
1365                 return err;
1366         err = client_write(fd, GRAB_HELP_TXT);
1367         if (err < 0)
1368                 return err;
1369         close(fd);
1370         return 1;
1371 }
1372
1373 static int __noreturn com_term(int fd, __unused int argc, __unused char **argv)
1374 {
1375         close(fd);
1376         clean_exit(EXIT_SUCCESS, "terminating on user request");
1377 }
1378
1379 static int com_on(int fd, __unused int argc, __unused char **argv)
1380 {
1381         audiod_status = AUDIOD_ON;
1382         close(fd);
1383         return 1;
1384 }
1385
1386 static int com_off(int fd, __unused int argc, __unused char **argv)
1387 {
1388         audiod_status = AUDIOD_OFF;
1389         close(fd);
1390         return 1;
1391 }
1392
1393 static int com_sb(int fd, __unused int argc, __unused char **argv)
1394 {
1395         audiod_status = AUDIOD_STANDBY;
1396         close(fd);
1397         return 1;
1398 }
1399
1400 static int com_cycle(int fd, int argc, char **argv)
1401 {
1402         switch (audiod_status) {
1403                 case  AUDIOD_ON:
1404                         return com_sb(fd, argc, argv);
1405                         break;
1406                 case  AUDIOD_OFF:
1407                         return com_on(fd, argc, argv);
1408                         break;
1409                 case  AUDIOD_STANDBY:
1410                         return com_off(fd, argc, argv);
1411                         break;
1412         }
1413         close(fd);
1414         return 1;
1415 }
1416
1417 static int check_perms(struct ucred *c)
1418 {
1419         int i;
1420
1421         if (!conf.user_allow_given)
1422                 return 1;
1423         for (i = 0; i < conf.user_allow_given; i++)
1424                 if (c->uid == conf.user_allow_arg[i])
1425                         return 1;
1426         return -E_UCRED_PERM;
1427 }
1428
1429 static int handle_connect(void)
1430 {
1431         int i, argc, ret, clifd = -1;
1432         struct ucred c;
1433         char *buf = para_malloc(MAXLINE), **argv = NULL;
1434         struct sockaddr_un unix_addr;
1435
1436         ret = para_accept(audiod_socket, &unix_addr, sizeof(struct sockaddr_un));
1437         if (ret < 0)
1438                 goto out;
1439         clifd = ret;
1440         ret = recv_cred_buffer(clifd, buf, MAXLINE - 1, &c);
1441         if (ret < 0)
1442                 goto out;
1443         PARA_INFO_LOG("pid: %i, uid: %i, gid: %i, ret: %i, buf: %s\n", c.pid, c.uid, c.gid, ret, buf);
1444         buf[ret] = '\0';
1445         ret = check_perms(&c);
1446         if (ret < 0)
1447                 goto out;
1448         argc = split_args(buf, &argv, '\n');
1449         PARA_INFO_LOG("argv[0]: %s\n", argv[0]);
1450         for (i = 0; cmds[i].name; i++) {
1451                 if (strcmp(cmds[i].name, argv[0]))
1452                         continue;
1453                 ret = cmds[i].handler(clifd, argc + 1, argv);
1454                 goto out;
1455         }
1456         ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1457 out:
1458         free(buf);
1459         free(argv);
1460         if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1461                 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1462                 client_write(clifd, tmp);
1463                 free(tmp);
1464                 close(clifd);
1465         }
1466         return ret;
1467 }
1468
1469 static void audiod_get_socket(void)
1470 {
1471         struct sockaddr_un unix_addr;
1472
1473         if (conf.socket_given)
1474                 socket_name = para_strdup(conf.socket_arg);
1475         else {
1476                 char *hn = para_hostname();
1477                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1478                         hn);
1479                 free(hn);
1480         }
1481         PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1482         if (conf.force_given)
1483                 unlink(socket_name);
1484         audiod_socket = create_pf_socket(socket_name, &unix_addr,
1485                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1486         if (audiod_socket < 0) {
1487                 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1488                 exit(EXIT_FAILURE); /* do not unlink socket */
1489         }
1490         if (listen(audiod_socket, 5) < 0) {
1491                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1492                 exit(EXIT_FAILURE); /* do not unlink socket */
1493         }
1494         add_close_on_fork_list(audiod_socket);
1495 }
1496
1497 static int open_stat_pipe(void)
1498 {
1499         int ret, fd[3] = {-1, 1, 0};
1500         pid_t pid;
1501         ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1502         if (ret >= 0) {
1503                 ret = fd[1];
1504                 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1505                 add_close_on_fork_list(ret);
1506         } else
1507                 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1508         return ret;
1509 }
1510
1511 static int pre_select(fd_set *rfds, fd_set *wfds, struct timeval *tv)
1512 {
1513         int i, ret, max = -1;
1514
1515         FOR_EACH_SLOT(i) {
1516                 struct slot_info *s = &slot[i];
1517                 struct audio_format_info *a;
1518                 struct receiver_node *rn = s->receiver_node;
1519                 if (s->format < 0 || !rn)
1520                         continue;
1521                 a = &afi[s->format];
1522                 ret = a->receiver->pre_select(rn, rfds, wfds, tv);
1523 //              PARA_NOTICE_LOG("%s preselect: %d\n", a->receiver->name, ret);
1524                 max = MAX(max, ret);
1525         }
1526         return max;
1527
1528 }
1529 static void audiod_post_select(int select_ret, fd_set *rfds, fd_set *wfds)
1530 {
1531         int i, ret;
1532
1533         FOR_EACH_SLOT(i) {
1534                 struct slot_info *s = &slot[i];
1535                 struct audio_format_info *a;
1536                 struct receiver_node *rn = s->receiver_node;
1537                 if (s->format < 0 || !rn || rn->eof)
1538                         continue;
1539                 a = &afi[s->format];
1540                 ret = a->receiver->post_select(rn, select_ret, rfds, wfds);
1541                 if (ret <= 0) {
1542                         if (ret)
1543                                 PARA_ERROR_LOG("%s post select failed: %s (slot %d)\n",
1544                                 a->receiver->name, PARA_STRERROR(-ret), i);
1545                         else
1546                                 PARA_INFO_LOG("eof in slot %d\n", i);
1547                         rn->eof = 1;
1548                 }
1549                 if (ret < 0 && s->fci)
1550                         s->fci->error = ret;
1551         }
1552 }
1553
1554 /* TODO: move everything before the select call to pre_select() */
1555 static void __noreturn audiod_mainloop(void)
1556 {
1557         fd_set rfds, wfds;
1558         int ret, max_fileno, sbo = 0;
1559         char status_buf[STRINGSIZE] = "";
1560         struct timeval tv;
1561 repeat:
1562         FD_ZERO(&rfds);
1563         FD_ZERO(&wfds);
1564         max_fileno = 0;
1565         if (audiod_status != AUDIOD_ON)
1566                 kill_all_decoders();
1567         else if (playing)
1568                 start_current_receiver();
1569         max_fileno = set_stream_fds(&wfds);
1570         /* stat pipe (read) */
1571         if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1572                 close_stat_pipe();
1573         if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1574                 stat_pipe = open_stat_pipe();
1575                 sbo = 0;
1576                 status_buf[0] = '\0';
1577         }
1578         if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF) {
1579                 FD_SET(stat_pipe, &rfds);
1580                 max_fileno = MAX(max_fileno, stat_pipe);
1581         }
1582         /* always check signal pipe */
1583         FD_SET(signal_pipe, &rfds);
1584         max_fileno = MAX(max_fileno, signal_pipe);
1585         /* local socket */
1586         if (audiod_socket < 0)
1587                 audiod_get_socket(); /* doesn't return on errors */
1588         FD_SET(audiod_socket, &rfds);
1589         max_fileno = MAX(max_fileno, audiod_socket);
1590         tv.tv_sec = 0;
1591         tv.tv_usec = 200 * 1000;
1592         ret = pre_select(&rfds, &wfds, &tv);
1593         max_fileno = MAX(max_fileno, ret);
1594         ret = select(max_fileno + 1, &rfds, &wfds, NULL, &tv);
1595         if (ret < 0 && errno != EINTR)
1596                 PARA_ERROR_LOG("select returned %d (%s)\n", ret,
1597                         strerror(errno));
1598         if (audiod_status != AUDIOD_OFF)
1599                 audiod_status_dump();
1600         if (ret < 0)
1601                 goto repeat;
1602         audiod_post_select(ret, &rfds, &wfds);
1603         /* read status pipe */
1604         if (stat_pipe >=0 && FD_ISSET(stat_pipe, &rfds)) {
1605                 ret = read(stat_pipe, status_buf + sbo, STRINGSIZE - 1 - sbo);
1606                 if (ret <= 0) {
1607                         close_stat_pipe();
1608                         /* avoid busy loop if server is down */
1609                         while (sleep(1) > 0)
1610                                 ; /* try again*/
1611                 } else {
1612                         status_buf[ret + sbo] = '\0';
1613                         sbo = for_each_line(status_buf, ret + sbo,
1614                                 &check_stat_line);
1615                 }
1616         }
1617         slot_io(&wfds);
1618         if (FD_ISSET(audiod_socket, &rfds)) {
1619                 ret = handle_connect();
1620                 if (ret < 0) {
1621                         PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1622                 }
1623         }
1624         /* signals */
1625         if (FD_ISSET(signal_pipe, &rfds)) {
1626                 int sig_nr = para_next_signal();
1627                 if (sig_nr > 0)
1628                         handle_signal(sig_nr);
1629         }
1630         goto repeat;
1631 }
1632
1633 static void set_initial_status(void)
1634 {
1635         audiod_status = AUDIOD_ON;
1636         if (!conf.mode_given)
1637                 return;
1638         if (!strcmp(conf.mode_arg, "sb")) {
1639                 audiod_status = AUDIOD_STANDBY;
1640                 return;
1641         }
1642         if (!strcmp(conf.mode_arg, "off")) {
1643                 audiod_status = AUDIOD_OFF;
1644                 return;
1645         }
1646         if (strcmp(conf.mode_arg, "on"))
1647                 PARA_WARNING_LOG("%s", "invalid mode\n");
1648 }
1649
1650 int __noreturn main(int argc, char *argv[])
1651 {
1652         char *cf;
1653         int i;
1654
1655         valid_fd_012();
1656         hostname = para_hostname();
1657         cmdline_parser(argc, argv, &conf);
1658         para_drop_privileges(conf.user_arg);
1659         cf = configfile_exists();
1660         if (cf) {
1661                 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1662                         fprintf(stderr, "parse error in config file\n");
1663                         exit(EXIT_FAILURE);
1664                 }
1665         }
1666         log_welcome("para_audiod", conf.loglevel_arg);
1667         i = init_stream_io();
1668         if (i < 0) {
1669                 fprintf(stderr, "init stream io error: %s\n",
1670                         PARA_STRERROR(-i));
1671                 exit(EXIT_FAILURE);
1672         }
1673         server_uptime(UPTIME_SET);
1674         set_initial_status();
1675         FOR_EACH_SLOT(i)
1676                 clear_slot(i);
1677         init_grabbing();
1678         setup_signal_handling();
1679         if (conf.daemon_given)
1680                 daemon_init();
1681         audiod_mainloop();
1682 }