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]",
157 "grab ('splice') the audio stream at any position in the filter \n"
158 "chain and send that data back to the client. Try\n"
159 "\t para_audioc -- grab -h\n"
160 "for the list of available options.\n"
166 .description = "display command list or help for given command",
167 .synopsis = "help [command]",
170 "When I was younger, so much younger than today, I never needed\n"
171 "anybody's help in any way. But now these days are gone, I'm not so\n"
172 "self assured. Now I find I've changed my mind and opened up the doors.\n"
174 " -- Beatles: Help\n"
180 .description = "deactivate para_audiod",
184 "Close connection to para_server and stop all decoders.\n"
190 .description = "activate para_audiod",
194 "Establish connection to para_server, retrieve para_server's current\n"
195 "status. If playing, start corresponding decoder. Otherwise stop\n"
202 .description = "enter standby mode",
206 "Stop all decoders but leave connection to para_server open.\n"
212 .description = "print status information",
213 .synopsis = "stat [item1 ...]",
216 "Dump given status items (all if none given) to stdout.\n"
222 .description = "terminate audiod",
226 "Stop all decoders, shut down connection to para_server and exit.\n"
234 /** iterate over all slots */
235 #define FOR_EACH_SLOT(slot) for (slot = 0; slot < MAX_STREAM_SLOTS; slot++)
236 /** iterate over all supported audio formats */
237 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
238 /** iterate over the array of all audiod commands */
239 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
242 * get the audio format number
243 * \param name the name of the audio format
245 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
246 * \a name is not a supported audio format.
248 int get_audio_format_num(char *name)
251 FOR_EACH_AUDIO_FORMAT(i)
252 if (!strcmp(name, audio_formats[i]))
254 return -E_UNSUPPORTED_AUDIO_FORMAT;
258 * log function. first argument is loglevel.
260 void para_log(int ll, const char* fmt,...)
266 char str[MAXLINE] = "";
268 if (ll < conf.loglevel_arg)
270 if (!logfile && conf.logfile_given)
271 logfile = open_log(conf.logfile_arg);
272 if (!logfile && conf.daemon_given)
283 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
284 fprintf(outfd, "%s %s ", str, hostname);
285 if (conf.loglevel_arg <= INFO)
286 fprintf(outfd, "%i ", ll);
288 vfprintf(outfd, fmt, argp);
292 static int client_write(int fd, const char *buf)
294 size_t len = strlen(buf);
295 return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
298 static char *get_time_string(struct timeval *newest_stime)
300 struct timeval now, diff, adj_stream_start, tmp;
301 int total = 0, use_server_time = 1;
306 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
308 if (audiod_status == AUDIOD_OFF)
310 if (sa_time_diff_sign > 0)
311 tv_diff(&server_stream_start, &sa_time_diff,
314 tv_add(&server_stream_start, &sa_time_diff,
316 tmp = adj_stream_start;
317 if (newest_stime && audiod_status == AUDIOD_ON) {
318 tv_diff(newest_stime, &adj_stream_start, &diff);
319 if (tv2ms(&diff) < 5000) {
324 gettimeofday(&now, NULL);
325 tv_diff(&now, &tmp, &diff);
326 total = diff.tv_sec + offset_seconds;
327 if (total > length_seconds)
328 total = length_seconds;
333 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
334 status_item_list[SI_PLAY_TIME],
335 use_server_time? "~" : "",
338 (length_seconds - total) / 60,
339 (length_seconds - total) % 60,
340 length_seconds? (total * 100 + length_seconds / 2) /
347 __malloc static char *audiod_status_string(void)
349 const char *status = (audiod_status == AUDIOD_ON)?
350 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
351 return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
354 static struct timeval *wstime(void)
357 struct timeval *max = NULL;
359 struct slot_info *s = &slot[i];
362 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
368 __malloc static char *decoder_flags(void)
371 char decoder_flags[MAX_STREAM_SLOTS + 1];
374 struct slot_info *s = &slot[i];
376 if (s->receiver_node)
381 flag += s->format * 4;
382 decoder_flags[i] = flag;
384 decoder_flags[MAX_STREAM_SLOTS] = '\0';
385 return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
389 static char *configfile_exists(void)
391 static char *config_file;
394 char *home = para_homedir();
395 config_file = make_message("%s/.paraslash/audiod.conf", home);
398 return file_exists(config_file)? config_file : NULL;
401 static void setup_signal_handling(void)
403 signal_pipe = para_signal_init();
404 PARA_INFO_LOG("signal pipe: fd %d\n", signal_pipe);
405 para_install_sighandler(SIGINT);
406 para_install_sighandler(SIGTERM);
407 para_install_sighandler(SIGCHLD);
408 para_install_sighandler(SIGHUP);
409 signal(SIGPIPE, SIG_IGN);
412 static void audiod_status_dump(void)
414 static char *p_ts, *p_us, *p_as, *p_df;
415 struct timeval *t = wstime();
416 char *us, *tmp = get_time_string(t);
418 if (tmp && (!p_ts || strcmp(tmp, p_ts)))
419 stat_client_write(tmp, SI_PLAY_TIME);
424 tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
426 if (!p_us || strcmp(p_us, tmp))
427 stat_client_write(tmp, SI_AUDIOD_UPTIME);
431 tmp = audiod_status_string();
432 if (!p_as || strcmp(p_as, tmp))
433 stat_client_write(tmp, SI_AUDIOD_STATUS);
437 tmp = decoder_flags();
438 if (!p_df || strcmp(p_df, tmp))
439 stat_client_write(tmp, SI_DECODER_FLAGS);
444 static void clear_slot(int slot_num)
446 struct slot_info *s = &slot[slot_num];
448 PARA_INFO_LOG("clearing slot %d\n", slot_num);
449 memset(s, 0, sizeof(struct slot_info));
453 static void kill_stream_writer(int slot_num)
455 struct slot_info *s = &slot[slot_num];
457 if (s->format < 0 || s->wkilled || s->wpid <= 0)
459 PARA_DEBUG_LOG("kill -TERM %d (%s stream writer in slot %d)\n",
460 s->wpid, audio_formats[s->format], slot_num);
461 kill(s->wpid, SIGTERM);
466 static void set_restart_barrier(int format, struct timeval *now)
473 gettimeofday(&tmp, NULL);
474 tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
477 static void close_receiver(int slot_num)
479 struct slot_info *s = &slot[slot_num];
480 struct audio_format_info *a;
482 if (s->format < 0 || !s->receiver_node)
485 PARA_NOTICE_LOG("closing %s recevier in slot %d\n",
486 audio_formats[s->format] , slot_num);
487 a->receiver->close(s->receiver_node);
488 free(s->receiver_node);
489 s->receiver_node = NULL;
490 set_restart_barrier(s->format, NULL);
493 static void kill_all_decoders(void)
498 if (slot[i].format >= 0) {
499 PARA_INFO_LOG("stopping decoder in slot %d\n", i);
500 kill_stream_writer(i);
504 static void check_sigchld(void)
509 gettimeofday(&now, NULL);
512 pid = para_reap_child();
516 struct slot_info *s = &slot[i];
520 if (pid == s->wpid) {
522 lifetime = now.tv_sec - s->wstime.tv_sec;
523 PARA_INFO_LOG("%s stream writer in slot %d died "
525 audio_formats[s->format], i, lifetime);
526 set_restart_barrier(s->format, &now);
527 goto reap_next_child;
530 PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
531 goto reap_next_child;
534 static int get_empty_slot(void)
545 if (s->write_fd > 0 || s->wpid > 0)
547 if (s->receiver_node)
554 return -E_NO_MORE_SLOTS;
557 static int decoder_running(int format)
564 if (s->format == format && s->receiver_node)
566 if (s->format == format && s->wpid > 0)
572 static void close_stat_pipe(void)
578 PARA_NOTICE_LOG("%s", "closing status pipe\n");
580 del_close_on_fork_list(stat_pipe);
583 for (i = 0; i < NUM_STAT_ITEMS; i++) {
584 free(stat_item_values[i]);
585 stat_item_values[i] = NULL;
590 audiod_status_dump();
592 stat_item_values[SI_STATUS_BAR] = make_message("%s:no connection to para_server\n",
593 status_item_list[SI_STATUS_BAR]);
594 stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
597 static void __noreturn clean_exit(int status, const char *msg)
599 PARA_EMERG_LOG("%s\n", msg);
608 __malloc static char *glob_cmd(char *cmd)
610 char *ret, *replacement;
611 struct timeval tmp, delay, rss; /* real stream start */
613 delay.tv_sec = conf.stream_delay_arg / 1000;
614 delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
615 // PARA_INFO_LOG("delay: %lu:%lu\n", delay.tv_sec, delay.tv_usec);
616 if (sa_time_diff_sign < 0)
617 tv_add(&server_stream_start, &sa_time_diff, &rss);
619 tv_diff(&server_stream_start, &sa_time_diff, &rss);
620 tv_add(&rss, &delay, &tmp);
621 replacement = make_message("%lu:%lu", tmp.tv_sec, tmp.tv_usec);
622 ret = s_a_r(cmd, "STREAM_START", replacement);
626 PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
629 gettimeofday(&now, NULL);
630 PARA_INFO_LOG("now: %lu:%lu\n", now.tv_sec, now.tv_usec);
636 /** get the number of filters for the given audio format */
637 int num_filters(int audio_format_num)
639 return afi[audio_format_num].num_filters;
642 static void open_filters(int slot_num)
644 struct slot_info *s = &slot[slot_num];
645 struct audio_format_info *a = &afi[s->format];
646 int nf = a->num_filters;
649 s->fci = para_calloc(sizeof(struct filter_chain_info));
650 INIT_LIST_HEAD(&s->fci->filters);
653 s->fci->inbuf = s->receiver_node->buf;
654 s->fci->in_loaded = &s->receiver_node->loaded;
655 s->fci->outbuf = s->receiver_node->buf;
656 s->fci->out_loaded = &s->receiver_node->loaded;
657 s->fci->eof = &s->receiver_node->eof;
658 for (i = 0; i < nf; i++) {
659 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
660 fn->conf = a->filter_conf[i];
662 fn->filter = a->filters[i];
663 INIT_LIST_HEAD(&fn->callbacks);
664 list_add_tail(&fn->node, &s->fci->filters);
665 fn->filter->open(fn);
666 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
667 audio_formats[s->format], i + 1, nf,
668 fn->filter->name, slot_num);
669 s->fci->outbuf = fn->buf;
670 s->fci->out_loaded = &fn->loaded;
672 PARA_DEBUG_LOG("output buffer for filter chain %p: %p\n", s->fci,
676 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
678 struct filter_node *fn;
682 struct slot_info *s = &slot[i];
683 if (s->format < 0 || !s->fci)
685 if (slot_num >= 0 && slot_num != i)
687 if (format >= 0 && s->format != format)
689 if (num_filters(i) < filternum)
693 list_for_each_entry(fn, &s->fci->filters, node)
694 if (filternum <= 0 || j++ == filternum)
701 static void start_stream_writer(int slot_num)
703 int ret, fds[3] = {1, -1, -1};
704 struct slot_info *s = &slot[slot_num];
705 struct audio_format_info *a = &afi[s->format];
709 glob = glob_cmd(a->write_cmd);
711 glob = para_strdup("para_play");
712 PARA_INFO_LOG("starting stream writer: %s\n", glob);
713 open_filters(slot_num);
714 ret = para_exec_cmdline_pid(&s->wpid, glob, fds);
717 PARA_ERROR_LOG("exec failed (%d)\n", ret);
720 s->write_fd = fds[0];
721 add_close_on_fork_list(s->write_fd);
722 /* we write to this fd in do_select, so we need non-blocking */
723 fcntl(s->write_fd, F_SETFL, O_NONBLOCK);
724 gettimeofday(&s->wstime, NULL);
725 current_decoder = slot_num;
726 activate_inactive_grab_clients(slot_num, s->format, &s->fci->filters);
729 static void open_receiver(int format)
731 struct audio_format_info *a = &afi[format];
735 slot_num = get_empty_slot();
737 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
740 gettimeofday(&s->rtime, NULL);
742 s->receiver_node = para_calloc(sizeof(struct receiver_node));
743 s->receiver_node->conf = a->receiver_conf;
744 ret = a->receiver->open(s->receiver_node);
746 PARA_ERROR_LOG("failed to open receiver (%s)\n",
747 PARA_STRERROR(-ret));
748 free(s->receiver_node);
749 s->receiver_node = NULL;
752 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
753 audio_formats[s->format], a->receiver->name, slot_num);
756 static int is_frozen(int format)
759 struct audio_format_info *a = &afi[format];
761 gettimeofday(&now, NULL);
762 return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
765 static void start_current_receiver(void)
771 i = get_audio_format_num(af_status);
774 if ((decoder_running(i) & 1) || is_frozen(i))
779 static void compute_time_diff(const struct timeval *status_time)
781 struct timeval now, tmp, diff;
784 const struct timeval max_deviation = {0, 500 * 1000};
785 const int time_smooth = 5;
787 gettimeofday(&now, NULL);
788 sign = tv_diff(status_time, &now, &diff);
789 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
790 // sign, sa_time_diff_sign);
792 sa_time_diff_sign = sign;
798 int s = tv_diff(&diff, &sa_time_diff, &tmp);
799 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
800 PARA_WARNING_LOG("time diff jump: %lims\n",
804 sa_time_diff_sign = tv_convex_combination(
805 sa_time_diff_sign * time_smooth, &sa_time_diff,
806 count > 10? sign : sign * time_smooth, &diff,
809 PARA_INFO_LOG("time diff (cur/avg): "
811 sign * diff.tv_sec, (diff.tv_usec + 500) / 1000,
812 sa_time_diff_sign * sa_time_diff.tv_sec,
813 (sa_time_diff.tv_usec + 500)/ 1000);
816 static void check_stat_line(char *line)
825 itemnum = stat_line_valid(line);
827 PARA_WARNING_LOG("invalid status line: %s\n", line);
830 tmp = make_message("%s\n", line);
831 stat_client_write(tmp, itemnum);
833 free(stat_item_values[itemnum]);
834 stat_item_values[itemnum] = para_strdup(line);
835 ilen = strlen(status_item_list[itemnum]);
838 playing = strstr(line, "playing")? 1 : 0;
842 af_status = para_strdup(line + ilen + 1);
845 offset_seconds = atoi(line + ilen + 1);
848 length_seconds = atoi(line + ilen + 1);
850 case SI_STREAM_START:
851 if (sscanf(line + ilen + 1, "%lu.%lu",
852 &tv.tv_sec, &tv.tv_usec) == 2)
853 server_stream_start = tv;
855 case SI_CURRENT_TIME:
856 if (sscanf(line + ilen + 1, "%lu.%lu", &tv.tv_sec,
858 compute_time_diff(&tv);
863 static void handle_signal(int sig)
867 return check_sigchld();
871 PARA_EMERG_LOG("terminating on signal %d\n", sig);
872 clean_exit(EXIT_FAILURE, "caught deadly signal");
877 static void check_timeouts(void)
880 int slot_num, timeout = conf.stream_timeout_arg;
882 gettimeofday(&now, NULL);
883 FOR_EACH_SLOT(slot_num) {
884 struct slot_info *s = &slot[slot_num];
887 /* check read time */
888 if (s->receiver_node &&
889 now.tv_sec > s->rtime.tv_sec + timeout) {
890 PARA_INFO_LOG("%s input buffer (slot %d) not ready\n",
891 audio_formats[s->format], slot_num);
895 close_receiver(slot_num);
897 /* check write time */
898 if (s->wpid > 0 && !s->wkilled &&
899 now.tv_sec > s->wtime.tv_sec + timeout) {
900 PARA_INFO_LOG("%s output buffer (slot %d) not ready\n",
901 audio_formats[s->format], slot_num);
908 static size_t get_loaded_bytes(int slot_num)
911 struct slot_info *s = &slot[slot_num];
912 struct receiver_node *rn = s->receiver_node;
917 if (afi[s->format].num_filters) {
919 loaded = *s->fci->out_loaded;
929 static void close_decoder_if_idle(int slot_num)
931 struct slot_info *s = &slot[slot_num];
932 struct receiver_node *rn = s->receiver_node;
938 if (!rn->eof && !s->fci->error && s->wpid > 0)
940 if (!s->fci->error && s->wpid > 0) { /* eof */
941 if (filter_io(s->fci) > 0)
943 if (get_loaded_bytes(slot_num))
946 if (s->write_fd > 0) {
947 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
950 del_close_on_fork_list(s->write_fd);
954 return; /* wait until writer dies before closing filters */
955 PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
957 close_filters(s->fci);
959 close_receiver(slot_num);
960 clear_slot(slot_num);
963 static int set_stream_fds(fd_set *wfds)
965 int i, max_fileno = -1;
969 struct slot_info *s = &slot[i];
970 struct audio_format_info *a;
971 struct receiver_node *rn;
973 close_decoder_if_idle(i);
978 rn = s->receiver_node;
979 if (rn && rn->loaded && !s->wpid) {
980 PARA_INFO_LOG("no writer in slot %d\n", i);
981 start_stream_writer(i);
983 if (s->write_fd <= 0)
985 if (!get_loaded_bytes(i))
987 FD_SET(s->write_fd, wfds);
989 max_fileno = MAX(s->write_fd, max_fileno);
991 // PARA_INFO_LOG("return %d\n", max_fileno);
995 static int write_audio_data(int slot_num)
997 struct slot_info *s = &slot[slot_num];
998 struct audio_format_info *a = &afi[s->format];
999 struct receiver_node *rn = s->receiver_node;
1004 if (a->num_filters) {
1005 buf = &s->fci->outbuf;
1006 len = s->fci->out_loaded;
1011 PARA_DEBUG_LOG("writing %p (%zd bytes)\n", *buf, *len);
1012 rv = write(s->write_fd, *buf, *len);
1013 PARA_DEBUG_LOG("wrote %d/%zd\n", rv, *len);
1015 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
1016 slot_num, s->write_fd, strerror(errno));
1018 s->fci->error = E_WRITE_AUDIO_DATA;
1019 } else if (rv != *len) {
1020 PARA_DEBUG_LOG("partial %s write (%i/%zd) for slot %d\n",
1021 audio_formats[s->format], rv, *len, slot_num);
1023 memmove(*buf, *buf + rv, *len);
1027 gettimeofday(&s->wtime, NULL);
1031 static void slot_io(fd_set *wfds)
1036 struct slot_info *s = &slot[i];
1037 struct receiver_node *rn = s->receiver_node;
1039 if (rn && rn->loaded)
1040 gettimeofday(&s->rtime, NULL);
1041 if (s->format >= 0 && s->write_fd > 0 && s->fci) {
1042 ret = filter_io(s->fci);
1044 s->fci->error = -ret;
1045 // PARA_DEBUG_LOG("slot %d, filter io %d bytes, check write: %d, loaded: %d/%d, eof: %d\n",
1046 // i, ret, s->wcheck, rn->loaded, *s->fci->out_loaded, rn->eof);
1048 if (s->write_fd <= 0 || !s->wcheck || !FD_ISSET(s->write_fd, wfds))
1050 write_audio_data(i);
1054 static int parse_stream_command(const char *txt, char **cmd)
1056 char *p = strchr(txt, ':');
1060 return -E_MISSING_COLON;
1062 FOR_EACH_AUDIO_FORMAT(i) {
1063 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1068 return -E_UNSUPPORTED_AUDIO_FORMAT;
1071 static int add_filter(int format, char *cmdline)
1073 struct audio_format_info *a = &afi[format];
1074 int filter_num, nf = a->num_filters;
1076 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1079 a->filters[nf] = &filters[filter_num];
1081 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1082 a->filters[nf]->name);
1086 static int setup_default_filters(void)
1090 FOR_EACH_AUDIO_FORMAT(i) {
1091 struct audio_format_info *a = &afi[i];
1096 /* add "dec" to audio format name */
1097 tmp = make_message("%sdec", audio_formats[i]);
1098 for (j = 0; filters[j].name; j++)
1099 if (!strcmp(tmp, filters[j].name))
1102 ret = -E_UNSUPPORTED_FILTER;
1103 if (!filters[j].name)
1105 tmp = para_strdup(filters[j].name);
1106 ret = add_filter(i, tmp);
1110 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i], filters[j].name);
1111 ret = add_filter(i, para_strdup("wav"));
1114 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1120 static int init_stream_io(void)
1122 int i, ret, receiver_num;
1125 for (i = 0; i < conf.stream_write_cmd_given; i++) {
1126 ret = parse_stream_command(conf.stream_write_cmd_arg[i], &cmd);
1129 afi[ret].write_cmd = para_strdup(cmd);
1130 PARA_INFO_LOG("%s write command: %s\n", audio_formats[ret], afi[ret].write_cmd);
1132 for (i = 0; receivers[i].name; i++) {
1133 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1134 receivers[i].init(&receivers[i]);
1136 for (i = 0; i < conf.receiver_given; i++) {
1137 char *arg = conf.receiver_arg[i];
1138 char *recv = strchr(arg, ':');
1139 ret = -E_MISSING_COLON;
1144 ret = get_audio_format_num(arg);
1147 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1148 if (!afi[ret].receiver_conf) {
1149 ret = -E_RECV_SYNTAX;
1152 afi[ret].receiver = &receivers[receiver_num];
1154 /* use the first available receiver with no arguments
1155 * for those audio formats for which no receiver
1158 cmd = para_strdup(receivers[0].name);
1159 FOR_EACH_AUDIO_FORMAT(i) {
1160 struct audio_format_info *a = &afi[i];
1161 if (a->receiver_conf)
1163 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1164 if (!a->receiver_conf)
1165 return -E_RECV_SYNTAX;
1166 a->receiver = &receivers[receiver_num];
1170 filter_init(filters);
1171 FOR_EACH_AUDIO_FORMAT(i) {
1172 afi[i].filter_conf = para_malloc((conf.filter_given + 1) * sizeof(char *));
1173 afi[i].filters = para_malloc((conf.filter_given + 1) * sizeof(struct filter *));
1175 if (!conf.no_default_filters_given)
1176 return setup_default_filters();
1177 for (i = 0; i < conf.filter_given; i++) {
1178 char *arg = conf.filter_arg[i];
1179 char *filter_name = strchr(arg, ':');
1180 ret = -E_MISSING_COLON;
1183 *filter_name = '\0';
1185 ret = get_audio_format_num(arg);
1188 ret = add_filter(ret, filter_name);
1197 static int dump_commands(int fd)
1199 char *buf = para_strdup(""), *tmp = NULL;
1203 FOR_EACH_COMMAND(i) {
1204 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1205 cmds[i].description);
1209 ret = client_write(fd, buf);
1215 * command handlers don't close their fd on errors (ret < 0) so that
1216 * its caller can send an error message. Otherwise (ret >= 0) it's up
1217 * to each individual command to close the fd if necessary.
1220 static int com_help(int fd, int argc, char **argv)
1224 const char *dflt = "No such command. Available commands:\n";
1227 ret = dump_commands(fd);
1230 FOR_EACH_COMMAND(i) {
1231 if (strcmp(cmds[i].name, argv[1]))
1234 "NAME\n\t%s -- %s\n"
1235 "SYNOPSIS\n\tpara_audioc %s\n"
1236 "DESCRIPTION\n%s\n",
1238 cmds[i].description,
1242 ret = client_write(fd, buf);
1246 ret = client_write(fd, dflt);
1248 ret = dump_commands(fd);
1255 static int com_stat(int fd, __unused int argc, __unused char **argv)
1259 long unsigned mask = ~0LU;
1263 for (i = 1; i < argc; i++) {
1264 ret = stat_item_valid(argv[i]);
1270 PARA_INFO_LOG("mask: 0x%lx\n", mask);
1271 if (mask & (1 << SI_PLAY_TIME)) {
1272 struct timeval *t = wstime();
1273 char *ts = get_time_string(t);
1275 ret = client_write(fd, ts);
1281 if (mask & (1 << SI_AUDIOD_UPTIME)) {
1282 char *tmp, *us = uptime_str();
1283 tmp = make_message("%s:%s\n",
1284 status_item_list[SI_AUDIOD_UPTIME], us);
1286 ret = client_write(fd, tmp);
1291 if (mask & (1 << SI_AUDIOD_STATUS)) {
1292 char *s = audiod_status_string();
1293 ret = client_write(fd, s);
1298 if (mask & (1 << SI_DECODER_FLAGS)) {
1299 char *df =decoder_flags();
1300 ret = client_write(fd, df);
1306 for (i = 0; i < NUM_STAT_ITEMS; i++) {
1308 if (!((1 << i) & mask))
1310 v = stat_item_values[i];
1311 tmp = make_message("%s%s%s", buf? buf: "",
1312 v? v : "", v? "\n" : "");
1316 ret = client_write(fd, buf);
1319 ret = stat_client_add(fd, mask);
1325 static char *list_filters(void)
1328 char *tmp, *msg = make_message("format\tnum\tcmd\n");
1330 FOR_EACH_AUDIO_FORMAT(i) {
1331 for (j = 0; j < afi[i].num_filters; j++) {
1332 tmp = make_message("%s\t%i\t%s\n",
1333 afi[i].name, j, afi[i].filter_cmds[j]);
1334 msg = para_strcat(msg, tmp);
1337 tmp = make_message("%s\t%i\t%s\n", afi[i].name,
1338 j, afi[i].write_cmd);
1339 msg = para_strcat(msg, tmp);
1346 static int com_grab(int fd, int argc, char **argv)
1348 struct grab_client *gc;
1349 struct filter_node *fn;
1353 PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1354 gc = grab_client_new(fd, argc, argv, &err);
1355 PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1358 fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1360 activate_grab_client(gc, fn);
1363 if (err != -E_GC_HELP_GIVEN && err != -E_GC_VERSION_GIVEN)
1365 if (err == -E_GC_HELP_GIVEN) {
1366 msg = make_message("%s\n\n", grab_client_args_info_usage);
1367 for (i = 0; grab_client_args_info_help[i]; i++) {
1368 char *tmp = make_message("%s%s\n", msg,
1369 grab_client_args_info_help[i]);
1374 msg = make_message("%s %s\n",
1375 GRAB_CLIENT_CMDLINE_PARSER_PACKAGE,
1376 GRAB_CLIENT_CMDLINE_PARSER_VERSION);
1377 err = client_write(fd, msg);
1385 static int __noreturn com_term(int fd, __unused int argc, __unused char **argv)
1388 clean_exit(EXIT_SUCCESS, "terminating on user request");
1391 static int com_on(int fd, __unused int argc, __unused char **argv)
1393 audiod_status = AUDIOD_ON;
1398 static int com_off(int fd, __unused int argc, __unused char **argv)
1400 audiod_status = AUDIOD_OFF;
1405 static int com_sb(int fd, __unused int argc, __unused char **argv)
1407 audiod_status = AUDIOD_STANDBY;
1412 static int com_cycle(int fd, int argc, char **argv)
1414 switch (audiod_status) {
1416 return com_sb(fd, argc, argv);
1419 return com_on(fd, argc, argv);
1421 case AUDIOD_STANDBY:
1422 return com_off(fd, argc, argv);
1429 static int check_perms(struct ucred *c)
1433 if (!conf.user_allow_given)
1435 for (i = 0; i < conf.user_allow_given; i++)
1436 if (c->uid == conf.user_allow_arg[i])
1438 return -E_UCRED_PERM;
1441 static int handle_connect(void)
1443 int i, argc, ret, clifd = -1;
1445 char *buf = para_malloc(MAXLINE), **argv = NULL;
1446 struct sockaddr_un unix_addr;
1448 ret = para_accept(audiod_socket, &unix_addr, sizeof(struct sockaddr_un));
1452 ret = recv_cred_buffer(clifd, buf, MAXLINE - 1, &c);
1455 PARA_INFO_LOG("pid: %i, uid: %i, gid: %i, ret: %i, buf: %s\n", c.pid, c.uid, c.gid, ret, buf);
1457 ret = check_perms(&c);
1460 argc = split_args(buf, &argv, '\n');
1461 PARA_INFO_LOG("argv[0]: %s\n", argv[0]);
1462 for (i = 0; cmds[i].name; i++) {
1463 if (strcmp(cmds[i].name, argv[0]))
1465 ret = cmds[i].handler(clifd, argc + 1, argv);
1468 ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1472 if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1473 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1474 client_write(clifd, tmp);
1481 static void audiod_get_socket(void)
1483 struct sockaddr_un unix_addr;
1485 if (conf.socket_given)
1486 socket_name = para_strdup(conf.socket_arg);
1488 char *hn = para_hostname();
1489 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1493 PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1494 if (conf.force_given)
1495 unlink(socket_name);
1496 audiod_socket = create_pf_socket(socket_name, &unix_addr,
1497 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1498 if (audiod_socket < 0) {
1499 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1500 exit(EXIT_FAILURE); /* do not unlink socket */
1502 if (listen(audiod_socket, 5) < 0) {
1503 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1504 exit(EXIT_FAILURE); /* do not unlink socket */
1506 add_close_on_fork_list(audiod_socket);
1509 static int open_stat_pipe(void)
1511 int ret, fd[3] = {-1, 1, 0};
1513 ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1516 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1517 add_close_on_fork_list(ret);
1519 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1523 static int pre_select(fd_set *rfds, fd_set *wfds, struct timeval *tv)
1525 int i, ret, max = -1;
1528 struct slot_info *s = &slot[i];
1529 struct audio_format_info *a;
1530 struct receiver_node *rn = s->receiver_node;
1531 if (s->format < 0 || !rn)
1533 a = &afi[s->format];
1534 ret = a->receiver->pre_select(rn, rfds, wfds, tv);
1535 // PARA_NOTICE_LOG("%s preselect: %d\n", a->receiver->name, ret);
1536 max = MAX(max, ret);
1541 static void audiod_post_select(int select_ret, fd_set *rfds, fd_set *wfds)
1546 struct slot_info *s = &slot[i];
1547 struct audio_format_info *a;
1548 struct receiver_node *rn = s->receiver_node;
1549 if (s->format < 0 || !rn || rn->eof)
1551 a = &afi[s->format];
1552 ret = a->receiver->post_select(rn, select_ret, rfds, wfds);
1555 PARA_ERROR_LOG("%s post select failed: %s (slot %d)\n",
1556 a->receiver->name, PARA_STRERROR(-ret), i);
1558 PARA_INFO_LOG("eof in slot %d\n", i);
1561 if (ret < 0 && s->fci)
1562 s->fci->error = ret;
1566 /* TODO: move everything before the select call to pre_select() */
1567 static void __noreturn audiod_mainloop(void)
1570 int ret, max_fileno, sbo = 0;
1571 char status_buf[STRINGSIZE] = "";
1577 if (audiod_status != AUDIOD_ON)
1578 kill_all_decoders();
1580 start_current_receiver();
1581 max_fileno = set_stream_fds(&wfds);
1582 /* stat pipe (read) */
1583 if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1585 if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1586 stat_pipe = open_stat_pipe();
1588 status_buf[0] = '\0';
1590 if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF) {
1591 FD_SET(stat_pipe, &rfds);
1592 max_fileno = MAX(max_fileno, stat_pipe);
1594 /* always check signal pipe */
1595 FD_SET(signal_pipe, &rfds);
1596 max_fileno = MAX(max_fileno, signal_pipe);
1598 if (audiod_socket < 0)
1599 audiod_get_socket(); /* doesn't return on errors */
1600 FD_SET(audiod_socket, &rfds);
1601 max_fileno = MAX(max_fileno, audiod_socket);
1603 tv.tv_usec = 200 * 1000;
1604 ret = pre_select(&rfds, &wfds, &tv);
1605 max_fileno = MAX(max_fileno, ret);
1606 ret = select(max_fileno + 1, &rfds, &wfds, NULL, &tv);
1607 if (ret < 0 && errno != EINTR)
1608 PARA_ERROR_LOG("select returned %d (%s)\n", ret,
1610 if (audiod_status != AUDIOD_OFF)
1611 audiod_status_dump();
1614 audiod_post_select(ret, &rfds, &wfds);
1615 /* read status pipe */
1616 if (stat_pipe >=0 && FD_ISSET(stat_pipe, &rfds)) {
1617 ret = read(stat_pipe, status_buf + sbo, STRINGSIZE - 1 - sbo);
1620 /* avoid busy loop if server is down */
1621 while (sleep(1) > 0)
1624 status_buf[ret + sbo] = '\0';
1625 sbo = for_each_line(status_buf, ret + sbo,
1630 if (FD_ISSET(audiod_socket, &rfds)) {
1631 ret = handle_connect();
1633 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1637 if (FD_ISSET(signal_pipe, &rfds)) {
1638 int sig_nr = para_next_signal();
1640 handle_signal(sig_nr);
1645 static void set_initial_status(void)
1647 audiod_status = AUDIOD_ON;
1648 if (!conf.mode_given)
1650 if (!strcmp(conf.mode_arg, "sb")) {
1651 audiod_status = AUDIOD_STANDBY;
1654 if (!strcmp(conf.mode_arg, "off")) {
1655 audiod_status = AUDIOD_OFF;
1658 if (strcmp(conf.mode_arg, "on"))
1659 PARA_WARNING_LOG("%s", "invalid mode\n");
1662 int __noreturn main(int argc, char *argv[])
1668 hostname = para_hostname();
1669 cmdline_parser(argc, argv, &conf);
1670 para_drop_privileges(conf.user_arg);
1671 cf = configfile_exists();
1673 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1674 fprintf(stderr, "parse error in config file\n");
1678 log_welcome("para_audiod", conf.loglevel_arg);
1679 i = init_stream_io();
1681 fprintf(stderr, "init stream io error: %s\n",
1685 server_uptime(UPTIME_SET);
1686 set_initial_status();
1690 setup_signal_handling();
1691 if (conf.daemon_given)