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