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",
214 "Add para_audiod status information to para_server's status information\n"
215 "and dump everything to stdout.\n"
221 .description = "terminate audiod",
225 "Stop all decoders, shut down connection to para_server and exit.\n"
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++)
241 * get the audio format number
242 * \param name the name of the audio format
244 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
245 * \a name is not a supported audio format.
247 int get_audio_format_num(char *name)
250 FOR_EACH_AUDIO_FORMAT(i)
251 if (!strcmp(name, audio_formats[i]))
253 return -E_UNSUPPORTED_AUDIO_FORMAT;
257 * log function. first argument is loglevel.
259 void para_log(int ll, const char* fmt,...)
265 char str[MAXLINE] = "";
267 if (ll < conf.loglevel_arg)
269 if (!logfile && conf.logfile_given)
270 logfile = open_log(conf.logfile_arg);
271 if (!logfile && conf.daemon_given)
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);
287 vfprintf(outfd, fmt, argp);
291 static int client_write(int fd, const char *buf)
293 size_t len = strlen(buf);
294 return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
297 static char *get_time_string(struct timeval *newest_stime)
299 struct timeval now, diff, adj_stream_start, tmp;
300 int total = 0, use_server_time = 1;
305 return make_message("%s:", status_item_list[SI_PLAY_TIME]);
307 if (audiod_status == AUDIOD_OFF)
309 if (sa_time_diff_sign > 0)
310 tv_diff(&server_stream_start, &sa_time_diff,
313 tv_add(&server_stream_start, &sa_time_diff,
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) {
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;
332 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
333 status_item_list[SI_PLAY_TIME],
334 use_server_time? "~" : "",
337 (length_seconds - total) / 60,
338 (length_seconds - total) % 60,
339 length_seconds? (total * 100 + length_seconds / 2) /
346 static char *audiod_status_string(void)
349 struct timeval *newest_stime = NULL;
350 char *ret, *time_string, *uptime_string, *decoder_flags =
351 para_malloc((MAX_STREAM_SLOTS + 1) * sizeof(char));
354 struct slot_info *s = &slot[i];
356 if (s->receiver_node)
361 flag += s->format * 4;
362 decoder_flags[i] = flag;
365 if (newest_stime && tv_diff(&s->wstime, newest_stime, NULL) <= 0)
367 newest_stime = &s->wstime;
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"));
378 ret = make_message("%s\n%s", ret, time_string);
385 static char *configfile_exists(void)
387 static char *config_file;
390 char *home = para_homedir();
391 config_file = make_message("%s/.paraslash/audiod.conf", home);
394 return file_exists(config_file)? config_file : NULL;
397 static void setup_signal_handling(void)
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);
408 static void audiod_status_dump(void)
410 static char *prev_status;
411 char *tmp = audiod_status_string();
413 if (!prev_status || strcmp(tmp, prev_status))
414 stat_client_write(tmp);
419 static void clear_slot(int slot_num)
421 struct slot_info *s = &slot[slot_num];
423 PARA_INFO_LOG("clearing slot %d\n", slot_num);
424 memset(s, 0, sizeof(struct slot_info));
428 static void kill_stream_writer(int slot_num)
430 struct slot_info *s = &slot[slot_num];
432 if (s->format < 0 || s->wkilled || s->wpid <= 0)
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);
441 static void set_restart_barrier(int format, struct timeval *now)
448 gettimeofday(&tmp, NULL);
449 tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
452 static void close_receiver(int slot_num)
454 struct slot_info *s = &slot[slot_num];
455 struct audio_format_info *a;
457 if (s->format < 0 || !s->receiver_node)
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);
468 static void kill_all_decoders(void)
473 if (slot[i].format >= 0) {
474 PARA_INFO_LOG("stopping decoder in slot %d\n", i);
475 kill_stream_writer(i);
479 static void check_sigchld(void)
484 gettimeofday(&now, NULL);
487 pid = para_reap_child();
491 struct slot_info *s = &slot[i];
495 if (pid == s->wpid) {
497 lifetime = now.tv_sec - s->wstime.tv_sec;
498 PARA_INFO_LOG("%s stream writer in slot %d died "
500 audio_formats[s->format], i, lifetime);
501 set_restart_barrier(s->format, &now);
502 goto reap_next_child;
505 PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
506 goto reap_next_child;
509 static int get_empty_slot(void)
520 if (s->write_fd > 0 || s->wpid > 0)
522 if (s->receiver_node)
529 return -E_NO_MORE_SLOTS;
532 static int decoder_running(int format)
539 if (s->format == format && s->receiver_node)
541 if (s->format == format && s->wpid > 0)
547 static void close_stat_pipe(void)
553 PARA_NOTICE_LOG("%s", "closing status pipe\n");
555 del_close_on_fork_list(stat_pipe);
558 for (i = 0; i < NUM_STAT_ITEMS; i++) {
559 free(stat_item_values[i]);
560 stat_item_values[i] = NULL;
565 audiod_status_dump();
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]);
572 static void __noreturn clean_exit(int status, const char *msg)
574 PARA_EMERG_LOG("%s\n", msg);
583 __malloc static char *glob_cmd(char *cmd)
585 char *ret, *replacement;
586 struct timeval tmp, delay, rss; /* real stream start */
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);
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);
601 PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
604 gettimeofday(&now, NULL);
605 PARA_INFO_LOG("now: %lu:%lu\n", now.tv_sec, now.tv_usec);
611 /** get the number of filters for the given audio format */
612 int num_filters(int audio_format_num)
614 return afi[audio_format_num].num_filters;
617 static void open_filters(int slot_num)
619 struct slot_info *s = &slot[slot_num];
620 struct audio_format_info *a = &afi[s->format];
621 int nf = a->num_filters;
624 s->fci = para_calloc(sizeof(struct filter_chain_info));
625 INIT_LIST_HEAD(&s->fci->filters);
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];
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;
647 PARA_DEBUG_LOG("output buffer for filter chain %p: %p\n", s->fci,
651 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
653 struct filter_node *fn;
657 struct slot_info *s = &slot[i];
658 if (s->format < 0 || !s->fci)
660 if (slot_num >= 0 && slot_num != i)
662 if (format >= 0 && s->format != format)
664 if (num_filters(i) < filternum)
668 list_for_each_entry(fn, &s->fci->filters, node)
669 if (filternum <= 0 || j++ == filternum)
676 static void start_stream_writer(int slot_num)
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];
684 glob = glob_cmd(a->write_cmd);
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);
692 PARA_ERROR_LOG("exec failed (%d)\n", ret);
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);
704 static void open_receiver(int format)
706 struct audio_format_info *a = &afi[format];
710 slot_num = get_empty_slot();
712 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
715 gettimeofday(&s->rtime, NULL);
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);
721 PARA_ERROR_LOG("failed to open receiver (%s)\n",
722 PARA_STRERROR(-ret));
723 free(s->receiver_node);
724 s->receiver_node = NULL;
727 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
728 audio_formats[s->format], a->receiver->name, slot_num);
731 static int is_frozen(int format)
734 struct audio_format_info *a = &afi[format];
736 gettimeofday(&now, NULL);
737 return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
740 static void start_current_receiver(void)
746 i = get_audio_format_num(af_status);
749 if ((decoder_running(i) & 1) || is_frozen(i))
754 static void compute_time_diff(const struct timeval *status_time)
756 struct timeval now, tmp, diff;
759 const struct timeval max_deviation = {0, 500 * 1000};
760 const int time_smooth = 5;
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);
767 sa_time_diff_sign = sign;
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",
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,
784 PARA_INFO_LOG("time diff (cur/avg): "
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);
791 static void check_stat_line(char *line)
799 itemnum = stat_line_valid(line);
801 PARA_WARNING_LOG("invalid status line: %s\n", line);
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]);
810 playing = strstr(line, "playing")? 1 : 0;
814 af_status = para_strdup(line + ilen + 1);
817 offset_seconds = atoi(line + ilen + 1);
820 length_seconds = atoi(line + ilen + 1);
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;
827 case SI_CURRENT_TIME:
828 if (sscanf(line + ilen + 1, "%lu.%lu", &tv.tv_sec,
830 compute_time_diff(&tv);
835 static void handle_signal(int sig)
839 return check_sigchld();
843 PARA_EMERG_LOG("terminating on signal %d\n", sig);
844 clean_exit(EXIT_FAILURE, "caught deadly signal");
849 static void check_timeouts(void)
852 int slot_num, timeout = conf.stream_timeout_arg;
854 gettimeofday(&now, NULL);
855 FOR_EACH_SLOT(slot_num) {
856 struct slot_info *s = &slot[slot_num];
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);
867 close_receiver(slot_num);
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);
880 static size_t get_loaded_bytes(int slot_num)
883 struct slot_info *s = &slot[slot_num];
884 struct receiver_node *rn = s->receiver_node;
889 if (afi[s->format].num_filters) {
891 loaded = *s->fci->out_loaded;
901 static void close_decoder_if_idle(int slot_num)
903 struct slot_info *s = &slot[slot_num];
904 struct receiver_node *rn = s->receiver_node;
910 if (!rn->eof && !s->fci->error && s->wpid > 0)
912 if (!s->fci->error && s->wpid > 0) { /* eof */
913 if (filter_io(s->fci) > 0)
915 if (get_loaded_bytes(slot_num))
918 if (s->write_fd > 0) {
919 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
922 del_close_on_fork_list(s->write_fd);
926 return; /* wait until writer dies before closing filters */
927 PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
929 close_filters(s->fci);
931 close_receiver(slot_num);
932 clear_slot(slot_num);
935 static int set_stream_fds(fd_set *wfds)
937 int i, max_fileno = -1;
941 struct slot_info *s = &slot[i];
942 struct audio_format_info *a;
943 struct receiver_node *rn;
945 close_decoder_if_idle(i);
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);
955 if (s->write_fd <= 0)
957 if (!get_loaded_bytes(i))
959 FD_SET(s->write_fd, wfds);
961 max_fileno = MAX(s->write_fd, max_fileno);
963 // PARA_INFO_LOG("return %d\n", max_fileno);
967 static int write_audio_data(int slot_num)
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;
976 if (a->num_filters) {
977 buf = &s->fci->outbuf;
978 len = s->fci->out_loaded;
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);
987 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
988 slot_num, s->write_fd, strerror(errno));
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);
995 memmove(*buf, *buf + rv, *len);
999 gettimeofday(&s->wtime, NULL);
1003 static void slot_io(fd_set *wfds)
1008 struct slot_info *s = &slot[i];
1009 struct receiver_node *rn = s->receiver_node;
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);
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);
1020 if (s->write_fd <= 0 || !s->wcheck || !FD_ISSET(s->write_fd, wfds))
1022 write_audio_data(i);
1026 static int parse_stream_command(const char *txt, char **cmd)
1028 char *p = strchr(txt, ':');
1032 return -E_MISSING_COLON;
1034 FOR_EACH_AUDIO_FORMAT(i) {
1035 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1040 return -E_UNSUPPORTED_AUDIO_FORMAT;
1043 static int add_filter(int format, char *cmdline)
1045 struct audio_format_info *a = &afi[format];
1046 int filter_num, nf = a->num_filters;
1048 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1051 a->filters[nf] = &filters[filter_num];
1053 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1054 a->filters[nf]->name);
1058 static int setup_default_filters(void)
1062 FOR_EACH_AUDIO_FORMAT(i) {
1063 struct audio_format_info *a = &afi[i];
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))
1074 ret = -E_UNSUPPORTED_FILTER;
1075 if (!filters[j].name)
1077 tmp = para_strdup(filters[j].name);
1078 ret = add_filter(i, tmp);
1082 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i], filters[j].name);
1083 ret = add_filter(i, para_strdup("wav"));
1086 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1092 static int init_stream_io(void)
1094 int i, ret, receiver_num;
1097 for (i = 0; i < conf.stream_write_cmd_given; i++) {
1098 ret = parse_stream_command(conf.stream_write_cmd_arg[i], &cmd);
1101 afi[ret].write_cmd = para_strdup(cmd);
1102 PARA_INFO_LOG("%s write command: %s\n", audio_formats[ret], afi[ret].write_cmd);
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]);
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;
1116 ret = get_audio_format_num(arg);
1119 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1120 if (!afi[ret].receiver_conf) {
1121 ret = -E_RECV_SYNTAX;
1124 afi[ret].receiver = &receivers[receiver_num];
1126 /* use the first available receiver with no arguments
1127 * for those audio formats for which no receiver
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)
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];
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 *));
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;
1155 *filter_name = '\0';
1157 ret = get_audio_format_num(arg);
1160 ret = add_filter(ret, filter_name);
1169 static int dump_commands(int fd)
1171 char *buf = para_strdup(""), *tmp = NULL;
1175 FOR_EACH_COMMAND(i) {
1176 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1177 cmds[i].description);
1181 ret = client_write(fd, buf);
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.
1192 static int com_help(int fd, int argc, char **argv)
1196 const char *dflt = "No such command. Available commands:\n";
1199 ret = dump_commands(fd);
1202 FOR_EACH_COMMAND(i) {
1203 if (strcmp(cmds[i].name, argv[1]))
1206 "NAME\n\t%s -- %s\n"
1207 "SYNOPSIS\n\tpara_audioc %s\n"
1208 "DESCRIPTION\n%s\n",
1210 cmds[i].description,
1214 ret = client_write(fd, buf);
1218 ret = client_write(fd, dflt);
1220 ret = dump_commands(fd);
1227 static int com_stat(int fd, __unused int argc, __unused char **argv)
1230 char *buf = make_message("%s\n", audiod_status_string());
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" : "");
1238 ret = client_write(fd, buf);
1240 ret = stat_client_add(fd);
1246 static char *list_filters(void)
1249 char *tmp, *msg = make_message("format\tnum\tcmd\n");
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);
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);
1267 static int com_grab(int fd, int argc, char **argv)
1269 struct grab_client *gc;
1270 struct filter_node *fn;
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);
1278 fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1280 activate_grab_client(gc, fn);
1283 if (err != -E_GC_HELP_GIVEN)
1285 err = client_write(fd, "Usage: para_audioc [audioc_options] -- "
1286 "grab [grab_options]\nAvailable options:\n");
1289 err = client_write(fd, GRAB_HELP_TXT);
1296 static int __noreturn com_term(int fd, __unused int argc, __unused char **argv)
1299 clean_exit(EXIT_SUCCESS, "terminating on user request");
1302 static int com_on(int fd, __unused int argc, __unused char **argv)
1304 audiod_status = AUDIOD_ON;
1309 static int com_off(int fd, __unused int argc, __unused char **argv)
1311 audiod_status = AUDIOD_OFF;
1316 static int com_sb(int fd, __unused int argc, __unused char **argv)
1318 audiod_status = AUDIOD_STANDBY;
1323 static int com_cycle(int fd, int argc, char **argv)
1325 switch (audiod_status) {
1327 return com_sb(fd, argc, argv);
1330 return com_on(fd, argc, argv);
1332 case AUDIOD_STANDBY:
1333 return com_off(fd, argc, argv);
1340 static int check_perms(struct ucred *c)
1344 if (!conf.user_allow_given)
1346 for (i = 0; i < conf.user_allow_given; i++)
1347 if (c->uid == conf.user_allow_arg[i])
1349 return -E_UCRED_PERM;
1352 static int handle_connect(void)
1354 int i, argc, ret, clifd = -1;
1356 char *buf = para_malloc(MAXLINE), **argv = NULL;
1357 struct sockaddr_un unix_addr;
1359 ret = para_accept(audiod_socket, &unix_addr, sizeof(struct sockaddr_un));
1363 ret = recv_cred_buffer(clifd, buf, MAXLINE - 1, &c);
1366 PARA_INFO_LOG("pid: %i, uid: %i, gid: %i, ret: %i, buf: %s\n", c.pid, c.uid, c.gid, ret, buf);
1368 ret = check_perms(&c);
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]))
1376 ret = cmds[i].handler(clifd, argc + 1, argv);
1379 ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
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);
1392 static void audiod_get_socket(void)
1394 struct sockaddr_un unix_addr;
1396 if (conf.socket_given)
1397 socket_name = para_strdup(conf.socket_arg);
1399 char *hn = para_hostname();
1400 socket_name = make_message("/var/paraslash/audiod_socket.%s",
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 */
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 */
1417 add_close_on_fork_list(audiod_socket);
1420 static int open_stat_pipe(void)
1422 int ret, fd[3] = {-1, 1, 0};
1424 ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1427 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1428 add_close_on_fork_list(ret);
1430 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1434 static int pre_select(fd_set *rfds, fd_set *wfds, struct timeval *tv)
1436 int i, ret, max = -1;
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)
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);
1452 static void audiod_post_select(int select_ret, fd_set *rfds, fd_set *wfds)
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)
1462 a = &afi[s->format];
1463 ret = a->receiver->post_select(rn, select_ret, rfds, wfds);
1466 PARA_ERROR_LOG("%s post select failed: %s (slot %d)\n",
1467 a->receiver->name, PARA_STRERROR(-ret), i);
1469 PARA_INFO_LOG("eof in slot %d\n", i);
1472 if (ret < 0 && s->fci)
1473 s->fci->error = ret;
1477 /* TODO: move everything before the select call to pre_select() */
1478 static void __noreturn audiod_mainloop(void)
1481 int ret, max_fileno, sbo = 0;
1482 char status_buf[STRINGSIZE] = "";
1488 if (audiod_status != AUDIOD_ON)
1489 kill_all_decoders();
1491 start_current_receiver();
1492 max_fileno = set_stream_fds(&wfds);
1493 /* stat pipe (read) */
1494 if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1496 if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1497 stat_pipe = open_stat_pipe();
1499 status_buf[0] = '\0';
1501 if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF) {
1502 FD_SET(stat_pipe, &rfds);
1503 max_fileno = MAX(max_fileno, stat_pipe);
1505 /* always check signal pipe */
1506 FD_SET(signal_pipe, &rfds);
1507 max_fileno = MAX(max_fileno, signal_pipe);
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);
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,
1521 if (audiod_status != AUDIOD_OFF)
1522 audiod_status_dump();
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);
1531 /* avoid busy loop if server is down */
1532 while (sleep(1) > 0)
1535 status_buf[ret + sbo] = '\0';
1536 sbo = for_each_line(status_buf, ret + sbo,
1541 if (FD_ISSET(audiod_socket, &rfds)) {
1542 ret = handle_connect();
1544 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1548 if (FD_ISSET(signal_pipe, &rfds)) {
1549 int sig_nr = para_next_signal();
1551 handle_signal(sig_nr);
1556 static void set_initial_status(void)
1558 audiod_status = AUDIOD_ON;
1559 if (!conf.mode_given)
1561 if (!strcmp(conf.mode_arg, "sb")) {
1562 audiod_status = AUDIOD_STANDBY;
1565 if (!strcmp(conf.mode_arg, "off")) {
1566 audiod_status = AUDIOD_OFF;
1569 if (strcmp(conf.mode_arg, "on"))
1570 PARA_WARNING_LOG("%s", "invalid mode\n");
1573 int __noreturn main(int argc, char *argv[])
1579 hostname = para_hostname();
1580 cmdline_parser(argc, argv, &conf);
1581 para_drop_privileges(conf.user_arg);
1582 cf = configfile_exists();
1584 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1585 fprintf(stderr, "parse error in config file\n");
1589 log_welcome("para_audiod", conf.loglevel_arg);
1590 i = init_stream_io();
1592 fprintf(stderr, "init stream io error: %s\n",
1596 server_uptime(UPTIME_SET);
1597 set_initial_status();
1601 setup_signal_handling();
1602 if (conf.daemon_given)