2 * Copyright (C) 2005-2006 Andre Noll <noll@mathematik.tu-darmstadt.de>
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.
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.
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.
19 /** \file audiod.c the paraslash's audio daemon */
21 #include <sys/time.h> /* gettimeofday */
24 #include "audiod.cmdline.h"
26 #include "close_on_fork.h"
29 #include "grab_client.cmdline.h"
30 #include "grab_client.h"
38 /** define the array of error lists needed by para_audiod */
40 /** define the array containing all supported audio formats */
41 DEFINE_AUDIO_FORMAT_ARRAY;
44 * the possible modes of operation
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
50 enum {AUDIOD_OFF, AUDIOD_ON, AUDIOD_STANDBY};
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 */
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 */
64 /** output of the last filter is written to stdin of this command */
66 /** do not start receiver/filters/writer before this time */
67 struct timeval restart_barrier;
71 * describes one instance of a receiver-filter-writer chain
73 * \sa receier_node, receiver, filter, filter_node, filter_chain_info
76 /** number of the audio format in this slot */
78 /** the file descriptor of the writer */
80 /** the process id of the writer */
82 /** time of the last successful read from the receiver */
84 /** time the last write to the write fd happend */
86 /** writer start time */
87 struct timeval wstime;
88 /** did we include \a write_fd in the fdset */
90 /** set to one if we have sent the TERM signal to \a wpid */
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;
98 static struct slot_info slot[MAX_STREAM_SLOTS];
100 /** defines one command of para_audiod */
101 struct audiod_command {
102 /** the name of the command */
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 */
114 extern const char *status_item_list[NUM_STAT_ITEMS];
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;
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};
137 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
139 static struct audiod_command cmds[] = {
142 .handler = com_cycle,
143 .description = "switch to next mode",
147 "on -> standby -> off -> on\n"
153 .description = "grab the audio stream",
154 .synopsis = "-- grab [grab_options]",
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"
164 .description = "display command list or help for given command",
165 .synopsis = "help [command]",
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"
172 " -- Beatles: Help\n"
178 .description = "deactivate para_audiod",
182 "Close connection to para_server and stop all decoders.\n"
188 .description = "activate para_audiod",
192 "Establish connection to para_server, retrieve para_server's current\n"
193 "status. If playing, start corresponding decoder. Otherwise stop\n"
200 .description = "enter standby mode",
204 "Stop all decoders but leave connection to para_server open.\n"
210 .description = "print status information",
211 .synopsis = "stat [item1 ...]",
214 "Dump given status items (all if none given) to stdout.\n"
220 .description = "terminate audiod",
224 "Stop all decoders, shut down connection to para_server and exit.\n"
232 /** iterate over all slots */
233 #define FOR_EACH_SLOT(slot) for (slot = 0; slot < MAX_STREAM_SLOTS; slot++)
234 /** iterate over all supported audio formats */
235 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
236 /** iterate over the array of all audiod commands */
237 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
240 * get the audio format number
241 * \param name the name of the audio format
243 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
244 * \a name is not a supported audio format.
246 int get_audio_format_num(char *name)
249 FOR_EACH_AUDIO_FORMAT(i)
250 if (!strcmp(name, audio_formats[i]))
252 return -E_UNSUPPORTED_AUDIO_FORMAT;
256 * log function. first argument is loglevel.
258 void para_log(int ll, const char* fmt,...)
264 char str[MAXLINE] = "";
266 if (ll < conf.loglevel_arg)
268 if (!logfile && conf.logfile_given)
269 logfile = open_log(conf.logfile_arg);
270 if (!logfile && conf.daemon_given)
281 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
282 fprintf(outfd, "%s %s ", str, hostname);
283 if (conf.loglevel_arg <= INFO)
284 fprintf(outfd, "%i ", ll);
286 vfprintf(outfd, fmt, argp);
290 static int client_write(int fd, const char *buf)
292 size_t len = strlen(buf);
293 return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
296 static char *get_time_string(struct timeval *newest_stime)
298 struct timeval now, diff, adj_stream_start, tmp;
299 int total = 0, use_server_time = 1;
304 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
306 if (audiod_status == AUDIOD_OFF)
308 if (sa_time_diff_sign > 0)
309 tv_diff(&server_stream_start, &sa_time_diff,
312 tv_add(&server_stream_start, &sa_time_diff,
314 tmp = adj_stream_start;
315 if (newest_stime && audiod_status == AUDIOD_ON) {
316 tv_diff(newest_stime, &adj_stream_start, &diff);
317 if (tv2ms(&diff) < 5000) {
322 gettimeofday(&now, NULL);
323 tv_diff(&now, &tmp, &diff);
324 total = diff.tv_sec + offset_seconds;
325 if (total > length_seconds)
326 total = length_seconds;
331 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
332 status_item_list[SI_PLAY_TIME],
333 use_server_time? "~" : "",
336 (length_seconds - total) / 60,
337 (length_seconds - total) % 60,
338 length_seconds? (total * 100 + length_seconds / 2) /
345 __malloc static char *audiod_status_string(void)
347 const char *status = (audiod_status == AUDIOD_ON)?
348 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
349 return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
352 static struct timeval *wstime(void)
355 struct timeval *max = NULL;
357 struct slot_info *s = &slot[i];
360 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
366 __malloc static char *decoder_flags(void)
369 char decoder_flags[MAX_STREAM_SLOTS + 1];
372 struct slot_info *s = &slot[i];
374 if (s->receiver_node)
379 flag += s->format * 4;
380 decoder_flags[i] = flag;
382 decoder_flags[MAX_STREAM_SLOTS] = '\0';
383 return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
387 static char *configfile_exists(void)
389 static char *config_file;
392 char *home = para_homedir();
393 config_file = make_message("%s/.paraslash/audiod.conf", home);
396 return file_exists(config_file)? config_file : NULL;
399 static void setup_signal_handling(void)
401 signal_pipe = para_signal_init();
402 PARA_INFO_LOG("signal pipe: fd %d\n", signal_pipe);
403 para_install_sighandler(SIGINT);
404 para_install_sighandler(SIGTERM);
405 para_install_sighandler(SIGCHLD);
406 para_install_sighandler(SIGHUP);
407 signal(SIGPIPE, SIG_IGN);
410 static void audiod_status_dump(void)
412 static char *p_ts, *p_us, *p_as, *p_df;
413 struct timeval *t = wstime();
414 char *us, *tmp = get_time_string(t);
416 if (tmp && (!p_ts || strcmp(tmp, p_ts)))
417 stat_client_write(tmp, SI_PLAY_TIME);
422 tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
424 if (!p_us || strcmp(p_us, tmp))
425 stat_client_write(tmp, SI_AUDIOD_UPTIME);
429 tmp = audiod_status_string();
430 if (!p_as || strcmp(p_as, tmp))
431 stat_client_write(tmp, SI_AUDIOD_STATUS);
435 tmp = decoder_flags();
436 if (!p_df || strcmp(p_df, tmp))
437 stat_client_write(tmp, SI_DECODER_FLAGS);
442 static void clear_slot(int slot_num)
444 struct slot_info *s = &slot[slot_num];
446 PARA_INFO_LOG("clearing slot %d\n", slot_num);
447 memset(s, 0, sizeof(struct slot_info));
451 static void kill_stream_writer(int slot_num)
453 struct slot_info *s = &slot[slot_num];
455 if (s->format < 0 || s->wkilled || s->wpid <= 0)
457 PARA_DEBUG_LOG("kill -TERM %d (%s stream writer in slot %d)\n",
458 s->wpid, audio_formats[s->format], slot_num);
459 kill(s->wpid, SIGTERM);
464 static void set_restart_barrier(int format, struct timeval *now)
471 gettimeofday(&tmp, NULL);
472 tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
475 static void close_receiver(int slot_num)
477 struct slot_info *s = &slot[slot_num];
478 struct audio_format_info *a;
480 if (s->format < 0 || !s->receiver_node)
483 PARA_NOTICE_LOG("closing %s recevier in slot %d\n",
484 audio_formats[s->format] , slot_num);
485 a->receiver->close(s->receiver_node);
486 free(s->receiver_node);
487 s->receiver_node = NULL;
488 set_restart_barrier(s->format, NULL);
491 static void kill_all_decoders(void)
496 if (slot[i].format >= 0) {
497 PARA_INFO_LOG("stopping decoder in slot %d\n", i);
498 kill_stream_writer(i);
502 static void check_sigchld(void)
507 gettimeofday(&now, NULL);
510 pid = para_reap_child();
514 struct slot_info *s = &slot[i];
518 if (pid == s->wpid) {
520 lifetime = now.tv_sec - s->wstime.tv_sec;
521 PARA_INFO_LOG("%s stream writer in slot %d died "
523 audio_formats[s->format], i, lifetime);
524 set_restart_barrier(s->format, &now);
525 goto reap_next_child;
528 PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
529 goto reap_next_child;
532 static int get_empty_slot(void)
543 if (s->write_fd > 0 || s->wpid > 0)
545 if (s->receiver_node)
552 return -E_NO_MORE_SLOTS;
555 static int decoder_running(int format)
562 if (s->format == format && s->receiver_node)
564 if (s->format == format && s->wpid > 0)
570 static void close_stat_pipe(void)
576 PARA_NOTICE_LOG("%s", "closing status pipe\n");
578 del_close_on_fork_list(stat_pipe);
581 for (i = 0; i < NUM_STAT_ITEMS; i++) {
582 free(stat_item_values[i]);
583 stat_item_values[i] = NULL;
588 audiod_status_dump();
590 stat_item_values[SI_STATUS_BAR] = make_message("%s:no connection to para_server\n",
591 status_item_list[SI_STATUS_BAR]);
592 stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
595 static void __noreturn clean_exit(int status, const char *msg)
597 PARA_EMERG_LOG("%s\n", msg);
606 __malloc static char *glob_cmd(char *cmd)
608 char *ret, *replacement;
609 struct timeval tmp, delay, rss; /* real stream start */
611 delay.tv_sec = conf.stream_delay_arg / 1000;
612 delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
613 // PARA_INFO_LOG("delay: %lu:%lu\n", delay.tv_sec, delay.tv_usec);
614 if (sa_time_diff_sign < 0)
615 tv_add(&server_stream_start, &sa_time_diff, &rss);
617 tv_diff(&server_stream_start, &sa_time_diff, &rss);
618 tv_add(&rss, &delay, &tmp);
619 replacement = make_message("%lu:%lu", tmp.tv_sec, tmp.tv_usec);
620 ret = s_a_r(cmd, "STREAM_START", replacement);
624 PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
627 gettimeofday(&now, NULL);
628 PARA_INFO_LOG("now: %lu:%lu\n", now.tv_sec, now.tv_usec);
634 /** get the number of filters for the given audio format */
635 int num_filters(int audio_format_num)
637 return afi[audio_format_num].num_filters;
640 static void open_filters(int slot_num)
642 struct slot_info *s = &slot[slot_num];
643 struct audio_format_info *a = &afi[s->format];
644 int nf = a->num_filters;
647 s->fci = para_calloc(sizeof(struct filter_chain_info));
648 INIT_LIST_HEAD(&s->fci->filters);
651 s->fci->inbuf = s->receiver_node->buf;
652 s->fci->in_loaded = &s->receiver_node->loaded;
653 s->fci->outbuf = s->receiver_node->buf;
654 s->fci->out_loaded = &s->receiver_node->loaded;
655 s->fci->eof = &s->receiver_node->eof;
656 for (i = 0; i < nf; i++) {
657 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
658 fn->conf = a->filter_conf[i];
660 fn->filter = a->filters[i];
661 INIT_LIST_HEAD(&fn->callbacks);
662 list_add_tail(&fn->node, &s->fci->filters);
663 fn->filter->open(fn);
664 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
665 audio_formats[s->format], i + 1, nf,
666 fn->filter->name, slot_num);
667 s->fci->outbuf = fn->buf;
668 s->fci->out_loaded = &fn->loaded;
670 PARA_DEBUG_LOG("output buffer for filter chain %p: %p\n", s->fci,
674 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
676 struct filter_node *fn;
680 struct slot_info *s = &slot[i];
681 if (s->format < 0 || !s->fci)
683 if (slot_num >= 0 && slot_num != i)
685 if (format >= 0 && s->format != format)
687 if (num_filters(i) < filternum)
691 list_for_each_entry(fn, &s->fci->filters, node)
692 if (filternum <= 0 || j++ == filternum)
699 static void start_stream_writer(int slot_num)
701 int ret, fds[3] = {1, -1, -1};
702 struct slot_info *s = &slot[slot_num];
703 struct audio_format_info *a = &afi[s->format];
707 glob = glob_cmd(a->write_cmd);
709 glob = para_strdup("para_play");
710 PARA_INFO_LOG("starting stream writer: %s\n", glob);
711 open_filters(slot_num);
712 ret = para_exec_cmdline_pid(&s->wpid, glob, fds);
715 PARA_ERROR_LOG("exec failed (%d)\n", ret);
718 s->write_fd = fds[0];
719 add_close_on_fork_list(s->write_fd);
720 /* we write to this fd in do_select, so we need non-blocking */
721 fcntl(s->write_fd, F_SETFL, O_NONBLOCK);
722 gettimeofday(&s->wstime, NULL);
723 current_decoder = slot_num;
724 activate_inactive_grab_clients(slot_num, s->format, &s->fci->filters);
727 static void open_receiver(int format)
729 struct audio_format_info *a = &afi[format];
733 slot_num = get_empty_slot();
735 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
738 gettimeofday(&s->rtime, NULL);
740 s->receiver_node = para_calloc(sizeof(struct receiver_node));
741 s->receiver_node->conf = a->receiver_conf;
742 ret = a->receiver->open(s->receiver_node);
744 PARA_ERROR_LOG("failed to open receiver (%s)\n",
745 PARA_STRERROR(-ret));
746 free(s->receiver_node);
747 s->receiver_node = NULL;
750 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
751 audio_formats[s->format], a->receiver->name, slot_num);
754 static int is_frozen(int format)
757 struct audio_format_info *a = &afi[format];
759 gettimeofday(&now, NULL);
760 return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
763 static void start_current_receiver(void)
769 i = get_audio_format_num(af_status);
772 if ((decoder_running(i) & 1) || is_frozen(i))
777 static void compute_time_diff(const struct timeval *status_time)
779 struct timeval now, tmp, diff;
782 const struct timeval max_deviation = {0, 500 * 1000};
783 const int time_smooth = 5;
785 gettimeofday(&now, NULL);
786 sign = tv_diff(status_time, &now, &diff);
787 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
788 // sign, sa_time_diff_sign);
790 sa_time_diff_sign = sign;
796 int s = tv_diff(&diff, &sa_time_diff, &tmp);
797 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
798 PARA_WARNING_LOG("time diff jump: %lims\n",
802 sa_time_diff_sign = tv_convex_combination(
803 sa_time_diff_sign * time_smooth, &sa_time_diff,
804 count > 10? sign : sign * time_smooth, &diff,
807 PARA_INFO_LOG("time diff (cur/avg): "
809 sign * diff.tv_sec, (diff.tv_usec + 500) / 1000,
810 sa_time_diff_sign * sa_time_diff.tv_sec,
811 (sa_time_diff.tv_usec + 500)/ 1000);
814 static void check_stat_line(char *line)
823 itemnum = stat_line_valid(line);
825 PARA_WARNING_LOG("invalid status line: %s\n", line);
828 tmp = make_message("%s\n", line);
829 stat_client_write(tmp, itemnum);
831 free(stat_item_values[itemnum]);
832 stat_item_values[itemnum] = para_strdup(line);
833 ilen = strlen(status_item_list[itemnum]);
836 playing = strstr(line, "playing")? 1 : 0;
840 af_status = para_strdup(line + ilen + 1);
843 offset_seconds = atoi(line + ilen + 1);
846 length_seconds = atoi(line + ilen + 1);
848 case SI_STREAM_START:
849 if (sscanf(line + ilen + 1, "%lu.%lu",
850 &tv.tv_sec, &tv.tv_usec) == 2)
851 server_stream_start = tv;
853 case SI_CURRENT_TIME:
854 if (sscanf(line + ilen + 1, "%lu.%lu", &tv.tv_sec,
856 compute_time_diff(&tv);
861 static void handle_signal(int sig)
865 return check_sigchld();
869 PARA_EMERG_LOG("terminating on signal %d\n", sig);
870 clean_exit(EXIT_FAILURE, "caught deadly signal");
875 static void check_timeouts(void)
878 int slot_num, timeout = conf.stream_timeout_arg;
880 gettimeofday(&now, NULL);
881 FOR_EACH_SLOT(slot_num) {
882 struct slot_info *s = &slot[slot_num];
885 /* check read time */
886 if (s->receiver_node &&
887 now.tv_sec > s->rtime.tv_sec + timeout) {
888 PARA_INFO_LOG("%s input buffer (slot %d) not ready\n",
889 audio_formats[s->format], slot_num);
893 close_receiver(slot_num);
895 /* check write time */
896 if (s->wpid > 0 && !s->wkilled &&
897 now.tv_sec > s->wtime.tv_sec + timeout) {
898 PARA_INFO_LOG("%s output buffer (slot %d) not ready\n",
899 audio_formats[s->format], slot_num);
906 static size_t get_loaded_bytes(int slot_num)
909 struct slot_info *s = &slot[slot_num];
910 struct receiver_node *rn = s->receiver_node;
915 if (afi[s->format].num_filters) {
917 loaded = *s->fci->out_loaded;
927 static void close_decoder_if_idle(int slot_num)
929 struct slot_info *s = &slot[slot_num];
930 struct receiver_node *rn = s->receiver_node;
936 if (!rn->eof && !s->fci->error && s->wpid > 0)
938 if (!s->fci->error && s->wpid > 0) { /* eof */
939 if (filter_io(s->fci) > 0)
941 if (get_loaded_bytes(slot_num))
944 if (s->write_fd > 0) {
945 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
948 del_close_on_fork_list(s->write_fd);
952 return; /* wait until writer dies before closing filters */
953 PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
955 close_filters(s->fci);
957 close_receiver(slot_num);
958 clear_slot(slot_num);
961 static int set_stream_fds(fd_set *wfds)
963 int i, max_fileno = -1;
967 struct slot_info *s = &slot[i];
968 struct audio_format_info *a;
969 struct receiver_node *rn;
971 close_decoder_if_idle(i);
976 rn = s->receiver_node;
977 if (rn && rn->loaded && !s->wpid) {
978 PARA_INFO_LOG("no writer in slot %d\n", i);
979 start_stream_writer(i);
981 if (s->write_fd <= 0)
983 if (!get_loaded_bytes(i))
985 FD_SET(s->write_fd, wfds);
987 max_fileno = MAX(s->write_fd, max_fileno);
989 // PARA_INFO_LOG("return %d\n", max_fileno);
993 static int write_audio_data(int slot_num)
995 struct slot_info *s = &slot[slot_num];
996 struct audio_format_info *a = &afi[s->format];
997 struct receiver_node *rn = s->receiver_node;
1002 if (a->num_filters) {
1003 buf = &s->fci->outbuf;
1004 len = s->fci->out_loaded;
1009 PARA_DEBUG_LOG("writing %p (%zd bytes)\n", *buf, *len);
1010 rv = write(s->write_fd, *buf, *len);
1011 PARA_DEBUG_LOG("wrote %d/%zd\n", rv, *len);
1013 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
1014 slot_num, s->write_fd, strerror(errno));
1016 s->fci->error = E_WRITE_AUDIO_DATA;
1017 } else if (rv != *len) {
1018 PARA_DEBUG_LOG("partial %s write (%i/%zd) for slot %d\n",
1019 audio_formats[s->format], rv, *len, slot_num);
1021 memmove(*buf, *buf + rv, *len);
1025 gettimeofday(&s->wtime, NULL);
1029 static void slot_io(fd_set *wfds)
1034 struct slot_info *s = &slot[i];
1035 struct receiver_node *rn = s->receiver_node;
1037 if (rn && rn->loaded)
1038 gettimeofday(&s->rtime, NULL);
1039 if (s->format >= 0 && s->write_fd > 0 && s->fci) {
1040 ret = filter_io(s->fci);
1042 s->fci->error = -ret;
1043 // PARA_DEBUG_LOG("slot %d, filter io %d bytes, check write: %d, loaded: %d/%d, eof: %d\n",
1044 // i, ret, s->wcheck, rn->loaded, *s->fci->out_loaded, rn->eof);
1046 if (s->write_fd <= 0 || !s->wcheck || !FD_ISSET(s->write_fd, wfds))
1048 write_audio_data(i);
1052 static int parse_stream_command(const char *txt, char **cmd)
1054 char *p = strchr(txt, ':');
1058 return -E_MISSING_COLON;
1060 FOR_EACH_AUDIO_FORMAT(i) {
1061 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1066 return -E_UNSUPPORTED_AUDIO_FORMAT;
1069 static int add_filter(int format, char *cmdline)
1071 struct audio_format_info *a = &afi[format];
1072 int filter_num, nf = a->num_filters;
1074 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1077 a->filters[nf] = &filters[filter_num];
1079 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1080 a->filters[nf]->name);
1084 static int setup_default_filters(void)
1088 FOR_EACH_AUDIO_FORMAT(i) {
1089 struct audio_format_info *a = &afi[i];
1094 /* add "dec" to audio format name */
1095 tmp = make_message("%sdec", audio_formats[i]);
1096 for (j = 0; filters[j].name; j++)
1097 if (!strcmp(tmp, filters[j].name))
1100 ret = -E_UNSUPPORTED_FILTER;
1101 if (!filters[j].name)
1103 tmp = para_strdup(filters[j].name);
1104 ret = add_filter(i, tmp);
1108 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i], filters[j].name);
1109 ret = add_filter(i, para_strdup("wav"));
1112 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1118 static int init_stream_io(void)
1120 int i, ret, receiver_num;
1123 for (i = 0; i < conf.stream_write_cmd_given; i++) {
1124 ret = parse_stream_command(conf.stream_write_cmd_arg[i], &cmd);
1127 afi[ret].write_cmd = para_strdup(cmd);
1128 PARA_INFO_LOG("%s write command: %s\n", audio_formats[ret], afi[ret].write_cmd);
1130 for (i = 0; receivers[i].name; i++) {
1131 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1132 receivers[i].init(&receivers[i]);
1134 for (i = 0; i < conf.receiver_given; i++) {
1135 char *arg = conf.receiver_arg[i];
1136 char *recv = strchr(arg, ':');
1137 ret = -E_MISSING_COLON;
1142 ret = get_audio_format_num(arg);
1145 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1146 if (!afi[ret].receiver_conf) {
1147 ret = -E_RECV_SYNTAX;
1150 afi[ret].receiver = &receivers[receiver_num];
1152 /* use the first available receiver with no arguments
1153 * for those audio formats for which no receiver
1156 cmd = para_strdup(receivers[0].name);
1157 FOR_EACH_AUDIO_FORMAT(i) {
1158 struct audio_format_info *a = &afi[i];
1159 if (a->receiver_conf)
1161 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1162 if (!a->receiver_conf)
1163 return -E_RECV_SYNTAX;
1164 a->receiver = &receivers[receiver_num];
1168 filter_init(filters);
1169 FOR_EACH_AUDIO_FORMAT(i) {
1170 afi[i].filter_conf = para_malloc((conf.filter_given + 1) * sizeof(char *));
1171 afi[i].filters = para_malloc((conf.filter_given + 1) * sizeof(struct filter *));
1173 if (!conf.no_default_filters_given)
1174 return setup_default_filters();
1175 for (i = 0; i < conf.filter_given; i++) {
1176 char *arg = conf.filter_arg[i];
1177 char *filter_name = strchr(arg, ':');
1178 ret = -E_MISSING_COLON;
1181 *filter_name = '\0';
1183 ret = get_audio_format_num(arg);
1186 ret = add_filter(ret, filter_name);
1195 static int dump_commands(int fd)
1197 char *buf = para_strdup(""), *tmp = NULL;
1201 FOR_EACH_COMMAND(i) {
1202 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1203 cmds[i].description);
1207 ret = client_write(fd, buf);
1213 * command handlers don't close their fd on errors (ret < 0) so that
1214 * its caller can send an error message. Otherwise (ret >= 0) it's up
1215 * to each individual command to close the fd if necessary.
1218 static int com_help(int fd, int argc, char **argv)
1222 const char *dflt = "No such command. Available commands:\n";
1225 ret = dump_commands(fd);
1228 FOR_EACH_COMMAND(i) {
1229 if (strcmp(cmds[i].name, argv[1]))
1232 "NAME\n\t%s -- %s\n"
1233 "SYNOPSIS\n\tpara_audioc %s\n"
1234 "DESCRIPTION\n%s\n",
1236 cmds[i].description,
1240 ret = client_write(fd, buf);
1244 ret = client_write(fd, dflt);
1246 ret = dump_commands(fd);
1253 static int com_stat(int fd, __unused int argc, __unused char **argv)
1257 long unsigned mask = ~0LU;
1261 for (i = 1; i < argc; i++) {
1262 ret = stat_item_valid(argv[i]);
1268 PARA_INFO_LOG("mask: 0x%lx\n", mask);
1269 if (mask & (1 << SI_PLAY_TIME)) {
1270 struct timeval *t = wstime();
1271 char *ts = get_time_string(t);
1273 ret = client_write(fd, ts);
1279 if (mask & (1 << SI_AUDIOD_UPTIME)) {
1280 char *tmp, *us = uptime_str();
1281 tmp = make_message("%s:%s\n",
1282 status_item_list[SI_AUDIOD_UPTIME], us);
1284 ret = client_write(fd, tmp);
1289 if (mask & (1 << SI_AUDIOD_STATUS)) {
1290 char *s = audiod_status_string();
1291 ret = client_write(fd, s);
1296 if (mask & (1 << SI_DECODER_FLAGS)) {
1297 char *df =decoder_flags();
1298 ret = client_write(fd, df);
1304 for (i = 0; i < NUM_STAT_ITEMS; i++) {
1306 if (!((1 << i) & mask))
1308 v = stat_item_values[i];
1309 tmp = make_message("%s%s%s", buf? buf: "",
1310 v? v : "", v? "\n" : "");
1314 ret = client_write(fd, buf);
1317 ret = stat_client_add(fd, mask);
1323 static char *list_filters(void)
1326 char *tmp, *msg = make_message("format\tnum\tcmd\n");
1328 FOR_EACH_AUDIO_FORMAT(i) {
1329 for (j = 0; j < afi[i].num_filters; j++) {
1330 tmp = make_message("%s\t%i\t%s\n",
1331 afi[i].name, j, afi[i].filter_cmds[j]);
1332 msg = para_strcat(msg, tmp);
1335 tmp = make_message("%s\t%i\t%s\n", afi[i].name,
1336 j, afi[i].write_cmd);
1337 msg = para_strcat(msg, tmp);
1344 static int com_grab(int fd, int argc, char **argv)
1346 struct grab_client *gc;
1347 struct filter_node *fn;
1350 PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1351 gc = grab_client_new(fd, argc, argv, &err);
1352 PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1355 fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1357 activate_grab_client(gc, fn);
1360 if (err != -E_GC_HELP_GIVEN)
1362 err = client_write(fd, "Usage: para_audioc [audioc_options] -- "
1363 "grab [grab_options]\nAvailable options:\n");
1366 err = client_write(fd, GRAB_HELP_TXT);
1373 static int __noreturn com_term(int fd, __unused int argc, __unused char **argv)
1376 clean_exit(EXIT_SUCCESS, "terminating on user request");
1379 static int com_on(int fd, __unused int argc, __unused char **argv)
1381 audiod_status = AUDIOD_ON;
1386 static int com_off(int fd, __unused int argc, __unused char **argv)
1388 audiod_status = AUDIOD_OFF;
1393 static int com_sb(int fd, __unused int argc, __unused char **argv)
1395 audiod_status = AUDIOD_STANDBY;
1400 static int com_cycle(int fd, int argc, char **argv)
1402 switch (audiod_status) {
1404 return com_sb(fd, argc, argv);
1407 return com_on(fd, argc, argv);
1409 case AUDIOD_STANDBY:
1410 return com_off(fd, argc, argv);
1417 static int check_perms(struct ucred *c)
1421 if (!conf.user_allow_given)
1423 for (i = 0; i < conf.user_allow_given; i++)
1424 if (c->uid == conf.user_allow_arg[i])
1426 return -E_UCRED_PERM;
1429 static int handle_connect(void)
1431 int i, argc, ret, clifd = -1;
1433 char *buf = para_malloc(MAXLINE), **argv = NULL;
1434 struct sockaddr_un unix_addr;
1436 ret = para_accept(audiod_socket, &unix_addr, sizeof(struct sockaddr_un));
1440 ret = recv_cred_buffer(clifd, buf, MAXLINE - 1, &c);
1443 PARA_INFO_LOG("pid: %i, uid: %i, gid: %i, ret: %i, buf: %s\n", c.pid, c.uid, c.gid, ret, buf);
1445 ret = check_perms(&c);
1448 argc = split_args(buf, &argv, '\n');
1449 PARA_INFO_LOG("argv[0]: %s\n", argv[0]);
1450 for (i = 0; cmds[i].name; i++) {
1451 if (strcmp(cmds[i].name, argv[0]))
1453 ret = cmds[i].handler(clifd, argc + 1, argv);
1456 ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1460 if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1461 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1462 client_write(clifd, tmp);
1469 static void audiod_get_socket(void)
1471 struct sockaddr_un unix_addr;
1473 if (conf.socket_given)
1474 socket_name = para_strdup(conf.socket_arg);
1476 char *hn = para_hostname();
1477 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1481 PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1482 if (conf.force_given)
1483 unlink(socket_name);
1484 audiod_socket = create_pf_socket(socket_name, &unix_addr,
1485 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1486 if (audiod_socket < 0) {
1487 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1488 exit(EXIT_FAILURE); /* do not unlink socket */
1490 if (listen(audiod_socket, 5) < 0) {
1491 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1492 exit(EXIT_FAILURE); /* do not unlink socket */
1494 add_close_on_fork_list(audiod_socket);
1497 static int open_stat_pipe(void)
1499 int ret, fd[3] = {-1, 1, 0};
1501 ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1504 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1505 add_close_on_fork_list(ret);
1507 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1511 static int pre_select(fd_set *rfds, fd_set *wfds, struct timeval *tv)
1513 int i, ret, max = -1;
1516 struct slot_info *s = &slot[i];
1517 struct audio_format_info *a;
1518 struct receiver_node *rn = s->receiver_node;
1519 if (s->format < 0 || !rn)
1521 a = &afi[s->format];
1522 ret = a->receiver->pre_select(rn, rfds, wfds, tv);
1523 // PARA_NOTICE_LOG("%s preselect: %d\n", a->receiver->name, ret);
1524 max = MAX(max, ret);
1529 static void audiod_post_select(int select_ret, fd_set *rfds, fd_set *wfds)
1534 struct slot_info *s = &slot[i];
1535 struct audio_format_info *a;
1536 struct receiver_node *rn = s->receiver_node;
1537 if (s->format < 0 || !rn || rn->eof)
1539 a = &afi[s->format];
1540 ret = a->receiver->post_select(rn, select_ret, rfds, wfds);
1543 PARA_ERROR_LOG("%s post select failed: %s (slot %d)\n",
1544 a->receiver->name, PARA_STRERROR(-ret), i);
1546 PARA_INFO_LOG("eof in slot %d\n", i);
1549 if (ret < 0 && s->fci)
1550 s->fci->error = ret;
1554 /* TODO: move everything before the select call to pre_select() */
1555 static void __noreturn audiod_mainloop(void)
1558 int ret, max_fileno, sbo = 0;
1559 char status_buf[STRINGSIZE] = "";
1565 if (audiod_status != AUDIOD_ON)
1566 kill_all_decoders();
1568 start_current_receiver();
1569 max_fileno = set_stream_fds(&wfds);
1570 /* stat pipe (read) */
1571 if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1573 if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1574 stat_pipe = open_stat_pipe();
1576 status_buf[0] = '\0';
1578 if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF) {
1579 FD_SET(stat_pipe, &rfds);
1580 max_fileno = MAX(max_fileno, stat_pipe);
1582 /* always check signal pipe */
1583 FD_SET(signal_pipe, &rfds);
1584 max_fileno = MAX(max_fileno, signal_pipe);
1586 if (audiod_socket < 0)
1587 audiod_get_socket(); /* doesn't return on errors */
1588 FD_SET(audiod_socket, &rfds);
1589 max_fileno = MAX(max_fileno, audiod_socket);
1591 tv.tv_usec = 200 * 1000;
1592 ret = pre_select(&rfds, &wfds, &tv);
1593 max_fileno = MAX(max_fileno, ret);
1594 ret = select(max_fileno + 1, &rfds, &wfds, NULL, &tv);
1595 if (ret < 0 && errno != EINTR)
1596 PARA_ERROR_LOG("select returned %d (%s)\n", ret,
1598 if (audiod_status != AUDIOD_OFF)
1599 audiod_status_dump();
1602 audiod_post_select(ret, &rfds, &wfds);
1603 /* read status pipe */
1604 if (stat_pipe >=0 && FD_ISSET(stat_pipe, &rfds)) {
1605 ret = read(stat_pipe, status_buf + sbo, STRINGSIZE - 1 - sbo);
1608 /* avoid busy loop if server is down */
1609 while (sleep(1) > 0)
1612 status_buf[ret + sbo] = '\0';
1613 sbo = for_each_line(status_buf, ret + sbo,
1618 if (FD_ISSET(audiod_socket, &rfds)) {
1619 ret = handle_connect();
1621 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1625 if (FD_ISSET(signal_pipe, &rfds)) {
1626 int sig_nr = para_next_signal();
1628 handle_signal(sig_nr);
1633 static void set_initial_status(void)
1635 audiod_status = AUDIOD_ON;
1636 if (!conf.mode_given)
1638 if (!strcmp(conf.mode_arg, "sb")) {
1639 audiod_status = AUDIOD_STANDBY;
1642 if (!strcmp(conf.mode_arg, "off")) {
1643 audiod_status = AUDIOD_OFF;
1646 if (strcmp(conf.mode_arg, "on"))
1647 PARA_WARNING_LOG("%s", "invalid mode\n");
1650 int __noreturn main(int argc, char *argv[])
1656 hostname = para_hostname();
1657 cmdline_parser(argc, argv, &conf);
1658 para_drop_privileges(conf.user_arg);
1659 cf = configfile_exists();
1661 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1662 fprintf(stderr, "parse error in config file\n");
1666 log_welcome("para_audiod", conf.loglevel_arg);
1667 i = init_stream_io();
1669 fprintf(stderr, "init stream io error: %s\n",
1673 server_uptime(UPTIME_SET);
1674 set_initial_status();
1678 setup_signal_handling();
1679 if (conf.daemon_given)