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 /** the number of filters that should be activated for this audio format */
64 unsigned int num_writers;
65 /** Array of writer numbers to be activated. */
67 /** pointer to the array of writer configurations */
69 /** do not start receiver/filters/writer before this time */
70 struct timeval restart_barrier;
73 /* Describes one instance of a receiver-filter-writer chain. */
75 /* Number of the audio format in this slot. */
77 /* The stream_start status item announced by para_server. */
78 struct timeval server_stream_start;
79 /* The offset status item announced by para_server. */
80 unsigned offset_seconds;
81 /* The seconds_total status item announced by para_server. */
82 unsigned seconds_total;
83 /* The receiver info associated with this slot. */
84 struct receiver_node *receiver_node;
85 /* The array of filter nodes. */
86 struct filter_node *fns;
87 /* The array of writers attached to the last filter. */
88 struct writer_node *wns;
91 #define RECEIVER_CMD(_a) lls_cmd((_a)->receiver_num, recv_cmd_suite)
92 #define RECEIVER(_a) ((const struct receiver *)lls_user_data(RECEIVER_CMD(_a)))
94 /** Maximal number of simultaneous instances. */
95 #define MAX_STREAM_SLOTS 5
97 /** Iterate over all slots. */
98 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
101 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
102 * be associated with a receiver/filter/writer triple. This array holds all
103 * information on the status of these slots.
105 * \sa struct slot_info
107 struct slot_info slot[MAX_STREAM_SLOTS];
109 /** The vss status flags audiod is interested in. */
110 enum vss_status_flags {
111 /** Whether the 'N' flag is set. */
112 VSS_STATUS_FLAG_NEXT = 1,
113 /** The 'P' flag is set. */
114 VSS_STATUS_FLAG_PLAYING = 2,
118 * The scheduler instance of para_audiod.
120 * This is needed also in audiod_command.c (for the tasks command), so it can
121 * not be made static.
123 struct sched sched = {.max_fileno = 0};
125 /* The task for obtaining para_server's status (para_client stat). */
127 /** The associated task structure of audiod. */
129 /** Client data associated with the stat task. */
130 struct client_task *ct;
131 /** Do not restart client command until this time. */
132 struct timeval restart_barrier;
133 /** Last time we received status data from para_server. */
134 struct timeval last_status_read;
136 /** The offset value announced by para_server. */
138 /** The length of the current audio file as announced by para_server. */
140 /** The start of the current stream from the view of para_server. */
141 struct timeval server_stream_start;
142 /** The average time deviation between para_server and para_audiod. */
143 struct timeval sa_time_diff;
144 /** Whether client time is ahead of server time. */
145 int sa_time_diff_sign;
146 /** The 'P' and the 'N' flags as announced by para_server. */
147 enum vss_status_flags vss_status;
148 /** Number of times the clock difference is to be checked. */
149 unsigned clock_diff_count;
150 /** When to start the next check for clock difference. */
151 struct timeval clock_diff_barrier;
152 /** Number of the audio format as announced by para_server. */
153 int current_audio_format_num;
154 /* The status task btrn is the child of the client task. */
155 struct btr_node *btrn;
158 /** The array of status items sent by para_server. */
159 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
162 * the current mode of operation of which can be changed by the on/off/cycle
163 * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
165 int audiod_status = AUDIOD_ON;
168 * the gengetopt args_info struct that holds information on all command line
171 static struct audiod_args_info conf;
173 static char *socket_name;
174 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
176 static struct signal_task *signal_task;
178 static struct status_task status_task_struct;
180 static uid_t *uid_whitelist;
183 * the task that calls the status command of para_server
185 * \sa struct status_task
187 static struct status_task *stat_task = &status_task_struct;
190 * The task for handling audiod commands.
192 * We need two listening sockets for backward compability: on Linux systems
193 * fd[0] is an abstract socket (more precisely, a socket bound to an address in
194 * the abstract namespace), and fd[1] is the usual pathname socket. On other
195 * systems, fd[0] is negative, and only the pathname socket is used.
197 * For 0.5.x we accept connections on both sockets to make sure that old
198 * para_audioc versions can still connect. New versions use only the abstract
199 * socket. Hence after v0.6.0 we can go back to a single socket, either an
200 * abstract one (Linux) or a pathname socket (all other systems).
202 struct command_task {
203 /** The local listening sockets. */
205 /** the associated task structure */
209 /** iterate over all supported audio formats */
210 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
213 * Get the audio format number.
215 * \param name The name of the audio format.
217 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
218 * \a name is not a supported audio format.
220 static int get_audio_format_num(const char *name)
224 while (para_isspace(*name))
226 FOR_EACH_AUDIO_FORMAT(i)
227 if (!strcmp(name, audio_formats[i]))
229 return -E_UNSUPPORTED_AUDIO_FORMAT;
233 * Return the flags for the \a decoder_flags status item.
235 * Allocates a string which contains one octal digit per slot. Bit zero (value
236 * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
237 * have the analogous meaning for filter and writer, respectively.
239 * \return String that must be freed by the caller.
241 __malloc char *audiod_get_decoder_flags(void)
244 char flags[MAX_STREAM_SLOTS + 1];
247 struct slot_info *s = &slot[i];
249 if (s->receiver_node)
257 flags[MAX_STREAM_SLOTS] = '\0';
258 return para_strdup(flags);
261 static int get_matching_audio_format_nums(const char *re)
266 ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
270 FOR_EACH_AUDIO_FORMAT(i)
271 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
277 static int get_play_time_slot_num(void)
279 int i, oldest_slot = -1;
280 struct timeval oldest_wstime = {0, 0};
283 struct slot_info *s = &slot[i];
284 struct timeval wstime;
285 if (!s->wns || !s->wns[0].btrn)
287 btr_get_node_start(s->wns[0].btrn, &wstime);
288 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
290 oldest_wstime = wstime;
297 * Compute the play time based on information of the current slot.
299 * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
300 * from the status items received from para_server and the start time of the
301 * (first) writer of the current slot.
303 * It has to take into account that the stream was probably not started at
304 * the beginning of the file, that the clock between the server and the client
305 * host may differ and that playback of the stream was delayed, e.g. because
306 * the prebuffer filter is used in the filter configuration.
308 * If no writer is active, for example because para_audiod runs in standby
309 * mode, an approximation based only on the status items is computed and the
310 * returned string is prefixed with "~".
312 * \return A string that must be freed by the caller.
314 char *get_time_string(void)
316 int ret, seconds = 0, length = stat_task->length_seconds;
317 struct timeval *tmp, sum, sss, /* server stream start */
318 rstime, /* receiver start time */
319 wstime, /* writer start time */
320 wtime, /* now - writer start */
321 rskip; /* receiver start - sss */
322 int slot_num = get_play_time_slot_num();
323 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
326 if (audiod_status == AUDIOD_OFF)
328 if (stat_task->server_stream_start.tv_sec == 0) {
329 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
330 goto out; /* server is about to change file */
331 if (length > 0) /* paused */
333 goto empty; /* stopped */
336 * Valid status items and playing, set length and tmp to the stream
337 * start. We use the slot info and fall back to the info from current
338 * status items if no slot info is available.
340 tmp = &stat_task->server_stream_start;
341 if (s && s->wns && s->wns[0].btrn) { /* writer active in this slot */
342 btr_get_node_start(s->wns[0].btrn, &wstime);
343 if (wstime.tv_sec != 0) { /* writer wrote something */
344 if (s->server_stream_start.tv_sec == 0) {
345 /* copy status info to slot */
346 s->server_stream_start = stat_task->server_stream_start;
347 s->offset_seconds = stat_task->offset_seconds;
348 s->seconds_total = stat_task->length_seconds;
350 length = s->seconds_total;
351 tmp = &s->server_stream_start;
354 if (stat_task->sa_time_diff_sign > 0)
355 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
357 tv_add(tmp, &stat_task->sa_time_diff, &sss);
358 if (!s || !s->wns || !s->wns[0].btrn || wstime.tv_sec == 0) {
360 tv_diff(now, &sss, &diff);
361 seconds = diff.tv_sec + stat_task->offset_seconds;
364 tv_diff(now, &wstime, &wtime);
365 //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
366 seconds = s->offset_seconds;
367 if (s->receiver_node->btrn) {
368 btr_get_node_start(s->receiver_node->btrn, &rstime);
369 ret = tv_diff(&rstime, &sss, &rskip);
370 if (ret > 0 && rskip.tv_sec > 2) {
371 /* audiod was started in the middle of the stream */
372 tv_add(&wtime, &rskip, &sum);
373 seconds += sum.tv_sec;
375 seconds += wtime.tv_sec;
377 seconds += wtime.tv_sec;
379 seconds = PARA_MIN(seconds, length);
380 seconds = PARA_MAX(seconds, 0);
382 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
386 (length - seconds) / 60,
387 (length - seconds) % 60,
388 length? (seconds * 100 + length / 2) / length : 0,
392 //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
395 return para_strdup(NULL);
398 static void parse_config_or_die(void)
402 struct audiod_cmdline_parser_params params = {
406 .check_ambiguity = 0,
410 if (conf.config_file_given)
411 config_file = para_strdup(conf.config_file_arg);
413 char *home = para_homedir();
414 config_file = make_message("%s/.paraslash/audiod.conf", home);
417 ret = file_exists(config_file);
418 if (conf.config_file_given && !ret) {
419 PARA_EMERG_LOG("can not read config file %s\n", config_file);
424 audiod_cmdline_parser_config_file(config_file, &conf, ¶ms);
425 daemon_set_loglevel(conf.loglevel_arg);
428 if (conf.user_allow_given > 0) {
429 uid_whitelist = para_malloc(conf.user_allow_given
431 for (i = 0; i < conf.user_allow_given; i++) {
434 ret = para_atoi32(conf.user_allow_arg[i], &val);
436 uid_whitelist[i] = val;
439 errno = 0; /* see getpwnam(3) */
440 pw = getpwnam(conf.user_allow_arg[i]);
442 PARA_EMERG_LOG("invalid username: %s\n",
443 conf.user_allow_arg[i]);
446 uid_whitelist[i] = pw->pw_uid;
454 static void setup_signal_handling(void)
456 signal_task = signal_init_or_die();
457 para_install_sighandler(SIGINT);
458 para_install_sighandler(SIGTERM);
459 para_install_sighandler(SIGHUP);
460 para_sigaction(SIGPIPE, SIG_IGN);
463 static void clear_slot(int slot_num)
465 struct slot_info *s = &slot[slot_num];
467 PARA_INFO_LOG("clearing slot %d\n", slot_num);
468 memset(s, 0, sizeof(struct slot_info));
472 static void close_receiver(int slot_num)
474 struct slot_info *s = &slot[slot_num];
475 struct audio_format_info *a;
477 if (s->format < 0 || !s->receiver_node)
480 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
481 audio_formats[s->format], slot_num);
482 RECEIVER(a)->close(s->receiver_node);
483 btr_remove_node(&s->receiver_node->btrn);
484 task_reap(&s->receiver_node->task);
485 free(s->receiver_node);
486 s->receiver_node = NULL;
487 stat_task->current_audio_format_num = -1;
488 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
489 &a->restart_barrier);
492 static void writer_cleanup(struct writer_node *wn)
498 w = writers + wn->writer_num;
499 PARA_INFO_LOG("closing %s\n", writer_names[wn->writer_num]);
501 btr_remove_node(&wn->btrn);
502 task_reap(&wn->task);
505 static void close_writers(struct slot_info *s)
507 struct audio_format_info *a;
514 if (a->num_writers == 0)
515 writer_cleanup(s->wns);
517 for (i = 0; i < a->num_writers; i++)
518 writer_cleanup(s->wns + i);
524 static void close_filters(struct slot_info *s)
527 struct audio_format_info *a = afi + s->format;
528 if (a->num_filters == 0)
530 for (i = a->num_filters - 1; i >= 0; i--) {
531 struct filter_node *fn = s->fns + i;
532 const struct filter *f;
536 f = filter_get(fn->filter_num);
539 btr_remove_node(&fn->btrn);
540 task_reap(&fn->task);
546 static void notify_receivers(int error)
551 struct slot_info *s = slot + i;
554 if (!s->receiver_node)
556 task_notify(s->receiver_node->task, error);
560 static int get_empty_slot(void)
571 if (s->wns || s->receiver_node || s->fns)
576 return -E_NO_MORE_SLOTS;
579 static void open_filters(struct slot_info *s)
581 struct audio_format_info *a = afi + s->format;
582 struct filter_node *fn;
583 int nf = a->num_filters;
584 struct btr_node *parent;
589 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
590 assert(s->fns == NULL);
591 s->fns = para_calloc(nf * sizeof(struct filter_node));
592 parent = s->receiver_node->btrn;
593 for (i = 0; i < nf; i++) {
595 const struct filter *f = filter_get(a->filter_nums[i]);
597 fn->filter_num = a->filter_nums[i];
598 fn->conf = a->filter_conf[i];
599 fn->btrn = btr_new_node(&(struct btr_node_description)
600 EMBRACE(.name = f->name, .parent = parent,
601 .handler = f->execute, .context = fn));
605 sprintf(buf, "%s (slot %d)", f->name, (int)(s - slot));
606 fn->task = task_register(&(struct task_info) {
608 .pre_select = f->pre_select,
609 .post_select = f->post_select,
613 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
614 audio_formats[s->format], i, nf, f->name, (int)(s - slot));
618 static void open_writers(struct slot_info *s)
621 struct audio_format_info *a = afi + s->format;
622 struct writer_node *wn;
623 struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
625 assert(s->wns == NULL);
626 s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
627 * sizeof(struct writer_node));
628 for (i = 0; i < a->num_writers; i++) {
630 wn->conf = a->writer_conf[i];
631 wn->writer_num = a->writer_nums[i];
632 register_writer_node(wn, parent, &sched);
633 PARA_NOTICE_LOG("%s writer started in slot %d\n",
634 writer_names[a->writer_nums[i]], (int)(s - slot));
638 /* returns slot num on success */
639 static int open_receiver(int format)
641 struct audio_format_info *a = &afi[format];
644 const struct receiver *r = RECEIVER(a);
645 const char *name = lls_command_name(RECEIVER_CMD(a));
646 struct receiver_node *rn;
648 tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
649 ret = get_empty_slot();
653 rn = para_calloc(sizeof(*rn));
655 rn->lpr = a->receiver_lpr;
656 rn->btrn = btr_new_node(&(struct btr_node_description)
657 EMBRACE(.name = name, .context = rn));
660 btr_remove_node(&rn->btrn);
666 s->receiver_node = rn;
667 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
668 audio_formats[format], name, slot_num);
669 rn->task = task_register(&(struct task_info) {
671 .pre_select = r->pre_select,
672 .post_select = r->post_select,
678 static bool receiver_running(void)
681 long unsigned ss1 = stat_task->server_stream_start.tv_sec;
684 struct slot_info *s = &slot[i];
685 long unsigned ss2 = s->server_stream_start.tv_sec;
687 if (!s->receiver_node)
689 if (task_status(s->receiver_node->task) >= 0)
698 * Return the root node of the current buffer tree.
700 * This is only used for stream grabbing.
702 * \return \p NULL if no slot is currently active. If more than one buffer tree
703 * exists, the node corresponding to the most recently started receiver is
706 struct btr_node *audiod_get_btr_root(void)
708 int i, newest_slot = -1;
709 struct timeval newest_rstime = {0, 0};
712 struct slot_info *s = &slot[i];
713 struct timeval rstime;
714 if (!s->receiver_node)
716 if (task_status(s->receiver_node->task) < 0)
718 btr_get_node_start(s->receiver_node->btrn, &rstime);
719 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
721 newest_rstime = rstime;
724 if (newest_slot == -1)
726 return slot[newest_slot].receiver_node->btrn;
729 /* whether a new instance of a decoder should be started. */
730 static bool must_start_decoder(void)
732 int cafn = stat_task->current_audio_format_num;
733 unsigned vs = stat_task->vss_status;
735 if (audiod_status != AUDIOD_ON)
741 if (vs & VSS_STATUS_FLAG_NEXT)
743 if (!(vs & VSS_STATUS_FLAG_PLAYING))
745 if (receiver_running())
747 if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
752 static void compute_time_diff(const struct timeval *status_time)
754 struct timeval tmp, diff;
755 static unsigned count;
756 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
757 const struct timeval max_deviation = {0, 500 * 1000};
758 const int time_smooth = 5;
760 sign = tv_diff(status_time, now, &diff);
761 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
762 // sign, sa_time_diff_sign);
764 sa_time_diff_sign = sign;
765 stat_task->sa_time_diff = diff;
770 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
771 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
772 PARA_WARNING_LOG("time diff jump: %lums\n",
776 sa_time_diff_sign = tv_convex_combination(
777 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
778 count > 10? sign : sign * time_smooth, &diff,
780 stat_task->sa_time_diff = tmp;
781 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
784 sa_time_diff_sign < 0? "-" : "+",
785 tv2ms(&stat_task->sa_time_diff)
788 stat_task->sa_time_diff_sign = sa_time_diff_sign;
791 static int update_item(int itemnum, char *buf)
793 long unsigned sec, usec;
795 if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
797 free(stat_item_values[itemnum]);
798 stat_item_values[itemnum] = para_strdup(buf);
799 stat_client_write_item(itemnum);
801 case SI_STATUS_FLAGS:
802 stat_task->vss_status = 0;
803 if (strchr(buf, 'N'))
804 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
805 if (strchr(buf, 'P'))
806 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
809 stat_task->offset_seconds = atoi(buf);
811 case SI_SECONDS_TOTAL:
812 stat_task->length_seconds = atoi(buf);
814 case SI_STREAM_START:
815 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
816 stat_task->server_stream_start.tv_sec = sec;
817 stat_task->server_stream_start.tv_usec = usec;
820 case SI_CURRENT_TIME:
821 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
822 struct timeval tv = {sec, usec};
823 compute_time_diff(&tv);
827 stat_task->current_audio_format_num
828 = get_audio_format_num(buf);
833 static int parse_stream_command(const char *txt, const char **cmd)
836 char *re, *p = strchr(txt, ':');
839 return -E_MISSING_COLON;
842 re = malloc(len + 1);
843 strncpy(re, txt, len);
845 ret = get_matching_audio_format_nums(re);
850 static int add_filter(int format, const char *cmdline)
852 struct audio_format_info *a = &afi[format];
853 int filter_num, nf = a->num_filters;
856 filter_num = check_filter_arg(cmdline, &cfg);
859 a->filter_conf = para_realloc(a->filter_conf,
860 (nf + 1) * sizeof(void *));
861 a->filter_nums = para_realloc(a->filter_nums,
862 (nf + 1) * sizeof(unsigned));
863 a->filter_nums[nf] = filter_num;
864 a->filter_conf[nf] = cfg;
866 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
867 filter_get(filter_num)->name);
871 static int parse_writer_args(void)
875 struct audio_format_info *a;
877 for (i = 0; i < conf.writer_given; i++) {
879 int j, nw, writer_num, af_mask;
881 ret = parse_stream_command(conf.writer_arg[i], &cmd);
885 FOR_EACH_AUDIO_FORMAT(j) {
887 if ((af_mask & (1 << j)) == 0) /* no match */
889 wconf = check_writer_arg_or_die(cmd, &writer_num);
891 a->writer_nums = para_realloc(a->writer_nums, (nw + 1) * sizeof(int));
892 a->writer_conf = para_realloc(a->writer_conf, (nw + 1) * sizeof(void *));
893 a->writer_nums[nw] = writer_num;
894 a->writer_conf[nw] = wconf;
895 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
896 nw, writer_names[writer_num]);
900 /* Use default writer for audio formats which are not yet set up. */
901 FOR_EACH_AUDIO_FORMAT(i) {
905 if (a->num_writers > 0)
906 continue; /* already set up */
907 writer_conf = check_writer_arg_or_die(NULL, &writer_num);
908 a->writer_nums = para_malloc(sizeof(int));
909 a->writer_nums[0] = writer_num;
910 a->writer_conf = para_malloc(sizeof(void *));
911 a->writer_conf[0] = writer_conf;
913 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
914 writer_names[writer_num]);
919 static int parse_receiver_args(void)
923 struct audio_format_info *a;
925 FOR_EACH_AUDIO_FORMAT(i)
926 afi[i].receiver_num = -1;
927 for (i = conf.receiver_given - 1; i >= 0; i--) {
930 ret = parse_stream_command(conf.receiver_arg[i], &arg);
934 FOR_EACH_AUDIO_FORMAT(j) {
936 if ((af_mask & (1 << j)) == 0) /* no match */
939 * If multiple receivers are given for this audio format, the
940 * last one wins and we have to free the previous receiver
941 * config here. Since we are iterating backwards, the winning
942 * receiver arg is in fact the first one given.
944 lls_free_parse_result(a->receiver_lpr, RECEIVER_CMD(a));
945 a->receiver_num = check_receiver_arg(arg, &a->receiver_lpr);
949 * Use the default receiver for those audio formats for which no
950 * receiver was specified.
952 FOR_EACH_AUDIO_FORMAT(i) {
954 if (a->receiver_num >= 0)
956 a->receiver_num = check_receiver_arg(NULL, &a->receiver_lpr);
958 FOR_EACH_AUDIO_FORMAT(i) {
960 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
961 audio_formats[i], lls_command_name(RECEIVER_CMD(a)));
968 static int init_default_filters(void)
972 FOR_EACH_AUDIO_FORMAT(i) {
973 struct audio_format_info *a = &afi[i];
974 const char *name = lls_command_name(RECEIVER_CMD(a));
979 continue; /* no default -- nothing to to */
981 * udp and dccp streams are fec-encoded, so add fecdec as the
984 if (strcmp(name, "udp") == 0 || strcmp(name, "dccp") == 0) {
985 tmp = para_strdup("fecdec");
991 /* add "dec" to audio format name */
992 tmp = make_message("%sdec", audio_formats[i]);
993 for (j = 0; filter_get(j); j++)
994 if (!strcmp(tmp, filter_get(j)->name))
997 ret = -E_UNSUPPORTED_FILTER;
1000 tmp = para_strdup(filter_get(j)->name);
1001 ret = add_filter(i, tmp);
1005 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1006 filter_get(j)->name);
1012 static int parse_filter_args(void)
1014 int i, j, ret, af_mask, num_matches;
1016 for (i = 0; i < conf.filter_given; i++) {
1018 ret = parse_stream_command(conf.filter_arg[i], &arg);
1023 FOR_EACH_AUDIO_FORMAT(j) {
1024 if ((af_mask & (1 << j)) == 0) /* no match */
1026 ret = add_filter(j, arg);
1031 if (num_matches == 0)
1032 PARA_WARNING_LOG("ignoring filter spec: %s\n",
1033 conf.filter_arg[i]);
1035 ret = init_default_filters(); /* use default values for the rest */
1040 static int parse_stream_args(void)
1044 ret = parse_receiver_args();
1047 ret = parse_filter_args();
1050 ret = parse_writer_args();
1056 /* does not unlink socket on errors */
1057 static void init_local_sockets(struct command_task *ct)
1059 if (conf.socket_given)
1060 socket_name = para_strdup(conf.socket_arg);
1062 char *hn = para_hostname();
1063 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1067 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1068 if (conf.force_given)
1069 unlink(socket_name);
1070 ct->fd[0] = create_local_socket(socket_name, 0);
1071 ct->fd[1] = create_local_socket(socket_name,
1072 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
1073 if (ct->fd[0] >= 0 || ct->fd[1] >= 0)
1075 PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd[1]));
1079 static int signal_post_select(struct sched *s, void *context)
1081 struct signal_task *st = context;
1084 ret = task_get_notification(st->task);
1087 signum = para_next_signal(&s->rfds);
1092 PARA_NOTICE_LOG("received signal %d\n", signum);
1093 task_notify_all(s, E_AUDIOD_SIGNAL);
1094 return -E_AUDIOD_SIGNAL;
1099 static void command_pre_select(struct sched *s, void *context)
1101 struct command_task *ct = context;
1104 for (i = 0; i < 2; i++)
1106 para_fd_set(ct->fd[i], &s->rfds, &s->max_fileno);
1109 static int command_post_select(struct sched *s, void *context)
1112 struct command_task *ct = context;
1113 static struct timeval last_status_dump;
1114 struct timeval tmp, delay;
1117 ret = task_get_notification(ct->task);
1120 for (i = 0; i < 2; i++) {
1123 ret = handle_connect(ct->fd[i], &s->rfds);
1125 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1126 if (ret == -E_AUDIOD_TERM) {
1127 task_notify_all(s, -ret);
1136 /* if last status dump was less than 500ms ago, do nothing */
1138 delay.tv_usec = 500 * 1000;
1139 tv_add(&last_status_dump, &delay, &tmp);
1140 if (tv_diff(now, &tmp, NULL) < 0)
1144 * If last status dump was more than 5s ago, force update. Otherwise,
1145 * update only those items that have changed.
1149 tv_add(&last_status_dump, &delay, &tmp);
1150 if (tv_diff(now, &tmp, NULL) > 0)
1153 audiod_status_dump(force);
1154 last_status_dump = *now;
1158 static void init_command_task(struct command_task *ct)
1160 init_local_sockets(ct); /* doesn't return on errors */
1162 ct->task = task_register(&(struct task_info) {
1164 .pre_select = command_pre_select,
1165 .post_select = command_post_select,
1170 static void close_stat_pipe(void)
1174 task_reap(&stat_task->ct->task);
1175 client_close(stat_task->ct);
1176 stat_task->ct = NULL;
1177 clear_and_dump_items();
1178 stat_task->length_seconds = 0;
1179 stat_task->offset_seconds = 0;
1180 stat_task->vss_status = 0;
1181 stat_task->current_audio_format_num = -1;
1182 audiod_status_dump(true);
1185 /* avoid busy loop if server is down */
1186 static void set_stat_task_restart_barrier(unsigned seconds)
1188 struct timeval delay = {seconds, 0};
1189 tv_add(now, &delay, &stat_task->restart_barrier);
1192 static bool must_close_slot(int slot_num)
1194 struct slot_info *s = &slot[slot_num];
1195 struct audio_format_info *a = afi + s->format;
1200 if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1202 for (i = 0; i < a->num_filters; i++)
1203 if (s->fns && task_status(s->fns[i].task) >= 0)
1205 if (a->num_writers > 0) {
1206 for (i = 0; i < a->num_writers; i++)
1207 if (s->wns && task_status(s->wns[i].task) >= 0)
1210 if (s->wns && task_status(s->wns[0].task) >= 0)
1216 static void close_slot(int slot_num)
1218 struct slot_info *s = slot + slot_num;
1220 PARA_INFO_LOG("closing slot %d\n", slot_num);
1223 close_receiver(slot_num);
1224 clear_slot(slot_num);
1227 static void close_unused_slots(void)
1233 if (must_close_slot(i)) {
1238 audiod_status_dump(true);
1242 * Cleanup all resources.
1244 * This performs various cleanups, removes the audiod socket and closes the
1245 * connection to para_server.
1247 static void audiod_cleanup(void)
1250 unlink(socket_name);
1252 close_unused_slots();
1253 audiod_cmdline_parser_free(&conf);
1254 close_stat_clients();
1255 free(uid_whitelist);
1259 * Check if any receivers/filters/writers need to be started and do so if
1262 static void start_stop_decoders(void)
1265 struct slot_info *sl;
1267 close_unused_slots();
1268 if (audiod_status != AUDIOD_ON ||
1269 !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1270 return notify_receivers(E_NOT_PLAYING);
1271 if (!must_start_decoder())
1273 ret = open_receiver(stat_task->current_audio_format_num);
1275 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1281 activate_grab_clients(&sched);
1282 btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1283 audiod_status_dump(true);
1286 static void status_pre_select(struct sched *s, void *context)
1288 struct status_task *st = context;
1289 int i, ret, cafn = stat_task->current_audio_format_num;
1291 if (must_start_decoder())
1294 if (must_close_slot(i))
1296 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1299 if (st->ct && audiod_status == AUDIOD_OFF)
1301 if (!st->ct && audiod_status != AUDIOD_OFF)
1302 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1304 sched_request_barrier(&afi[cafn].restart_barrier, s);
1306 * If para_server is playing we'd like to have a smooth time display
1307 * even if we are running in standby mode. So we request a timeout that
1308 * expires at the next full second.
1310 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1311 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1317 /* restart the client task if necessary */
1318 static int status_post_select(struct sched *s, void *context)
1320 struct status_task *st = context;
1323 ret = task_get_notification(st->task);
1326 if (audiod_status == AUDIOD_OFF) {
1329 if (task_status(st->ct->task) >= 0) {
1330 task_notify(st->ct->task, E_AUDIOD_OFF);
1334 st->clock_diff_count = conf.clock_diff_count_arg;
1341 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1346 if (st->ct->status != CL_EXECUTING)
1349 struct timeval diff;
1350 tv_diff(now, &st->last_status_read, &diff);
1351 if (diff.tv_sec > 61)
1352 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1355 btr_merge(st->btrn, st->min_iqs);
1356 sz = btr_next_buffer(st->btrn, &buf);
1357 ret = for_each_stat_item(buf, sz, update_item);
1359 task_notify(st->ct->task, -ret);
1363 btr_consume(st->btrn, sz - ret);
1364 st->last_status_read = *now;
1366 } else /* current status item crosses buffers */
1367 st->min_iqs = sz + 1;
1370 btr_drain(st->btrn);
1371 st->current_audio_format_num = -1;
1372 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1374 if (st->clock_diff_count) { /* get status only one time */
1375 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1377 PARA_INFO_LOG("clock diff count: %u\n", st->clock_diff_count);
1378 st->clock_diff_count--;
1379 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1380 set_stat_task_restart_barrier(2);
1383 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1385 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1386 set_stat_task_restart_barrier(5);
1388 free(stat_item_values[SI_BASENAME]);
1389 stat_item_values[SI_BASENAME] = para_strdup(
1390 "no connection to para_server");
1391 stat_client_write_item(SI_BASENAME);
1392 st->last_status_read = *now;
1394 start_stop_decoders();
1398 static void init_status_task(struct status_task *st)
1400 memset(st, 0, sizeof(struct status_task));
1401 st->sa_time_diff_sign = 1;
1402 st->clock_diff_count = conf.clock_diff_count_arg;
1403 st->current_audio_format_num = -1;
1404 st->btrn = btr_new_node(&(struct btr_node_description)
1405 EMBRACE(.name = "stat"));
1407 stat_task->task = task_register(&(struct task_info) {
1409 .pre_select = status_pre_select,
1410 .post_select = status_post_select,
1411 .context = stat_task,
1415 static void set_initial_status(void)
1417 audiod_status = AUDIOD_ON;
1418 if (!conf.mode_given)
1420 if (!strcmp(conf.mode_arg, "sb")) {
1421 audiod_status = AUDIOD_STANDBY;
1424 if (!strcmp(conf.mode_arg, "off")) {
1425 audiod_status = AUDIOD_OFF;
1428 if (strcmp(conf.mode_arg, "on"))
1429 PARA_WARNING_LOG("invalid mode\n");
1432 __noreturn static void print_help_and_die(void)
1434 struct ggo_help h = DEFINE_GGO_HELP(audiod);
1435 bool d = conf.detailed_help_given;
1438 flags = d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
1439 ggo_print_help(&h, flags);
1441 flags = d? GPH_MODULE_FLAGS_DETAILED : GPH_MODULE_FLAGS;
1442 print_receiver_helps(flags);
1443 print_filter_helps(flags);
1444 print_writer_helps(flags);
1449 * Lookup the given UID in the whitelist.
1451 * The whitelist is the array of arguments to the --user-allow opion. If the
1452 * option was not given, the array is empty, in which case the check succeeds.
1454 * \param uid User ID to look up.
1456 * \return True if --user-allow was not given, or if uid matches an element of
1459 bool uid_is_whitelisted(uid_t uid)
1463 if (!conf.user_allow_given)
1465 for (i = 0; i < conf.user_allow_given; i++)
1466 if (uid == uid_whitelist[i])
1472 * the main function of para_audiod
1474 * \param argc usual argument count
1475 * \param argv usual argument vector
1477 * \return EXIT_SUCCESS or EXIT_FAILURE
1479 * \sa para_audiod(1)
1481 int main(int argc, char *argv[])
1484 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1485 struct audiod_cmdline_parser_params params = {
1488 .check_required = 0,
1489 .check_ambiguity = 0,
1494 audiod_cmdline_parser_ext(argc, argv, &conf, ¶ms);
1495 daemon_set_loglevel(conf.loglevel_arg);
1496 version_handle_flag("audiod", conf.version_given);
1497 /* init receivers/filters/writers early to make help work */
1501 if (conf.help_given || conf.detailed_help_given)
1502 print_help_and_die();
1503 daemon_set_priority(conf.priority_arg);
1504 daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
1505 parse_config_or_die();
1506 if (daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
1507 conf.logfile_given)) {
1508 for (i = 0; i < conf.log_color_given; i++)
1509 daemon_set_log_color_or_die(conf.log_color_arg[i]);
1511 init_random_seed_or_die();
1512 daemon_set_flag(DF_LOG_TIME);
1513 daemon_set_flag(DF_LOG_HOSTNAME);
1514 daemon_set_flag(DF_LOG_LL);
1515 if (conf.log_timing_given)
1516 daemon_set_flag(DF_LOG_TIMING);
1517 if (conf.logfile_given) {
1518 daemon_set_logfile(conf.logfile_arg);
1519 daemon_open_log_or_die();
1521 ret = parse_stream_args();
1523 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1526 daemon_log_welcome("audiod");
1527 daemon_set_start_time();
1528 set_initial_status();
1531 setup_signal_handling();
1533 init_status_task(stat_task);
1534 init_command_task(cmd_task);
1536 if (conf.daemon_given)
1537 daemonize(false /* parent exits immediately */);
1539 signal_task->task = task_register(&(struct task_info) {
1541 .pre_select = signal_pre_select,
1542 .post_select = signal_post_select,
1543 .context = signal_task,
1546 sched.default_timeout.tv_sec = 2;
1547 sched.default_timeout.tv_usec = 999 * 1000;
1548 ret = schedule(&sched);
1550 sched_shutdown(&sched);
1551 signal_shutdown(signal_task);
1554 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1555 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;