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"
30 #include "grab_client.cmdline.h"
31 #include "grab_client.h"
40 #include "write_common.h"
42 /** define the array of error lists needed by para_audiod */
44 /** define the array containing all supported audio formats */
45 DEFINE_AUDIO_FORMAT_ARRAY;
48 * the possible modes of operation
50 * - off: disconnect from para_server
51 * - on: receive status information from para_server and play the audio stream
52 * - sb: only receive status information but not the audio stream
54 enum {AUDIOD_OFF, AUDIOD_ON, AUDIOD_STANDBY};
56 /** defines how to handle one supported audio format */
57 struct audio_format_info {
58 /** pointer to the receiver for this audio format */
59 struct receiver *receiver;
60 /** the receiver configuration */
62 /** the number of filters that should be activated for this audio format */
63 unsigned int num_filters;
64 /** pointer to the array of filters to be activated */
65 struct filter **filters;
66 /** pointer to the array of filter configurations */
68 /** the number of filters that should be activated for this audio format */
69 unsigned int num_writers;
70 /** pointer to the array of writers to be activated */
71 struct writer **writers;
72 /** pointer to the array of writer configurations */
74 /** do not start receiver/filters/writer before this time */
75 struct timeval restart_barrier;
79 * describes one instance of a receiver-filter-writer chain
81 * \sa receier_node, receiver, filter, filter_node, filter_chain, writer,
82 * writer_node, writer_node_group.
85 /** number of the audio format in this slot */
87 /** time of the last successful read from the receiver */
89 /** time the last write to the write fd happend */
91 /** writer start time */
92 struct timeval wstime;
93 /** the receiver info associated with this slot */
94 struct receiver_node *receiver_node;
95 /** the active filter chain */
96 struct filter_chain *fc;
97 /** the active writer node group */
98 struct writer_node_group *wng;
100 static struct slot_info slot[MAX_STREAM_SLOTS];
102 extern const char *status_item_list[NUM_STAT_ITEMS];
104 static struct gengetopt_args_info conf;
105 static struct timeval server_stream_start, sa_time_diff;
106 static int playing, current_decoder = -1,
107 audiod_status = AUDIOD_ON, offset_seconds, length_seconds,
108 sa_time_diff_sign = 1;
109 static char *af_status, /* the audio format announced in server status */
110 *socket_name, *hostname;
111 static char *stat_item_values[NUM_STAT_ITEMS];
112 static FILE *logfile;
113 static const struct timeval restart_delay = {0, 300 * 1000};
115 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
117 static struct signal_task signal_task_struct, *sig_task = &signal_task_struct;
119 struct command_task {
123 static struct command_task command_task_struct, *cmd_task = &command_task_struct;
128 char buf[STRINGSIZE];
131 static struct status_task status_task_struct, *stat_task = &status_task_struct;
136 static struct audiod_task audiod_task_struct, *at = &audiod_task_struct;
145 /** defines one command of para_audiod */
146 struct audiod_command {
147 /** the name of the command */
149 /** pointer to the function that handles the command */
150 int (*handler)(int, int, char**);
151 int (*line_handler)(int, char*);
152 /** one-line description of the command */
153 const char *description;
154 /** summary of the command line options */
155 const char *synopsis;
156 /** the long help text */
159 static int com_grab(int, char *);
160 static int com_cycle(int, int, char **);
161 static int com_help(int, int, char **);
162 static int com_off(int, int, char **);
163 static int com_on(int, int, char **);
164 static int com_sb(int, int, char **);
165 static int com_stat(int, int, char **);
166 static int com_term(int, int, char **);
167 static struct audiod_command cmds[] = {
170 .handler = com_cycle,
171 .description = "switch to next mode",
175 "on -> standby -> off -> on\n"
180 .line_handler = com_grab,
181 .description = "grab the audio stream",
182 .synopsis = "-- grab [grab_options]",
185 "grab ('splice') the audio stream at any position in the filter \n"
186 "chain and send that data back to the client. Try\n"
187 "\t para_audioc -- grab -h\n"
188 "for the list of available options.\n"
194 .description = "display command list or help for given command",
195 .synopsis = "help [command]",
198 "When I was younger, so much younger than today, I never needed\n"
199 "anybody's help in any way. But now these days are gone, I'm not so\n"
200 "self assured. Now I find I've changed my mind and opened up the doors.\n"
202 " -- Beatles: Help\n"
208 .description = "deactivate para_audiod",
212 "Close connection to para_server and stop all decoders.\n"
218 .description = "activate para_audiod",
222 "Establish connection to para_server, retrieve para_server's current\n"
223 "status. If playing, start corresponding decoder. Otherwise stop\n"
230 .description = "enter standby mode",
234 "Stop all decoders but leave connection to para_server open.\n"
240 .description = "print status information",
241 .synopsis = "stat [item1 ...]",
244 "Dump given status items (all if none given) to stdout.\n"
250 .description = "terminate audiod",
254 "Stop all decoders, shut down connection to para_server and exit.\n"
262 /** iterate over all slots */
263 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
264 /** iterate over all supported audio formats */
265 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
266 /** iterate over the array of all audiod commands */
267 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
270 * get the audio format number
271 * \param name the name of the audio format
273 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
274 * \a name is not a supported audio format.
276 int get_audio_format_num(char *name)
279 FOR_EACH_AUDIO_FORMAT(i)
280 if (!strcmp(name, audio_formats[i]))
282 return -E_UNSUPPORTED_AUDIO_FORMAT;
286 * log function. first argument is loglevel.
288 void para_log(int ll, const char* fmt,...)
294 char str[MAXLINE] = "";
296 if (ll < conf.loglevel_arg)
298 outfd = logfile? logfile : stderr;
301 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
302 fprintf(outfd, "%s %s ", str, hostname);
303 if (conf.loglevel_arg <= INFO)
304 fprintf(outfd, "%i ", ll);
306 vfprintf(outfd, fmt, argp);
310 static int client_write(int fd, const char *buf)
312 size_t len = strlen(buf);
313 return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
316 static char *get_time_string(struct timeval *newest_stime)
318 struct timeval now, diff, adj_stream_start, tmp;
319 int total = 0, use_server_time = 1;
324 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
326 if (audiod_status == AUDIOD_OFF)
328 if (sa_time_diff_sign > 0)
329 tv_diff(&server_stream_start, &sa_time_diff,
332 tv_add(&server_stream_start, &sa_time_diff,
334 tmp = adj_stream_start;
335 if (newest_stime && audiod_status == AUDIOD_ON) {
336 tv_diff(newest_stime, &adj_stream_start, &diff);
337 if (tv2ms(&diff) < 5000) {
342 gettimeofday(&now, NULL);
343 tv_diff(&now, &tmp, &diff);
344 total = diff.tv_sec + offset_seconds;
345 if (total > length_seconds)
346 total = length_seconds;
351 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
352 status_item_list[SI_PLAY_TIME],
353 use_server_time? "~" : "",
356 (length_seconds - total) / 60,
357 (length_seconds - total) % 60,
358 length_seconds? (total * 100 + length_seconds / 2) /
365 __malloc static char *audiod_status_string(void)
367 const char *status = (audiod_status == AUDIOD_ON)?
368 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
369 return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
372 static struct timeval *wstime(void)
375 struct timeval *max = NULL;
377 struct slot_info *s = &slot[i];
380 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
386 __malloc static char *decoder_flags(void)
389 char decoder_flags[MAX_STREAM_SLOTS + 1];
392 struct slot_info *s = &slot[i];
394 if (s->receiver_node)
398 decoder_flags[i] = flag;
400 decoder_flags[MAX_STREAM_SLOTS] = '\0';
401 return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
405 static char *configfile_exists(void)
407 static char *config_file;
410 char *home = para_homedir();
411 config_file = make_message("%s/.paraslash/audiod.conf", home);
414 return file_exists(config_file)? config_file : NULL;
417 static void setup_signal_handling(void)
419 sig_task->fd = para_signal_init();
420 PARA_INFO_LOG("signal pipe: fd %d\n", sig_task->fd);
421 para_install_sighandler(SIGINT);
422 para_install_sighandler(SIGTERM);
423 para_install_sighandler(SIGCHLD);
424 para_install_sighandler(SIGHUP);
425 signal(SIGPIPE, SIG_IGN);
428 static void audiod_status_dump(void)
430 static char *p_ts, *p_us, *p_as, *p_df;
431 struct timeval *t = wstime();
432 char *us, *tmp = get_time_string(t);
434 if (tmp && (!p_ts || strcmp(tmp, p_ts)))
435 stat_client_write(tmp, SI_PLAY_TIME);
440 tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
442 if (!p_us || strcmp(p_us, tmp))
443 stat_client_write(tmp, SI_AUDIOD_UPTIME);
447 tmp = audiod_status_string();
448 if (!p_as || strcmp(p_as, tmp))
449 stat_client_write(tmp, SI_AUDIOD_STATUS);
453 tmp = decoder_flags();
454 if (!p_df || strcmp(p_df, tmp))
455 stat_client_write(tmp, SI_DECODER_FLAGS);
460 static void clear_slot(int slot_num)
462 struct slot_info *s = &slot[slot_num];
464 PARA_INFO_LOG("clearing slot %d\n", slot_num);
465 memset(s, 0, sizeof(struct slot_info));
469 static void set_restart_barrier(int format, struct timeval *now)
476 gettimeofday(&tmp, NULL);
477 tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
480 static void close_receiver(int slot_num)
482 struct slot_info *s = &slot[slot_num];
483 struct audio_format_info *a;
485 if (s->format < 0 || !s->receiver_node)
488 PARA_NOTICE_LOG("closing %s recevier in slot %d (eof = %d)\n",
489 audio_formats[s->format] , slot_num, s->receiver_node->eof);
490 if (!s->receiver_node->eof)
491 unregister_task(&s->receiver_node->task);
492 a->receiver->close(s->receiver_node);
493 free(s->receiver_node);
494 s->receiver_node = NULL;
495 set_restart_barrier(s->format, NULL);
497 static void close_writer(int slot_num)
499 struct slot_info *s = &slot[slot_num];
501 PARA_INFO_LOG("slot %d: closing writer node group\n",
507 *s->fc->output_eof = 1; /* FIXME */
511 static void kill_all_decoders(void)
519 static void check_sigchld(void)
523 gettimeofday(&now, NULL);
526 pid = para_reap_child();
529 PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
530 goto reap_next_child;
533 static int get_empty_slot(void)
546 if (s->receiver_node)
553 return -E_NO_MORE_SLOTS;
556 static int decoder_running(int format)
563 if (s->format == format && s->receiver_node)
565 if (s->format == format && s->wng)
571 static void close_stat_pipe(void)
575 if (stat_task->fd < 0)
577 PARA_NOTICE_LOG("%s", "closing status pipe\n");
578 close(stat_task->fd);
579 del_close_on_fork_list(stat_task->fd);
582 for (i = 0; i < NUM_STAT_ITEMS; i++) {
583 free(stat_item_values[i]);
584 stat_item_values[i] = NULL;
589 audiod_status_dump();
591 stat_item_values[SI_STATUS_BAR] = make_message("%s:no connection to para_server\n",
592 status_item_list[SI_STATUS_BAR]);
593 stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
596 static void __noreturn clean_exit(int status, const char *msg)
598 PARA_EMERG_LOG("%s\n", msg);
602 if (stat_task->fd >= 0)
607 /** get the number of filters for the given audio format */
608 int num_filters(int audio_format_num)
610 return afi[audio_format_num].num_filters;
613 void filter_event_handler(struct task *t)
615 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
619 static void open_filters(int slot_num)
621 struct slot_info *s = &slot[slot_num];
622 struct audio_format_info *a = &afi[s->format];
623 int nf = a->num_filters;
629 s->fc = para_calloc(sizeof(struct filter_chain));
630 INIT_LIST_HEAD(&s->fc->filters);
631 s->fc->inbuf = s->receiver_node->buf;
632 s->fc->in_loaded = &s->receiver_node->loaded;
633 s->fc->input_eof = &s->receiver_node->eof;
635 s->fc->task.pre_select = filter_pre_select;
636 s->fc->task.event_handler = filter_event_handler;
637 s->fc->task.private_data = s->fc;
638 s->fc->task.flags = 0;
640 sprintf(s->fc->task.status, "filter chain");
641 for (i = 0; i < nf; i++) {
642 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
643 fn->conf = a->filter_conf[i];
645 fn->filter = a->filters[i];
646 INIT_LIST_HEAD(&fn->callbacks);
647 list_add_tail(&fn->node, &s->fc->filters);
648 fn->filter->open(fn);
649 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
650 audio_formats[s->format], i + 1, nf,
651 fn->filter->name, slot_num);
652 s->fc->outbuf = fn->buf;
653 s->fc->out_loaded = &fn->loaded;
655 register_task(&s->fc->task);
656 // PARA_DEBUG_LOG("output loaded for filter chain %p: %p\n", s->fc,
657 // s->fc->out_loaded);
660 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
662 struct filter_node *fn;
666 struct slot_info *s = &slot[i];
667 if (s->format < 0 || !s->fc)
669 if (slot_num >= 0 && slot_num != i)
671 if (format >= 0 && s->format != format)
673 if (num_filters(i) < filternum)
677 list_for_each_entry(fn, &s->fc->filters, node)
678 if (filternum <= 0 || j++ == filternum)
685 static void wng_event_handler(struct task *t)
687 struct writer_node_group *g = t->private_data;
690 PARA_INFO_LOG("%s\n", PARA_STRERROR(-t->ret));
693 if (slot[i].wng != g)
701 static void start_stream_writer(int slot_num, struct timeval *now)
704 struct slot_info *s = &slot[slot_num];
705 struct audio_format_info *a = &afi[s->format];
707 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
708 open_filters(slot_num);
709 PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
711 s->wng = setup_default_wng();
713 s->wng = wng_new(a->num_writers);
715 s->wng->buf = s->fc->outbuf;
716 s->wng->loaded = s->fc->out_loaded;
717 s->wng->input_eof = &s->fc->eof;
718 s->fc->output_eof = &s->wng->eof;
720 s->wng->buf = s->receiver_node->buf;
721 s->wng->loaded = &s->receiver_node->loaded;
722 s->wng->input_eof = &s->receiver_node->eof;
724 s->wng->task.event_handler = wng_event_handler;
725 for (i = 0; i < a->num_writers; i++) {
726 s->wng->writer_nodes[i].conf = a->writer_conf[i];
727 s->wng->writer_nodes[i].writer = a->writers[i];
728 sprintf(s->wng->writer_nodes[i].task.status, "writer_ node");
730 ret = wng_open(s->wng);
732 current_decoder = slot_num;
733 activate_inactive_grab_clients(slot_num, s->format, &s->fc->filters);
736 void rn_event_handler(struct task *t)
738 // struct receiver_node *rn = t->private_data;
739 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
742 static void open_receiver(int format)
744 struct audio_format_info *a = &afi[format];
747 struct receiver_node *rn;
749 slot_num = get_empty_slot();
751 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
754 gettimeofday(&s->rtime, NULL);
756 s->receiver_node = para_calloc(sizeof(struct receiver_node));
757 rn = s->receiver_node;
758 rn->receiver = a->receiver;
759 rn->conf = a->receiver_conf;
760 ret = a->receiver->open(s->receiver_node);
762 PARA_ERROR_LOG("failed to open receiver (%s)\n",
763 PARA_STRERROR(-ret));
764 free(s->receiver_node);
765 s->receiver_node = NULL;
768 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
769 audio_formats[s->format], a->receiver->name, slot_num);
770 rn->task.private_data = s->receiver_node;
771 PARA_NOTICE_LOG("rn = %p\n", rn->task.private_data);
772 rn->task.pre_select = a->receiver->pre_select;
773 rn->task.post_select = a->receiver->post_select;
774 rn->task.event_handler = rn_event_handler;
776 sprintf(rn->task.status, "receiver node");
777 register_task(&rn->task);
780 static int is_frozen(int format)
783 struct audio_format_info *a = &afi[format];
785 gettimeofday(&now, NULL);
786 return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
789 static void start_current_receiver(void)
795 i = get_audio_format_num(af_status);
798 if ((decoder_running(i) & 1) || is_frozen(i))
803 static void compute_time_diff(const struct timeval *status_time)
805 struct timeval now, tmp, diff;
808 const struct timeval max_deviation = {0, 500 * 1000};
809 const int time_smooth = 5;
811 gettimeofday(&now, NULL);
812 sign = tv_diff(status_time, &now, &diff);
813 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
814 // sign, sa_time_diff_sign);
816 sa_time_diff_sign = sign;
822 int s = tv_diff(&diff, &sa_time_diff, &tmp);
823 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
824 PARA_WARNING_LOG("time diff jump: %lims\n",
828 sa_time_diff_sign = tv_convex_combination(
829 sa_time_diff_sign * time_smooth, &sa_time_diff,
830 count > 10? sign : sign * time_smooth, &diff,
833 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
836 sa_time_diff_sign ? "+" : "-",
841 static void check_stat_line(char *line)
845 long unsigned sec, usec;
848 // PARA_INFO_LOG("line: %s\n", line);
851 itemnum = stat_line_valid(line);
853 PARA_WARNING_LOG("invalid status line: %s\n", line);
856 tmp = make_message("%s\n", line);
857 stat_client_write(tmp, itemnum);
859 free(stat_item_values[itemnum]);
860 stat_item_values[itemnum] = para_strdup(line);
861 ilen = strlen(status_item_list[itemnum]);
864 playing = strstr(line, "playing")? 1 : 0;
868 af_status = para_strdup(line + ilen + 1);
871 offset_seconds = atoi(line + ilen + 1);
874 length_seconds = atoi(line + ilen + 1);
876 case SI_STREAM_START:
877 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
878 server_stream_start.tv_sec = sec;
879 server_stream_start.tv_usec = usec;
882 case SI_CURRENT_TIME:
883 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
884 struct timeval tv = {sec, usec};
885 compute_time_diff(&tv);
891 static void handle_signal(int sig)
895 return check_sigchld();
899 PARA_EMERG_LOG("terminating on signal %d\n", sig);
900 clean_exit(EXIT_FAILURE, "caught deadly signal");
905 static void check_timeouts(void)
908 int slot_num, timeout = conf.stream_timeout_arg;
910 gettimeofday(&now, NULL);
911 FOR_EACH_SLOT(slot_num) {
912 struct slot_info *s = &slot[slot_num];
915 /* check read time */
916 if (s->receiver_node &&
917 now.tv_sec > s->rtime.tv_sec + timeout) {
918 PARA_INFO_LOG("%s stream (slot %d) not ready\n",
919 audio_formats[s->format], slot_num);
920 s->receiver_node->eof = 1;
925 static void close_decoder_if_idle(int slot_num)
927 struct slot_info *s = &slot[slot_num];
935 PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
937 close_filters(s->fc);
939 close_receiver(slot_num);
940 clear_slot(slot_num);
943 static void audiod_pre_select(__a_unused struct sched *s, __a_unused struct task *t)
947 if (audiod_status != AUDIOD_ON)
950 start_current_receiver();
953 struct receiver_node *rn;
955 close_decoder_if_idle(i);
956 if (slot[i].format < 0)
958 rn = slot[i].receiver_node;
959 if (rn && rn->loaded && !slot[i].wng) {
960 PARA_INFO_LOG("no writer in slot %d\n", i);
961 start_stream_writer(i, &s->now);
966 static void audiod_post_select(struct sched *s, __a_unused struct task *t)
971 struct receiver_node *rn = slot[i].receiver_node;
973 if (rn && rn->loaded)
974 slot[i].rtime = s->now;
978 static void init_audiod_task(struct audiod_task *at)
980 at->task.pre_select = audiod_pre_select;
981 at->task.post_select = audiod_post_select;
982 at->task.private_data = at;
984 sprintf(at->task.status, "audiod task");
987 static int parse_stream_command(const char *txt, char **cmd)
989 char *p = strchr(txt, ':');
993 return -E_MISSING_COLON;
995 FOR_EACH_AUDIO_FORMAT(i) {
996 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1001 return -E_UNSUPPORTED_AUDIO_FORMAT;
1004 static int add_filter(int format, char *cmdline)
1006 struct audio_format_info *a = &afi[format];
1007 int filter_num, nf = a->num_filters;
1009 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1012 a->filters[nf] = &filters[filter_num];
1014 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1015 a->filters[nf]->name);
1019 static int setup_default_filters(void)
1023 FOR_EACH_AUDIO_FORMAT(i) {
1024 struct audio_format_info *a = &afi[i];
1029 /* add "dec" to audio format name */
1030 tmp = make_message("%sdec", audio_formats[i]);
1031 for (j = 0; filters[j].name; j++)
1032 if (!strcmp(tmp, filters[j].name))
1035 ret = -E_UNSUPPORTED_FILTER;
1036 if (!filters[j].name)
1038 tmp = para_strdup(filters[j].name);
1039 ret = add_filter(i, tmp);
1043 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1045 ret = add_filter(i, "wav");
1048 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1054 static int init_stream_io(void)
1056 int i, ret, receiver_num, nf, nw;
1058 struct audio_format_info *a;
1060 init_supported_writers();
1061 nw = PARA_MAX(1, conf.writer_given);
1062 PARA_INFO_LOG("allocating space for %d writers\n", nw);
1063 FOR_EACH_AUDIO_FORMAT(i) {
1065 a->writer_conf = para_malloc(nw * sizeof(void *));
1066 a->writers = para_malloc(nw * sizeof(struct writer *));
1069 for (i = 0; i < conf.writer_given; i++) {
1072 ret = parse_stream_command(conf.writer_arg[i], &cmd);
1076 nw = a->num_writers;
1077 wconf = check_writer_arg(cmd, &writer_num);
1082 a->writers[nw] = &writers[ret];
1083 a->writer_conf[nw] = wconf;
1084 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
1085 nw, writer_names[writer_num]);
1088 for (i = 0; receivers[i].name; i++) {
1089 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1090 receivers[i].init(&receivers[i]);
1092 for (i = 0; i < conf.receiver_given; i++) {
1093 char *arg = conf.receiver_arg[i];
1094 char *recv = strchr(arg, ':');
1095 ret = -E_MISSING_COLON;
1100 ret = get_audio_format_num(arg);
1103 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1104 if (!afi[ret].receiver_conf) {
1105 ret = -E_RECV_SYNTAX;
1108 afi[ret].receiver = &receivers[receiver_num];
1110 /* use the first available receiver with no arguments
1111 * for those audio formats for which no receiver
1114 cmd = para_strdup(receivers[0].name);
1115 FOR_EACH_AUDIO_FORMAT(i) {
1117 if (a->receiver_conf)
1119 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1120 if (!a->receiver_conf)
1121 return -E_RECV_SYNTAX;
1122 a->receiver = &receivers[receiver_num];
1126 filter_init(filters);
1127 nf = PARA_MAX(2, conf.filter_given) + 1;
1128 PARA_INFO_LOG("allocating space for %d filters\n", nf);
1129 FOR_EACH_AUDIO_FORMAT(i) {
1130 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
1131 afi[i].filters = para_malloc(nf * sizeof(struct filter *));
1133 if (!conf.no_default_filters_given)
1134 return setup_default_filters();
1135 for (i = 0; i < conf.filter_given; i++) {
1136 char *arg = conf.filter_arg[i];
1137 char *filter_name = strchr(arg, ':');
1138 ret = -E_MISSING_COLON;
1141 *filter_name = '\0';
1143 ret = get_audio_format_num(arg);
1146 ret = add_filter(ret, filter_name);
1155 static int dump_commands(int fd)
1157 char *buf = para_strdup(""), *tmp = NULL;
1161 FOR_EACH_COMMAND(i) {
1162 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1163 cmds[i].description);
1167 ret = client_write(fd, buf);
1173 * command handlers don't close their fd on errors (ret < 0) so that
1174 * its caller can send an error message. Otherwise (ret >= 0) it's up
1175 * to each individual command to close the fd if necessary.
1178 static int com_help(int fd, int argc, char **argv)
1182 const char *dflt = "No such command. Available commands:\n";
1185 ret = dump_commands(fd);
1188 FOR_EACH_COMMAND(i) {
1189 if (strcmp(cmds[i].name, argv[1]))
1192 "NAME\n\t%s -- %s\n"
1193 "SYNOPSIS\n\tpara_audioc %s\n"
1194 "DESCRIPTION\n%s\n",
1196 cmds[i].description,
1200 ret = client_write(fd, buf);
1204 ret = client_write(fd, dflt);
1206 ret = dump_commands(fd);
1213 static int com_stat(int fd, __a_unused int argc, __a_unused char **argv)
1217 long unsigned mask = ~0LU;
1221 for (i = 1; i < argc; i++) {
1222 ret = stat_item_valid(argv[i]);
1228 PARA_INFO_LOG("mask: 0x%lx\n", mask);
1229 if (mask & (1 << SI_PLAY_TIME)) {
1230 struct timeval *t = wstime();
1231 char *ts = get_time_string(t);
1233 ret = client_write(fd, ts);
1239 if (mask & (1 << SI_AUDIOD_UPTIME)) {
1240 char *tmp, *us = uptime_str();
1241 tmp = make_message("%s:%s\n",
1242 status_item_list[SI_AUDIOD_UPTIME], us);
1244 ret = client_write(fd, tmp);
1249 if (mask & (1 << SI_AUDIOD_STATUS)) {
1250 char *s = audiod_status_string();
1251 ret = client_write(fd, s);
1256 if (mask & (1 << SI_DECODER_FLAGS)) {
1257 char *df =decoder_flags();
1258 ret = client_write(fd, df);
1264 for (i = 0; i < NUM_STAT_ITEMS; i++) {
1266 if (!((1 << i) & mask))
1268 v = stat_item_values[i];
1269 tmp = make_message("%s%s%s", buf? buf: "",
1270 v? v : "", v? "\n" : "");
1274 ret = client_write(fd, buf);
1277 ret = stat_client_add(fd, mask);
1282 static int com_grab(int fd, char *cmdline)
1284 struct grab_client *gc;
1285 struct filter_node *fn;
1289 gc = grab_client_new(fd, cmdline, &err);
1292 fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1294 activate_grab_client(gc, fn);
1297 if (err != -E_GC_HELP_GIVEN && err != -E_GC_VERSION_GIVEN)
1299 if (err == -E_GC_HELP_GIVEN) {
1300 msg = make_message("%s\n\n", grab_client_args_info_usage);
1301 for (i = 0; grab_client_args_info_help[i]; i++) {
1302 char *tmp = make_message("%s%s\n", msg,
1303 grab_client_args_info_help[i]);
1308 msg = make_message("%s %s\n",
1309 GRAB_CLIENT_CMDLINE_PARSER_PACKAGE,
1310 GRAB_CLIENT_CMDLINE_PARSER_VERSION);
1311 err = client_write(fd, msg);
1319 static int __noreturn com_term(int fd, __a_unused int argc, __a_unused char **argv)
1322 clean_exit(EXIT_SUCCESS, "terminating on user request");
1325 static int com_on(int fd, __a_unused int argc, __a_unused char **argv)
1327 audiod_status = AUDIOD_ON;
1332 static int com_off(int fd, __a_unused int argc, __a_unused char **argv)
1334 audiod_status = AUDIOD_OFF;
1339 static int com_sb(int fd, __a_unused int argc, __a_unused char **argv)
1341 audiod_status = AUDIOD_STANDBY;
1346 static int com_cycle(int fd, int argc, char **argv)
1348 switch (audiod_status) {
1350 return com_sb(fd, argc, argv);
1353 return com_on(fd, argc, argv);
1355 case AUDIOD_STANDBY:
1356 return com_off(fd, argc, argv);
1363 static int check_perms(uid_t uid)
1367 if (!conf.user_allow_given)
1369 for (i = 0; i < conf.user_allow_given; i++)
1370 if (uid == conf.user_allow_arg[i])
1372 return -E_UCRED_PERM;
1375 static int handle_connect(void)
1377 int i, argc, ret, clifd = -1;
1378 char *cmd = NULL, *p, *buf = para_calloc(MAXLINE), **argv = NULL;
1379 struct sockaddr_un unix_addr;
1381 ret = para_accept(cmd_task->fd, &unix_addr, sizeof(struct sockaddr_un));
1385 ret = recv_cred_buffer(clifd, buf, MAXLINE - 1);
1388 PARA_INFO_LOG("connection from user %i, buf: %s\n", ret, buf);
1389 ret = check_perms(ret);
1392 ret = -E_INVALID_AUDIOD_CMD;
1393 cmd = para_strdup(buf);
1394 p = strchr(cmd, '\n');
1401 for (i = 0; cmds[i].name; i++) {
1403 if (strcmp(cmds[i].name, cmd))
1405 if (cmds[i].handler) {
1406 argc = split_args(buf, &argv, "\n");
1407 PARA_INFO_LOG("argv[0]: %s, argc= %d\n", argv[0], argc);
1408 ret = cmds[i].handler(clifd, argc, argv);
1411 for (j = 0; p[j]; j++)
1414 PARA_INFO_LOG("cmd: %s, options: %s\n", cmd, p);
1415 ret = cmds[i].line_handler(clifd, p);
1418 ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1423 if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1424 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1425 client_write(clifd, tmp);
1432 static void audiod_get_socket(void)
1434 struct sockaddr_un unix_addr;
1436 if (conf.socket_given)
1437 socket_name = para_strdup(conf.socket_arg);
1439 char *hn = para_hostname();
1440 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1444 PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1445 if (conf.force_given)
1446 unlink(socket_name);
1447 cmd_task->fd = create_pf_socket(socket_name, &unix_addr,
1448 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1449 if (cmd_task->fd < 0) {
1450 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1451 exit(EXIT_FAILURE); /* do not unlink socket */
1453 if (listen(cmd_task->fd , 5) < 0) {
1454 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1455 exit(EXIT_FAILURE); /* do not unlink socket */
1457 add_close_on_fork_list(cmd_task->fd);
1460 static int open_stat_pipe(void)
1462 int ret, fd[3] = {-1, 1, 0};
1464 ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1467 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1468 add_close_on_fork_list(ret);
1470 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1474 void signal_event_handler(struct task *t)
1476 struct signal_task *st = t->private_data;
1477 handle_signal(st->signum);
1480 void signal_pre_select(struct sched *s, struct task *t)
1482 struct signal_task *st = t->private_data;
1484 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1487 void signal_post_select(struct sched *s, struct task *t)
1489 struct signal_task *st = t->private_data;
1491 if (!FD_ISSET(st->fd, &s->rfds))
1493 t->ret = -E_SIGNAL_CAUGHT;
1494 st->signum = para_next_signal();
1497 void signal_setup_default(struct signal_task *st)
1499 st->task.pre_select = signal_pre_select;
1500 st->task.post_select = signal_post_select;
1501 st->task.private_data = st;
1503 sprintf(st->task.status, "signal task");
1506 static void command_pre_select(struct sched *s, struct task *t)
1508 struct command_task *ct = t->private_data;
1509 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
1513 static void command_post_select(struct sched *s, struct task *t)
1516 struct command_task *ct = t->private_data;
1518 if (audiod_status != AUDIOD_OFF)
1519 audiod_status_dump();
1520 t->ret = 1; /* always successful */
1521 if (!FD_ISSET(ct->fd, &s->rfds))
1523 ret = handle_connect();
1525 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1528 void init_command_task(struct command_task *ct)
1530 ct->task.pre_select = command_pre_select;
1531 ct->task.post_select = command_post_select;
1532 ct->task.private_data = ct;
1534 sprintf(ct->task.status, "command task");
1537 static void status_pre_select(struct sched *s, struct task *t)
1539 struct status_task *st = t->private_data;
1541 if (st->fd >= 0 && audiod_status == AUDIOD_OFF)
1543 if (st->fd < 0 && audiod_status != AUDIOD_OFF) {
1544 st->fd = open_stat_pipe();
1548 if (st->fd >= 0 && audiod_status != AUDIOD_OFF)
1549 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1552 static void status_post_select(struct sched *s, struct task *t)
1554 struct status_task *st = t->private_data;
1558 if (st->fd < 0 || !FD_ISSET(st->fd, &s->rfds))
1560 ret = read(st->fd, st->buf + st->loaded,
1561 STRINGSIZE - 1 - st->loaded);
1564 /* avoid busy loop if server is down */
1565 while (sleep(1) > 0)
1568 st->buf[ret + st->loaded] = '\0';
1569 st->loaded = for_each_line(st->buf, ret + st->loaded,
1574 static void init_status_task(struct status_task *st)
1576 st->task.pre_select = status_pre_select;
1577 st->task.post_select = status_post_select;
1578 st->task.private_data = st;
1583 sprintf(st->task.status, "status task");
1586 static void set_initial_status(void)
1588 audiod_status = AUDIOD_ON;
1589 if (!conf.mode_given)
1591 if (!strcmp(conf.mode_arg, "sb")) {
1592 audiod_status = AUDIOD_STANDBY;
1595 if (!strcmp(conf.mode_arg, "off")) {
1596 audiod_status = AUDIOD_OFF;
1599 if (strcmp(conf.mode_arg, "on"))
1600 PARA_WARNING_LOG("%s", "invalid mode\n");
1603 int main(int argc, char *argv[])
1612 hostname = para_hostname();
1613 cmdline_parser(argc, argv, &conf);
1614 para_drop_privileges(conf.user_arg, conf.group_arg);
1615 cf = configfile_exists();
1617 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1618 PARA_EMERG_LOG("%s", "parse error in config file\n");
1622 if (conf.logfile_given)
1623 logfile = open_log(conf.logfile_arg);
1624 log_welcome("para_audiod", conf.loglevel_arg);
1625 i = init_stream_io();
1627 PARA_EMERG_LOG("init stream io error: %s\n", PARA_STRERROR(-i));
1630 server_uptime(UPTIME_SET);
1631 set_initial_status();
1635 setup_signal_handling();
1636 if (conf.daemon_given)
1638 audiod_get_socket(); /* doesn't return on errors */
1640 signal_setup_default(sig_task);
1641 sig_task->task.event_handler = signal_event_handler;
1643 init_status_task(stat_task);
1644 init_command_task(cmd_task);
1645 init_audiod_task(at);
1647 register_task(&sig_task->task);
1648 register_task(&cmd_task->task);
1649 register_task(&stat_task->task);
1650 register_task(&at->task);
1651 s.default_timeout.tv_sec = 0;
1652 s.default_timeout.tv_usec = 99 * 1000;
1655 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
1656 return EXIT_FAILURE;