1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file audiod.c The paraslash's audio daemon. */
5 #include <netinet/in.h>
6 #include <sys/socket.h>
16 #include "audiod.lsg.h"
17 #include "recv_cmd.lsg.h"
24 #include "buffer_tree.h"
27 #include "grab_client.h"
38 /** Array of error strings. */
41 static struct lls_parse_result *lpr;
42 #define CMD_PTR (lls_cmd(0, audiod_suite))
43 #define OPT_RESULT(_name) (lls_opt_result(LSG_AUDIOD_PARA_AUDIOD_OPT_ ## _name, lpr))
44 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
45 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
46 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
48 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
49 /* Audio formats supported by audiod */
50 static const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY};
51 #define NUM_AUDIO_FORMATS ARRAY_SIZE(audio_formats)
53 /** Defines how audiod handles one supported audio format. */
54 struct audio_format_info {
55 /** the receiver for this audio format */
57 /** Parsed receiver command line. */
58 struct lls_parse_result *receiver_lpr;
59 /** the number of filters that should be activated for this audio format */
60 unsigned int num_filters;
61 /** Array of filter numbers to be activated. */
62 unsigned *filter_nums;
63 /** Pointer to the array of filter configurations. */
65 /** Parsed filter command line, one parse result per filter. */
66 struct lls_parse_result **filter_lpr;
67 /** the number of filters that should be activated for this audio format */
68 unsigned int num_writers;
69 /** Array of writer IDs to be activated. */
71 /** Parsed writer command line(s) */
72 struct lls_parse_result **writer_lpr;
73 /** do not start receiver/filters/writer before this time */
74 struct timeval restart_barrier;
77 /* Describes one instance of a receiver-filter-writer chain. */
79 /* Number of the audio format in this slot. */
81 /* The stream_start status item announced by para_server. */
82 struct timeval server_stream_start;
83 /* The offset status item announced by para_server. */
84 unsigned offset_seconds;
85 /* The seconds_total status item announced by para_server. */
86 unsigned seconds_total;
87 /* The receiver info associated with this slot. */
88 struct receiver_node *receiver_node;
89 /* The array of filter nodes. */
90 struct filter_node *fns;
91 /* The array of writers attached to the last filter. */
92 struct writer_node *wns;
95 #define RECEIVER_CMD(_a) lls_cmd((_a)->receiver_num, recv_cmd_suite)
96 #define RECEIVER(_a) ((const struct receiver *)lls_user_data(RECEIVER_CMD(_a)))
98 /** Maximal number of simultaneous instances. */
99 #define MAX_STREAM_SLOTS 5
101 /** Iterate over all slots. */
102 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
105 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
106 * be associated with a receiver/filter/writer triple. This array holds all
107 * information on the status of these slots.
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 = {.timeout = 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 (AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY).
165 * Set by the on/off/cycle commands.
167 int audiod_status = AUDIOD_ON;
169 static char *socket_name;
170 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
171 static struct signal_task *signal_task;
172 static struct status_task status_task_struct;
173 static uid_t *uid_whitelist;
176 * The task that calls the status command of para_server.
178 * \sa \ref struct status_task.
180 static struct status_task *stat_task = &status_task_struct;
182 struct command_task {
183 /** The local listening socket. */
185 /** The associated task structure. */
189 /** Iterate over all supported audio formats. */
190 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
193 * Get the audio format number.
195 * \param name The name of the audio format.
197 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
198 * \a name is not a supported audio format.
200 static int get_audio_format_num(const char *name)
204 while (para_isspace(*name))
206 FOR_EACH_AUDIO_FORMAT(i)
207 if (!strcmp(name, audio_formats[i]))
209 return -E_UNSUPPORTED_AUDIO_FORMAT;
213 * Return the flags for the \a decoder_flags status item.
215 * Allocates a string which contains one octal digit per slot. Bit zero (value
216 * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
217 * have the analogous meaning for filter and writer, respectively.
219 * \return String that must be freed by the caller.
221 __malloc char *audiod_get_decoder_flags(void)
224 char flags[MAX_STREAM_SLOTS + 1];
227 struct slot_info *s = &slot[i];
229 if (s->receiver_node)
237 flags[MAX_STREAM_SLOTS] = '\0';
238 return para_strdup(flags);
241 static int get_matching_audio_format_nums(const char *re)
246 ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
250 FOR_EACH_AUDIO_FORMAT(i)
251 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
257 static int get_play_time_slot_num(void)
259 int i, oldest_slot = -1;
260 struct timeval oldest_wstime = {0, 0};
263 struct slot_info *s = &slot[i];
264 struct timeval wstime;
265 if (!s->wns || !s->wns[0].btrn)
267 btr_get_node_start(s->wns[0].btrn, &wstime);
268 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
270 oldest_wstime = wstime;
277 * Compute the play time based on information of the current slot.
279 * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
280 * from the status items received from para_server and the start time of the
281 * (first) writer of the current slot.
283 * It has to take into account that the stream was probably not started at
284 * the beginning of the file, that the clock between the server and the client
285 * host may differ and that playback of the stream was delayed, e.g. because
286 * the prebuffer filter is used in the filter configuration.
288 * If no writer is active, for example because para_audiod runs in standby
289 * mode, an approximation based only on the status items is computed and the
290 * returned string is prefixed with "~".
292 * \return A string that must be freed by the caller.
294 __malloc char *get_time_string(void)
296 int ret, seconds = 0, length = stat_task->length_seconds;
297 struct timeval *tmp, sum, sss, /* server stream start */
298 rstime, /* receiver start time */
299 wstime, /* writer start time */
300 wtime, /* now - writer start */
301 rskip; /* receiver start - sss */
302 int slot_num = get_play_time_slot_num();
303 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
304 bool writer_active = s && s->wns && s->wns[0].btrn;
307 if (audiod_status == AUDIOD_OFF)
309 if (stat_task->server_stream_start.tv_sec == 0) {
310 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
311 goto out; /* server is about to change file */
312 if (length > 0) /* paused */
314 goto empty; /* stopped */
317 * Valid status items and playing, set length and tmp to the stream
318 * start. We use the writer start time from the slot info and fall back
319 * to the info from current status items if no writer is active yet.
321 tmp = &stat_task->server_stream_start;
323 btr_get_node_start(s->wns[0].btrn, &wstime);
324 if (wstime.tv_sec != 0) { /* writer wrote something */
325 if (s->server_stream_start.tv_sec == 0) {
326 /* copy status info to slot */
327 s->server_stream_start = stat_task->server_stream_start;
328 s->offset_seconds = stat_task->offset_seconds;
329 s->seconds_total = stat_task->length_seconds;
331 length = s->seconds_total;
332 tmp = &s->server_stream_start;
335 if (stat_task->sa_time_diff_sign > 0)
336 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
338 tv_add(tmp, &stat_task->sa_time_diff, &sss);
339 if (!writer_active) {
341 tv_diff(now, &sss, &diff);
342 seconds = diff.tv_sec + stat_task->offset_seconds;
345 tv_diff(now, &wstime, &wtime);
346 //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
347 seconds = s->offset_seconds;
348 if (s->receiver_node->btrn) {
349 btr_get_node_start(s->receiver_node->btrn, &rstime);
350 ret = tv_diff(&rstime, &sss, &rskip);
351 if (ret > 0 && rskip.tv_sec > 2) {
352 /* audiod was started in the middle of the stream */
353 tv_add(&wtime, &rskip, &sum);
354 seconds += sum.tv_sec;
356 seconds += wtime.tv_sec;
358 seconds += wtime.tv_sec;
360 seconds = PARA_MIN(seconds, length);
361 seconds = PARA_MAX(seconds, 0);
363 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
367 (length - seconds) / 60,
368 (length - seconds) % 60,
369 length? (seconds * 100 + length / 2) / length : 0,
373 //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
376 return para_strdup(NULL);
379 static void parse_config_or_die(void)
384 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
385 "audiod.conf", &lpr, CMD_PTR, audiod_suite, 0U /* flags */);
387 PARA_EMERG_LOG("failed to parse config file: %s\n",
388 para_strerror(-ret));
391 daemon_set_loglevel(OPT_UINT32_VAL(LOGLEVEL));
392 n = OPT_GIVEN(USER_ALLOW);
395 uid_whitelist = arr_alloc(n, sizeof(uid_t));
396 for (i = 0; i < n; i++) {
397 const char *arg = lls_string_val(i, OPT_RESULT(USER_ALLOW));
400 ret = para_atoi32(arg, &val);
402 uid_whitelist[i] = val;
407 PARA_EMERG_LOG("invalid username: %s\n", arg);
410 uid_whitelist[i] = pw->pw_uid;
414 static void setup_signal_handling(void)
416 signal_task = signal_init_or_die();
417 para_install_sighandler(SIGINT);
418 para_install_sighandler(SIGTERM);
419 para_install_sighandler(SIGHUP);
420 para_sigaction(SIGPIPE, SIG_IGN);
423 static void clear_slot(int slot_num)
425 struct slot_info *s = &slot[slot_num];
427 PARA_INFO_LOG("clearing slot %d\n", slot_num);
428 memset(s, 0, sizeof(struct slot_info));
432 static void close_receiver(int slot_num)
434 struct slot_info *s = &slot[slot_num];
435 struct audio_format_info *a;
437 if (s->format < 0 || !s->receiver_node)
440 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
441 audio_formats[s->format], slot_num);
442 RECEIVER(a)->close(s->receiver_node);
443 btr_remove_node(&s->receiver_node->btrn);
444 task_reap(&s->receiver_node->task);
445 free(s->receiver_node);
446 s->receiver_node = NULL;
447 if (audiod_status == AUDIOD_ON)
448 stat_task->current_audio_format_num = -1;
449 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
450 &a->restart_barrier);
453 static void writer_cleanup(struct writer_node *wn)
457 PARA_INFO_LOG("closing %s\n", writer_name(wn->wid));
458 writer_get(wn->wid)->close(wn);
459 btr_remove_node(&wn->btrn);
460 task_reap(&wn->task);
463 static void close_writers(struct slot_info *s)
465 struct audio_format_info *a;
472 if (a->num_writers == 0)
473 writer_cleanup(s->wns);
475 for (i = 0; i < a->num_writers; i++)
476 writer_cleanup(s->wns + i);
482 static void notify_writers(int error)
487 struct slot_info *s = slot + i;
488 struct audio_format_info *a;
494 for (j = 0; j < a->num_writers; j++)
495 task_notify(s->wns[j].task, error);
499 static void close_filters(struct slot_info *s)
502 struct audio_format_info *a = afi + s->format;
503 if (a->num_filters == 0)
505 for (i = a->num_filters - 1; i >= 0; i--) {
506 struct filter_node *fn = s->fns + i;
507 const struct filter *f;
511 f = filter_get(fn->filter_num);
514 btr_remove_node(&fn->btrn);
515 task_reap(&fn->task);
521 static void notify_receivers(int error)
526 struct slot_info *s = slot + i;
529 if (!s->receiver_node)
531 task_notify(s->receiver_node->task, error);
535 static int get_empty_slot(void)
546 if (s->wns || s->receiver_node || s->fns)
551 return -E_NO_MORE_SLOTS;
554 static void open_filters(struct slot_info *s)
556 struct audio_format_info *a = afi + s->format;
557 struct filter_node *fn;
558 int nf = a->num_filters;
559 struct btr_node *parent;
564 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
565 assert(s->fns == NULL);
566 s->fns = zalloc(nf * sizeof(struct filter_node));
567 parent = s->receiver_node->btrn;
568 for (i = 0; i < nf; i++) {
571 const struct filter *f = filter_get(a->filter_nums[i]);
573 fn->filter_num = a->filter_nums[i];
574 fn->conf = a->filter_conf[i];
575 fn->lpr = a->filter_lpr[i];
576 name = filter_name(fn->filter_num);
577 fn->btrn = btr_new_node(&(struct btr_node_description)
578 EMBRACE(.name = name, .parent = parent,
579 .handler = f->execute, .context = fn));
583 sprintf(buf, "%s (slot %d)", name, (int)(s - slot));
584 fn->task = task_register(&(struct task_info) {
586 .pre_monitor = f->pre_monitor,
587 .post_monitor = f->post_monitor,
591 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
592 audio_formats[s->format], i, nf, name, (int)(s - slot));
596 static void open_writers(struct slot_info *s)
599 struct audio_format_info *a = afi + s->format;
600 struct writer_node *wn;
601 struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
603 assert(s->wns == NULL);
604 s->wns = zalloc(PARA_MAX(1U, a->num_writers)
605 * sizeof(struct writer_node));
606 for (i = 0; i < a->num_writers; i++) {
608 wn->wid = a->wids[i];
609 wn->lpr = a->writer_lpr[i];
610 register_writer_node(wn, parent, &sched);
611 PARA_NOTICE_LOG("%s writer started in slot %d\n",
612 writer_name(a->wids[i]), (int)(s - slot));
616 /* returns slot num on success */
617 static int open_receiver(int format)
619 struct audio_format_info *a = &afi[format];
622 const struct receiver *r = RECEIVER(a);
623 const char *name = lls_command_name(RECEIVER_CMD(a));
624 struct receiver_node *rn;
626 tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
627 ret = get_empty_slot();
631 rn = zalloc(sizeof(*rn));
633 rn->lpr = a->receiver_lpr;
634 rn->btrn = btr_new_node(&(struct btr_node_description)
635 EMBRACE(.name = name, .context = rn));
638 PARA_ERROR_LOG("could not open %s receiver\n", name);
639 btr_remove_node(&rn->btrn);
645 s->receiver_node = rn;
646 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
647 audio_formats[format], name, slot_num);
648 rn->task = task_register(&(struct task_info) {
650 .pre_monitor = r->pre_monitor,
651 .post_monitor = r->post_monitor,
657 static bool receiver_running(void)
660 long unsigned ss1 = stat_task->server_stream_start.tv_sec;
663 struct slot_info *s = &slot[i];
664 long unsigned ss2 = s->server_stream_start.tv_sec;
666 if (!s->receiver_node)
668 if (task_status(s->receiver_node->task) >= 0)
677 * Return the root node of the current buffer tree.
679 * This is only used for stream grabbing.
681 * \return \p NULL if no slot is currently active. If more than one buffer tree
682 * exists, the node corresponding to the most recently started receiver is
685 struct btr_node *audiod_get_btr_root(void)
687 int i, newest_slot = -1;
688 struct timeval newest_rstime = {0, 0};
691 struct slot_info *s = &slot[i];
692 struct timeval rstime;
693 if (!s->receiver_node)
695 if (task_status(s->receiver_node->task) < 0)
697 btr_get_node_start(s->receiver_node->btrn, &rstime);
698 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
700 newest_rstime = rstime;
703 if (newest_slot == -1)
705 return slot[newest_slot].receiver_node->btrn;
708 /* whether a new instance of a decoder should be started. */
709 static bool must_start_decoder(void)
711 int cafn = stat_task->current_audio_format_num;
712 unsigned vs = stat_task->vss_status;
714 if (audiod_status != AUDIOD_ON)
720 if (vs & VSS_STATUS_FLAG_NEXT)
722 if (!(vs & VSS_STATUS_FLAG_PLAYING))
724 if (receiver_running())
726 if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
731 static void compute_time_diff(const struct timeval *status_time)
733 struct timeval tmp, diff;
734 static unsigned count;
735 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
736 const struct timeval max_deviation = {0, 500 * 1000};
737 const int time_smooth = 5;
739 sign = tv_diff(status_time, now, &diff);
740 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
741 // sign, sa_time_diff_sign);
743 sa_time_diff_sign = sign;
744 stat_task->sa_time_diff = diff;
749 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
750 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
751 PARA_WARNING_LOG("time diff jump: %c%lums\n",
752 s < 0? '-' : '+', tv2ms(&tmp));
755 sa_time_diff_sign = tv_convex_combination(
756 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
757 count > 10? sign : sign * time_smooth, &diff,
759 stat_task->sa_time_diff = tmp;
760 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
763 sa_time_diff_sign < 0? "-" : "+",
764 tv2ms(&stat_task->sa_time_diff)
767 stat_task->sa_time_diff_sign = sa_time_diff_sign;
770 static int update_item(int itemnum, char *buf)
772 long unsigned sec, usec;
774 if (stat_task->clock_diff_count && itemnum != SI_current_time)
776 free(stat_item_values[itemnum]);
777 stat_item_values[itemnum] = para_strdup(buf);
778 stat_client_write_item(itemnum);
780 case SI_status_flags:
781 stat_task->vss_status = 0;
782 if (strchr(buf, 'N'))
783 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
784 if (strchr(buf, 'P'))
785 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
788 stat_task->offset_seconds = atoi(buf);
790 case SI_seconds_total:
791 stat_task->length_seconds = atoi(buf);
793 case SI_stream_start:
794 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
795 stat_task->server_stream_start.tv_sec = sec;
796 stat_task->server_stream_start.tv_usec = usec;
799 case SI_current_time:
800 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
801 struct timeval tv = {sec, usec};
802 compute_time_diff(&tv);
806 stat_task->current_audio_format_num
807 = get_audio_format_num(buf);
812 static int parse_stream_command(const char *txt, const char **cmd)
815 char *re, *p = strchr(txt, ':');
818 return -E_MISSING_COLON;
822 strncpy(re, txt, len);
824 ret = get_matching_audio_format_nums(re);
829 static int add_filter(int format, const char *cmdline)
831 struct audio_format_info *a = &afi[format];
832 int filter_num, nf = a->num_filters;
834 struct lls_parse_result *flpr;
836 filter_num = filter_setup(cmdline, &cfg, &flpr);
837 a->filter_lpr = arr_realloc(a->filter_lpr, nf + 1, sizeof(flpr));
838 a->filter_conf = arr_realloc(a->filter_conf, nf + 1, sizeof(void *));
839 a->filter_nums = arr_realloc(a->filter_nums, nf + 1, sizeof(unsigned));
841 a->filter_nums[nf] = filter_num;
842 a->filter_conf[nf] = cfg;
843 a->filter_lpr[nf] = flpr;
845 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
846 filter_name(filter_num));
850 static int parse_writer_args(void)
854 struct audio_format_info *a;
856 for (i = 0; i < OPT_GIVEN(WRITER); i++) {
859 ret = parse_stream_command(lls_string_val(i,
860 OPT_RESULT(WRITER)), &cmd);
864 FOR_EACH_AUDIO_FORMAT(j) {
866 if ((af_mask & (1 << j)) == 0) /* no match */
869 a->wids = para_realloc(a->wids, (nw + 1) * sizeof(int));
870 a->writer_lpr = para_realloc(a->writer_lpr,
871 (nw + 1) * sizeof(struct lls_parse_result *));
872 a->wids[nw] = check_writer_arg_or_die(cmd,
874 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
875 nw, writer_name(a->wids[nw]));
879 /* Use default writer for audio formats which are not yet set up. */
880 FOR_EACH_AUDIO_FORMAT(i) {
882 if (a->num_writers > 0)
883 continue; /* already set up */
885 a->wids = alloc(sizeof(int));
886 a->writer_lpr = alloc(sizeof(struct lls_parse_result *));
887 a->wids[0] = check_writer_arg_or_die(NULL, a->writer_lpr);
888 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
889 writer_name(a->wids[0]));
894 static int parse_receiver_args(void)
898 struct audio_format_info *a;
900 FOR_EACH_AUDIO_FORMAT(i)
901 afi[i].receiver_num = -1;
902 for (i = OPT_GIVEN(RECEIVER) - 1; i >= 0; i--) {
905 ret = parse_stream_command(lls_string_val(i,
906 OPT_RESULT(RECEIVER)), &arg);
910 FOR_EACH_AUDIO_FORMAT(j) {
912 if ((af_mask & (1 << j)) == 0) /* no match */
915 * If multiple receivers are given for this audio format, the
916 * last one wins and we have to free the previous receiver
917 * config here. Since we are iterating backwards, the winning
918 * receiver arg is in fact the first one given.
920 lls_free_parse_result(a->receiver_lpr, RECEIVER_CMD(a));
921 a->receiver_num = check_receiver_arg(arg, &a->receiver_lpr);
925 * Use the default receiver for those audio formats for which no
926 * receiver was specified.
928 FOR_EACH_AUDIO_FORMAT(i) {
930 if (a->receiver_num >= 0)
932 a->receiver_num = check_receiver_arg(NULL, &a->receiver_lpr);
934 FOR_EACH_AUDIO_FORMAT(i) {
936 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
937 audio_formats[i], lls_command_name(RECEIVER_CMD(a)));
944 static int init_default_filters(void)
948 FOR_EACH_AUDIO_FORMAT(i) {
949 struct audio_format_info *a = &afi[i];
950 const char *name = lls_command_name(RECEIVER_CMD(a));
955 continue; /* no default -- nothing to to */
957 * udp and dccp streams are fec-encoded, so add fecdec as the
960 if (strcmp(name, "udp") == 0 || strcmp(name, "dccp") == 0) {
961 tmp = para_strdup("fecdec");
962 ret = add_filter(i, tmp);
967 /* add "dec" to audio format name */
968 tmp = make_message("%sdec", audio_formats[i]);
969 for (j = 1; filter_get(j); j++)
970 if (!strcmp(tmp, filter_name(j)))
973 ret = -E_UNSUPPORTED_FILTER;
976 tmp = para_strdup(filter_name(j));
977 ret = add_filter(i, tmp);
981 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
988 static int parse_filter_args(void)
990 int i, j, ret, af_mask, num_matches;
992 for (i = 0; i < OPT_GIVEN(FILTER); i++) {
994 ret = parse_stream_command(lls_string_val(i,
995 OPT_RESULT(FILTER)), &arg);
1000 FOR_EACH_AUDIO_FORMAT(j) {
1001 if ((af_mask & (1 << j)) == 0) /* no match */
1003 ret = add_filter(j, arg);
1008 if (num_matches == 0)
1009 PARA_WARNING_LOG("ignoring filter spec: %s\n",
1010 lls_string_val(i, OPT_RESULT(FILTER)));
1012 ret = init_default_filters(); /* use default values for the rest */
1017 static int parse_stream_args(void)
1021 ret = parse_receiver_args();
1024 ret = parse_filter_args();
1027 ret = parse_writer_args();
1033 /* does not unlink socket on errors */
1034 static void init_local_socket(struct command_task *ct)
1036 if (OPT_GIVEN(SOCKET))
1037 socket_name = para_strdup(OPT_STRING_VAL(SOCKET));
1039 char *hn = para_hostname();
1040 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1044 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1045 if (OPT_GIVEN(FORCE))
1046 unlink(socket_name);
1047 ct->fd = create_local_socket(socket_name);
1050 PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd));
1054 static int signal_post_monitor(struct sched *s, void *context)
1056 struct signal_task *st = context;
1059 ret = task_get_notification(st->task);
1062 signum = para_next_signal();
1067 PARA_WARNING_LOG("terminating on signal %d\n", signum);
1068 task_notify_all(s, E_AUDIOD_SIGNAL);
1069 return -E_AUDIOD_SIGNAL;
1074 static void command_pre_monitor(struct sched *s, void *context)
1076 struct command_task *ct = context;
1077 sched_monitor_readfd(ct->fd, s);
1080 static int command_post_monitor(struct sched *s, void *context)
1083 struct command_task *ct = context;
1084 static struct timeval last_status_dump;
1085 struct timeval tmp, delay;
1088 ret = task_get_notification(ct->task);
1091 ret = dispatch_local_connection(ct->fd);
1093 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1094 if (ret == -E_AUDIOD_TERM) {
1095 task_notify_all(s, -ret);
1103 /* if last status dump was less than 500ms ago, do nothing */
1105 delay.tv_usec = 500 * 1000;
1106 tv_add(&last_status_dump, &delay, &tmp);
1107 if (tv_diff(now, &tmp, NULL) < 0)
1111 * If last status dump was more than 5s ago, force update. Otherwise,
1112 * update only those items that have changed.
1116 tv_add(&last_status_dump, &delay, &tmp);
1117 if (tv_diff(now, &tmp, NULL) > 0)
1120 audiod_status_dump(force);
1121 last_status_dump = *now;
1125 static void init_command_task(struct command_task *ct)
1127 init_local_socket(ct); /* doesn't return on errors */
1129 ct->task = task_register(&(struct task_info) {
1131 .pre_monitor = command_pre_monitor,
1132 .post_monitor = command_post_monitor,
1137 static void close_stat_pipe(void)
1141 task_reap(&stat_task->ct->task);
1142 client_close(stat_task->ct);
1143 stat_task->ct = NULL;
1144 clear_and_dump_items();
1145 stat_task->length_seconds = 0;
1146 stat_task->offset_seconds = 0;
1147 stat_task->vss_status = 0;
1148 stat_task->current_audio_format_num = -1;
1149 audiod_status_dump(true);
1152 /* avoid busy loop if server is down */
1153 static void set_stat_task_restart_barrier(unsigned seconds)
1155 struct timeval delay = {seconds, 0};
1156 tv_add(now, &delay, &stat_task->restart_barrier);
1159 static bool must_close_slot(int slot_num)
1161 struct slot_info *s = &slot[slot_num];
1162 struct audio_format_info *a = afi + s->format;
1167 if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1169 for (i = 0; i < a->num_filters; i++)
1170 if (s->fns && task_status(s->fns[i].task) >= 0)
1172 if (a->num_writers > 0) {
1173 for (i = 0; i < a->num_writers; i++)
1174 if (s->wns && task_status(s->wns[i].task) >= 0)
1177 if (s->wns && task_status(s->wns[0].task) >= 0)
1183 static void close_slot(int slot_num)
1185 struct slot_info *s = slot + slot_num;
1187 PARA_INFO_LOG("closing slot %d\n", slot_num);
1190 close_receiver(slot_num);
1191 clear_slot(slot_num);
1194 static void close_unused_slots(void)
1200 if (must_close_slot(i)) {
1205 audiod_status_dump(true);
1209 * Cleanup all resources.
1211 * This performs various cleanups, removes the audiod socket and closes the
1212 * connection to para_server.
1214 static void audiod_cleanup(void)
1217 unlink(socket_name);
1219 close_unused_slots();
1220 close_stat_clients();
1221 free(uid_whitelist);
1225 * Check if any receivers/filters/writers need to be started and do so if
1228 static void start_stop_decoders(void)
1231 struct slot_info *sl;
1233 close_unused_slots();
1234 if (audiod_status != AUDIOD_ON)
1235 return notify_writers(E_NOT_PLAYING);
1236 if (!(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1237 return notify_receivers(E_NOT_PLAYING);
1238 if (!must_start_decoder())
1240 ret = open_receiver(stat_task->current_audio_format_num);
1242 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1248 activate_grab_clients(&sched);
1249 btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1250 audiod_status_dump(true);
1253 static void status_pre_monitor(struct sched *s, void *context)
1255 struct status_task *st = context;
1256 int i, ret, cafn = stat_task->current_audio_format_num;
1258 if (must_start_decoder())
1261 if (must_close_slot(i))
1263 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1266 if (st->ct && audiod_status == AUDIOD_OFF)
1268 if (!st->ct && audiod_status != AUDIOD_OFF)
1269 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1271 sched_request_barrier(&afi[cafn].restart_barrier, s);
1273 * If para_server is playing we'd like to have a smooth time display
1274 * even if we are running in standby mode. So we request a timeout that
1275 * expires at the next full second.
1277 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1278 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1284 /* restart the client task if necessary */
1285 static int status_post_monitor(struct sched *s, void *context)
1287 struct status_task *st = context;
1290 ret = task_get_notification(st->task);
1293 if (audiod_status == AUDIOD_OFF) {
1296 if (task_status(st->ct->task) >= 0) {
1297 task_notify(st->ct->task, E_AUDIOD_OFF);
1301 st->clock_diff_count = OPT_UINT32_VAL(CLOCK_DIFF_COUNT);
1308 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1313 if (st->ct->status != CL_EXECUTING)
1316 struct timeval diff;
1317 tv_diff(now, &st->last_status_read, &diff);
1318 if (diff.tv_sec > 61)
1319 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1322 btr_merge(st->btrn, st->min_iqs);
1323 sz = btr_next_buffer(st->btrn, &buf);
1324 ret = for_each_stat_item(buf, sz, update_item);
1326 task_notify(st->ct->task, -ret);
1330 btr_consume(st->btrn, sz - ret);
1331 st->last_status_read = *now;
1333 } else /* current status item crosses buffers */
1334 st->min_iqs = sz + 1;
1337 btr_drain(st->btrn);
1338 st->current_audio_format_num = -1;
1339 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1341 if (st->clock_diff_count) { /* get status only one time */
1342 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1344 PARA_INFO_LOG("clock diff count: %u\n", st->clock_diff_count);
1345 st->clock_diff_count--;
1346 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1347 set_stat_task_restart_barrier(2);
1350 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1352 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1353 set_stat_task_restart_barrier(5);
1355 free(stat_item_values[SI_basename]);
1356 stat_item_values[SI_basename] = para_strdup(
1357 "no connection to para_server");
1358 stat_client_write_item(SI_basename);
1359 st->last_status_read = *now;
1361 start_stop_decoders();
1365 static void init_status_task(struct status_task *st)
1367 memset(st, 0, sizeof(struct status_task));
1368 st->sa_time_diff_sign = 1;
1369 st->clock_diff_count = OPT_UINT32_VAL(CLOCK_DIFF_COUNT);
1370 st->current_audio_format_num = -1;
1371 st->btrn = btr_new_node(&(struct btr_node_description)
1372 EMBRACE(.name = "stat"));
1374 stat_task->task = task_register(&(struct task_info) {
1376 .pre_monitor = status_pre_monitor,
1377 .post_monitor = status_post_monitor,
1378 .context = stat_task,
1382 static void set_initial_status(void)
1384 audiod_status = AUDIOD_ON;
1385 if (!OPT_GIVEN(MODE))
1387 if (!strcmp(OPT_STRING_VAL(MODE), "sb")) {
1388 audiod_status = AUDIOD_STANDBY;
1391 if (!strcmp(OPT_STRING_VAL(MODE), "off")) {
1392 audiod_status = AUDIOD_OFF;
1395 if (strcmp(OPT_STRING_VAL(MODE), "on"))
1396 PARA_WARNING_LOG("invalid mode\n");
1400 * Lookup the given UID in the whitelist.
1402 * The whitelist is the array of arguments to the --user-allow opion. If the
1403 * option was not given, the array is empty, in which case the check succeeds.
1405 * \param uid User ID to look up.
1407 * \return True if --user-allow was not given, or if uid matches an element of
1410 bool uid_is_whitelisted(uid_t uid)
1414 if (!OPT_GIVEN(USER_ALLOW))
1416 for (i = 0; i < OPT_GIVEN(USER_ALLOW); i++)
1417 if (uid == uid_whitelist[i])
1422 static void handle_help_flags(void)
1425 bool d = OPT_GIVEN(DETAILED_HELP);
1428 help = lls_long_help(CMD_PTR);
1429 else if (OPT_GIVEN(HELP))
1430 help = lls_short_help(CMD_PTR);
1433 printf("%s\n", help);
1435 print_receiver_helps(d);
1436 print_filter_helps(d);
1437 print_writer_helps(d);
1442 * the main function of para_audiod
1444 * \param argc usual argument count
1445 * \param argv usual argument vector
1447 * \return EXIT_SUCCESS or EXIT_FAILURE
1449 * \sa para_audiod(1)
1451 int main(int argc, char *argv[])
1454 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1458 ret = lls(lls_parse(argc, argv, CMD_PTR, &lpr, &errctx));
1461 daemon_set_loglevel(OPT_UINT32_VAL(LOGLEVEL));
1462 daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
1463 OPT_STRING_VAL(GROUP));
1464 version_handle_flag("audiod", OPT_GIVEN(VERSION));
1465 handle_help_flags();
1466 parse_config_or_die();
1468 daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
1469 if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
1470 COLOR_NO, OPT_GIVEN(LOGFILE))) {
1471 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
1472 daemon_set_log_color_or_die(lls_string_val(i,
1473 OPT_RESULT(LOG_COLOR)));
1475 daemon_set_flag(DF_LOG_TIME);
1476 daemon_set_flag(DF_LOG_HOSTNAME);
1477 daemon_set_flag(DF_LOG_LL);
1478 if (OPT_GIVEN(LOG_TIMING))
1479 daemon_set_flag(DF_LOG_TIMING);
1480 if (OPT_GIVEN(LOGFILE)) {
1481 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
1482 daemon_open_log_or_die();
1484 ret = parse_stream_args();
1486 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1489 daemon_log_welcome("audiod");
1490 daemon_set_start_time();
1491 set_initial_status();
1494 setup_signal_handling();
1496 init_status_task(stat_task);
1497 init_command_task(cmd_task);
1499 if (OPT_GIVEN(DAEMON))
1500 daemonize(false /* parent exits immediately */);
1502 signal_task->task = task_register(&(struct task_info) {
1504 .pre_monitor = signal_pre_monitor,
1505 .post_monitor = signal_post_monitor,
1506 .context = signal_task,
1509 sched.default_timeout = 2999;
1510 ret = schedule(&sched);
1512 sched_shutdown(&sched);
1513 signal_shutdown(signal_task);
1516 lls_free_parse_result(lpr, CMD_PTR);
1518 PARA_ERROR_LOG("%s\n", errctx);
1520 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1521 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;