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"
31 #include "ringbuffer.h"
39 /** define the array of error lists needed by para_audiod */
41 /** define the array containing all supported audio formats */
42 DEFINE_AUDIO_FORMAT_ARRAY;
45 * the possible modes of operation
47 * - off: disconnect from para_server
48 * - on: receive status information from para_server and play the audio stream
49 * - sb: only receive status information but not the audio stream
51 enum {AUDIOD_OFF, AUDIOD_ON, AUDIOD_STANDBY};
53 /** defines how to handle one supported audio format */
54 struct audio_format_info {
55 /** pointer to the receiver for this audio format */
56 struct receiver *receiver;
57 /** the receiver configuration */
59 /** the number of filters that should be activated for this audio format */
60 unsigned int num_filters;
61 /** pointer to the array of filters to be activated */
62 struct filter **filters;
63 /** pointer to the array of filter configurations */
65 /** output of the last filter is written to stdin of this command */
67 /** do not start receiver/filters/writer before this time */
68 struct timeval restart_barrier;
72 * describes one instance of a receiver-filter-writer chain
74 * \sa receier_node, receiver, filter, filter_node, filter_chain_info
77 /** number of the audio format in this slot */
79 /** the file descriptor of the writer */
81 /** the process id of the writer */
83 /** time of the last successful read from the receiver */
85 /** time the last write to the write fd happend */
87 /** writer start time */
88 struct timeval wstime;
89 /** did we include \a write_fd in the fdset */
91 /** set to one if we have sent the TERM signal to \a wpid */
93 /** the receiver info associated with this slot */
94 struct receiver_node *receiver_node;
95 /** the active filter chain */
96 struct filter_chain_info *fci;
99 static struct slot_info slot[MAX_STREAM_SLOTS];
101 /** defines one command of para_audiod */
102 struct audiod_command {
103 /** the name of the command */
105 /** pointer to the function that handles the command */
106 int (*handler)(int, int, char**);
107 /** one-line description of the command */
108 const char *description;
109 /** summary of the command line options */
110 const char *synopsis;
111 /** the long help text */
115 extern const char *status_item_list[NUM_STAT_ITEMS];
117 static int com_grab(int, int, char **);
118 static int com_cycle(int, int, char **);
119 static int com_help(int, int, char **);
120 static int com_off(int, int, char **);
121 static int com_on(int, int, char **);
122 static int com_sb(int, int, char **);
123 static int com_stat(int, int, char **);
124 static int com_term(int, int, char **);
125 static int stat_pipe = -1, signal_pipe;
127 static struct gengetopt_args_info conf;
128 static struct timeval server_stream_start, sa_time_diff;
129 static int playing, current_decoder = -1,
130 audiod_status = AUDIOD_ON, offset_seconds, length_seconds,
131 sa_time_diff_sign = 1, audiod_socket = -1;
132 static char *af_status, /* the audio format announced in server status */
133 *socket_name, *hostname;
134 /** how many status items to remember */
135 #define RINGBUFFER_SIZE 32
136 static void *stat_item_ringbuf;
137 static FILE *logfile;
138 static const struct timeval restart_delay = {0, 300 * 1000};
140 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
142 static struct audiod_command cmds[] = {
145 .handler = com_cycle,
146 .description = "switch to next mode",
150 "on -> standby -> off -> on\n"
156 .description = "grab the audio stream",
157 .synopsis = "-- grab [grab_options]",
159 "grab ('splice') the audio stream at any position in the filter \n"
160 "chain and send that data back to the client. \n"
161 "Available options:\n\n"
167 .description = "display command list or help for given command",
168 .synopsis = "help [command]",
171 "When I was younger, so much younger than today, I never needed\n"
172 "anybody's help in any way. But now these days are gone, I'm not so\n"
173 "self assured. Now I find I've changed my mind and opened up the doors.\n"
175 " -- Beatles: Help\n"
181 .description = "deactivate para_audiod",
185 "Close connection to para_server and stop all decoders.\n"
191 .description = "activate para_audiod",
195 "Establish connection to para_server, retrieve para_server's current\n"
196 "status. If playing, start corresponding decoder. Otherwise stop\n"
203 .description = "enter standby mode",
207 "Stop all decoders but leave connection to para_server open.\n"
213 .description = "print status information",
217 "Add para_audiod status information to para_server's status information\n"
218 "and dump everything to stdout.\n"
224 .description = "terminate audiod",
228 "Stop all decoders, shut down connection to para_server and exit.\n"
236 /** iterate over all slots */
237 #define FOR_EACH_SLOT(slot) for (slot = 0; slot < MAX_STREAM_SLOTS; slot++)
238 /** iterate over all supported audio formats */
239 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
240 /** iterate over the array of all audiod commands */
241 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
244 * get the audio format number
245 * \param name the name of the audio format
247 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
248 * \a name is not a supported audio format.
250 int get_audio_format_num(char *name)
253 FOR_EACH_AUDIO_FORMAT(i)
254 if (!strcmp(name, audio_formats[i]))
256 return -E_UNSUPPORTED_AUDIO_FORMAT;
260 * log function. first argument is loglevel.
262 void para_log(int ll, const char* fmt,...)
268 char str[MAXLINE] = "";
270 if (ll < conf.loglevel_arg)
272 if (!logfile && conf.logfile_given)
273 logfile = open_log(conf.logfile_arg);
274 if (!logfile && conf.daemon_given)
285 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
286 fprintf(outfd, "%s %s ", str, hostname);
287 if (conf.loglevel_arg <= INFO)
288 fprintf(outfd, "%i ", ll);
290 vfprintf(outfd, fmt, argp);
294 static int client_write(int fd, const char *buf)
296 size_t len = strlen(buf);
297 return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
300 static char *get_time_string(struct timeval *newest_stime)
302 struct timeval now, diff, adj_stream_start, tmp;
303 int total = 0, use_server_time = 1;
306 return make_message("%s:", length_seconds?
307 "" : 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)",
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 static char *audiod_status_string(void)
350 struct timeval *newest_stime = NULL;
351 char *ret, *time_string, *uptime_string, *decoder_flags =
352 para_malloc((MAX_STREAM_SLOTS + 1) * sizeof(char));
355 struct slot_info *s = &slot[i];
357 if (s->receiver_node)
362 flag += s->format * 4;
363 decoder_flags[i] = flag;
366 if (newest_stime && tv_diff(&s->wstime, newest_stime, NULL) <= 0)
368 newest_stime = &s->wstime;
370 decoder_flags[MAX_STREAM_SLOTS] = '\0';
371 time_string = get_time_string(newest_stime);
372 uptime_string = uptime_str();
373 ret = make_message("%s:%s\n%s:%s\n%s:%s\n%s",
374 status_item_list[SI_AUDIOD_UPTIME], uptime_string,
375 status_item_list[SI_DECODER_FLAGS], decoder_flags,
376 status_item_list[SI_AUDIOD_STATUS], audiod_status == AUDIOD_ON?
377 "on" : (audiod_status == AUDIOD_OFF? "off": "sb"),
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)
554 PARA_NOTICE_LOG("%s", "closing status pipe\n");
556 del_close_on_fork_list(stat_pipe);
559 for (i = 0; i < RINGBUFFER_SIZE; i++)
560 free(ringbuffer_add(stat_item_ringbuf, para_strdup(NULL)));
564 audiod_status_dump();
566 msg = make_message("%s:no connection to para_server\n",
567 status_item_list[SI_STATUS_BAR]);
568 free(ringbuffer_add(stat_item_ringbuf, msg));
569 stat_client_write(msg);
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 free(ringbuffer_add(stat_item_ringbuf, para_strdup(line)));
800 stat_client_write(line);
801 itemnum = stat_line_valid(line);
804 ilen = strlen(status_item_list[itemnum]);
807 playing = strstr(line, "playing")? 1 : 0;
811 af_status = para_strdup(line + ilen + 1);
814 offset_seconds = atoi(line + ilen + 1);
817 length_seconds = atoi(line + ilen + 1);
819 case SI_STREAM_START:
820 if (sscanf(line + ilen + 1, "%lu.%lu",
821 &tv.tv_sec, &tv.tv_usec) == 2)
822 server_stream_start = tv;
824 case SI_CURRENT_TIME:
825 if (sscanf(line + ilen + 1, "%lu.%lu", &tv.tv_sec,
827 compute_time_diff(&tv);
832 static void handle_signal(int sig)
836 return check_sigchld();
840 PARA_EMERG_LOG("terminating on signal %d\n", sig);
841 clean_exit(EXIT_FAILURE, "caught deadly signal");
846 static void check_timeouts(void)
849 int slot_num, timeout = conf.stream_timeout_arg;
851 gettimeofday(&now, NULL);
852 FOR_EACH_SLOT(slot_num) {
853 struct slot_info *s = &slot[slot_num];
856 /* check read time */
857 if (s->receiver_node &&
858 now.tv_sec > s->rtime.tv_sec + timeout) {
859 PARA_INFO_LOG("%s input buffer (slot %d) not ready\n",
860 audio_formats[s->format], slot_num);
864 close_receiver(slot_num);
866 /* check write time */
867 if (s->wpid > 0 && !s->wkilled &&
868 now.tv_sec > s->wtime.tv_sec + timeout) {
869 PARA_INFO_LOG("%s output buffer (slot %d) not ready\n",
870 audio_formats[s->format], slot_num);
877 static size_t get_loaded_bytes(int slot_num)
880 struct slot_info *s = &slot[slot_num];
881 struct receiver_node *rn = s->receiver_node;
886 if (afi[s->format].num_filters) {
888 loaded = *s->fci->out_loaded;
898 static void close_decoder_if_idle(int slot_num)
900 struct slot_info *s = &slot[slot_num];
901 struct receiver_node *rn = s->receiver_node;
907 if (!rn->eof && !s->fci->error && s->wpid > 0)
909 if (!s->fci->error && s->wpid > 0) { /* eof */
910 if (filter_io(s->fci) > 0)
912 if (get_loaded_bytes(slot_num))
915 if (s->write_fd > 0) {
916 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
919 del_close_on_fork_list(s->write_fd);
923 return; /* wait until writer dies before closing filters */
924 PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
926 close_filters(s->fci);
928 close_receiver(slot_num);
929 clear_slot(slot_num);
932 static int set_stream_fds(fd_set *wfds)
934 int i, max_fileno = -1;
938 struct slot_info *s = &slot[i];
939 struct audio_format_info *a;
940 struct receiver_node *rn;
942 close_decoder_if_idle(i);
947 rn = s->receiver_node;
948 if (rn && rn->loaded && !s->wpid) {
949 PARA_INFO_LOG("no writer in slot %d\n", i);
950 start_stream_writer(i);
952 if (s->write_fd <= 0)
954 if (!get_loaded_bytes(i))
956 FD_SET(s->write_fd, wfds);
958 max_fileno = MAX(s->write_fd, max_fileno);
960 // PARA_INFO_LOG("return %d\n", max_fileno);
964 static int write_audio_data(int slot_num)
966 struct slot_info *s = &slot[slot_num];
967 struct audio_format_info *a = &afi[s->format];
968 struct receiver_node *rn = s->receiver_node;
973 if (a->num_filters) {
974 buf = &s->fci->outbuf;
975 len = s->fci->out_loaded;
980 PARA_DEBUG_LOG("writing %p (%zd bytes)\n", *buf, *len);
981 rv = write(s->write_fd, *buf, *len);
982 PARA_DEBUG_LOG("wrote %d/%zd\n", rv, *len);
984 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
985 slot_num, s->write_fd, strerror(errno));
987 s->fci->error = E_WRITE_AUDIO_DATA;
988 } else if (rv != *len) {
989 PARA_DEBUG_LOG("partial %s write (%i/%zd) for slot %d\n",
990 audio_formats[s->format], rv, *len, slot_num);
992 memmove(*buf, *buf + rv, *len);
996 gettimeofday(&s->wtime, NULL);
1000 static void slot_io(fd_set *wfds)
1005 struct slot_info *s = &slot[i];
1006 struct receiver_node *rn = s->receiver_node;
1008 if (rn && rn->loaded)
1009 gettimeofday(&s->rtime, NULL);
1010 if (s->format >= 0 && s->write_fd > 0 && s->fci) {
1011 ret = filter_io(s->fci);
1013 s->fci->error = -ret;
1014 // PARA_DEBUG_LOG("slot %d, filter io %d bytes, check write: %d, loaded: %d/%d, eof: %d\n",
1015 // i, ret, s->wcheck, rn->loaded, *s->fci->out_loaded, rn->eof);
1017 if (s->write_fd <= 0 || !s->wcheck || !FD_ISSET(s->write_fd, wfds))
1019 write_audio_data(i);
1023 static int parse_stream_command(const char *txt, char **cmd)
1025 char *p = strchr(txt, ':');
1029 return -E_MISSING_COLON;
1031 FOR_EACH_AUDIO_FORMAT(i) {
1032 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1037 return -E_UNSUPPORTED_AUDIO_FORMAT;
1040 static int add_filter(int format, char *cmdline)
1042 struct audio_format_info *a = &afi[format];
1043 int filter_num, nf = a->num_filters;
1045 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1048 a->filters[nf] = &filters[filter_num];
1050 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1051 a->filters[nf]->name);
1055 static int setup_default_filters(void)
1059 FOR_EACH_AUDIO_FORMAT(i) {
1060 struct audio_format_info *a = &afi[i];
1065 /* add "dec" to audio format name */
1066 tmp = make_message("%sdec", audio_formats[i]);
1067 for (j = 0; filters[j].name; j++)
1068 if (!strcmp(tmp, filters[j].name))
1071 ret = -E_UNSUPPORTED_FILTER;
1072 if (!filters[j].name)
1074 tmp = para_strdup(filters[j].name);
1075 ret = add_filter(i, tmp);
1079 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i], filters[j].name);
1080 ret = add_filter(i, para_strdup("wav"));
1083 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1089 static int init_stream_io(void)
1091 int i, ret, receiver_num;
1094 for (i = 0; i < conf.stream_write_cmd_given; i++) {
1095 ret = parse_stream_command(conf.stream_write_cmd_arg[i], &cmd);
1098 afi[ret].write_cmd = para_strdup(cmd);
1099 PARA_INFO_LOG("%s write command: %s\n", audio_formats[ret], afi[ret].write_cmd);
1101 for (i = 0; receivers[i].name; i++) {
1102 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1103 receivers[i].init(&receivers[i]);
1105 for (i = 0; i < conf.receiver_given; i++) {
1106 char *arg = conf.receiver_arg[i];
1107 char *recv = strchr(arg, ':');
1108 ret = -E_MISSING_COLON;
1113 ret = get_audio_format_num(arg);
1116 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1117 if (!afi[ret].receiver_conf) {
1118 ret = -E_RECV_SYNTAX;
1121 afi[ret].receiver = &receivers[receiver_num];
1123 /* use the first available receiver with no arguments
1124 * for those audio formats for which no receiver
1127 cmd = para_strdup(receivers[0].name);
1128 FOR_EACH_AUDIO_FORMAT(i) {
1129 struct audio_format_info *a = &afi[i];
1130 if (a->receiver_conf)
1132 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1133 if (!a->receiver_conf)
1134 return -E_RECV_SYNTAX;
1135 a->receiver = &receivers[receiver_num];
1139 filter_init(filters);
1140 FOR_EACH_AUDIO_FORMAT(i) {
1141 afi[i].filter_conf = para_malloc((conf.filter_given + 1) * sizeof(char *));
1142 afi[i].filters = para_malloc((conf.filter_given + 1) * sizeof(struct filter *));
1144 if (!conf.no_default_filters_given)
1145 return setup_default_filters();
1146 for (i = 0; i < conf.filter_given; i++) {
1147 char *arg = conf.filter_arg[i];
1148 char *filter_name = strchr(arg, ':');
1149 ret = -E_MISSING_COLON;
1152 *filter_name = '\0';
1154 ret = get_audio_format_num(arg);
1157 ret = add_filter(ret, filter_name);
1166 static int dump_commands(int fd)
1168 char *buf = para_strdup(""), *tmp = NULL;
1172 FOR_EACH_COMMAND(i) {
1173 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1174 cmds[i].description);
1178 ret = client_write(fd, buf);
1184 * command handlers don't close their fd on errors (ret < 0) so that
1185 * its caller can send an error message. Otherwise (ret >= 0) it's up
1186 * to each individual command to close the fd if necessary.
1189 static int com_help(int fd, int argc, char **argv)
1193 const char *dflt = "No such command. Available commands:\n";
1196 ret = dump_commands(fd);
1199 FOR_EACH_COMMAND(i) {
1200 if (strcmp(cmds[i].name, argv[1]))
1203 "NAME\n\t%s -- %s\n"
1204 "SYNOPSIS\n\tpara_audioc %s\n"
1205 "DESCRIPTION\n%s\n",
1207 cmds[i].description,
1211 ret = client_write(fd, buf);
1215 ret = client_write(fd, dflt);
1217 ret = dump_commands(fd);
1224 static int com_stat(int fd, __unused int argc, __unused char **argv)
1227 char *buf = audiod_status_string();
1229 buf = para_strcat(buf, "\n");
1230 for (i = RINGBUFFER_SIZE - 1; i >= 0; i--) {
1231 char *tmp, *line = ringbuffer_get(stat_item_ringbuf, i);
1234 tmp = make_message("%s\n", line);
1235 buf = para_strcat(buf, tmp);
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();
1600 stat_item_ringbuf = ringbuffer_new(RINGBUFFER_SIZE);
1602 setup_signal_handling();
1603 if (conf.daemon_given)