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"
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 static char *stat_item_values[NUM_STAT_ITEMS];
135 static FILE *logfile;
136 static const struct timeval restart_delay = {0, 300 * 1000};
138 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
140 static struct audiod_command cmds[] = {
143 .handler = com_cycle,
144 .description = "switch to next mode",
148 "on -> standby -> off -> on\n"
154 .description = "grab the audio stream",
155 .synopsis = "-- grab [grab_options]",
158 "grab ('splice') the audio stream at any position in the filter \n"
159 "chain and send that data back to the client. Try\n"
160 "\t para_audioc -- grab -h\n"
161 "for the list of available options.\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",
214 .synopsis = "stat [item1 ...]",
217 "Dump given status items (all if none given) to stdout.\n"
223 .description = "terminate audiod",
227 "Stop all decoders, shut down connection to para_server and exit.\n"
235 /** iterate over all slots */
236 #define FOR_EACH_SLOT(slot) for (slot = 0; slot < MAX_STREAM_SLOTS; slot++)
237 /** iterate over all supported audio formats */
238 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
239 /** iterate over the array of all audiod commands */
240 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
243 * get the audio format number
244 * \param name the name of the audio format
246 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
247 * \a name is not a supported audio format.
249 int get_audio_format_num(char *name)
252 FOR_EACH_AUDIO_FORMAT(i)
253 if (!strcmp(name, audio_formats[i]))
255 return -E_UNSUPPORTED_AUDIO_FORMAT;
259 * log function. first argument is loglevel.
261 void para_log(int ll, const char* fmt,...)
267 char str[MAXLINE] = "";
269 if (ll < conf.loglevel_arg)
271 if (!logfile && conf.logfile_given)
272 logfile = open_log(conf.logfile_arg);
273 if (!logfile && conf.daemon_given)
284 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
285 fprintf(outfd, "%s %s ", str, hostname);
286 if (conf.loglevel_arg <= INFO)
287 fprintf(outfd, "%i ", ll);
289 vfprintf(outfd, fmt, argp);
293 static int client_write(int fd, const char *buf)
295 size_t len = strlen(buf);
296 return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
299 static char *get_time_string(struct timeval *newest_stime)
301 struct timeval now, diff, adj_stream_start, tmp;
302 int total = 0, use_server_time = 1;
307 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
309 if (audiod_status == AUDIOD_OFF)
311 if (sa_time_diff_sign > 0)
312 tv_diff(&server_stream_start, &sa_time_diff,
315 tv_add(&server_stream_start, &sa_time_diff,
317 tmp = adj_stream_start;
318 if (newest_stime && audiod_status == AUDIOD_ON) {
319 tv_diff(newest_stime, &adj_stream_start, &diff);
320 if (tv2ms(&diff) < 5000) {
325 gettimeofday(&now, NULL);
326 tv_diff(&now, &tmp, &diff);
327 total = diff.tv_sec + offset_seconds;
328 if (total > length_seconds)
329 total = length_seconds;
334 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
335 status_item_list[SI_PLAY_TIME],
336 use_server_time? "~" : "",
339 (length_seconds - total) / 60,
340 (length_seconds - total) % 60,
341 length_seconds? (total * 100 + length_seconds / 2) /
348 __malloc static char *audiod_status_string(void)
350 const char *status = (audiod_status == AUDIOD_ON)?
351 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
352 return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
355 static struct timeval *wstime(void)
358 struct timeval *max = NULL;
360 struct slot_info *s = &slot[i];
363 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
369 __malloc static char *decoder_flags(void)
372 char decoder_flags[MAX_STREAM_SLOTS + 1];
375 struct slot_info *s = &slot[i];
377 if (s->receiver_node)
382 flag += s->format * 4;
383 decoder_flags[i] = flag;
385 decoder_flags[MAX_STREAM_SLOTS] = '\0';
386 return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
390 static char *configfile_exists(void)
392 static char *config_file;
395 char *home = para_homedir();
396 config_file = make_message("%s/.paraslash/audiod.conf", home);
399 return file_exists(config_file)? config_file : NULL;
402 static void setup_signal_handling(void)
404 signal_pipe = para_signal_init();
405 PARA_INFO_LOG("signal pipe: fd %d\n", signal_pipe);
406 para_install_sighandler(SIGINT);
407 para_install_sighandler(SIGTERM);
408 para_install_sighandler(SIGCHLD);
409 para_install_sighandler(SIGHUP);
410 signal(SIGPIPE, SIG_IGN);
413 static void audiod_status_dump(void)
415 static char *p_ts, *p_us, *p_as, *p_df;
416 struct timeval *t = wstime();
417 char *us, *tmp = get_time_string(t);
419 if (tmp && (!p_ts || strcmp(tmp, p_ts)))
420 stat_client_write(tmp, SI_PLAY_TIME);
425 tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
427 if (!p_us || strcmp(p_us, tmp))
428 stat_client_write(tmp, SI_AUDIOD_UPTIME);
432 tmp = audiod_status_string();
433 if (!p_as || strcmp(p_as, tmp))
434 stat_client_write(tmp, SI_AUDIOD_STATUS);
438 tmp = decoder_flags();
439 if (!p_df || strcmp(p_df, tmp))
440 stat_client_write(tmp, SI_DECODER_FLAGS);
445 static void clear_slot(int slot_num)
447 struct slot_info *s = &slot[slot_num];
449 PARA_INFO_LOG("clearing slot %d\n", slot_num);
450 memset(s, 0, sizeof(struct slot_info));
454 static void kill_stream_writer(int slot_num)
456 struct slot_info *s = &slot[slot_num];
458 if (s->format < 0 || s->wkilled || s->wpid <= 0)
460 PARA_DEBUG_LOG("kill -TERM %d (%s stream writer in slot %d)\n",
461 s->wpid, audio_formats[s->format], slot_num);
462 kill(s->wpid, SIGTERM);
467 static void set_restart_barrier(int format, struct timeval *now)
474 gettimeofday(&tmp, NULL);
475 tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
478 static void close_receiver(int slot_num)
480 struct slot_info *s = &slot[slot_num];
481 struct audio_format_info *a;
483 if (s->format < 0 || !s->receiver_node)
486 PARA_NOTICE_LOG("closing %s recevier in slot %d\n",
487 audio_formats[s->format] , slot_num);
488 a->receiver->close(s->receiver_node);
489 free(s->receiver_node);
490 s->receiver_node = NULL;
491 set_restart_barrier(s->format, NULL);
494 static void kill_all_decoders(void)
499 if (slot[i].format >= 0) {
500 PARA_INFO_LOG("stopping decoder in slot %d\n", i);
501 kill_stream_writer(i);
505 static void check_sigchld(void)
510 gettimeofday(&now, NULL);
513 pid = para_reap_child();
517 struct slot_info *s = &slot[i];
521 if (pid == s->wpid) {
523 lifetime = now.tv_sec - s->wstime.tv_sec;
524 PARA_INFO_LOG("%s stream writer in slot %d died "
526 audio_formats[s->format], i, lifetime);
527 set_restart_barrier(s->format, &now);
528 goto reap_next_child;
531 PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
532 goto reap_next_child;
535 static int get_empty_slot(void)
546 if (s->write_fd > 0 || s->wpid > 0)
548 if (s->receiver_node)
555 return -E_NO_MORE_SLOTS;
558 static int decoder_running(int format)
565 if (s->format == format && s->receiver_node)
567 if (s->format == format && s->wpid > 0)
573 static void close_stat_pipe(void)
579 PARA_NOTICE_LOG("%s", "closing status pipe\n");
581 del_close_on_fork_list(stat_pipe);
584 for (i = 0; i < NUM_STAT_ITEMS; i++) {
585 free(stat_item_values[i]);
586 stat_item_values[i] = NULL;
591 audiod_status_dump();
593 stat_item_values[SI_STATUS_BAR] = make_message("%s:no connection to para_server\n",
594 status_item_list[SI_STATUS_BAR]);
595 stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
598 static void __noreturn clean_exit(int status, const char *msg)
600 PARA_EMERG_LOG("%s\n", msg);
609 __malloc static char *glob_cmd(char *cmd)
611 char *ret, *replacement;
612 struct timeval tmp, delay, rss; /* real stream start */
614 delay.tv_sec = conf.stream_delay_arg / 1000;
615 delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
616 // PARA_INFO_LOG("delay: %lu:%lu\n", delay.tv_sec, delay.tv_usec);
617 if (sa_time_diff_sign < 0)
618 tv_add(&server_stream_start, &sa_time_diff, &rss);
620 tv_diff(&server_stream_start, &sa_time_diff, &rss);
621 tv_add(&rss, &delay, &tmp);
622 replacement = make_message("%lu:%lu", tmp.tv_sec, tmp.tv_usec);
623 ret = s_a_r(cmd, "STREAM_START", replacement);
627 PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
630 gettimeofday(&now, NULL);
631 PARA_INFO_LOG("now: %lu:%lu\n", now.tv_sec, now.tv_usec);
637 /** get the number of filters for the given audio format */
638 int num_filters(int audio_format_num)
640 return afi[audio_format_num].num_filters;
643 static void open_filters(int slot_num)
645 struct slot_info *s = &slot[slot_num];
646 struct audio_format_info *a = &afi[s->format];
647 int nf = a->num_filters;
650 s->fci = para_calloc(sizeof(struct filter_chain_info));
651 INIT_LIST_HEAD(&s->fci->filters);
654 s->fci->inbuf = s->receiver_node->buf;
655 s->fci->in_loaded = &s->receiver_node->loaded;
656 s->fci->outbuf = s->receiver_node->buf;
657 s->fci->out_loaded = &s->receiver_node->loaded;
658 s->fci->eof = &s->receiver_node->eof;
659 for (i = 0; i < nf; i++) {
660 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
661 fn->conf = a->filter_conf[i];
663 fn->filter = a->filters[i];
664 INIT_LIST_HEAD(&fn->callbacks);
665 list_add_tail(&fn->node, &s->fci->filters);
666 fn->filter->open(fn);
667 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
668 audio_formats[s->format], i + 1, nf,
669 fn->filter->name, slot_num);
670 s->fci->outbuf = fn->buf;
671 s->fci->out_loaded = &fn->loaded;
673 PARA_DEBUG_LOG("output buffer for filter chain %p: %p\n", s->fci,
677 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
679 struct filter_node *fn;
683 struct slot_info *s = &slot[i];
684 if (s->format < 0 || !s->fci)
686 if (slot_num >= 0 && slot_num != i)
688 if (format >= 0 && s->format != format)
690 if (num_filters(i) < filternum)
694 list_for_each_entry(fn, &s->fci->filters, node)
695 if (filternum <= 0 || j++ == filternum)
702 static void start_stream_writer(int slot_num)
704 int ret, fds[3] = {1, -1, -1};
705 struct slot_info *s = &slot[slot_num];
706 struct audio_format_info *a = &afi[s->format];
710 glob = glob_cmd(a->write_cmd);
712 glob = para_strdup("para_play");
713 PARA_INFO_LOG("starting stream writer: %s\n", glob);
714 open_filters(slot_num);
715 ret = para_exec_cmdline_pid(&s->wpid, glob, fds);
718 PARA_ERROR_LOG("exec failed (%d)\n", ret);
721 s->write_fd = fds[0];
722 add_close_on_fork_list(s->write_fd);
723 /* we write to this fd in do_select, so we need non-blocking */
724 mark_fd_nonblock(s->write_fd);
725 gettimeofday(&s->wstime, NULL);
726 current_decoder = slot_num;
727 activate_inactive_grab_clients(slot_num, s->format, &s->fci->filters);
730 static void open_receiver(int format)
732 struct audio_format_info *a = &afi[format];
736 slot_num = get_empty_slot();
738 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
741 gettimeofday(&s->rtime, NULL);
743 s->receiver_node = para_calloc(sizeof(struct receiver_node));
744 s->receiver_node->conf = a->receiver_conf;
745 ret = a->receiver->open(s->receiver_node);
747 PARA_ERROR_LOG("failed to open receiver (%s)\n",
748 PARA_STRERROR(-ret));
749 free(s->receiver_node);
750 s->receiver_node = NULL;
753 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
754 audio_formats[s->format], a->receiver->name, slot_num);
757 static int is_frozen(int format)
760 struct audio_format_info *a = &afi[format];
762 gettimeofday(&now, NULL);
763 return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
766 static void start_current_receiver(void)
772 i = get_audio_format_num(af_status);
775 if ((decoder_running(i) & 1) || is_frozen(i))
780 static void compute_time_diff(const struct timeval *status_time)
782 struct timeval now, tmp, diff;
785 const struct timeval max_deviation = {0, 500 * 1000};
786 const int time_smooth = 5;
788 gettimeofday(&now, NULL);
789 sign = tv_diff(status_time, &now, &diff);
790 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
791 // sign, sa_time_diff_sign);
793 sa_time_diff_sign = sign;
799 int s = tv_diff(&diff, &sa_time_diff, &tmp);
800 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
801 PARA_WARNING_LOG("time diff jump: %lims\n",
805 sa_time_diff_sign = tv_convex_combination(
806 sa_time_diff_sign * time_smooth, &sa_time_diff,
807 count > 10? sign : sign * time_smooth, &diff,
810 PARA_INFO_LOG("time diff (cur/avg): "
812 sign * diff.tv_sec, (diff.tv_usec + 500) / 1000,
813 sa_time_diff_sign * sa_time_diff.tv_sec,
814 (sa_time_diff.tv_usec + 500)/ 1000);
817 static void check_stat_line(char *line)
826 itemnum = stat_line_valid(line);
828 PARA_WARNING_LOG("invalid status line: %s\n", line);
831 tmp = make_message("%s\n", line);
832 stat_client_write(tmp, itemnum);
834 free(stat_item_values[itemnum]);
835 stat_item_values[itemnum] = para_strdup(line);
836 ilen = strlen(status_item_list[itemnum]);
839 playing = strstr(line, "playing")? 1 : 0;
843 af_status = para_strdup(line + ilen + 1);
846 offset_seconds = atoi(line + ilen + 1);
849 length_seconds = atoi(line + ilen + 1);
851 case SI_STREAM_START:
852 if (sscanf(line + ilen + 1, "%lu.%lu",
853 &tv.tv_sec, &tv.tv_usec) == 2)
854 server_stream_start = tv;
856 case SI_CURRENT_TIME:
857 if (sscanf(line + ilen + 1, "%lu.%lu", &tv.tv_sec,
859 compute_time_diff(&tv);
864 static void handle_signal(int sig)
868 return check_sigchld();
872 PARA_EMERG_LOG("terminating on signal %d\n", sig);
873 clean_exit(EXIT_FAILURE, "caught deadly signal");
878 static void check_timeouts(void)
881 int slot_num, timeout = conf.stream_timeout_arg;
883 gettimeofday(&now, NULL);
884 FOR_EACH_SLOT(slot_num) {
885 struct slot_info *s = &slot[slot_num];
888 /* check read time */
889 if (s->receiver_node &&
890 now.tv_sec > s->rtime.tv_sec + timeout) {
891 PARA_INFO_LOG("%s input buffer (slot %d) not ready\n",
892 audio_formats[s->format], slot_num);
896 close_receiver(slot_num);
898 /* check write time */
899 if (s->wpid > 0 && !s->wkilled &&
900 now.tv_sec > s->wtime.tv_sec + timeout) {
901 PARA_INFO_LOG("%s output buffer (slot %d) not ready\n",
902 audio_formats[s->format], slot_num);
909 static size_t get_loaded_bytes(int slot_num)
912 struct slot_info *s = &slot[slot_num];
913 struct receiver_node *rn = s->receiver_node;
918 if (afi[s->format].num_filters) {
920 loaded = *s->fci->out_loaded;
930 static void close_decoder_if_idle(int slot_num)
932 struct slot_info *s = &slot[slot_num];
933 struct receiver_node *rn = s->receiver_node;
939 if (!rn->eof && !s->fci->error && s->wpid > 0)
941 if (!s->fci->error && s->wpid > 0) { /* eof */
942 if (filter_io(s->fci) > 0)
944 if (get_loaded_bytes(slot_num))
947 if (s->write_fd > 0) {
948 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
951 del_close_on_fork_list(s->write_fd);
955 return; /* wait until writer dies before closing filters */
956 PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
958 close_filters(s->fci);
960 close_receiver(slot_num);
961 clear_slot(slot_num);
964 static int set_stream_fds(fd_set *wfds)
966 int i, max_fileno = -1;
970 struct slot_info *s = &slot[i];
971 struct audio_format_info *a;
972 struct receiver_node *rn;
974 close_decoder_if_idle(i);
979 rn = s->receiver_node;
980 if (rn && rn->loaded && !s->wpid) {
981 PARA_INFO_LOG("no writer in slot %d\n", i);
982 start_stream_writer(i);
984 if (s->write_fd <= 0)
986 if (!get_loaded_bytes(i))
988 FD_SET(s->write_fd, wfds);
990 max_fileno = MAX(s->write_fd, max_fileno);
992 // PARA_INFO_LOG("return %d\n", max_fileno);
996 static int write_audio_data(int slot_num)
998 struct slot_info *s = &slot[slot_num];
999 struct audio_format_info *a = &afi[s->format];
1000 struct receiver_node *rn = s->receiver_node;
1005 if (a->num_filters) {
1006 buf = &s->fci->outbuf;
1007 len = s->fci->out_loaded;
1012 PARA_DEBUG_LOG("writing %p (%zd bytes)\n", *buf, *len);
1013 rv = write(s->write_fd, *buf, *len);
1014 PARA_DEBUG_LOG("wrote %d/%zd\n", rv, *len);
1016 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
1017 slot_num, s->write_fd, strerror(errno));
1019 s->fci->error = E_WRITE_AUDIO_DATA;
1020 } else if (rv != *len) {
1021 PARA_DEBUG_LOG("partial %s write (%i/%zd) for slot %d\n",
1022 audio_formats[s->format], rv, *len, slot_num);
1024 memmove(*buf, *buf + rv, *len);
1028 gettimeofday(&s->wtime, NULL);
1032 static void slot_io(fd_set *wfds)
1037 struct slot_info *s = &slot[i];
1038 struct receiver_node *rn = s->receiver_node;
1040 if (rn && rn->loaded)
1041 gettimeofday(&s->rtime, NULL);
1042 if (s->format >= 0 && s->write_fd > 0 && s->fci) {
1043 ret = filter_io(s->fci);
1045 s->fci->error = -ret;
1046 // PARA_DEBUG_LOG("slot %d, filter io %d bytes, check write: %d, loaded: %d/%d, eof: %d\n",
1047 // i, ret, s->wcheck, rn->loaded, *s->fci->out_loaded, rn->eof);
1049 if (s->write_fd <= 0 || !s->wcheck || !FD_ISSET(s->write_fd, wfds))
1051 write_audio_data(i);
1055 static int parse_stream_command(const char *txt, char **cmd)
1057 char *p = strchr(txt, ':');
1061 return -E_MISSING_COLON;
1063 FOR_EACH_AUDIO_FORMAT(i) {
1064 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1069 return -E_UNSUPPORTED_AUDIO_FORMAT;
1072 static int add_filter(int format, char *cmdline)
1074 struct audio_format_info *a = &afi[format];
1075 int filter_num, nf = a->num_filters;
1077 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1080 a->filters[nf] = &filters[filter_num];
1082 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1083 a->filters[nf]->name);
1087 static int setup_default_filters(void)
1091 FOR_EACH_AUDIO_FORMAT(i) {
1092 struct audio_format_info *a = &afi[i];
1097 /* add "dec" to audio format name */
1098 tmp = make_message("%sdec", audio_formats[i]);
1099 for (j = 0; filters[j].name; j++)
1100 if (!strcmp(tmp, filters[j].name))
1103 ret = -E_UNSUPPORTED_FILTER;
1104 if (!filters[j].name)
1106 tmp = para_strdup(filters[j].name);
1107 ret = add_filter(i, tmp);
1111 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i], filters[j].name);
1112 ret = add_filter(i, para_strdup("wav"));
1115 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1121 static int init_stream_io(void)
1123 int i, ret, receiver_num;
1126 for (i = 0; i < conf.stream_write_cmd_given; i++) {
1127 ret = parse_stream_command(conf.stream_write_cmd_arg[i], &cmd);
1130 afi[ret].write_cmd = para_strdup(cmd);
1131 PARA_INFO_LOG("%s write command: %s\n", audio_formats[ret], afi[ret].write_cmd);
1133 for (i = 0; receivers[i].name; i++) {
1134 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1135 receivers[i].init(&receivers[i]);
1137 for (i = 0; i < conf.receiver_given; i++) {
1138 char *arg = conf.receiver_arg[i];
1139 char *recv = strchr(arg, ':');
1140 ret = -E_MISSING_COLON;
1145 ret = get_audio_format_num(arg);
1148 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1149 if (!afi[ret].receiver_conf) {
1150 ret = -E_RECV_SYNTAX;
1153 afi[ret].receiver = &receivers[receiver_num];
1155 /* use the first available receiver with no arguments
1156 * for those audio formats for which no receiver
1159 cmd = para_strdup(receivers[0].name);
1160 FOR_EACH_AUDIO_FORMAT(i) {
1161 struct audio_format_info *a = &afi[i];
1162 if (a->receiver_conf)
1164 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1165 if (!a->receiver_conf)
1166 return -E_RECV_SYNTAX;
1167 a->receiver = &receivers[receiver_num];
1171 filter_init(filters);
1172 FOR_EACH_AUDIO_FORMAT(i) {
1173 afi[i].filter_conf = para_malloc((conf.filter_given + 1) * sizeof(char *));
1174 afi[i].filters = para_malloc((conf.filter_given + 1) * sizeof(struct filter *));
1176 if (!conf.no_default_filters_given)
1177 return setup_default_filters();
1178 for (i = 0; i < conf.filter_given; i++) {
1179 char *arg = conf.filter_arg[i];
1180 char *filter_name = strchr(arg, ':');
1181 ret = -E_MISSING_COLON;
1184 *filter_name = '\0';
1186 ret = get_audio_format_num(arg);
1189 ret = add_filter(ret, filter_name);
1198 static int dump_commands(int fd)
1200 char *buf = para_strdup(""), *tmp = NULL;
1204 FOR_EACH_COMMAND(i) {
1205 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1206 cmds[i].description);
1210 ret = client_write(fd, buf);
1216 * command handlers don't close their fd on errors (ret < 0) so that
1217 * its caller can send an error message. Otherwise (ret >= 0) it's up
1218 * to each individual command to close the fd if necessary.
1221 static int com_help(int fd, int argc, char **argv)
1225 const char *dflt = "No such command. Available commands:\n";
1228 ret = dump_commands(fd);
1231 FOR_EACH_COMMAND(i) {
1232 if (strcmp(cmds[i].name, argv[1]))
1235 "NAME\n\t%s -- %s\n"
1236 "SYNOPSIS\n\tpara_audioc %s\n"
1237 "DESCRIPTION\n%s\n",
1239 cmds[i].description,
1243 ret = client_write(fd, buf);
1247 ret = client_write(fd, dflt);
1249 ret = dump_commands(fd);
1256 static int com_stat(int fd, __unused int argc, __unused char **argv)
1260 long unsigned mask = ~0LU;
1264 for (i = 1; i < argc; i++) {
1265 ret = stat_item_valid(argv[i]);
1271 PARA_INFO_LOG("mask: 0x%lx\n", mask);
1272 if (mask & (1 << SI_PLAY_TIME)) {
1273 struct timeval *t = wstime();
1274 char *ts = get_time_string(t);
1276 ret = client_write(fd, ts);
1282 if (mask & (1 << SI_AUDIOD_UPTIME)) {
1283 char *tmp, *us = uptime_str();
1284 tmp = make_message("%s:%s\n",
1285 status_item_list[SI_AUDIOD_UPTIME], us);
1287 ret = client_write(fd, tmp);
1292 if (mask & (1 << SI_AUDIOD_STATUS)) {
1293 char *s = audiod_status_string();
1294 ret = client_write(fd, s);
1299 if (mask & (1 << SI_DECODER_FLAGS)) {
1300 char *df =decoder_flags();
1301 ret = client_write(fd, df);
1307 for (i = 0; i < NUM_STAT_ITEMS; i++) {
1309 if (!((1 << i) & mask))
1311 v = stat_item_values[i];
1312 tmp = make_message("%s%s%s", buf? buf: "",
1313 v? v : "", v? "\n" : "");
1317 ret = client_write(fd, buf);
1320 ret = stat_client_add(fd, mask);
1326 static char *list_filters(void)
1329 char *tmp, *msg = make_message("format\tnum\tcmd\n");
1331 FOR_EACH_AUDIO_FORMAT(i) {
1332 for (j = 0; j < afi[i].num_filters; j++) {
1333 tmp = make_message("%s\t%i\t%s\n",
1334 afi[i].name, j, afi[i].filter_cmds[j]);
1335 msg = para_strcat(msg, tmp);
1338 tmp = make_message("%s\t%i\t%s\n", afi[i].name,
1339 j, afi[i].write_cmd);
1340 msg = para_strcat(msg, tmp);
1347 static int com_grab(int fd, int argc, char **argv)
1349 struct grab_client *gc;
1350 struct filter_node *fn;
1354 PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1355 gc = grab_client_new(fd, argc, argv, &err);
1356 PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1359 fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1361 activate_grab_client(gc, fn);
1364 if (err != -E_GC_HELP_GIVEN && err != -E_GC_VERSION_GIVEN)
1366 if (err == -E_GC_HELP_GIVEN) {
1367 msg = make_message("%s\n\n", grab_client_args_info_usage);
1368 for (i = 0; grab_client_args_info_help[i]; i++) {
1369 char *tmp = make_message("%s%s\n", msg,
1370 grab_client_args_info_help[i]);
1375 msg = make_message("%s %s\n",
1376 GRAB_CLIENT_CMDLINE_PARSER_PACKAGE,
1377 GRAB_CLIENT_CMDLINE_PARSER_VERSION);
1378 err = client_write(fd, msg);
1386 static int __noreturn com_term(int fd, __unused int argc, __unused char **argv)
1389 clean_exit(EXIT_SUCCESS, "terminating on user request");
1392 static int com_on(int fd, __unused int argc, __unused char **argv)
1394 audiod_status = AUDIOD_ON;
1399 static int com_off(int fd, __unused int argc, __unused char **argv)
1401 audiod_status = AUDIOD_OFF;
1406 static int com_sb(int fd, __unused int argc, __unused char **argv)
1408 audiod_status = AUDIOD_STANDBY;
1413 static int com_cycle(int fd, int argc, char **argv)
1415 switch (audiod_status) {
1417 return com_sb(fd, argc, argv);
1420 return com_on(fd, argc, argv);
1422 case AUDIOD_STANDBY:
1423 return com_off(fd, argc, argv);
1430 static int check_perms(struct ucred *c)
1434 if (!conf.user_allow_given)
1436 for (i = 0; i < conf.user_allow_given; i++)
1437 if (c->uid == conf.user_allow_arg[i])
1439 return -E_UCRED_PERM;
1442 static int handle_connect(void)
1444 int i, argc, ret, clifd = -1;
1446 char *buf = para_malloc(MAXLINE), **argv = NULL;
1447 struct sockaddr_un unix_addr;
1449 ret = para_accept(audiod_socket, &unix_addr, sizeof(struct sockaddr_un));
1453 ret = recv_cred_buffer(clifd, buf, MAXLINE - 1, &c);
1456 PARA_INFO_LOG("pid: %i, uid: %i, gid: %i, ret: %i, buf: %s\n", c.pid, c.uid, c.gid, ret, buf);
1458 ret = check_perms(&c);
1461 argc = split_args(buf, &argv, '\n');
1462 PARA_INFO_LOG("argv[0]: %s\n", argv[0]);
1463 for (i = 0; cmds[i].name; i++) {
1464 if (strcmp(cmds[i].name, argv[0]))
1466 ret = cmds[i].handler(clifd, argc + 1, argv);
1469 ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1473 if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1474 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1475 client_write(clifd, tmp);
1482 static void audiod_get_socket(void)
1484 struct sockaddr_un unix_addr;
1486 if (conf.socket_given)
1487 socket_name = para_strdup(conf.socket_arg);
1489 char *hn = para_hostname();
1490 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1494 PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1495 if (conf.force_given)
1496 unlink(socket_name);
1497 audiod_socket = create_pf_socket(socket_name, &unix_addr,
1498 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1499 if (audiod_socket < 0) {
1500 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1501 exit(EXIT_FAILURE); /* do not unlink socket */
1503 if (listen(audiod_socket, 5) < 0) {
1504 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1505 exit(EXIT_FAILURE); /* do not unlink socket */
1507 add_close_on_fork_list(audiod_socket);
1510 static int open_stat_pipe(void)
1512 int ret, fd[3] = {-1, 1, 0};
1514 ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1517 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1518 add_close_on_fork_list(ret);
1520 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1524 static int audiod_pre_select(fd_set *rfds, fd_set *wfds, struct timeval *tv)
1526 int i, ret, max = -1;
1529 struct slot_info *s = &slot[i];
1530 struct audio_format_info *a;
1531 struct receiver_node *rn = s->receiver_node;
1532 if (s->format < 0 || !rn)
1534 a = &afi[s->format];
1535 ret = a->receiver->pre_select(rn, rfds, wfds, tv);
1536 // PARA_NOTICE_LOG("%s preselect: %d\n", a->receiver->name, ret);
1537 max = MAX(max, ret);
1542 static void audiod_post_select(int select_ret, fd_set *rfds, fd_set *wfds)
1547 struct slot_info *s = &slot[i];
1548 struct audio_format_info *a;
1549 struct receiver_node *rn = s->receiver_node;
1550 if (s->format < 0 || !rn || rn->eof)
1552 a = &afi[s->format];
1553 ret = a->receiver->post_select(rn, select_ret, rfds, wfds);
1556 PARA_ERROR_LOG("%s post select failed: %s (slot %d)\n",
1557 a->receiver->name, PARA_STRERROR(-ret), i);
1559 PARA_INFO_LOG("eof in slot %d\n", i);
1562 if (ret < 0 && s->fci)
1563 s->fci->error = ret;
1567 /* TODO: move everything before the select call to pre_select() */
1568 static void __noreturn audiod_mainloop(void)
1571 int ret, max_fileno, sbo = 0;
1572 char status_buf[STRINGSIZE] = "";
1577 /* always check signal pipe and the local socket */
1578 FD_SET(signal_pipe, &rfds);
1579 max_fileno = signal_pipe;
1580 FD_SET(audiod_socket, &rfds);
1581 max_fileno = MAX(max_fileno, audiod_socket);
1583 if (audiod_status != AUDIOD_ON)
1584 kill_all_decoders();
1586 start_current_receiver();
1588 max_fileno = MAX(max_fileno, set_stream_fds(&wfds));
1590 if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1592 if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1593 stat_pipe = open_stat_pipe();
1595 status_buf[0] = '\0';
1597 if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF) {
1598 FD_SET(stat_pipe, &rfds);
1599 max_fileno = MAX(max_fileno, stat_pipe);
1603 tv.tv_usec = 200 * 1000;
1604 ret = audiod_pre_select(&rfds, &wfds, &tv);
1605 max_fileno = MAX(max_fileno, ret);
1607 ret = para_select(max_fileno + 1, &rfds, &wfds, &tv);
1610 if (audiod_status != AUDIOD_OFF)
1611 audiod_status_dump();
1612 audiod_post_select(ret, &rfds, &wfds);
1613 /* read status pipe */
1614 if (stat_pipe >=0 && FD_ISSET(stat_pipe, &rfds)) {
1615 ret = read(stat_pipe, status_buf + sbo, STRINGSIZE - 1 - sbo);
1618 /* avoid busy loop if server is down */
1619 while (sleep(1) > 0)
1622 status_buf[ret + sbo] = '\0';
1623 sbo = for_each_line(status_buf, ret + sbo,
1628 if (FD_ISSET(audiod_socket, &rfds)) {
1629 ret = handle_connect();
1631 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1635 if (FD_ISSET(signal_pipe, &rfds)) {
1636 int sig_nr = para_next_signal();
1638 handle_signal(sig_nr);
1643 static void set_initial_status(void)
1645 audiod_status = AUDIOD_ON;
1646 if (!conf.mode_given)
1648 if (!strcmp(conf.mode_arg, "sb")) {
1649 audiod_status = AUDIOD_STANDBY;
1652 if (!strcmp(conf.mode_arg, "off")) {
1653 audiod_status = AUDIOD_OFF;
1656 if (strcmp(conf.mode_arg, "on"))
1657 PARA_WARNING_LOG("%s", "invalid mode\n");
1660 int __noreturn main(int argc, char *argv[])
1666 hostname = para_hostname();
1667 cmdline_parser(argc, argv, &conf);
1668 para_drop_privileges(conf.user_arg);
1669 cf = configfile_exists();
1671 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1672 fprintf(stderr, "parse error in config file\n");
1676 log_welcome("para_audiod", conf.loglevel_arg);
1677 i = init_stream_io();
1679 fprintf(stderr, "init stream io error: %s\n",
1683 server_uptime(UPTIME_SET);
1684 set_initial_status();
1688 setup_signal_handling();
1689 if (conf.daemon_given)
1691 audiod_get_socket(); /* doesn't return on errors */