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