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>
20 #include "recv_cmd.lsg.h"
21 #include "client.lsg.h"
25 #include "audiod.cmdline.h"
29 #include "buffer_tree.h"
32 #include "grab_client.h"
40 #include "write_common.h"
44 /** Array of error strings. */
47 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
48 /** define the array containing all supported audio formats */
49 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
51 /** Defines how audiod handles one supported audio format. */
52 struct audio_format_info {
53 /** the receiver for this audio format */
55 /** Parsed receiver command line. */
56 struct lls_parse_result *receiver_lpr;
57 /** the number of filters that should be activated for this audio format */
58 unsigned int num_filters;
59 /** Array of filter numbers to be activated. */
60 unsigned *filter_nums;
61 /** Pointer to the array of filter configurations. */
63 /** Parsed filter command line, one parse result per filter. */
64 struct lls_parse_result **filter_lpr;
65 /** the number of filters that should be activated for this audio format */
66 unsigned int num_writers;
67 /** Array of writer numbers to be activated. */
69 /** pointer to the array of writer configurations */
71 /** do not start receiver/filters/writer before this time */
72 struct timeval restart_barrier;
75 /* Describes one instance of a receiver-filter-writer chain. */
77 /* Number of the audio format in this slot. */
79 /* The stream_start status item announced by para_server. */
80 struct timeval server_stream_start;
81 /* The offset status item announced by para_server. */
82 unsigned offset_seconds;
83 /* The seconds_total status item announced by para_server. */
84 unsigned seconds_total;
85 /* The receiver info associated with this slot. */
86 struct receiver_node *receiver_node;
87 /* The array of filter nodes. */
88 struct filter_node *fns;
89 /* The array of writers attached to the last filter. */
90 struct writer_node *wns;
93 #define RECEIVER_CMD(_a) lls_cmd((_a)->receiver_num, recv_cmd_suite)
94 #define RECEIVER(_a) ((const struct receiver *)lls_user_data(RECEIVER_CMD(_a)))
96 /** Maximal number of simultaneous instances. */
97 #define MAX_STREAM_SLOTS 5
99 /** Iterate over all slots. */
100 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
103 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
104 * be associated with a receiver/filter/writer triple. This array holds all
105 * information on the status of these slots.
107 * \sa struct slot_info
109 struct slot_info slot[MAX_STREAM_SLOTS];
111 /** The vss status flags audiod is interested in. */
112 enum vss_status_flags {
113 /** Whether the 'N' flag is set. */
114 VSS_STATUS_FLAG_NEXT = 1,
115 /** The 'P' flag is set. */
116 VSS_STATUS_FLAG_PLAYING = 2,
120 * The scheduler instance of para_audiod.
122 * This is needed also in audiod_command.c (for the tasks command), so it can
123 * not be made static.
125 struct sched sched = {.max_fileno = 0};
127 /* The task for obtaining para_server's status (para_client stat). */
129 /** The associated task structure of audiod. */
131 /** Client data associated with the stat task. */
132 struct client_task *ct;
133 /** Do not restart client command until this time. */
134 struct timeval restart_barrier;
135 /** Last time we received status data from para_server. */
136 struct timeval last_status_read;
138 /** The offset value announced by para_server. */
140 /** The length of the current audio file as announced by para_server. */
142 /** The start of the current stream from the view of para_server. */
143 struct timeval server_stream_start;
144 /** The average time deviation between para_server and para_audiod. */
145 struct timeval sa_time_diff;
146 /** Whether client time is ahead of server time. */
147 int sa_time_diff_sign;
148 /** The 'P' and the 'N' flags as announced by para_server. */
149 enum vss_status_flags vss_status;
150 /** Number of times the clock difference is to be checked. */
151 unsigned clock_diff_count;
152 /** When to start the next check for clock difference. */
153 struct timeval clock_diff_barrier;
154 /** Number of the audio format as announced by para_server. */
155 int current_audio_format_num;
156 /* The status task btrn is the child of the client task. */
157 struct btr_node *btrn;
160 /** The array of status items sent by para_server. */
161 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
164 * the current mode of operation of which can be changed by the on/off/cycle
165 * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
167 int audiod_status = AUDIOD_ON;
170 * the gengetopt args_info struct that holds information on all command line
173 static struct audiod_args_info conf;
175 static char *socket_name;
176 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
178 static struct signal_task *signal_task;
180 static struct status_task status_task_struct;
182 static uid_t *uid_whitelist;
185 * the task that calls the status command of para_server
187 * \sa struct status_task
189 static struct status_task *stat_task = &status_task_struct;
192 * The task for handling audiod commands.
194 * We need two listening sockets for backward compability: on Linux systems
195 * fd[0] is an abstract socket (more precisely, a socket bound to an address in
196 * the abstract namespace), and fd[1] is the usual pathname socket. On other
197 * systems, fd[0] is negative, and only the pathname socket is used.
199 * For 0.5.x we accept connections on both sockets to make sure that old
200 * para_audioc versions can still connect. New versions use only the abstract
201 * socket. Hence after v0.6.0 we can go back to a single socket, either an
202 * abstract one (Linux) or a pathname socket (all other systems).
204 struct command_task {
205 /** The local listening sockets. */
207 /** the associated task structure */
211 /** iterate over all supported audio formats */
212 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
215 * Get the audio format number.
217 * \param name The name of the audio format.
219 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
220 * \a name is not a supported audio format.
222 static int get_audio_format_num(const char *name)
226 while (para_isspace(*name))
228 FOR_EACH_AUDIO_FORMAT(i)
229 if (!strcmp(name, audio_formats[i]))
231 return -E_UNSUPPORTED_AUDIO_FORMAT;
235 * Return the flags for the \a decoder_flags status item.
237 * Allocates a string which contains one octal digit per slot. Bit zero (value
238 * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
239 * have the analogous meaning for filter and writer, respectively.
241 * \return String that must be freed by the caller.
243 __malloc char *audiod_get_decoder_flags(void)
246 char flags[MAX_STREAM_SLOTS + 1];
249 struct slot_info *s = &slot[i];
251 if (s->receiver_node)
259 flags[MAX_STREAM_SLOTS] = '\0';
260 return para_strdup(flags);
263 static int get_matching_audio_format_nums(const char *re)
268 ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
272 FOR_EACH_AUDIO_FORMAT(i)
273 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
279 static int get_play_time_slot_num(void)
281 int i, oldest_slot = -1;
282 struct timeval oldest_wstime = {0, 0};
285 struct slot_info *s = &slot[i];
286 struct timeval wstime;
287 if (!s->wns || !s->wns[0].btrn)
289 btr_get_node_start(s->wns[0].btrn, &wstime);
290 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
292 oldest_wstime = wstime;
299 * Compute the play time based on information of the current slot.
301 * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
302 * from the status items received from para_server and the start time of the
303 * (first) writer of the current slot.
305 * It has to take into account that the stream was probably not started at
306 * the beginning of the file, that the clock between the server and the client
307 * host may differ and that playback of the stream was delayed, e.g. because
308 * the prebuffer filter is used in the filter configuration.
310 * If no writer is active, for example because para_audiod runs in standby
311 * mode, an approximation based only on the status items is computed and the
312 * returned string is prefixed with "~".
314 * \return A string that must be freed by the caller.
316 char *get_time_string(void)
318 int ret, seconds = 0, length = stat_task->length_seconds;
319 struct timeval *tmp, sum, sss, /* server stream start */
320 rstime, /* receiver start time */
321 wstime, /* writer start time */
322 wtime, /* now - writer start */
323 rskip; /* receiver start - sss */
324 int slot_num = get_play_time_slot_num();
325 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
328 if (audiod_status == AUDIOD_OFF)
330 if (stat_task->server_stream_start.tv_sec == 0) {
331 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
332 goto out; /* server is about to change file */
333 if (length > 0) /* paused */
335 goto empty; /* stopped */
338 * Valid status items and playing, set length and tmp to the stream
339 * start. We use the slot info and fall back to the info from current
340 * status items if no slot info is available.
342 tmp = &stat_task->server_stream_start;
343 if (s && s->wns && s->wns[0].btrn) { /* writer active in this slot */
344 btr_get_node_start(s->wns[0].btrn, &wstime);
345 if (wstime.tv_sec != 0) { /* writer wrote something */
346 if (s->server_stream_start.tv_sec == 0) {
347 /* copy status info to slot */
348 s->server_stream_start = stat_task->server_stream_start;
349 s->offset_seconds = stat_task->offset_seconds;
350 s->seconds_total = stat_task->length_seconds;
352 length = s->seconds_total;
353 tmp = &s->server_stream_start;
356 if (stat_task->sa_time_diff_sign > 0)
357 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
359 tv_add(tmp, &stat_task->sa_time_diff, &sss);
360 if (!s || !s->wns || !s->wns[0].btrn || wstime.tv_sec == 0) {
362 tv_diff(now, &sss, &diff);
363 seconds = diff.tv_sec + stat_task->offset_seconds;
366 tv_diff(now, &wstime, &wtime);
367 //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
368 seconds = s->offset_seconds;
369 if (s->receiver_node->btrn) {
370 btr_get_node_start(s->receiver_node->btrn, &rstime);
371 ret = tv_diff(&rstime, &sss, &rskip);
372 if (ret > 0 && rskip.tv_sec > 2) {
373 /* audiod was started in the middle of the stream */
374 tv_add(&wtime, &rskip, &sum);
375 seconds += sum.tv_sec;
377 seconds += wtime.tv_sec;
379 seconds += wtime.tv_sec;
381 seconds = PARA_MIN(seconds, length);
382 seconds = PARA_MAX(seconds, 0);
384 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
388 (length - seconds) / 60,
389 (length - seconds) % 60,
390 length? (seconds * 100 + length / 2) / length : 0,
394 //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
397 return para_strdup(NULL);
400 static void parse_config_or_die(void)
404 struct audiod_cmdline_parser_params params = {
408 .check_ambiguity = 0,
412 if (conf.config_file_given)
413 config_file = para_strdup(conf.config_file_arg);
415 char *home = para_homedir();
416 config_file = make_message("%s/.paraslash/audiod.conf", home);
419 ret = file_exists(config_file);
420 if (conf.config_file_given && !ret) {
421 PARA_EMERG_LOG("can not read config file %s\n", config_file);
426 audiod_cmdline_parser_config_file(config_file, &conf, ¶ms);
427 daemon_set_loglevel(conf.loglevel_arg);
430 if (conf.user_allow_given > 0) {
431 uid_whitelist = para_malloc(conf.user_allow_given
433 for (i = 0; i < conf.user_allow_given; i++) {
436 ret = para_atoi32(conf.user_allow_arg[i], &val);
438 uid_whitelist[i] = val;
441 errno = 0; /* see getpwnam(3) */
442 pw = getpwnam(conf.user_allow_arg[i]);
444 PARA_EMERG_LOG("invalid username: %s\n",
445 conf.user_allow_arg[i]);
448 uid_whitelist[i] = pw->pw_uid;
456 static void setup_signal_handling(void)
458 signal_task = signal_init_or_die();
459 para_install_sighandler(SIGINT);
460 para_install_sighandler(SIGTERM);
461 para_install_sighandler(SIGHUP);
462 para_sigaction(SIGPIPE, SIG_IGN);
465 static void clear_slot(int slot_num)
467 struct slot_info *s = &slot[slot_num];
469 PARA_INFO_LOG("clearing slot %d\n", slot_num);
470 memset(s, 0, sizeof(struct slot_info));
474 static void close_receiver(int slot_num)
476 struct slot_info *s = &slot[slot_num];
477 struct audio_format_info *a;
479 if (s->format < 0 || !s->receiver_node)
482 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
483 audio_formats[s->format], slot_num);
484 RECEIVER(a)->close(s->receiver_node);
485 btr_remove_node(&s->receiver_node->btrn);
486 task_reap(&s->receiver_node->task);
487 free(s->receiver_node);
488 s->receiver_node = NULL;
489 stat_task->current_audio_format_num = -1;
490 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
491 &a->restart_barrier);
494 static void writer_cleanup(struct writer_node *wn)
500 w = writers + wn->writer_num;
501 PARA_INFO_LOG("closing %s\n", writer_names[wn->writer_num]);
503 btr_remove_node(&wn->btrn);
504 task_reap(&wn->task);
507 static void close_writers(struct slot_info *s)
509 struct audio_format_info *a;
516 if (a->num_writers == 0)
517 writer_cleanup(s->wns);
519 for (i = 0; i < a->num_writers; i++)
520 writer_cleanup(s->wns + i);
526 static void close_filters(struct slot_info *s)
529 struct audio_format_info *a = afi + s->format;
530 if (a->num_filters == 0)
532 for (i = a->num_filters - 1; i >= 0; i--) {
533 struct filter_node *fn = s->fns + i;
534 const struct filter *f;
538 f = filter_get(fn->filter_num);
541 btr_remove_node(&fn->btrn);
542 task_reap(&fn->task);
548 static void notify_receivers(int error)
553 struct slot_info *s = slot + i;
556 if (!s->receiver_node)
558 task_notify(s->receiver_node->task, error);
562 static int get_empty_slot(void)
573 if (s->wns || s->receiver_node || s->fns)
578 return -E_NO_MORE_SLOTS;
581 static void open_filters(struct slot_info *s)
583 struct audio_format_info *a = afi + s->format;
584 struct filter_node *fn;
585 int nf = a->num_filters;
586 struct btr_node *parent;
591 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
592 assert(s->fns == NULL);
593 s->fns = para_calloc(nf * sizeof(struct filter_node));
594 parent = s->receiver_node->btrn;
595 for (i = 0; i < nf; i++) {
598 const struct filter *f = filter_get(a->filter_nums[i]);
600 fn->filter_num = a->filter_nums[i];
601 fn->conf = a->filter_conf[i];
602 fn->lpr = a->filter_lpr[i];
603 name = filter_name(fn->filter_num);
604 fn->btrn = btr_new_node(&(struct btr_node_description)
605 EMBRACE(.name = name, .parent = parent,
606 .handler = f->execute, .context = fn));
610 sprintf(buf, "%s (slot %d)", name, (int)(s - slot));
611 fn->task = task_register(&(struct task_info) {
613 .pre_select = f->pre_select,
614 .post_select = f->post_select,
618 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
619 audio_formats[s->format], i, nf, name, (int)(s - slot));
623 static void open_writers(struct slot_info *s)
626 struct audio_format_info *a = afi + s->format;
627 struct writer_node *wn;
628 struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
630 assert(s->wns == NULL);
631 s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
632 * sizeof(struct writer_node));
633 for (i = 0; i < a->num_writers; i++) {
635 wn->conf = a->writer_conf[i];
636 wn->writer_num = a->writer_nums[i];
637 register_writer_node(wn, parent, &sched);
638 PARA_NOTICE_LOG("%s writer started in slot %d\n",
639 writer_names[a->writer_nums[i]], (int)(s - slot));
643 /* returns slot num on success */
644 static int open_receiver(int format)
646 struct audio_format_info *a = &afi[format];
649 const struct receiver *r = RECEIVER(a);
650 const char *name = lls_command_name(RECEIVER_CMD(a));
651 struct receiver_node *rn;
653 tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
654 ret = get_empty_slot();
658 rn = para_calloc(sizeof(*rn));
660 rn->lpr = a->receiver_lpr;
661 rn->btrn = btr_new_node(&(struct btr_node_description)
662 EMBRACE(.name = name, .context = rn));
665 btr_remove_node(&rn->btrn);
671 s->receiver_node = rn;
672 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
673 audio_formats[format], name, slot_num);
674 rn->task = task_register(&(struct task_info) {
676 .pre_select = r->pre_select,
677 .post_select = r->post_select,
683 static bool receiver_running(void)
686 long unsigned ss1 = stat_task->server_stream_start.tv_sec;
689 struct slot_info *s = &slot[i];
690 long unsigned ss2 = s->server_stream_start.tv_sec;
692 if (!s->receiver_node)
694 if (task_status(s->receiver_node->task) >= 0)
703 * Return the root node of the current buffer tree.
705 * This is only used for stream grabbing.
707 * \return \p NULL if no slot is currently active. If more than one buffer tree
708 * exists, the node corresponding to the most recently started receiver is
711 struct btr_node *audiod_get_btr_root(void)
713 int i, newest_slot = -1;
714 struct timeval newest_rstime = {0, 0};
717 struct slot_info *s = &slot[i];
718 struct timeval rstime;
719 if (!s->receiver_node)
721 if (task_status(s->receiver_node->task) < 0)
723 btr_get_node_start(s->receiver_node->btrn, &rstime);
724 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
726 newest_rstime = rstime;
729 if (newest_slot == -1)
731 return slot[newest_slot].receiver_node->btrn;
734 /* whether a new instance of a decoder should be started. */
735 static bool must_start_decoder(void)
737 int cafn = stat_task->current_audio_format_num;
738 unsigned vs = stat_task->vss_status;
740 if (audiod_status != AUDIOD_ON)
746 if (vs & VSS_STATUS_FLAG_NEXT)
748 if (!(vs & VSS_STATUS_FLAG_PLAYING))
750 if (receiver_running())
752 if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
757 static void compute_time_diff(const struct timeval *status_time)
759 struct timeval tmp, diff;
760 static unsigned count;
761 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
762 const struct timeval max_deviation = {0, 500 * 1000};
763 const int time_smooth = 5;
765 sign = tv_diff(status_time, now, &diff);
766 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
767 // sign, sa_time_diff_sign);
769 sa_time_diff_sign = sign;
770 stat_task->sa_time_diff = diff;
775 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
776 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
777 PARA_WARNING_LOG("time diff jump: %lums\n",
781 sa_time_diff_sign = tv_convex_combination(
782 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
783 count > 10? sign : sign * time_smooth, &diff,
785 stat_task->sa_time_diff = tmp;
786 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
789 sa_time_diff_sign < 0? "-" : "+",
790 tv2ms(&stat_task->sa_time_diff)
793 stat_task->sa_time_diff_sign = sa_time_diff_sign;
796 static int update_item(int itemnum, char *buf)
798 long unsigned sec, usec;
800 if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
802 free(stat_item_values[itemnum]);
803 stat_item_values[itemnum] = para_strdup(buf);
804 stat_client_write_item(itemnum);
806 case SI_STATUS_FLAGS:
807 stat_task->vss_status = 0;
808 if (strchr(buf, 'N'))
809 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
810 if (strchr(buf, 'P'))
811 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
814 stat_task->offset_seconds = atoi(buf);
816 case SI_SECONDS_TOTAL:
817 stat_task->length_seconds = atoi(buf);
819 case SI_STREAM_START:
820 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
821 stat_task->server_stream_start.tv_sec = sec;
822 stat_task->server_stream_start.tv_usec = usec;
825 case SI_CURRENT_TIME:
826 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
827 struct timeval tv = {sec, usec};
828 compute_time_diff(&tv);
832 stat_task->current_audio_format_num
833 = get_audio_format_num(buf);
838 static int parse_stream_command(const char *txt, const char **cmd)
841 char *re, *p = strchr(txt, ':');
844 return -E_MISSING_COLON;
847 re = malloc(len + 1);
848 strncpy(re, txt, len);
850 ret = get_matching_audio_format_nums(re);
855 static int add_filter(int format, const char *cmdline)
857 struct audio_format_info *a = &afi[format];
858 int filter_num, nf = a->num_filters;
860 struct lls_parse_result *flpr;
862 filter_num = filter_setup(cmdline, &cfg, &flpr);
863 a->filter_lpr = para_realloc(a->filter_lpr,
864 (nf + 1) * sizeof(flpr));
865 a->filter_conf = para_realloc(a->filter_conf,
866 (nf + 1) * sizeof(void *));
867 a->filter_nums = para_realloc(a->filter_nums,
868 (nf + 1) * sizeof(unsigned));
870 a->filter_nums[nf] = filter_num;
871 a->filter_conf[nf] = cfg;
872 a->filter_lpr[nf] = flpr;
874 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
875 filter_name(filter_num));
879 static int parse_writer_args(void)
883 struct audio_format_info *a;
885 for (i = 0; i < conf.writer_given; i++) {
887 int j, nw, writer_num, af_mask;
889 ret = parse_stream_command(conf.writer_arg[i], &cmd);
893 FOR_EACH_AUDIO_FORMAT(j) {
895 if ((af_mask & (1 << j)) == 0) /* no match */
897 wconf = check_writer_arg_or_die(cmd, &writer_num);
899 a->writer_nums = para_realloc(a->writer_nums, (nw + 1) * sizeof(int));
900 a->writer_conf = para_realloc(a->writer_conf, (nw + 1) * sizeof(void *));
901 a->writer_nums[nw] = writer_num;
902 a->writer_conf[nw] = wconf;
903 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
904 nw, writer_names[writer_num]);
908 /* Use default writer for audio formats which are not yet set up. */
909 FOR_EACH_AUDIO_FORMAT(i) {
913 if (a->num_writers > 0)
914 continue; /* already set up */
915 writer_conf = check_writer_arg_or_die(NULL, &writer_num);
916 a->writer_nums = para_malloc(sizeof(int));
917 a->writer_nums[0] = writer_num;
918 a->writer_conf = para_malloc(sizeof(void *));
919 a->writer_conf[0] = writer_conf;
921 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
922 writer_names[writer_num]);
927 static int parse_receiver_args(void)
931 struct audio_format_info *a;
933 FOR_EACH_AUDIO_FORMAT(i)
934 afi[i].receiver_num = -1;
935 for (i = conf.receiver_given - 1; i >= 0; i--) {
938 ret = parse_stream_command(conf.receiver_arg[i], &arg);
942 FOR_EACH_AUDIO_FORMAT(j) {
944 if ((af_mask & (1 << j)) == 0) /* no match */
947 * If multiple receivers are given for this audio format, the
948 * last one wins and we have to free the previous receiver
949 * config here. Since we are iterating backwards, the winning
950 * receiver arg is in fact the first one given.
952 lls_free_parse_result(a->receiver_lpr, RECEIVER_CMD(a));
953 a->receiver_num = check_receiver_arg(arg, &a->receiver_lpr);
957 * Use the default receiver for those audio formats for which no
958 * receiver was specified.
960 FOR_EACH_AUDIO_FORMAT(i) {
962 if (a->receiver_num >= 0)
964 a->receiver_num = check_receiver_arg(NULL, &a->receiver_lpr);
966 FOR_EACH_AUDIO_FORMAT(i) {
968 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
969 audio_formats[i], lls_command_name(RECEIVER_CMD(a)));
976 static int init_default_filters(void)
980 FOR_EACH_AUDIO_FORMAT(i) {
981 struct audio_format_info *a = &afi[i];
982 const char *name = lls_command_name(RECEIVER_CMD(a));
987 continue; /* no default -- nothing to to */
989 * udp and dccp streams are fec-encoded, so add fecdec as the
992 if (strcmp(name, "udp") == 0 || strcmp(name, "dccp") == 0) {
993 tmp = para_strdup("fecdec");
999 /* add "dec" to audio format name */
1000 tmp = make_message("%sdec", audio_formats[i]);
1001 for (j = 0; filter_get(j); j++)
1002 if (!strcmp(tmp, filter_name(j)))
1005 ret = -E_UNSUPPORTED_FILTER;
1008 tmp = para_strdup(filter_name(j));
1009 ret = add_filter(i, tmp);
1013 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1020 static int parse_filter_args(void)
1022 int i, j, ret, af_mask, num_matches;
1024 for (i = 0; i < conf.filter_given; i++) {
1026 ret = parse_stream_command(conf.filter_arg[i], &arg);
1031 FOR_EACH_AUDIO_FORMAT(j) {
1032 if ((af_mask & (1 << j)) == 0) /* no match */
1034 ret = add_filter(j, arg);
1039 if (num_matches == 0)
1040 PARA_WARNING_LOG("ignoring filter spec: %s\n",
1041 conf.filter_arg[i]);
1043 ret = init_default_filters(); /* use default values for the rest */
1048 static int parse_stream_args(void)
1052 ret = parse_receiver_args();
1055 ret = parse_filter_args();
1058 ret = parse_writer_args();
1064 /* does not unlink socket on errors */
1065 static void init_local_sockets(struct command_task *ct)
1067 if (conf.socket_given)
1068 socket_name = para_strdup(conf.socket_arg);
1070 char *hn = para_hostname();
1071 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1075 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1076 if (conf.force_given)
1077 unlink(socket_name);
1078 ct->fd[0] = create_local_socket(socket_name, 0);
1079 ct->fd[1] = create_local_socket(socket_name,
1080 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
1081 if (ct->fd[0] >= 0 || ct->fd[1] >= 0)
1083 PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd[1]));
1087 static int signal_post_select(struct sched *s, void *context)
1089 struct signal_task *st = context;
1092 ret = task_get_notification(st->task);
1095 signum = para_next_signal(&s->rfds);
1100 PARA_NOTICE_LOG("received signal %d\n", signum);
1101 task_notify_all(s, E_AUDIOD_SIGNAL);
1102 return -E_AUDIOD_SIGNAL;
1107 static void command_pre_select(struct sched *s, void *context)
1109 struct command_task *ct = context;
1112 for (i = 0; i < 2; i++)
1114 para_fd_set(ct->fd[i], &s->rfds, &s->max_fileno);
1117 static int command_post_select(struct sched *s, void *context)
1120 struct command_task *ct = context;
1121 static struct timeval last_status_dump;
1122 struct timeval tmp, delay;
1125 ret = task_get_notification(ct->task);
1128 for (i = 0; i < 2; i++) {
1131 ret = handle_connect(ct->fd[i], &s->rfds);
1133 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1134 if (ret == -E_AUDIOD_TERM) {
1135 task_notify_all(s, -ret);
1144 /* if last status dump was less than 500ms ago, do nothing */
1146 delay.tv_usec = 500 * 1000;
1147 tv_add(&last_status_dump, &delay, &tmp);
1148 if (tv_diff(now, &tmp, NULL) < 0)
1152 * If last status dump was more than 5s ago, force update. Otherwise,
1153 * update only those items that have changed.
1157 tv_add(&last_status_dump, &delay, &tmp);
1158 if (tv_diff(now, &tmp, NULL) > 0)
1161 audiod_status_dump(force);
1162 last_status_dump = *now;
1166 static void init_command_task(struct command_task *ct)
1168 init_local_sockets(ct); /* doesn't return on errors */
1170 ct->task = task_register(&(struct task_info) {
1172 .pre_select = command_pre_select,
1173 .post_select = command_post_select,
1178 static void close_stat_pipe(void)
1182 task_reap(&stat_task->ct->task);
1183 client_close(stat_task->ct);
1184 stat_task->ct = NULL;
1185 clear_and_dump_items();
1186 stat_task->length_seconds = 0;
1187 stat_task->offset_seconds = 0;
1188 stat_task->vss_status = 0;
1189 stat_task->current_audio_format_num = -1;
1190 audiod_status_dump(true);
1193 /* avoid busy loop if server is down */
1194 static void set_stat_task_restart_barrier(unsigned seconds)
1196 struct timeval delay = {seconds, 0};
1197 tv_add(now, &delay, &stat_task->restart_barrier);
1200 static bool must_close_slot(int slot_num)
1202 struct slot_info *s = &slot[slot_num];
1203 struct audio_format_info *a = afi + s->format;
1208 if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1210 for (i = 0; i < a->num_filters; i++)
1211 if (s->fns && task_status(s->fns[i].task) >= 0)
1213 if (a->num_writers > 0) {
1214 for (i = 0; i < a->num_writers; i++)
1215 if (s->wns && task_status(s->wns[i].task) >= 0)
1218 if (s->wns && task_status(s->wns[0].task) >= 0)
1224 static void close_slot(int slot_num)
1226 struct slot_info *s = slot + slot_num;
1228 PARA_INFO_LOG("closing slot %d\n", slot_num);
1231 close_receiver(slot_num);
1232 clear_slot(slot_num);
1235 static void close_unused_slots(void)
1241 if (must_close_slot(i)) {
1246 audiod_status_dump(true);
1250 * Cleanup all resources.
1252 * This performs various cleanups, removes the audiod socket and closes the
1253 * connection to para_server.
1255 static void audiod_cleanup(void)
1258 unlink(socket_name);
1260 close_unused_slots();
1261 audiod_cmdline_parser_free(&conf);
1262 close_stat_clients();
1263 free(uid_whitelist);
1267 * Check if any receivers/filters/writers need to be started and do so if
1270 static void start_stop_decoders(void)
1273 struct slot_info *sl;
1275 close_unused_slots();
1276 if (audiod_status != AUDIOD_ON ||
1277 !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1278 return notify_receivers(E_NOT_PLAYING);
1279 if (!must_start_decoder())
1281 ret = open_receiver(stat_task->current_audio_format_num);
1283 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1289 activate_grab_clients(&sched);
1290 btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1291 audiod_status_dump(true);
1294 static void status_pre_select(struct sched *s, void *context)
1296 struct status_task *st = context;
1297 int i, ret, cafn = stat_task->current_audio_format_num;
1299 if (must_start_decoder())
1302 if (must_close_slot(i))
1304 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1307 if (st->ct && audiod_status == AUDIOD_OFF)
1309 if (!st->ct && audiod_status != AUDIOD_OFF)
1310 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1312 sched_request_barrier(&afi[cafn].restart_barrier, s);
1314 * If para_server is playing we'd like to have a smooth time display
1315 * even if we are running in standby mode. So we request a timeout that
1316 * expires at the next full second.
1318 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1319 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1325 /* restart the client task if necessary */
1326 static int status_post_select(struct sched *s, void *context)
1328 struct status_task *st = context;
1331 ret = task_get_notification(st->task);
1334 if (audiod_status == AUDIOD_OFF) {
1337 if (task_status(st->ct->task) >= 0) {
1338 task_notify(st->ct->task, E_AUDIOD_OFF);
1342 st->clock_diff_count = conf.clock_diff_count_arg;
1349 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1354 if (st->ct->status != CL_EXECUTING)
1357 struct timeval diff;
1358 tv_diff(now, &st->last_status_read, &diff);
1359 if (diff.tv_sec > 61)
1360 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1363 btr_merge(st->btrn, st->min_iqs);
1364 sz = btr_next_buffer(st->btrn, &buf);
1365 ret = for_each_stat_item(buf, sz, update_item);
1367 task_notify(st->ct->task, -ret);
1371 btr_consume(st->btrn, sz - ret);
1372 st->last_status_read = *now;
1374 } else /* current status item crosses buffers */
1375 st->min_iqs = sz + 1;
1378 btr_drain(st->btrn);
1379 st->current_audio_format_num = -1;
1380 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1382 if (st->clock_diff_count) { /* get status only one time */
1383 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1385 PARA_INFO_LOG("clock diff count: %u\n", st->clock_diff_count);
1386 st->clock_diff_count--;
1387 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1388 set_stat_task_restart_barrier(2);
1391 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1393 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1394 set_stat_task_restart_barrier(5);
1396 free(stat_item_values[SI_BASENAME]);
1397 stat_item_values[SI_BASENAME] = para_strdup(
1398 "no connection to para_server");
1399 stat_client_write_item(SI_BASENAME);
1400 st->last_status_read = *now;
1402 start_stop_decoders();
1406 static void init_status_task(struct status_task *st)
1408 memset(st, 0, sizeof(struct status_task));
1409 st->sa_time_diff_sign = 1;
1410 st->clock_diff_count = conf.clock_diff_count_arg;
1411 st->current_audio_format_num = -1;
1412 st->btrn = btr_new_node(&(struct btr_node_description)
1413 EMBRACE(.name = "stat"));
1415 stat_task->task = task_register(&(struct task_info) {
1417 .pre_select = status_pre_select,
1418 .post_select = status_post_select,
1419 .context = stat_task,
1423 static void set_initial_status(void)
1425 audiod_status = AUDIOD_ON;
1426 if (!conf.mode_given)
1428 if (!strcmp(conf.mode_arg, "sb")) {
1429 audiod_status = AUDIOD_STANDBY;
1432 if (!strcmp(conf.mode_arg, "off")) {
1433 audiod_status = AUDIOD_OFF;
1436 if (strcmp(conf.mode_arg, "on"))
1437 PARA_WARNING_LOG("invalid mode\n");
1440 __noreturn static void print_help_and_die(void)
1442 struct ggo_help h = DEFINE_GGO_HELP(audiod);
1443 bool d = conf.detailed_help_given;
1446 flags = d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
1447 ggo_print_help(&h, flags);
1449 flags = d? GPH_MODULE_FLAGS_DETAILED : GPH_MODULE_FLAGS;
1450 print_receiver_helps(flags);
1451 print_filter_helps(flags);
1452 print_writer_helps(flags);
1457 * Lookup the given UID in the whitelist.
1459 * The whitelist is the array of arguments to the --user-allow opion. If the
1460 * option was not given, the array is empty, in which case the check succeeds.
1462 * \param uid User ID to look up.
1464 * \return True if --user-allow was not given, or if uid matches an element of
1467 bool uid_is_whitelisted(uid_t uid)
1471 if (!conf.user_allow_given)
1473 for (i = 0; i < conf.user_allow_given; i++)
1474 if (uid == uid_whitelist[i])
1480 * the main function of para_audiod
1482 * \param argc usual argument count
1483 * \param argv usual argument vector
1485 * \return EXIT_SUCCESS or EXIT_FAILURE
1487 * \sa para_audiod(1)
1489 int main(int argc, char *argv[])
1492 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1493 struct audiod_cmdline_parser_params params = {
1496 .check_required = 0,
1497 .check_ambiguity = 0,
1502 audiod_cmdline_parser_ext(argc, argv, &conf, ¶ms);
1503 daemon_set_loglevel(conf.loglevel_arg);
1504 version_handle_flag("audiod", conf.version_given);
1505 /* init receivers/filters/writers early to make help work */
1508 if (conf.help_given || conf.detailed_help_given)
1509 print_help_and_die();
1510 daemon_set_priority(conf.priority_arg);
1511 daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
1512 parse_config_or_die();
1513 if (daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
1514 conf.logfile_given)) {
1515 for (i = 0; i < conf.log_color_given; i++)
1516 daemon_set_log_color_or_die(conf.log_color_arg[i]);
1518 init_random_seed_or_die();
1519 daemon_set_flag(DF_LOG_TIME);
1520 daemon_set_flag(DF_LOG_HOSTNAME);
1521 daemon_set_flag(DF_LOG_LL);
1522 if (conf.log_timing_given)
1523 daemon_set_flag(DF_LOG_TIMING);
1524 if (conf.logfile_given) {
1525 daemon_set_logfile(conf.logfile_arg);
1526 daemon_open_log_or_die();
1528 ret = parse_stream_args();
1530 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1533 daemon_log_welcome("audiod");
1534 daemon_set_start_time();
1535 set_initial_status();
1538 setup_signal_handling();
1540 init_status_task(stat_task);
1541 init_command_task(cmd_task);
1543 if (conf.daemon_given)
1544 daemonize(false /* parent exits immediately */);
1546 signal_task->task = task_register(&(struct task_info) {
1548 .pre_select = signal_pre_select,
1549 .post_select = signal_post_select,
1550 .context = signal_task,
1553 sched.default_timeout.tv_sec = 2;
1554 sched.default_timeout.tv_usec = 999 * 1000;
1555 ret = schedule(&sched);
1557 sched_shutdown(&sched);
1558 signal_shutdown(signal_task);
1561 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1562 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;