2 * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file audiod.c The paraslash's audio daemon. */
9 #include <netinet/in.h>
10 #include <sys/socket.h>
12 #include <sys/types.h>
13 #include <arpa/inet.h>
22 #include "audiod.cmdline.h"
26 #include "buffer_tree.h"
29 #include "grab_client.h"
30 #include "client.cmdline.h"
38 #include "write_common.h"
42 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
43 /** define the array of error lists needed by para_audiod */
45 /** define the array containing all supported audio formats */
46 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
48 DEFINE_RECEIVER_ARRAY;
50 /** Defines how audiod handles one supported audio format. */
51 struct audio_format_info {
52 /** pointer to the receiver for this audio format */
53 struct receiver *receiver;
54 /** the receiver configuration */
56 /** the number of filters that should be activated for this audio format */
57 unsigned int num_filters;
58 /** Array of filter numbers to be activated. */
59 unsigned *filter_nums;
60 /** Pointer to the array of filter configurations. */
62 /** the number of filters that should be activated for this audio format */
63 unsigned int num_writers;
64 /** Array of writer numbers to be activated. */
66 /** pointer to the array of writer configurations */
68 /** do not start receiver/filters/writer before this time */
69 struct timeval restart_barrier;
72 /* Describes one instance of a receiver-filter-writer chain. */
74 /* Number of the audio format in this slot. */
76 /* The stream_start status item announced by para_server. */
77 struct timeval server_stream_start;
78 /* The offset status item announced by para_server. */
79 unsigned offset_seconds;
80 /* The seconds_total status item announced by para_server. */
81 unsigned seconds_total;
82 /* The receiver info associated with this slot. */
83 struct receiver_node *receiver_node;
84 /* The array of filter nodes. */
85 struct filter_node *fns;
86 /* The array of writers attached to the last filter. */
87 struct writer_node *wns;
90 /** Maximal number of simultaneous instances. */
91 #define MAX_STREAM_SLOTS 5
93 /** Iterate over all slots. */
94 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
97 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
98 * be associated with a receiver/filter/writer triple. This array holds all
99 * information on the status of these slots.
101 * \sa struct slot_info
103 struct slot_info slot[MAX_STREAM_SLOTS];
105 /** The vss status flags audiod is interested in. */
106 enum vss_status_flags {
107 /** Whether the 'N' flag is set. */
108 VSS_STATUS_FLAG_NEXT = 1,
109 /** The 'P' flag is set. */
110 VSS_STATUS_FLAG_PLAYING = 2,
114 * The scheduler instance of para_audiod.
116 * This is needed also in audiod_command.c (for the tasks command), so it can
117 * not be made static.
119 struct sched sched = {.max_fileno = 0};
121 /* The task for obtaining para_server's status (para_client stat). */
123 /** The associated task structure of audiod. */
125 /** Client data associated with the stat task. */
126 struct client_task *ct;
127 /** Do not restart client command until this time. */
128 struct timeval restart_barrier;
129 /** Last time we received status data from para_server. */
130 struct timeval last_status_read;
132 /** The offset value announced by para_server. */
134 /** The length of the current audio file as announced by para_server. */
136 /** The start of the current stream from the view of para_server. */
137 struct timeval server_stream_start;
138 /** The average time deviation between para_server and para_audiod. */
139 struct timeval sa_time_diff;
140 /** Whether client time is ahead of server time. */
141 int sa_time_diff_sign;
142 /** The 'P' and the 'N' flags as announced by para_server. */
143 enum vss_status_flags vss_status;
144 /** Number of times the clock difference is to be checked. */
145 unsigned clock_diff_count;
146 /** When to start the next check for clock difference. */
147 struct timeval clock_diff_barrier;
148 /** Number of the audio format as announced by para_server. */
149 int current_audio_format_num;
150 /* The status task btrn is the child of the client task. */
151 struct btr_node *btrn;
154 /** The array of status items sent by para_server. */
155 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
158 * the current mode of operation of which can be changed by the on/off/cycle
159 * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
161 int audiod_status = AUDIOD_ON;
164 * the gengetopt args_info struct that holds information on all command line
167 struct audiod_args_info conf;
169 static char *socket_name;
170 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
172 static struct signal_task *signal_task;
174 static struct status_task status_task_struct;
176 static uid_t *uid_whitelist;
179 * the task that calls the status command of para_server
181 * \sa struct status_task
183 static struct status_task *stat_task = &status_task_struct;
186 * The task for handling audiod commands.
188 * We need two listening sockets for backward compability: on Linux systems
189 * fd[0] is an abstract socket (more precisely, a socket bound to an address in
190 * the abstract namespace), and fd[1] is the usual pathname socket. On other
191 * systems, fd[0] is negative, and only the pathname socket is used.
193 * For 0.5.x we accept connections on both sockets to make sure that old
194 * para_audioc versions can still connect. New versions use only the abstract
195 * socket. Hence after v0.6.0 we can go back to a single socket, either an
196 * abstract one (Linux) or a pathname socket (all other systems).
198 struct command_task {
199 /** The local listening sockets. */
201 /** the associated task structure */
205 /** iterate over all supported audio formats */
206 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
209 * Get the audio format number.
211 * \param name The name of the audio format.
213 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
214 * \a name is not a supported audio format.
216 static int get_audio_format_num(const char *name)
220 while (para_isspace(*name))
222 FOR_EACH_AUDIO_FORMAT(i)
223 if (!strcmp(name, audio_formats[i]))
225 return -E_UNSUPPORTED_AUDIO_FORMAT;
229 * Return the flags for the \a decoder_flags status item.
231 * Allocates a string which contains one octal digit per slot. Bit zero (value
232 * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
233 * have the analogous meaning for filter and writer, respectively.
235 * \return String that must be freed by the caller.
237 __malloc char *audiod_get_decoder_flags(void)
240 char flags[MAX_STREAM_SLOTS + 1];
243 struct slot_info *s = &slot[i];
245 if (s->receiver_node)
253 flags[MAX_STREAM_SLOTS] = '\0';
254 return para_strdup(flags);
257 static int get_matching_audio_format_nums(const char *re)
262 ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
266 FOR_EACH_AUDIO_FORMAT(i)
267 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
273 static int get_play_time_slot_num(void)
275 int i, oldest_slot = -1;
276 struct timeval oldest_wstime = {0, 0};
279 struct slot_info *s = &slot[i];
280 struct timeval wstime;
281 if (!s->wns || !s->wns[0].btrn)
283 btr_get_node_start(s->wns[0].btrn, &wstime);
284 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
286 oldest_wstime = wstime;
293 * Compute the play time based on information of the current slot.
295 * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
296 * from the status items received from para_server and the start time of the
297 * (first) writer of the current slot.
299 * It has to take into account that the stream was probably not started at
300 * the beginning of the file, that the clock between the server and the client
301 * host may differ and that playback of the stream was delayed, e.g. because
302 * the prebuffer filter is used in the filter configuration.
304 * If no writer is active, for example because para_audiod runs in standby
305 * mode, an approximation based only on the status items is computed and the
306 * returned string is prefixed with "~".
308 * \return A string that must be freed by the caller.
310 char *get_time_string(void)
312 int ret, seconds = 0, length;
313 struct timeval *tmp, sum, sss, /* server stream start */
314 rstime, /* receiver start time */
315 wstime, /* writer start time */
316 wtime, /* now - writer start */
317 rskip; /* receiver start - sss */
318 int slot_num = get_play_time_slot_num();
319 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
322 if (audiod_status == AUDIOD_OFF)
324 if (!(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)) {
325 if (stat_task->length_seconds) /* paused */
327 goto empty; /* stopped */
329 if (audiod_status == AUDIOD_ON && !s)
332 * Valid status items and playing, set length and tmp to the stream
333 * start. We use the slot info and fall back to the info from current
334 * status items if no slot info is available.
336 length = stat_task->length_seconds;
337 tmp = &stat_task->server_stream_start;
338 if (s && s->wns && s->wns[0].btrn) { /* writer active in this slot */
339 btr_get_node_start(s->wns[0].btrn, &wstime);
340 if (wstime.tv_sec != 0) { /* writer wrote something */
341 if (s->server_stream_start.tv_sec == 0) {
342 /* copy status info to slot */
343 s->server_stream_start = stat_task->server_stream_start;
344 s->offset_seconds = stat_task->offset_seconds;
345 s->seconds_total = stat_task->length_seconds;
347 length = s->seconds_total;
348 tmp = &s->server_stream_start;
351 if (stat_task->sa_time_diff_sign > 0)
352 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
354 tv_add(tmp, &stat_task->sa_time_diff, &sss);
355 if (!s || !s->wns || !s->wns[0].btrn) {
357 tv_diff(now, &sss, &diff);
358 seconds = diff.tv_sec + stat_task->offset_seconds;
361 tv_diff(now, &wstime, &wtime);
362 //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
363 seconds = s->offset_seconds;
364 if (s->receiver_node->btrn) {
365 btr_get_node_start(s->receiver_node->btrn, &rstime);
366 ret = tv_diff(&rstime, &sss, &rskip);
367 if (ret > 0) { /* audiod was started in the middle of the stream */
368 tv_add(&wtime, &rskip, &sum);
369 seconds += sum.tv_sec;
371 seconds += wtime.tv_sec;
373 seconds += wtime.tv_sec;
375 seconds = PARA_MIN(seconds, length);
376 seconds = PARA_MAX(seconds, 0);
378 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
382 (length - seconds) / 60,
383 (length - seconds) % 60,
384 length? (seconds * 100 + length / 2) / length : 0,
388 //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
391 return para_strdup(NULL);
394 static void parse_config_or_die(void)
398 struct audiod_cmdline_parser_params params = {
402 .check_ambiguity = 0,
406 if (conf.config_file_given)
407 config_file = para_strdup(conf.config_file_arg);
409 char *home = para_homedir();
410 config_file = make_message("%s/.paraslash/audiod.conf", home);
413 ret = file_exists(config_file);
414 if (conf.config_file_given && !ret) {
415 PARA_EMERG_LOG("can not read config file %s\n", config_file);
420 audiod_cmdline_parser_config_file(config_file, &conf, ¶ms);
421 daemon_set_loglevel(conf.loglevel_arg);
424 if (conf.user_allow_given > 0) {
425 uid_whitelist = para_malloc(conf.user_allow_given
427 for (i = 0; i < conf.user_allow_given; i++) {
430 ret = para_atoi32(conf.user_allow_arg[i], &val);
432 uid_whitelist[i] = val;
435 errno = 0; /* see getpwnam(3) */
436 pw = getpwnam(conf.user_allow_arg[i]);
438 PARA_EMERG_LOG("invalid username: %s\n",
439 conf.user_allow_arg[i]);
442 uid_whitelist[i] = pw->pw_uid;
450 static void setup_signal_handling(void)
452 signal_task = signal_init_or_die();
453 para_install_sighandler(SIGINT);
454 para_install_sighandler(SIGTERM);
455 para_install_sighandler(SIGHUP);
456 para_sigaction(SIGPIPE, SIG_IGN);
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 close_receiver(int slot_num)
470 struct slot_info *s = &slot[slot_num];
471 struct audio_format_info *a;
473 if (s->format < 0 || !s->receiver_node)
476 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
477 audio_formats[s->format], slot_num);
478 a->receiver->close(s->receiver_node);
479 btr_remove_node(&s->receiver_node->btrn);
480 task_reap(&s->receiver_node->task);
481 free(s->receiver_node);
482 s->receiver_node = NULL;
483 stat_task->current_audio_format_num = -1;
484 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
485 &a->restart_barrier);
488 static void writer_cleanup(struct writer_node *wn)
494 w = writers + wn->writer_num;
495 PARA_INFO_LOG("closing %s\n", writer_names[wn->writer_num]);
497 btr_remove_node(&wn->btrn);
498 task_reap(&wn->task);
501 static void close_writers(struct slot_info *s)
503 struct audio_format_info *a;
510 if (a->num_writers == 0)
511 writer_cleanup(s->wns);
513 for (i = 0; i < a->num_writers; i++)
514 writer_cleanup(s->wns + i);
520 static void close_filters(struct slot_info *s)
523 struct audio_format_info *a = afi + s->format;
524 if (a->num_filters == 0)
526 for (i = a->num_filters - 1; i >= 0; i--) {
527 struct filter_node *fn = s->fns + i;
532 f = filters + fn->filter_num;
535 btr_remove_node(&fn->btrn);
536 task_reap(&fn->task);
542 static void notify_receivers(int error)
547 struct slot_info *s = slot + i;
550 if (!s->receiver_node)
552 task_notify(s->receiver_node->task, error);
556 static int get_empty_slot(void)
567 if (s->wns || s->receiver_node || s->fns)
572 return -E_NO_MORE_SLOTS;
575 static void open_filters(struct slot_info *s)
577 struct audio_format_info *a = afi + s->format;
578 struct filter_node *fn;
579 int nf = a->num_filters;
580 struct btr_node *parent;
585 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
586 assert(s->fns == NULL);
587 s->fns = para_calloc(nf * sizeof(struct filter_node));
588 parent = s->receiver_node->btrn;
589 for (i = 0; i < nf; i++) {
591 struct filter *f = filters + a->filter_nums[i];
593 fn->filter_num = a->filter_nums[i];
594 fn->conf = a->filter_conf[i];
595 fn->btrn = btr_new_node(&(struct btr_node_description)
596 EMBRACE(.name = f->name, .parent = parent,
597 .handler = f->execute, .context = fn));
600 sprintf(buf, "%s (slot %d)", f->name, (int)(s - slot));
601 fn->task = task_register(&(struct task_info) {
603 .pre_select = f->pre_select,
604 .post_select = f->post_select,
608 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
609 audio_formats[s->format], i, nf, f->name, (int)(s - slot));
613 static void open_writers(struct slot_info *s)
616 struct audio_format_info *a = afi + s->format;
617 struct writer_node *wn;
618 struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
620 assert(s->wns == NULL);
621 s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
622 * sizeof(struct writer_node));
623 for (i = 0; i < a->num_writers; i++) {
625 wn->conf = a->writer_conf[i];
626 wn->writer_num = a->writer_nums[i];
627 register_writer_node(wn, parent, &sched);
628 PARA_NOTICE_LOG("%s writer started in slot %d\n",
629 writer_names[a->writer_nums[i]], (int)(s - slot));
633 /* returns slot num on success */
634 static int open_receiver(int format)
636 struct audio_format_info *a = &afi[format];
639 struct receiver *r = a->receiver;
640 struct receiver_node *rn;
642 tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
643 ret = get_empty_slot();
647 rn = para_calloc(sizeof(*rn));
649 rn->conf = a->receiver_conf;
650 rn->btrn = btr_new_node(&(struct btr_node_description)
651 EMBRACE(.name = r->name, .context = rn));
654 btr_remove_node(&rn->btrn);
660 s->receiver_node = rn;
661 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
662 audio_formats[format], r->name, slot_num);
663 rn->task = task_register(&(struct task_info) {
665 .pre_select = r->pre_select,
666 .post_select = r->post_select,
672 static bool receiver_running(void)
675 long unsigned ss1 = stat_task->server_stream_start.tv_sec;
678 struct slot_info *s = &slot[i];
679 long unsigned ss2 = s->server_stream_start.tv_sec;
681 if (!s->receiver_node)
683 if (task_status(s->receiver_node->task) >= 0)
692 * Return the root node of the current buffer tree.
694 * This is only used for stream grabbing.
696 * \return \p NULL if no slot is currently active. If more than one buffer tree
697 * exists, the node corresponding to the most recently started receiver is
700 struct btr_node *audiod_get_btr_root(void)
702 int i, newest_slot = -1;
703 struct timeval newest_rstime = {0, 0};
706 struct slot_info *s = &slot[i];
707 struct timeval rstime;
708 if (!s->receiver_node)
710 if (task_status(s->receiver_node->task) < 0)
712 btr_get_node_start(s->receiver_node->btrn, &rstime);
713 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
715 newest_rstime = rstime;
718 if (newest_slot == -1)
720 return slot[newest_slot].receiver_node->btrn;
723 /* whether a new instance of a decoder should be started. */
724 static bool must_start_decoder(void)
726 int cafn = stat_task->current_audio_format_num;
727 unsigned vs = stat_task->vss_status;
729 if (audiod_status != AUDIOD_ON)
735 if (vs & VSS_STATUS_FLAG_NEXT)
737 if (!(vs & VSS_STATUS_FLAG_PLAYING))
739 if (receiver_running())
741 if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
746 static void compute_time_diff(const struct timeval *status_time)
748 struct timeval tmp, diff;
749 static unsigned count;
750 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
751 const struct timeval max_deviation = {0, 500 * 1000};
752 const int time_smooth = 5;
754 sign = tv_diff(status_time, now, &diff);
755 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
756 // sign, sa_time_diff_sign);
758 sa_time_diff_sign = sign;
759 stat_task->sa_time_diff = diff;
764 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
765 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
766 PARA_WARNING_LOG("time diff jump: %lims\n",
770 sa_time_diff_sign = tv_convex_combination(
771 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
772 count > 10? sign : sign * time_smooth, &diff,
774 stat_task->sa_time_diff = tmp;
775 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
778 sa_time_diff_sign < 0? "-" : "+",
779 tv2ms(&stat_task->sa_time_diff)
782 stat_task->sa_time_diff_sign = sa_time_diff_sign;
785 static int update_item(int itemnum, char *buf)
787 long unsigned sec, usec;
789 if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
791 free(stat_item_values[itemnum]);
792 stat_item_values[itemnum] = para_strdup(buf);
793 stat_client_write_item(itemnum);
795 case SI_STATUS_FLAGS:
796 stat_task->vss_status = 0;
797 if (strchr(buf, 'N'))
798 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
799 if (strchr(buf, 'P'))
800 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
803 stat_task->offset_seconds = atoi(buf);
805 case SI_SECONDS_TOTAL:
806 stat_task->length_seconds = atoi(buf);
808 case SI_STREAM_START:
809 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
810 stat_task->server_stream_start.tv_sec = sec;
811 stat_task->server_stream_start.tv_usec = usec;
814 case SI_CURRENT_TIME:
815 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
816 struct timeval tv = {sec, usec};
817 compute_time_diff(&tv);
821 stat_task->current_audio_format_num
822 = get_audio_format_num(buf);
827 static int parse_stream_command(const char *txt, char **cmd)
830 char *re, *p = strchr(txt, ':');
833 return -E_MISSING_COLON;
836 re = malloc(len + 1);
837 strncpy(re, txt, len);
839 ret = get_matching_audio_format_nums(re);
844 static int add_filter(int format, char *cmdline)
846 struct audio_format_info *a = &afi[format];
847 int filter_num, nf = a->num_filters;
850 filter_num = check_filter_arg(cmdline, &cfg);
853 a->filter_conf = para_realloc(a->filter_conf,
854 (nf + 1) * sizeof(void *));
855 a->filter_nums = para_realloc(a->filter_nums,
856 (nf + 1) * sizeof(unsigned));
857 a->filter_nums[nf] = filter_num;
858 a->filter_conf[nf] = cfg;
860 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
861 filters[filter_num].name);
865 static int parse_writer_args(void)
869 struct audio_format_info *a;
871 for (i = 0; i < conf.writer_given; i++) {
873 int j, nw, writer_num, af_mask;
875 ret = parse_stream_command(conf.writer_arg[i], &cmd);
879 FOR_EACH_AUDIO_FORMAT(j) {
881 if ((af_mask & (1 << j)) == 0) /* no match */
883 wconf = check_writer_arg_or_die(cmd, &writer_num);
885 a->writer_nums = para_realloc(a->writer_nums, (nw + 1) * sizeof(int));
886 a->writer_conf = para_realloc(a->writer_conf, (nw + 1) * sizeof(void *));
887 a->writer_nums[nw] = writer_num;
888 a->writer_conf[nw] = wconf;
889 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
890 nw, writer_names[writer_num]);
894 /* Use default writer for audio formats which are not yet set up. */
895 FOR_EACH_AUDIO_FORMAT(i) {
899 if (a->num_writers > 0)
900 continue; /* already set up */
901 writer_conf = check_writer_arg_or_die(NULL, &writer_num);
902 a->writer_nums = para_malloc(sizeof(int));
903 a->writer_nums[0] = writer_num;
904 a->writer_conf = para_malloc(sizeof(void *));
905 a->writer_conf[0] = writer_conf;
907 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
908 writer_names[writer_num]);
913 static int parse_receiver_args(void)
915 int i, ret, receiver_num;
917 struct audio_format_info *a;
919 for (i = conf.receiver_given - 1; i >= 0; i--) {
923 ret = parse_stream_command(conf.receiver_arg[i], &arg);
927 FOR_EACH_AUDIO_FORMAT(j) {
929 if ((af_mask & (1 << j)) == 0) /* no match */
932 * If multiple receivers are given for this audio format, the
933 * last one wins and we have to free the previous receiver
934 * config here. Since we are iterating backwards, the winning
935 * receiver arg is in fact the first one given.
937 if (a->receiver_conf)
938 a->receiver->free_config(a->receiver_conf);
939 a->receiver_conf = check_receiver_arg(arg, &receiver_num);
940 ret = -E_RECV_SYNTAX;
941 if (!a->receiver_conf)
943 a->receiver = receivers + receiver_num;
947 * Use the first available receiver with no arguments for those audio
948 * formats for which no receiver was specified.
950 cmd = para_strdup(receivers[0].name);
951 FOR_EACH_AUDIO_FORMAT(i) {
953 if (a->receiver_conf)
955 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
956 if (!a->receiver_conf)
957 return -E_RECV_SYNTAX;
958 a->receiver = &receivers[receiver_num];
960 FOR_EACH_AUDIO_FORMAT(i) {
962 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
963 audio_formats[i], a->receiver->name);
971 static int init_default_filters(void)
975 FOR_EACH_AUDIO_FORMAT(i) {
976 struct audio_format_info *a = &afi[i];
981 continue; /* no default -- nothing to to */
983 * udp and dccp streams are fec-encoded, so add fecdec as the
986 if (strcmp(afi[i].receiver->name, "udp") == 0 ||
987 strcmp(afi[i].receiver->name, "dccp") == 0) {
988 tmp = para_strdup("fecdec");
994 /* add "dec" to audio format name */
995 tmp = make_message("%sdec", audio_formats[i]);
996 for (j = 0; filters[j].name; j++)
997 if (!strcmp(tmp, filters[j].name))
1000 ret = -E_UNSUPPORTED_FILTER;
1001 if (!filters[j].name)
1003 tmp = para_strdup(filters[j].name);
1004 ret = add_filter(i, tmp);
1008 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1015 static int parse_filter_args(void)
1017 int i, j, ret, af_mask, num_matches;
1019 for (i = 0; i < conf.filter_given; i++) {
1021 ret = parse_stream_command(conf.filter_arg[i], &arg);
1026 FOR_EACH_AUDIO_FORMAT(j) {
1027 if ((af_mask & (1 << j)) == 0) /* no match */
1029 ret = add_filter(j, arg);
1034 if (num_matches == 0)
1035 PARA_WARNING_LOG("ignoring filter spec: %s\n",
1036 conf.filter_arg[i]);
1038 ret = init_default_filters(); /* use default values for the rest */
1043 static int parse_stream_args(void)
1047 ret = parse_receiver_args();
1050 ret = parse_filter_args();
1053 ret = parse_writer_args();
1059 /* does not unlink socket on errors */
1060 static void init_local_sockets(struct command_task *ct)
1062 if (conf.socket_given)
1063 socket_name = para_strdup(conf.socket_arg);
1065 char *hn = para_hostname();
1066 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1070 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1071 if (conf.force_given)
1072 unlink(socket_name);
1073 ct->fd[0] = create_local_socket(socket_name, 0);
1074 ct->fd[1] = create_local_socket(socket_name,
1075 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1076 if (ct->fd[0] >= 0 || ct->fd[1] >= 0)
1078 PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd[1]));
1082 static int signal_post_select(struct sched *s, void *context)
1084 struct signal_task *st = context;
1087 ret = task_get_notification(st->task);
1090 signum = para_next_signal(&s->rfds);
1095 PARA_NOTICE_LOG("received signal %d\n", signum);
1096 task_notify_all(s, E_AUDIOD_SIGNAL);
1097 return -E_AUDIOD_SIGNAL;
1102 static void command_pre_select(struct sched *s, void *context)
1104 struct command_task *ct = context;
1107 for (i = 0; i < 2; i++)
1109 para_fd_set(ct->fd[i], &s->rfds, &s->max_fileno);
1112 static int command_post_select(struct sched *s, void *context)
1115 struct command_task *ct = context;
1116 static struct timeval last_status_dump;
1117 struct timeval tmp, delay;
1120 ret = task_get_notification(ct->task);
1123 for (i = 0; i < 2; i++) {
1126 ret = handle_connect(ct->fd[i], &s->rfds, uid_whitelist);
1128 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1129 if (ret == -E_AUDIOD_TERM) {
1130 task_notify_all(s, -ret);
1139 /* if last status dump was less than 500ms ago, do nothing */
1141 delay.tv_usec = 500 * 1000;
1142 tv_add(&last_status_dump, &delay, &tmp);
1143 if (tv_diff(now, &tmp, NULL) < 0)
1147 * If last status dump was more than 5s ago, force update. Otherwise,
1148 * update only those items that have changed.
1152 tv_add(&last_status_dump, &delay, &tmp);
1153 if (tv_diff(now, &tmp, NULL) > 0)
1156 audiod_status_dump(force);
1157 last_status_dump = *now;
1161 static void init_command_task(struct command_task *ct)
1163 init_local_sockets(ct); /* doesn't return on errors */
1165 ct->task = task_register(&(struct task_info) {
1167 .pre_select = command_pre_select,
1168 .post_select = command_post_select,
1173 static void close_stat_pipe(void)
1177 task_reap(&stat_task->ct->task);
1178 client_close(stat_task->ct);
1179 stat_task->ct = NULL;
1180 clear_and_dump_items();
1181 stat_task->length_seconds = 0;
1182 stat_task->offset_seconds = 0;
1183 stat_task->vss_status = 0;
1184 stat_task->current_audio_format_num = -1;
1185 audiod_status_dump(true);
1188 /* avoid busy loop if server is down */
1189 static void set_stat_task_restart_barrier(unsigned seconds)
1191 struct timeval delay = {seconds, 0};
1192 tv_add(now, &delay, &stat_task->restart_barrier);
1195 static bool must_close_slot(int slot_num)
1197 struct slot_info *s = &slot[slot_num];
1198 struct audio_format_info *a = afi + s->format;
1203 if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1205 for (i = 0; i < a->num_filters; i++)
1206 if (s->fns && task_status(s->fns[i].task) >= 0)
1208 if (a->num_writers > 0) {
1209 for (i = 0; i < a->num_writers; i++)
1210 if (s->wns && task_status(s->wns[i].task) >= 0)
1213 if (s->wns && task_status(s->wns[0].task) >= 0)
1219 static void close_slot(int slot_num)
1221 struct slot_info *s = slot + slot_num;
1223 PARA_INFO_LOG("closing slot %d\n", slot_num);
1226 close_receiver(slot_num);
1227 clear_slot(slot_num);
1230 static void close_unused_slots(void)
1235 if (must_close_slot(i))
1240 * Cleanup all resources.
1242 * This performs various cleanups, removes the audiod socket and closes the
1243 * connection to para_server.
1245 static void audiod_cleanup(void)
1248 unlink(socket_name);
1250 close_unused_slots();
1251 audiod_cmdline_parser_free(&conf);
1252 close_stat_clients();
1253 free(uid_whitelist);
1257 * Check if any receivers/filters/writers need to be started and do so if
1260 static void start_stop_decoders(void)
1263 struct slot_info *sl;
1265 close_unused_slots();
1266 if (audiod_status != AUDIOD_ON ||
1267 !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1268 return notify_receivers(E_NOT_PLAYING);
1269 if (!must_start_decoder())
1271 ret = open_receiver(stat_task->current_audio_format_num);
1273 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1279 activate_grab_clients(&sched);
1280 btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1283 static void status_pre_select(struct sched *s, void *context)
1285 struct status_task *st = context;
1286 int i, ret, cafn = stat_task->current_audio_format_num;
1288 if (must_start_decoder())
1291 if (must_close_slot(i))
1293 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1296 if (st->ct && audiod_status == AUDIOD_OFF)
1298 if (!st->ct && audiod_status != AUDIOD_OFF)
1299 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1301 sched_request_barrier(&afi[cafn].restart_barrier, s);
1303 * If para_server is playing we'd like to have a smooth time display
1304 * even if we are running in standby mode. So we request a timeout that
1305 * expires at the next full second.
1307 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1308 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1314 /* restart the client task if necessary */
1315 static int status_post_select(struct sched *s, void *context)
1317 struct status_task *st = context;
1320 ret = task_get_notification(st->task);
1323 if (audiod_status == AUDIOD_OFF) {
1326 if (task_status(st->ct->task) >= 0) {
1327 task_notify(st->ct->task, E_AUDIOD_OFF);
1331 st->clock_diff_count = conf.clock_diff_count_arg;
1338 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1343 if (st->ct->status != CL_EXECUTING)
1346 struct timeval diff;
1347 tv_diff(now, &st->last_status_read, &diff);
1348 if (diff.tv_sec > 61)
1349 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1352 btr_merge(st->btrn, st->min_iqs);
1353 sz = btr_next_buffer(st->btrn, &buf);
1354 ret = for_each_stat_item(buf, sz, update_item);
1356 task_notify(st->ct->task, -ret);
1360 btr_consume(st->btrn, sz - ret);
1361 st->last_status_read = *now;
1363 } else /* current status item crosses buffers */
1364 st->min_iqs = sz + 1;
1367 btr_drain(st->btrn);
1368 st->current_audio_format_num = -1;
1369 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1371 if (st->clock_diff_count) { /* get status only one time */
1372 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1374 PARA_INFO_LOG("clock diff count: %d\n", st->clock_diff_count);
1375 st->clock_diff_count--;
1376 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1377 set_stat_task_restart_barrier(2);
1380 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1382 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1383 set_stat_task_restart_barrier(5);
1385 free(stat_item_values[SI_BASENAME]);
1386 stat_item_values[SI_BASENAME] = para_strdup(
1387 "no connection to para_server");
1388 stat_client_write_item(SI_BASENAME);
1389 st->last_status_read = *now;
1391 start_stop_decoders();
1395 static void init_status_task(struct status_task *st)
1397 memset(st, 0, sizeof(struct status_task));
1398 st->sa_time_diff_sign = 1;
1399 st->clock_diff_count = conf.clock_diff_count_arg;
1400 st->current_audio_format_num = -1;
1401 st->btrn = btr_new_node(&(struct btr_node_description)
1402 EMBRACE(.name = "stat"));
1404 stat_task->task = task_register(&(struct task_info) {
1406 .pre_select = status_pre_select,
1407 .post_select = status_post_select,
1408 .context = stat_task,
1412 static void set_initial_status(void)
1414 audiod_status = AUDIOD_ON;
1415 if (!conf.mode_given)
1417 if (!strcmp(conf.mode_arg, "sb")) {
1418 audiod_status = AUDIOD_STANDBY;
1421 if (!strcmp(conf.mode_arg, "off")) {
1422 audiod_status = AUDIOD_OFF;
1425 if (strcmp(conf.mode_arg, "on"))
1426 PARA_WARNING_LOG("invalid mode\n");
1429 __noreturn static void print_help_and_die(void)
1431 struct ggo_help h = DEFINE_GGO_HELP(audiod);
1432 bool d = conf.detailed_help_given;
1435 flags = d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
1436 ggo_print_help(&h, flags);
1438 flags = d? GPH_MODULE_FLAGS_DETAILED : GPH_MODULE_FLAGS;
1439 print_receiver_helps(flags);
1440 print_filter_helps(flags);
1441 print_writer_helps(flags);
1446 * the main function of para_audiod
1448 * \param argc usual argument count
1449 * \param argv usual argument vector
1451 * \return EXIT_SUCCESS or EXIT_FAILURE
1453 * \sa para_audiod(1)
1455 int main(int argc, char *argv[])
1458 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1459 struct audiod_cmdline_parser_params params = {
1462 .check_required = 0,
1463 .check_ambiguity = 0,
1468 audiod_cmdline_parser_ext(argc, argv, &conf, ¶ms);
1469 daemon_set_loglevel(conf.loglevel_arg);
1470 version_handle_flag("audiod", conf.version_given);
1471 /* init receivers/filters/writers early to make help work */
1475 if (conf.help_given || conf.detailed_help_given)
1476 print_help_and_die();
1477 daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
1478 parse_config_or_die();
1479 daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
1480 conf.logfile_given, conf.log_color_arg, conf.log_color_given);
1481 init_random_seed_or_die();
1482 daemon_set_flag(DF_LOG_TIME);
1483 daemon_set_flag(DF_LOG_HOSTNAME);
1484 daemon_set_flag(DF_LOG_LL);
1485 if (conf.log_timing_given)
1486 daemon_set_flag(DF_LOG_TIMING);
1487 if (conf.logfile_given) {
1488 daemon_set_logfile(conf.logfile_arg);
1489 daemon_open_log_or_die();
1491 ret = parse_stream_args();
1493 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1496 daemon_log_welcome("audiod");
1497 daemon_set_start_time();
1498 set_initial_status();
1501 setup_signal_handling();
1503 init_status_task(stat_task);
1504 init_command_task(cmd_task);
1506 if (conf.daemon_given)
1507 daemonize(false /* parent exits immediately */);
1509 signal_task->task = task_register(&(struct task_info) {
1511 .pre_select = signal_pre_select,
1512 .post_select = signal_post_select,
1513 .context = signal_task,
1516 sched.default_timeout.tv_sec = 2;
1517 sched.default_timeout.tv_usec = 999 * 1000;
1518 ret = schedule(&sched);
1520 sched_shutdown(&sched);
1521 signal_shutdown(signal_task);
1524 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1525 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;