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 /** define the array of error lists needed by para_audiod */
42 /** define the array containing all supported audio formats */
43 DEFINE_AUDIO_FORMAT_ARRAY;
46 * the possible modes of operation
48 * - off: disconnect from para_server
49 * - on: receive status information from para_server and play the audio stream
50 * - sb: only receive status information but not the audio stream
52 enum {AUDIOD_OFF, AUDIOD_ON, AUDIOD_STANDBY};
54 /** defines how to handle one supported audio format */
55 struct audio_format_info {
56 /** pointer to the receiver for this audio format */
57 struct receiver *receiver;
58 /** the receiver configuration */
60 /** the number of filters that should be activated for this audio format */
61 unsigned int num_filters;
62 /** pointer to the array of filters to be activated */
63 struct filter **filters;
64 /** pointer to the array of filter configurations */
66 /** output of the last filter is written to stdin of this command */
68 /** do not start receiver/filters/writer before this time */
69 struct timeval restart_barrier;
73 * describes one instance of a receiver-filter-writer chain
75 * \sa receier_node, receiver, filter, filter_node, filter_chain_info
78 /** number of the audio format in this slot */
80 /** the file descriptor of the writer */
82 /** the process id of the writer */
84 /** time of the last successful read from the receiver */
86 /** time the last write to the write fd happend */
88 /** writer start time */
89 struct timeval wstime;
90 /** did we include \a write_fd in the fdset */
92 /** set to one if we have sent the TERM signal to \a wpid */
94 /** the receiver info associated with this slot */
95 struct receiver_node *receiver_node;
96 /** the active filter chain */
97 struct filter_chain *fc;
99 static struct slot_info slot[MAX_STREAM_SLOTS];
101 extern const char *status_item_list[NUM_STAT_ITEMS];
103 static struct gengetopt_args_info conf;
104 static struct timeval server_stream_start, sa_time_diff;
105 static int playing, current_decoder = -1,
106 audiod_status = AUDIOD_ON, offset_seconds, length_seconds,
107 sa_time_diff_sign = 1;
108 static char *af_status, /* the audio format announced in server status */
109 *socket_name, *hostname;
110 static char *stat_item_values[NUM_STAT_ITEMS];
111 static FILE *logfile;
112 static const struct timeval restart_delay = {0, 300 * 1000};
114 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
116 static struct signal_task signal_task_struct, *sig_task = &signal_task_struct;
118 struct command_task {
122 static struct command_task command_task_struct, *cmd_task = &command_task_struct;
127 char buf[STRINGSIZE];
130 static struct status_task status_task_struct, *stat_task = &status_task_struct;
135 static struct audiod_task audiod_task_struct, *at = &audiod_task_struct;
144 /** defines one command of para_audiod */
145 struct audiod_command {
146 /** the name of the command */
148 /** pointer to the function that handles the command */
149 int (*handler)(int, int, char**);
150 int (*line_handler)(int, char*);
151 /** one-line description of the command */
152 const char *description;
153 /** summary of the command line options */
154 const char *synopsis;
155 /** the long help text */
158 static int com_grab(int, char *);
159 static int com_cycle(int, int, char **);
160 static int com_help(int, int, char **);
161 static int com_off(int, int, char **);
162 static int com_on(int, int, char **);
163 static int com_sb(int, int, char **);
164 static int com_stat(int, int, char **);
165 static int com_term(int, int, char **);
166 static struct audiod_command cmds[] = {
169 .handler = com_cycle,
170 .description = "switch to next mode",
174 "on -> standby -> off -> on\n"
179 .line_handler = com_grab,
180 .description = "grab the audio stream",
181 .synopsis = "-- grab [grab_options]",
184 "grab ('splice') the audio stream at any position in the filter \n"
185 "chain and send that data back to the client. Try\n"
186 "\t para_audioc -- grab -h\n"
187 "for the list of available options.\n"
193 .description = "display command list or help for given command",
194 .synopsis = "help [command]",
197 "When I was younger, so much younger than today, I never needed\n"
198 "anybody's help in any way. But now these days are gone, I'm not so\n"
199 "self assured. Now I find I've changed my mind and opened up the doors.\n"
201 " -- Beatles: Help\n"
207 .description = "deactivate para_audiod",
211 "Close connection to para_server and stop all decoders.\n"
217 .description = "activate para_audiod",
221 "Establish connection to para_server, retrieve para_server's current\n"
222 "status. If playing, start corresponding decoder. Otherwise stop\n"
229 .description = "enter standby mode",
233 "Stop all decoders but leave connection to para_server open.\n"
239 .description = "print status information",
240 .synopsis = "stat [item1 ...]",
243 "Dump given status items (all if none given) to stdout.\n"
249 .description = "terminate audiod",
253 "Stop all decoders, shut down connection to para_server and exit.\n"
261 /** iterate over all slots */
262 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
263 /** iterate over all supported audio formats */
264 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
265 /** iterate over the array of all audiod commands */
266 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
269 * get the audio format number
270 * \param name the name of the audio format
272 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
273 * \a name is not a supported audio format.
275 int get_audio_format_num(char *name)
278 FOR_EACH_AUDIO_FORMAT(i)
279 if (!strcmp(name, audio_formats[i]))
281 return -E_UNSUPPORTED_AUDIO_FORMAT;
285 * log function. first argument is loglevel.
287 void para_log(int ll, const char* fmt,...)
293 char str[MAXLINE] = "";
295 if (ll < conf.loglevel_arg)
297 outfd = logfile? logfile : stderr;
300 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
301 fprintf(outfd, "%s %s ", str, hostname);
302 if (conf.loglevel_arg <= INFO)
303 fprintf(outfd, "%i ", ll);
305 vfprintf(outfd, fmt, argp);
309 static int client_write(int fd, const char *buf)
311 size_t len = strlen(buf);
312 return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
315 static char *get_time_string(struct timeval *newest_stime)
317 struct timeval now, diff, adj_stream_start, tmp;
318 int total = 0, use_server_time = 1;
323 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
325 if (audiod_status == AUDIOD_OFF)
327 if (sa_time_diff_sign > 0)
328 tv_diff(&server_stream_start, &sa_time_diff,
331 tv_add(&server_stream_start, &sa_time_diff,
333 tmp = adj_stream_start;
334 if (newest_stime && audiod_status == AUDIOD_ON) {
335 tv_diff(newest_stime, &adj_stream_start, &diff);
336 if (tv2ms(&diff) < 5000) {
341 gettimeofday(&now, NULL);
342 tv_diff(&now, &tmp, &diff);
343 total = diff.tv_sec + offset_seconds;
344 if (total > length_seconds)
345 total = length_seconds;
350 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
351 status_item_list[SI_PLAY_TIME],
352 use_server_time? "~" : "",
355 (length_seconds - total) / 60,
356 (length_seconds - total) % 60,
357 length_seconds? (total * 100 + length_seconds / 2) /
364 __malloc static char *audiod_status_string(void)
366 const char *status = (audiod_status == AUDIOD_ON)?
367 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
368 return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
371 static struct timeval *wstime(void)
374 struct timeval *max = NULL;
376 struct slot_info *s = &slot[i];
379 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
385 __malloc static char *decoder_flags(void)
388 char decoder_flags[MAX_STREAM_SLOTS + 1];
391 struct slot_info *s = &slot[i];
393 if (s->receiver_node)
397 decoder_flags[i] = flag;
399 decoder_flags[MAX_STREAM_SLOTS] = '\0';
400 return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
404 static char *configfile_exists(void)
406 static char *config_file;
409 char *home = para_homedir();
410 config_file = make_message("%s/.paraslash/audiod.conf", home);
413 return file_exists(config_file)? config_file : NULL;
416 static void setup_signal_handling(void)
418 sig_task->fd = para_signal_init();
419 PARA_INFO_LOG("signal pipe: fd %d\n", sig_task->fd);
420 para_install_sighandler(SIGINT);
421 para_install_sighandler(SIGTERM);
422 para_install_sighandler(SIGCHLD);
423 para_install_sighandler(SIGHUP);
424 signal(SIGPIPE, SIG_IGN);
427 static void audiod_status_dump(void)
429 static char *p_ts, *p_us, *p_as, *p_df;
430 struct timeval *t = wstime();
431 char *us, *tmp = get_time_string(t);
433 if (tmp && (!p_ts || strcmp(tmp, p_ts)))
434 stat_client_write(tmp, SI_PLAY_TIME);
439 tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
441 if (!p_us || strcmp(p_us, tmp))
442 stat_client_write(tmp, SI_AUDIOD_UPTIME);
446 tmp = audiod_status_string();
447 if (!p_as || strcmp(p_as, tmp))
448 stat_client_write(tmp, SI_AUDIOD_STATUS);
452 tmp = decoder_flags();
453 if (!p_df || strcmp(p_df, tmp))
454 stat_client_write(tmp, SI_DECODER_FLAGS);
459 static void clear_slot(int slot_num)
461 struct slot_info *s = &slot[slot_num];
463 PARA_INFO_LOG("clearing slot %d\n", slot_num);
464 memset(s, 0, sizeof(struct slot_info));
468 static void kill_stream_writer(int slot_num)
470 struct slot_info *s = &slot[slot_num];
472 if (s->format < 0 || s->wkilled || s->wpid <= 0)
474 PARA_DEBUG_LOG("kill -TERM %d (%s stream writer in slot %d)\n",
475 s->wpid, audio_formats[s->format], slot_num);
476 kill(s->wpid, SIGTERM);
480 static void set_restart_barrier(int format, struct timeval *now)
487 gettimeofday(&tmp, NULL);
488 tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
491 static void close_receiver(int slot_num)
493 struct slot_info *s = &slot[slot_num];
494 struct audio_format_info *a;
496 if (s->format < 0 || !s->receiver_node)
499 PARA_NOTICE_LOG("closing %s recevier in slot %d (eof = %d)\n",
500 audio_formats[s->format] , slot_num, s->receiver_node->eof);
501 if (!s->receiver_node->eof)
502 unregister_task(&s->receiver_node->task);
503 a->receiver->close(s->receiver_node);
504 free(s->receiver_node);
505 s->receiver_node = NULL;
506 set_restart_barrier(s->format, NULL);
509 static void kill_all_decoders(void)
514 if (slot[i].format >= 0) {
515 PARA_INFO_LOG("stopping decoder in slot %d\n", i);
516 kill_stream_writer(i);
520 static void check_sigchld(void)
525 gettimeofday(&now, NULL);
528 pid = para_reap_child();
532 struct slot_info *s = &slot[i];
536 if (pid == s->wpid) {
538 lifetime = now.tv_sec - s->wstime.tv_sec;
539 PARA_INFO_LOG("%s stream writer in slot %d died "
541 audio_formats[s->format], i, lifetime);
542 set_restart_barrier(s->format, &now);
543 goto reap_next_child;
546 PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
547 goto reap_next_child;
550 static int get_empty_slot(void)
561 if (s->write_fd > 0 || s->wpid > 0)
563 if (s->receiver_node)
570 return -E_NO_MORE_SLOTS;
573 static int decoder_running(int format)
580 if (s->format == format && s->receiver_node)
582 if (s->format == format && s->wpid > 0)
588 static void close_stat_pipe(void)
592 if (stat_task->fd < 0)
594 PARA_NOTICE_LOG("%s", "closing status pipe\n");
595 close(stat_task->fd);
596 del_close_on_fork_list(stat_task->fd);
599 for (i = 0; i < NUM_STAT_ITEMS; i++) {
600 free(stat_item_values[i]);
601 stat_item_values[i] = NULL;
606 audiod_status_dump();
608 stat_item_values[SI_STATUS_BAR] = make_message("%s:no connection to para_server\n",
609 status_item_list[SI_STATUS_BAR]);
610 stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
613 static void __noreturn clean_exit(int status, const char *msg)
615 PARA_EMERG_LOG("%s\n", msg);
619 if (stat_task->fd >= 0)
624 __malloc static char *glob_cmd(char *cmd)
626 char *ret, *replacement;
627 struct timeval tmp, delay, rss; /* real stream start */
629 delay.tv_sec = conf.stream_delay_arg / 1000;
630 delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
631 // PARA_INFO_LOG("delay: %lu:%lu\n", delay.tv_sec, delay.tv_usec);
632 if (sa_time_diff_sign < 0)
633 tv_add(&server_stream_start, &sa_time_diff, &rss);
635 tv_diff(&server_stream_start, &sa_time_diff, &rss);
636 tv_add(&rss, &delay, &tmp);
637 replacement = make_message("%lu:%lu",
638 (long unsigned)tmp.tv_sec,
639 (long unsigned)tmp.tv_usec);
640 ret = s_a_r(cmd, "STREAM_START", replacement);
644 PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
649 /** get the number of filters for the given audio format */
650 int num_filters(int audio_format_num)
652 return afi[audio_format_num].num_filters;
655 void filter_event_handler(struct task *t)
657 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
661 static void open_filters(int slot_num)
663 struct slot_info *s = &slot[slot_num];
664 struct audio_format_info *a = &afi[s->format];
665 int nf = a->num_filters;
667 static int output_eof; /* FIXME */
669 s->fc = para_calloc(sizeof(struct filter_chain));
670 INIT_LIST_HEAD(&s->fc->filters);
673 s->fc->inbuf = s->receiver_node->buf;
674 s->fc->in_loaded = &s->receiver_node->loaded;
675 s->fc->input_eof = &s->receiver_node->eof;
676 s->fc->output_eof = &output_eof;
679 s->fc->task.pre_select = filter_pre_select;
680 s->fc->task.event_handler = filter_event_handler;
681 s->fc->task.private_data = s->fc;
682 s->fc->task.flags = 0;
684 sprintf(s->fc->task.status, "filter chain");
685 for (i = 0; i < nf; i++) {
686 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
687 fn->conf = a->filter_conf[i];
689 fn->filter = a->filters[i];
690 INIT_LIST_HEAD(&fn->callbacks);
691 list_add_tail(&fn->node, &s->fc->filters);
692 fn->filter->open(fn);
693 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
694 audio_formats[s->format], i + 1, nf,
695 fn->filter->name, slot_num);
696 s->fc->outbuf = fn->buf;
697 s->fc->out_loaded = &fn->loaded;
699 register_task(&s->fc->task);
700 // PARA_DEBUG_LOG("output loaded for filter chain %p: %p\n", s->fc,
701 // s->fc->out_loaded);
704 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
706 struct filter_node *fn;
710 struct slot_info *s = &slot[i];
711 if (s->format < 0 || !s->fc)
713 if (slot_num >= 0 && slot_num != i)
715 if (format >= 0 && s->format != format)
717 if (num_filters(i) < filternum)
721 list_for_each_entry(fn, &s->fc->filters, node)
722 if (filternum <= 0 || j++ == filternum)
729 static void start_stream_writer(int slot_num)
731 int ret, fds[3] = {1, -1, -1};
732 struct slot_info *s = &slot[slot_num];
733 struct audio_format_info *a = &afi[s->format];
737 glob = glob_cmd(a->write_cmd);
739 glob = para_strdup("para_write -w alsa");
740 PARA_INFO_LOG("starting stream writer: %s\n", glob);
741 open_filters(slot_num);
742 ret = para_exec_cmdline_pid(&s->wpid, glob, fds);
745 PARA_ERROR_LOG("exec failed (%d)\n", ret);
748 s->write_fd = fds[0];
749 add_close_on_fork_list(s->write_fd);
750 /* we write to this fd in do_select, so we need non-blocking */
751 mark_fd_nonblock(s->write_fd);
752 gettimeofday(&s->wstime, NULL);
753 current_decoder = slot_num;
754 activate_inactive_grab_clients(slot_num, s->format, &s->fc->filters);
757 void rn_event_handler(struct task *t)
759 // struct receiver_node *rn = t->private_data;
760 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
763 static void open_receiver(int format)
765 struct audio_format_info *a = &afi[format];
768 struct receiver_node *rn;
770 slot_num = get_empty_slot();
772 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
775 gettimeofday(&s->rtime, NULL);
777 s->receiver_node = para_calloc(sizeof(struct receiver_node));
778 rn = s->receiver_node;
779 rn->receiver = a->receiver;
780 rn->conf = a->receiver_conf;
781 ret = a->receiver->open(s->receiver_node);
783 PARA_ERROR_LOG("failed to open receiver (%s)\n",
784 PARA_STRERROR(-ret));
785 free(s->receiver_node);
786 s->receiver_node = NULL;
789 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
790 audio_formats[s->format], a->receiver->name, slot_num);
791 rn->task.private_data = s->receiver_node;
792 PARA_NOTICE_LOG("rn = %p\n", rn->task.private_data);
793 rn->task.pre_select = a->receiver->pre_select;
794 rn->task.post_select = a->receiver->post_select;
795 rn->task.event_handler = rn_event_handler;
797 sprintf(rn->task.status, "receiver node");
798 register_task(&rn->task);
801 static int is_frozen(int format)
804 struct audio_format_info *a = &afi[format];
806 gettimeofday(&now, NULL);
807 return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
810 static void start_current_receiver(void)
816 i = get_audio_format_num(af_status);
819 if ((decoder_running(i) & 1) || is_frozen(i))
824 static void compute_time_diff(const struct timeval *status_time)
826 struct timeval now, tmp, diff;
829 const struct timeval max_deviation = {0, 500 * 1000};
830 const int time_smooth = 5;
832 gettimeofday(&now, NULL);
833 sign = tv_diff(status_time, &now, &diff);
834 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
835 // sign, sa_time_diff_sign);
837 sa_time_diff_sign = sign;
843 int s = tv_diff(&diff, &sa_time_diff, &tmp);
844 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
845 PARA_WARNING_LOG("time diff jump: %lims\n",
849 sa_time_diff_sign = tv_convex_combination(
850 sa_time_diff_sign * time_smooth, &sa_time_diff,
851 count > 10? sign : sign * time_smooth, &diff,
854 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
857 sa_time_diff_sign ? "+" : "-",
862 static void check_stat_line(char *line)
866 long unsigned sec, usec;
869 // PARA_INFO_LOG("line: %s\n", line);
872 itemnum = stat_line_valid(line);
874 PARA_WARNING_LOG("invalid status line: %s\n", line);
877 tmp = make_message("%s\n", line);
878 stat_client_write(tmp, itemnum);
880 free(stat_item_values[itemnum]);
881 stat_item_values[itemnum] = para_strdup(line);
882 ilen = strlen(status_item_list[itemnum]);
885 playing = strstr(line, "playing")? 1 : 0;
889 af_status = para_strdup(line + ilen + 1);
892 offset_seconds = atoi(line + ilen + 1);
895 length_seconds = atoi(line + ilen + 1);
897 case SI_STREAM_START:
898 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
899 server_stream_start.tv_sec = sec;
900 server_stream_start.tv_usec = usec;
903 case SI_CURRENT_TIME:
904 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
905 struct timeval tv = {sec, usec};
906 compute_time_diff(&tv);
912 static void handle_signal(int sig)
916 return check_sigchld();
920 PARA_EMERG_LOG("terminating on signal %d\n", sig);
921 clean_exit(EXIT_FAILURE, "caught deadly signal");
926 static void check_timeouts(void)
929 int slot_num, timeout = conf.stream_timeout_arg;
931 gettimeofday(&now, NULL);
932 FOR_EACH_SLOT(slot_num) {
933 struct slot_info *s = &slot[slot_num];
936 /* check read time */
937 if (s->receiver_node &&
938 now.tv_sec > s->rtime.tv_sec + timeout) {
939 PARA_INFO_LOG("%s input buffer (slot %d) not ready\n",
940 audio_formats[s->format], slot_num);
941 s->receiver_node->eof = 1;
943 /* check write time */
944 if (s->wpid > 0 && !s->wkilled &&
945 now.tv_sec > s->wtime.tv_sec + timeout) {
946 PARA_INFO_LOG("%s output buffer (slot %d) not ready\n",
947 audio_formats[s->format], slot_num);
948 kill_stream_writer(slot_num);
953 static size_t get_loaded_bytes(int slot_num)
956 struct slot_info *s = &slot[slot_num];
957 struct receiver_node *rn = s->receiver_node;
962 if (afi[s->format].num_filters) {
964 loaded = *s->fc->out_loaded;
973 static void close_writer(int slot_num)
975 struct slot_info *s = &slot[slot_num];
976 if (s->write_fd > 0) {
977 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
980 del_close_on_fork_list(s->write_fd);
984 *s->fc->output_eof = 1; /* FIXME */
988 static void close_decoder_if_idle(int slot_num)
990 struct slot_info *s = &slot[slot_num];
991 struct receiver_node *rn = s->receiver_node;
997 if (!rn->eof && !s->fc->eof && s->wpid > 0)
999 if (!s->fc->eof && s->wpid > 0 && get_loaded_bytes(slot_num))
1001 close_writer(slot_num);
1003 return; /* wait until writer dies before closing filters */
1004 PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
1006 close_filters(s->fc);
1008 close_receiver(slot_num);
1009 clear_slot(slot_num);
1012 static void audiod_pre_select(struct sched *s, struct task *t)
1016 if (audiod_status != AUDIOD_ON)
1017 kill_all_decoders();
1019 start_current_receiver();
1022 struct audio_format_info *a;
1023 struct receiver_node *rn;
1025 close_decoder_if_idle(i);
1027 if (slot[i].format < 0)
1029 a = &afi[slot[i].format];
1030 rn = slot[i].receiver_node;
1031 if (rn && rn->loaded && !slot[i].wpid) {
1032 PARA_INFO_LOG("no writer in slot %d\n", i);
1033 start_stream_writer(i);
1035 if (slot[i].write_fd <= 0)
1037 if (!get_loaded_bytes(i))
1039 para_fd_set(slot[i].write_fd, &s->wfds, &s->max_fileno);
1044 static int write_audio_data(int slot_num)
1046 struct slot_info *s = &slot[slot_num];
1047 struct audio_format_info *a = &afi[s->format];
1048 struct receiver_node *rn = s->receiver_node;
1053 if (a->num_filters) {
1054 buf = &s->fc->outbuf;
1055 len = s->fc->out_loaded;
1060 PARA_DEBUG_LOG("writing %p (%zd bytes)\n", *buf, *len);
1061 ret = write(s->write_fd, *buf, *len);
1062 PARA_DEBUG_LOG("wrote %d/%zd\n", ret, *len);
1064 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
1065 slot_num, s->write_fd, strerror(errno));
1067 close_writer(slot_num);
1068 // s->fc->error = E_WRITE_AUDIO_DATA;
1069 } else if (ret != *len) {
1070 PARA_DEBUG_LOG("partial %s write (%i/%zd) for slot %d\n",
1071 audio_formats[s->format], ret, *len, slot_num);
1073 memmove(*buf, *buf + ret, *len);
1077 gettimeofday(&s->wtime, NULL);
1081 static void audiod_post_select(struct sched *s, struct task *t)
1086 struct receiver_node *rn = slot[i].receiver_node;
1088 if (rn && rn->loaded)
1089 slot[i].rtime = s->now;
1090 if (slot[i].write_fd <= 0 || !slot[i].wcheck
1091 || !FD_ISSET(slot[i].write_fd, &s->wfds))
1093 ret = write_audio_data(i);
1097 static void init_audiod_task(struct audiod_task *at)
1099 at->task.pre_select = audiod_pre_select;
1100 at->task.post_select = audiod_post_select;
1101 at->task.private_data = at;
1103 sprintf(at->task.status, "audiod task");
1106 static int parse_stream_command(const char *txt, char **cmd)
1108 char *p = strchr(txt, ':');
1112 return -E_MISSING_COLON;
1114 FOR_EACH_AUDIO_FORMAT(i) {
1115 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1120 return -E_UNSUPPORTED_AUDIO_FORMAT;
1123 static int add_filter(int format, char *cmdline)
1125 struct audio_format_info *a = &afi[format];
1126 int filter_num, nf = a->num_filters;
1128 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1131 a->filters[nf] = &filters[filter_num];
1133 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1134 a->filters[nf]->name);
1138 static int setup_default_filters(void)
1142 FOR_EACH_AUDIO_FORMAT(i) {
1143 struct audio_format_info *a = &afi[i];
1148 /* add "dec" to audio format name */
1149 tmp = make_message("%sdec", audio_formats[i]);
1150 for (j = 0; filters[j].name; j++)
1151 if (!strcmp(tmp, filters[j].name))
1154 ret = -E_UNSUPPORTED_FILTER;
1155 if (!filters[j].name)
1157 tmp = para_strdup(filters[j].name);
1158 ret = add_filter(i, tmp);
1162 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1164 ret = add_filter(i, "wav");
1167 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1173 static int init_stream_io(void)
1175 int i, ret, receiver_num, nf;
1178 for (i = 0; i < conf.stream_write_cmd_given; i++) {
1179 ret = parse_stream_command(conf.stream_write_cmd_arg[i], &cmd);
1182 afi[ret].write_cmd = para_strdup(cmd);
1183 PARA_INFO_LOG("%s write command: %s\n", audio_formats[ret], afi[ret].write_cmd);
1185 for (i = 0; receivers[i].name; i++) {
1186 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1187 receivers[i].init(&receivers[i]);
1189 for (i = 0; i < conf.receiver_given; i++) {
1190 char *arg = conf.receiver_arg[i];
1191 char *recv = strchr(arg, ':');
1192 ret = -E_MISSING_COLON;
1197 ret = get_audio_format_num(arg);
1200 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1201 if (!afi[ret].receiver_conf) {
1202 ret = -E_RECV_SYNTAX;
1205 afi[ret].receiver = &receivers[receiver_num];
1207 /* use the first available receiver with no arguments
1208 * for those audio formats for which no receiver
1211 cmd = para_strdup(receivers[0].name);
1212 FOR_EACH_AUDIO_FORMAT(i) {
1213 struct audio_format_info *a = &afi[i];
1214 if (a->receiver_conf)
1216 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1217 if (!a->receiver_conf)
1218 return -E_RECV_SYNTAX;
1219 a->receiver = &receivers[receiver_num];
1223 filter_init(filters);
1224 nf = PARA_MAX(2, conf.filter_given) + 1;
1225 PARA_INFO_LOG("allocating space for %d filters\n", nf);
1226 FOR_EACH_AUDIO_FORMAT(i) {
1227 afi[i].filter_conf = para_malloc(nf * sizeof(char *));
1228 afi[i].filters = para_malloc(nf * sizeof(struct filter *));
1230 if (!conf.no_default_filters_given)
1231 return setup_default_filters();
1232 for (i = 0; i < conf.filter_given; i++) {
1233 char *arg = conf.filter_arg[i];
1234 char *filter_name = strchr(arg, ':');
1235 ret = -E_MISSING_COLON;
1238 *filter_name = '\0';
1240 ret = get_audio_format_num(arg);
1243 ret = add_filter(ret, filter_name);
1252 static int dump_commands(int fd)
1254 char *buf = para_strdup(""), *tmp = NULL;
1258 FOR_EACH_COMMAND(i) {
1259 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1260 cmds[i].description);
1264 ret = client_write(fd, buf);
1270 * command handlers don't close their fd on errors (ret < 0) so that
1271 * its caller can send an error message. Otherwise (ret >= 0) it's up
1272 * to each individual command to close the fd if necessary.
1275 static int com_help(int fd, int argc, char **argv)
1279 const char *dflt = "No such command. Available commands:\n";
1282 ret = dump_commands(fd);
1285 FOR_EACH_COMMAND(i) {
1286 if (strcmp(cmds[i].name, argv[1]))
1289 "NAME\n\t%s -- %s\n"
1290 "SYNOPSIS\n\tpara_audioc %s\n"
1291 "DESCRIPTION\n%s\n",
1293 cmds[i].description,
1297 ret = client_write(fd, buf);
1301 ret = client_write(fd, dflt);
1303 ret = dump_commands(fd);
1310 static int com_stat(int fd, __a_unused int argc, __a_unused char **argv)
1314 long unsigned mask = ~0LU;
1318 for (i = 1; i < argc; i++) {
1319 ret = stat_item_valid(argv[i]);
1325 PARA_INFO_LOG("mask: 0x%lx\n", mask);
1326 if (mask & (1 << SI_PLAY_TIME)) {
1327 struct timeval *t = wstime();
1328 char *ts = get_time_string(t);
1330 ret = client_write(fd, ts);
1336 if (mask & (1 << SI_AUDIOD_UPTIME)) {
1337 char *tmp, *us = uptime_str();
1338 tmp = make_message("%s:%s\n",
1339 status_item_list[SI_AUDIOD_UPTIME], us);
1341 ret = client_write(fd, tmp);
1346 if (mask & (1 << SI_AUDIOD_STATUS)) {
1347 char *s = audiod_status_string();
1348 ret = client_write(fd, s);
1353 if (mask & (1 << SI_DECODER_FLAGS)) {
1354 char *df =decoder_flags();
1355 ret = client_write(fd, df);
1361 for (i = 0; i < NUM_STAT_ITEMS; i++) {
1363 if (!((1 << i) & mask))
1365 v = stat_item_values[i];
1366 tmp = make_message("%s%s%s", buf? buf: "",
1367 v? v : "", v? "\n" : "");
1371 ret = client_write(fd, buf);
1374 ret = stat_client_add(fd, mask);
1380 static char *list_filters(void)
1383 char *tmp, *msg = make_message("format\tnum\tcmd\n");
1385 FOR_EACH_AUDIO_FORMAT(i) {
1386 for (j = 0; j < afi[i].num_filters; j++) {
1387 tmp = make_message("%s\t%i\t%s\n",
1388 afi[i].name, j, afi[i].filter_cmds[j]);
1389 msg = para_strcat(msg, tmp);
1392 tmp = make_message("%s\t%i\t%s\n", afi[i].name,
1393 j, afi[i].write_cmd);
1394 msg = para_strcat(msg, tmp);
1402 static int com_grab(int fd, char *cmdline)
1404 struct grab_client *gc;
1405 struct filter_node *fn;
1409 gc = grab_client_new(fd, cmdline, &err);
1412 fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1414 activate_grab_client(gc, fn);
1417 if (err != -E_GC_HELP_GIVEN && err != -E_GC_VERSION_GIVEN)
1419 if (err == -E_GC_HELP_GIVEN) {
1420 msg = make_message("%s\n\n", grab_client_args_info_usage);
1421 for (i = 0; grab_client_args_info_help[i]; i++) {
1422 char *tmp = make_message("%s%s\n", msg,
1423 grab_client_args_info_help[i]);
1428 msg = make_message("%s %s\n",
1429 GRAB_CLIENT_CMDLINE_PARSER_PACKAGE,
1430 GRAB_CLIENT_CMDLINE_PARSER_VERSION);
1431 err = client_write(fd, msg);
1439 static int __noreturn com_term(int fd, __a_unused int argc, __a_unused char **argv)
1442 clean_exit(EXIT_SUCCESS, "terminating on user request");
1445 static int com_on(int fd, __a_unused int argc, __a_unused char **argv)
1447 audiod_status = AUDIOD_ON;
1452 static int com_off(int fd, __a_unused int argc, __a_unused char **argv)
1454 audiod_status = AUDIOD_OFF;
1459 static int com_sb(int fd, __a_unused int argc, __a_unused char **argv)
1461 audiod_status = AUDIOD_STANDBY;
1466 static int com_cycle(int fd, int argc, char **argv)
1468 switch (audiod_status) {
1470 return com_sb(fd, argc, argv);
1473 return com_on(fd, argc, argv);
1475 case AUDIOD_STANDBY:
1476 return com_off(fd, argc, argv);
1483 static int check_perms(uid_t uid)
1487 if (!conf.user_allow_given)
1489 for (i = 0; i < conf.user_allow_given; i++)
1490 if (uid == conf.user_allow_arg[i])
1492 return -E_UCRED_PERM;
1495 static int handle_connect(void)
1497 int i, argc, ret, clifd = -1;
1498 char *cmd = NULL, *p, *buf = para_calloc(MAXLINE), **argv = NULL;
1499 struct sockaddr_un unix_addr;
1501 ret = para_accept(cmd_task->fd, &unix_addr, sizeof(struct sockaddr_un));
1505 ret = recv_cred_buffer(clifd, buf, MAXLINE - 1);
1508 PARA_INFO_LOG("connection from user %i, buf: %s\n", ret, buf);
1509 ret = check_perms(ret);
1512 ret = -E_INVALID_AUDIOD_CMD;
1513 cmd = para_strdup(buf);
1514 p = strchr(cmd, '\n');
1521 for (i = 0; cmds[i].name; i++) {
1523 if (strcmp(cmds[i].name, cmd))
1525 if (cmds[i].handler) {
1526 argc = split_args(buf, &argv, "\n");
1527 PARA_INFO_LOG("argv[0]: %s, argc= %d\n", argv[0], argc);
1528 ret = cmds[i].handler(clifd, argc, argv);
1531 for (j = 0; p[j]; j++)
1534 PARA_INFO_LOG("cmd: %s, options: %s\n", cmd, p);
1535 ret = cmds[i].line_handler(clifd, p);
1538 ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1543 if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1544 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1545 client_write(clifd, tmp);
1552 static void audiod_get_socket(void)
1554 struct sockaddr_un unix_addr;
1556 if (conf.socket_given)
1557 socket_name = para_strdup(conf.socket_arg);
1559 char *hn = para_hostname();
1560 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1564 PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1565 if (conf.force_given)
1566 unlink(socket_name);
1567 cmd_task->fd = create_pf_socket(socket_name, &unix_addr,
1568 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1569 if (cmd_task->fd < 0) {
1570 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1571 exit(EXIT_FAILURE); /* do not unlink socket */
1573 if (listen(cmd_task->fd , 5) < 0) {
1574 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1575 exit(EXIT_FAILURE); /* do not unlink socket */
1577 add_close_on_fork_list(cmd_task->fd);
1580 static int open_stat_pipe(void)
1582 int ret, fd[3] = {-1, 1, 0};
1584 ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1587 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1588 add_close_on_fork_list(ret);
1590 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1594 void signal_event_handler(struct task *t)
1596 struct signal_task *st = t->private_data;
1597 handle_signal(st->signum);
1600 void signal_pre_select(struct sched *s, struct task *t)
1602 struct signal_task *st = t->private_data;
1604 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1607 void signal_post_select(struct sched *s, struct task *t)
1609 struct signal_task *st = t->private_data;
1611 if (!FD_ISSET(st->fd, &s->rfds))
1613 t->ret = -E_SIGNAL_CAUGHT;
1614 st->signum = para_next_signal();
1617 void signal_setup_default(struct signal_task *st)
1619 st->task.pre_select = signal_pre_select;
1620 st->task.post_select = signal_post_select;
1621 st->task.private_data = st;
1623 sprintf(st->task.status, "signal task");
1626 static void command_pre_select(struct sched *s, struct task *t)
1628 struct command_task *ct = t->private_data;
1629 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
1633 static void command_post_select(struct sched *s, struct task *t)
1636 struct command_task *ct = t->private_data;
1638 if (audiod_status != AUDIOD_OFF)
1639 audiod_status_dump();
1640 t->ret = 1; /* always successful */
1641 if (!FD_ISSET(ct->fd, &s->rfds))
1643 ret = handle_connect();
1645 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1648 void init_command_task(struct command_task *ct)
1650 ct->task.pre_select = command_pre_select;
1651 ct->task.post_select = command_post_select;
1652 ct->task.private_data = ct;
1654 sprintf(ct->task.status, "command task");
1657 static void status_pre_select(struct sched *s, struct task *t)
1659 struct status_task *st = t->private_data;
1661 if (st->fd >= 0 && audiod_status == AUDIOD_OFF)
1663 if (st->fd < 0 && audiod_status != AUDIOD_OFF) {
1664 st->fd = open_stat_pipe();
1668 if (st->fd >= 0 && audiod_status != AUDIOD_OFF)
1669 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1672 static void status_post_select(struct sched *s, struct task *t)
1674 struct status_task *st = t->private_data;
1678 if (st->fd < 0 || !FD_ISSET(st->fd, &s->rfds))
1680 ret = read(st->fd, st->buf + st->loaded,
1681 STRINGSIZE - 1 - st->loaded);
1684 /* avoid busy loop if server is down */
1685 while (sleep(1) > 0)
1688 st->buf[ret + st->loaded] = '\0';
1689 st->loaded = for_each_line(st->buf, ret + st->loaded,
1694 static void init_status_task(struct status_task *st)
1696 st->task.pre_select = status_pre_select;
1697 st->task.post_select = status_post_select;
1698 st->task.private_data = st;
1703 sprintf(st->task.status, "status task");
1709 /* TODO: move everything before the select call to pre_select() */
1710 static void __noreturn audiod_mainloop(void)
1713 int ret, max_fileno, sbo = 0;
1714 char status_buf[STRINGSIZE] = "";
1723 /* always check signal pipe and the local socket */
1724 para_fd_set(signal_pipe, &rfds, &max_fileno);
1725 para_fd_set(audiod_socket, &rfds, &max_fileno);
1727 if (audiod_status != AUDIOD_ON)
1728 kill_all_decoders();
1730 start_current_receiver();
1732 set_stream_fds(&wfds, &max_fileno);
1734 if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1736 if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1737 stat_pipe = open_stat_pipe();
1739 status_buf[0] = '\0';
1741 if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF)
1742 para_fd_set(stat_pipe, &rfds, &max_fileno);
1745 tv.tv_usec = 200 * 1000;
1746 audiod_pre_select(&rfds, &wfds, &tv, &max_fileno);
1747 ret = para_select(max_fileno + 1, &rfds, &wfds, &tv);
1750 if (audiod_status != AUDIOD_OFF)
1751 audiod_status_dump();
1752 audiod_post_select(ret, &rfds, &wfds);
1753 /* read status pipe */
1754 if (stat_pipe >=0 && FD_ISSET(stat_pipe, &rfds)) {
1755 ret = read(stat_pipe, status_buf + sbo, STRINGSIZE - 1 - sbo);
1758 /* avoid busy loop if server is down */
1759 while (sleep(1) > 0)
1762 status_buf[ret + sbo] = '\0';
1763 sbo = for_each_line(status_buf, ret + sbo,
1768 if (FD_ISSET(audiod_socket, &rfds)) {
1769 ret = handle_connect();
1771 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1775 if (FD_ISSET(signal_pipe, &rfds)) {
1776 int sig_nr = para_next_signal();
1778 handle_signal(sig_nr);
1784 static void set_initial_status(void)
1786 audiod_status = AUDIOD_ON;
1787 if (!conf.mode_given)
1789 if (!strcmp(conf.mode_arg, "sb")) {
1790 audiod_status = AUDIOD_STANDBY;
1793 if (!strcmp(conf.mode_arg, "off")) {
1794 audiod_status = AUDIOD_OFF;
1797 if (strcmp(conf.mode_arg, "on"))
1798 PARA_WARNING_LOG("%s", "invalid mode\n");
1801 int main(int argc, char *argv[])
1810 hostname = para_hostname();
1811 cmdline_parser(argc, argv, &conf);
1812 para_drop_privileges(conf.user_arg, conf.group_arg);
1813 cf = configfile_exists();
1815 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1816 PARA_EMERG_LOG("%s", "parse error in config file\n");
1820 if (conf.logfile_given)
1821 logfile = open_log(conf.logfile_arg);
1822 log_welcome("para_audiod", conf.loglevel_arg);
1823 i = init_stream_io();
1825 PARA_EMERG_LOG("init stream io error: %s\n", PARA_STRERROR(-i));
1828 server_uptime(UPTIME_SET);
1829 set_initial_status();
1833 setup_signal_handling();
1834 if (conf.daemon_given)
1836 audiod_get_socket(); /* doesn't return on errors */
1838 signal_setup_default(sig_task);
1839 sig_task->task.event_handler = signal_event_handler;
1841 init_status_task(stat_task);
1842 init_command_task(cmd_task);
1843 init_audiod_task(at);
1845 register_task(&sig_task->task);
1846 register_task(&cmd_task->task);
1847 register_task(&stat_task->task);
1848 register_task(&at->task);
1849 s.default_timeout.tv_sec = 0;
1850 s.default_timeout.tv_usec = 999 * 1000;
1853 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
1854 return EXIT_FAILURE;