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