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