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"
43 /** Array of error strings. */
46 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
47 /** define the array containing all supported audio formats */
48 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
50 /** Defines how audiod handles one supported audio format. */
51 struct audio_format_info {
52 /** the receiver for this audio format */
54 /** Parsed receiver command line. */
55 struct lls_parse_result *receiver_lpr;
56 /** the number of filters that should be activated for this audio format */
57 unsigned int num_filters;
58 /** Array of filter numbers to be activated. */
59 unsigned *filter_nums;
60 /** Pointer to the array of filter configurations. */
62 /** Parsed filter command line, one parse result per filter. */
63 struct lls_parse_result **filter_lpr;
64 /** the number of filters that should be activated for this audio format */
65 unsigned int num_writers;
66 /** Array of writer IDs to be activated. */
68 /** Parsed writer command line(s) */
69 struct lls_parse_result **writer_lpr;
70 /** do not start receiver/filters/writer before this time */
71 struct timeval restart_barrier;
74 /* Describes one instance of a receiver-filter-writer chain. */
76 /* Number of the audio format in this slot. */
78 /* The stream_start status item announced by para_server. */
79 struct timeval server_stream_start;
80 /* The offset status item announced by para_server. */
81 unsigned offset_seconds;
82 /* The seconds_total status item announced by para_server. */
83 unsigned seconds_total;
84 /* The receiver info associated with this slot. */
85 struct receiver_node *receiver_node;
86 /* The array of filter nodes. */
87 struct filter_node *fns;
88 /* The array of writers attached to the last filter. */
89 struct writer_node *wns;
92 #define RECEIVER_CMD(_a) lls_cmd((_a)->receiver_num, recv_cmd_suite)
93 #define RECEIVER(_a) ((const struct receiver *)lls_user_data(RECEIVER_CMD(_a)))
95 /** Maximal number of simultaneous instances. */
96 #define MAX_STREAM_SLOTS 5
98 /** Iterate over all slots. */
99 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
102 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
103 * be associated with a receiver/filter/writer triple. This array holds all
104 * information on the status of these slots.
106 * \sa struct slot_info
108 struct slot_info slot[MAX_STREAM_SLOTS];
110 /** The vss status flags audiod is interested in. */
111 enum vss_status_flags {
112 /** Whether the 'N' flag is set. */
113 VSS_STATUS_FLAG_NEXT = 1,
114 /** The 'P' flag is set. */
115 VSS_STATUS_FLAG_PLAYING = 2,
119 * The scheduler instance of para_audiod.
121 * This is needed also in audiod_command.c (for the tasks command), so it can
122 * not be made static.
124 struct sched sched = {.max_fileno = 0};
126 /* The task for obtaining para_server's status (para_client stat). */
128 /** The associated task structure of audiod. */
130 /** Client data associated with the stat task. */
131 struct client_task *ct;
132 /** Do not restart client command until this time. */
133 struct timeval restart_barrier;
134 /** Last time we received status data from para_server. */
135 struct timeval last_status_read;
137 /** The offset value announced by para_server. */
139 /** The length of the current audio file as announced by para_server. */
141 /** The start of the current stream from the view of para_server. */
142 struct timeval server_stream_start;
143 /** The average time deviation between para_server and para_audiod. */
144 struct timeval sa_time_diff;
145 /** Whether client time is ahead of server time. */
146 int sa_time_diff_sign;
147 /** The 'P' and the 'N' flags as announced by para_server. */
148 enum vss_status_flags vss_status;
149 /** Number of times the clock difference is to be checked. */
150 unsigned clock_diff_count;
151 /** When to start the next check for clock difference. */
152 struct timeval clock_diff_barrier;
153 /** Number of the audio format as announced by para_server. */
154 int current_audio_format_num;
155 /* The status task btrn is the child of the client task. */
156 struct btr_node *btrn;
159 /** The array of status items sent by para_server. */
160 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
163 * the current mode of operation of which can be changed by the on/off/cycle
164 * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
166 int audiod_status = AUDIOD_ON;
169 * the gengetopt args_info struct that holds information on all command line
172 static struct audiod_args_info conf;
174 static char *socket_name;
175 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
177 static struct signal_task *signal_task;
179 static struct status_task status_task_struct;
181 static uid_t *uid_whitelist;
184 * the task that calls the status command of para_server
186 * \sa struct status_task
188 static struct status_task *stat_task = &status_task_struct;
191 * The task for handling audiod commands.
193 * We need two listening sockets for backward compability: on Linux systems
194 * fd[0] is an abstract socket (more precisely, a socket bound to an address in
195 * the abstract namespace), and fd[1] is the usual pathname socket. On other
196 * systems, fd[0] is negative, and only the pathname socket is used.
198 * For 0.5.x we accept connections on both sockets to make sure that old
199 * para_audioc versions can still connect. New versions use only the abstract
200 * socket. Hence after v0.6.0 we can go back to a single socket, either an
201 * abstract one (Linux) or a pathname socket (all other systems).
203 struct command_task {
204 /** The local listening sockets. */
206 /** the associated task structure */
210 /** iterate over all supported audio formats */
211 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
214 * Get the audio format number.
216 * \param name The name of the audio format.
218 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
219 * \a name is not a supported audio format.
221 static int get_audio_format_num(const char *name)
225 while (para_isspace(*name))
227 FOR_EACH_AUDIO_FORMAT(i)
228 if (!strcmp(name, audio_formats[i]))
230 return -E_UNSUPPORTED_AUDIO_FORMAT;
234 * Return the flags for the \a decoder_flags status item.
236 * Allocates a string which contains one octal digit per slot. Bit zero (value
237 * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
238 * have the analogous meaning for filter and writer, respectively.
240 * \return String that must be freed by the caller.
242 __malloc char *audiod_get_decoder_flags(void)
245 char flags[MAX_STREAM_SLOTS + 1];
248 struct slot_info *s = &slot[i];
250 if (s->receiver_node)
258 flags[MAX_STREAM_SLOTS] = '\0';
259 return para_strdup(flags);
262 static int get_matching_audio_format_nums(const char *re)
267 ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
271 FOR_EACH_AUDIO_FORMAT(i)
272 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
278 static int get_play_time_slot_num(void)
280 int i, oldest_slot = -1;
281 struct timeval oldest_wstime = {0, 0};
284 struct slot_info *s = &slot[i];
285 struct timeval wstime;
286 if (!s->wns || !s->wns[0].btrn)
288 btr_get_node_start(s->wns[0].btrn, &wstime);
289 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
291 oldest_wstime = wstime;
298 * Compute the play time based on information of the current slot.
300 * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
301 * from the status items received from para_server and the start time of the
302 * (first) writer of the current slot.
304 * It has to take into account that the stream was probably not started at
305 * the beginning of the file, that the clock between the server and the client
306 * host may differ and that playback of the stream was delayed, e.g. because
307 * the prebuffer filter is used in the filter configuration.
309 * If no writer is active, for example because para_audiod runs in standby
310 * mode, an approximation based only on the status items is computed and the
311 * returned string is prefixed with "~".
313 * \return A string that must be freed by the caller.
315 char *get_time_string(void)
317 int ret, seconds = 0, length = stat_task->length_seconds;
318 struct timeval *tmp, sum, sss, /* server stream start */
319 rstime, /* receiver start time */
320 wstime, /* writer start time */
321 wtime, /* now - writer start */
322 rskip; /* receiver start - sss */
323 int slot_num = get_play_time_slot_num();
324 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
327 if (audiod_status == AUDIOD_OFF)
329 if (stat_task->server_stream_start.tv_sec == 0) {
330 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
331 goto out; /* server is about to change file */
332 if (length > 0) /* paused */
334 goto empty; /* stopped */
337 * Valid status items and playing, set length and tmp to the stream
338 * start. We use the slot info and fall back to the info from current
339 * status items if no slot info is available.
341 tmp = &stat_task->server_stream_start;
342 if (s && s->wns && s->wns[0].btrn) { /* writer active in this slot */
343 btr_get_node_start(s->wns[0].btrn, &wstime);
344 if (wstime.tv_sec != 0) { /* writer wrote something */
345 if (s->server_stream_start.tv_sec == 0) {
346 /* copy status info to slot */
347 s->server_stream_start = stat_task->server_stream_start;
348 s->offset_seconds = stat_task->offset_seconds;
349 s->seconds_total = stat_task->length_seconds;
351 length = s->seconds_total;
352 tmp = &s->server_stream_start;
355 if (stat_task->sa_time_diff_sign > 0)
356 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
358 tv_add(tmp, &stat_task->sa_time_diff, &sss);
359 if (!s || !s->wns || !s->wns[0].btrn || wstime.tv_sec == 0) {
361 tv_diff(now, &sss, &diff);
362 seconds = diff.tv_sec + stat_task->offset_seconds;
365 tv_diff(now, &wstime, &wtime);
366 //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
367 seconds = s->offset_seconds;
368 if (s->receiver_node->btrn) {
369 btr_get_node_start(s->receiver_node->btrn, &rstime);
370 ret = tv_diff(&rstime, &sss, &rskip);
371 if (ret > 0 && rskip.tv_sec > 2) {
372 /* audiod was started in the middle of the stream */
373 tv_add(&wtime, &rskip, &sum);
374 seconds += sum.tv_sec;
376 seconds += wtime.tv_sec;
378 seconds += wtime.tv_sec;
380 seconds = PARA_MIN(seconds, length);
381 seconds = PARA_MAX(seconds, 0);
383 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
387 (length - seconds) / 60,
388 (length - seconds) % 60,
389 length? (seconds * 100 + length / 2) / length : 0,
393 //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
396 return para_strdup(NULL);
399 static void parse_config_or_die(void)
403 struct audiod_cmdline_parser_params params = {
407 .check_ambiguity = 0,
411 if (conf.config_file_given)
412 config_file = para_strdup(conf.config_file_arg);
414 char *home = para_homedir();
415 config_file = make_message("%s/.paraslash/audiod.conf", home);
418 ret = file_exists(config_file);
419 if (conf.config_file_given && !ret) {
420 PARA_EMERG_LOG("can not read config file %s\n", config_file);
425 audiod_cmdline_parser_config_file(config_file, &conf, ¶ms);
426 daemon_set_loglevel(conf.loglevel_arg);
429 if (conf.user_allow_given > 0) {
430 uid_whitelist = para_malloc(conf.user_allow_given
432 for (i = 0; i < conf.user_allow_given; i++) {
435 ret = para_atoi32(conf.user_allow_arg[i], &val);
437 uid_whitelist[i] = val;
440 errno = 0; /* see getpwnam(3) */
441 pw = getpwnam(conf.user_allow_arg[i]);
443 PARA_EMERG_LOG("invalid username: %s\n",
444 conf.user_allow_arg[i]);
447 uid_whitelist[i] = pw->pw_uid;
455 static void setup_signal_handling(void)
457 signal_task = signal_init_or_die();
458 para_install_sighandler(SIGINT);
459 para_install_sighandler(SIGTERM);
460 para_install_sighandler(SIGHUP);
461 para_sigaction(SIGPIPE, SIG_IGN);
464 static void clear_slot(int slot_num)
466 struct slot_info *s = &slot[slot_num];
468 PARA_INFO_LOG("clearing slot %d\n", slot_num);
469 memset(s, 0, sizeof(struct slot_info));
473 static void close_receiver(int slot_num)
475 struct slot_info *s = &slot[slot_num];
476 struct audio_format_info *a;
478 if (s->format < 0 || !s->receiver_node)
481 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
482 audio_formats[s->format], slot_num);
483 RECEIVER(a)->close(s->receiver_node);
484 btr_remove_node(&s->receiver_node->btrn);
485 task_reap(&s->receiver_node->task);
486 free(s->receiver_node);
487 s->receiver_node = NULL;
488 stat_task->current_audio_format_num = -1;
489 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
490 &a->restart_barrier);
493 static void writer_cleanup(struct writer_node *wn)
497 PARA_INFO_LOG("closing %s\n", writer_name(wn->wid));
498 writer_get(wn->wid)->close(wn);
499 btr_remove_node(&wn->btrn);
500 task_reap(&wn->task);
503 static void close_writers(struct slot_info *s)
505 struct audio_format_info *a;
512 if (a->num_writers == 0)
513 writer_cleanup(s->wns);
515 for (i = 0; i < a->num_writers; i++)
516 writer_cleanup(s->wns + i);
522 static void close_filters(struct slot_info *s)
525 struct audio_format_info *a = afi + s->format;
526 if (a->num_filters == 0)
528 for (i = a->num_filters - 1; i >= 0; i--) {
529 struct filter_node *fn = s->fns + i;
530 const struct filter *f;
534 f = filter_get(fn->filter_num);
537 btr_remove_node(&fn->btrn);
538 task_reap(&fn->task);
544 static void notify_receivers(int error)
549 struct slot_info *s = slot + i;
552 if (!s->receiver_node)
554 task_notify(s->receiver_node->task, error);
558 static int get_empty_slot(void)
569 if (s->wns || s->receiver_node || s->fns)
574 return -E_NO_MORE_SLOTS;
577 static void open_filters(struct slot_info *s)
579 struct audio_format_info *a = afi + s->format;
580 struct filter_node *fn;
581 int nf = a->num_filters;
582 struct btr_node *parent;
587 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
588 assert(s->fns == NULL);
589 s->fns = para_calloc(nf * sizeof(struct filter_node));
590 parent = s->receiver_node->btrn;
591 for (i = 0; i < nf; i++) {
594 const struct filter *f = filter_get(a->filter_nums[i]);
596 fn->filter_num = a->filter_nums[i];
597 fn->conf = a->filter_conf[i];
598 fn->lpr = a->filter_lpr[i];
599 name = filter_name(fn->filter_num);
600 fn->btrn = btr_new_node(&(struct btr_node_description)
601 EMBRACE(.name = name, .parent = parent,
602 .handler = f->execute, .context = fn));
606 sprintf(buf, "%s (slot %d)", name, (int)(s - slot));
607 fn->task = task_register(&(struct task_info) {
609 .pre_select = f->pre_select,
610 .post_select = f->post_select,
614 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
615 audio_formats[s->format], i, nf, name, (int)(s - slot));
619 static void open_writers(struct slot_info *s)
622 struct audio_format_info *a = afi + s->format;
623 struct writer_node *wn;
624 struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
626 assert(s->wns == NULL);
627 s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
628 * sizeof(struct writer_node));
629 for (i = 0; i < a->num_writers; i++) {
631 wn->wid = a->wids[i];
632 wn->lpr = a->writer_lpr[i];
633 register_writer_node(wn, parent, &sched);
634 PARA_NOTICE_LOG("%s writer started in slot %d\n",
635 writer_name(a->wids[i]), (int)(s - slot));
639 /* returns slot num on success */
640 static int open_receiver(int format)
642 struct audio_format_info *a = &afi[format];
645 const struct receiver *r = RECEIVER(a);
646 const char *name = lls_command_name(RECEIVER_CMD(a));
647 struct receiver_node *rn;
649 tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
650 ret = get_empty_slot();
654 rn = para_calloc(sizeof(*rn));
656 rn->lpr = a->receiver_lpr;
657 rn->btrn = btr_new_node(&(struct btr_node_description)
658 EMBRACE(.name = name, .context = rn));
661 btr_remove_node(&rn->btrn);
667 s->receiver_node = rn;
668 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
669 audio_formats[format], name, slot_num);
670 rn->task = task_register(&(struct task_info) {
672 .pre_select = r->pre_select,
673 .post_select = r->post_select,
679 static bool receiver_running(void)
682 long unsigned ss1 = stat_task->server_stream_start.tv_sec;
685 struct slot_info *s = &slot[i];
686 long unsigned ss2 = s->server_stream_start.tv_sec;
688 if (!s->receiver_node)
690 if (task_status(s->receiver_node->task) >= 0)
699 * Return the root node of the current buffer tree.
701 * This is only used for stream grabbing.
703 * \return \p NULL if no slot is currently active. If more than one buffer tree
704 * exists, the node corresponding to the most recently started receiver is
707 struct btr_node *audiod_get_btr_root(void)
709 int i, newest_slot = -1;
710 struct timeval newest_rstime = {0, 0};
713 struct slot_info *s = &slot[i];
714 struct timeval rstime;
715 if (!s->receiver_node)
717 if (task_status(s->receiver_node->task) < 0)
719 btr_get_node_start(s->receiver_node->btrn, &rstime);
720 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
722 newest_rstime = rstime;
725 if (newest_slot == -1)
727 return slot[newest_slot].receiver_node->btrn;
730 /* whether a new instance of a decoder should be started. */
731 static bool must_start_decoder(void)
733 int cafn = stat_task->current_audio_format_num;
734 unsigned vs = stat_task->vss_status;
736 if (audiod_status != AUDIOD_ON)
742 if (vs & VSS_STATUS_FLAG_NEXT)
744 if (!(vs & VSS_STATUS_FLAG_PLAYING))
746 if (receiver_running())
748 if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
753 static void compute_time_diff(const struct timeval *status_time)
755 struct timeval tmp, diff;
756 static unsigned count;
757 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
758 const struct timeval max_deviation = {0, 500 * 1000};
759 const int time_smooth = 5;
761 sign = tv_diff(status_time, now, &diff);
762 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
763 // sign, sa_time_diff_sign);
765 sa_time_diff_sign = sign;
766 stat_task->sa_time_diff = diff;
771 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
772 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
773 PARA_WARNING_LOG("time diff jump: %lums\n",
777 sa_time_diff_sign = tv_convex_combination(
778 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
779 count > 10? sign : sign * time_smooth, &diff,
781 stat_task->sa_time_diff = tmp;
782 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
785 sa_time_diff_sign < 0? "-" : "+",
786 tv2ms(&stat_task->sa_time_diff)
789 stat_task->sa_time_diff_sign = sa_time_diff_sign;
792 static int update_item(int itemnum, char *buf)
794 long unsigned sec, usec;
796 if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
798 free(stat_item_values[itemnum]);
799 stat_item_values[itemnum] = para_strdup(buf);
800 stat_client_write_item(itemnum);
802 case SI_STATUS_FLAGS:
803 stat_task->vss_status = 0;
804 if (strchr(buf, 'N'))
805 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
806 if (strchr(buf, 'P'))
807 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
810 stat_task->offset_seconds = atoi(buf);
812 case SI_SECONDS_TOTAL:
813 stat_task->length_seconds = atoi(buf);
815 case SI_STREAM_START:
816 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
817 stat_task->server_stream_start.tv_sec = sec;
818 stat_task->server_stream_start.tv_usec = usec;
821 case SI_CURRENT_TIME:
822 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
823 struct timeval tv = {sec, usec};
824 compute_time_diff(&tv);
828 stat_task->current_audio_format_num
829 = get_audio_format_num(buf);
834 static int parse_stream_command(const char *txt, const char **cmd)
837 char *re, *p = strchr(txt, ':');
840 return -E_MISSING_COLON;
843 re = malloc(len + 1);
844 strncpy(re, txt, len);
846 ret = get_matching_audio_format_nums(re);
851 static int add_filter(int format, const char *cmdline)
853 struct audio_format_info *a = &afi[format];
854 int filter_num, nf = a->num_filters;
856 struct lls_parse_result *flpr;
858 filter_num = filter_setup(cmdline, &cfg, &flpr);
859 a->filter_lpr = para_realloc(a->filter_lpr,
860 (nf + 1) * sizeof(flpr));
861 a->filter_conf = para_realloc(a->filter_conf,
862 (nf + 1) * sizeof(void *));
863 a->filter_nums = para_realloc(a->filter_nums,
864 (nf + 1) * sizeof(unsigned));
866 a->filter_nums[nf] = filter_num;
867 a->filter_conf[nf] = cfg;
868 a->filter_lpr[nf] = flpr;
870 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
871 filter_name(filter_num));
875 static int parse_writer_args(void)
879 struct audio_format_info *a;
881 for (i = 0; i < conf.writer_given; i++) {
884 ret = parse_stream_command(conf.writer_arg[i], &cmd);
888 FOR_EACH_AUDIO_FORMAT(j) {
890 if ((af_mask & (1 << j)) == 0) /* no match */
893 a->wids = para_realloc(a->wids, (nw + 1) * sizeof(int));
894 a->writer_lpr = para_realloc(a->writer_lpr,
895 (nw + 1) * sizeof(struct lls_parse_result *));
896 a->wids[nw] = check_writer_arg_or_die(cmd,
898 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
899 nw, writer_name(a->wids[nw]));
903 /* Use default writer for audio formats which are not yet set up. */
904 FOR_EACH_AUDIO_FORMAT(i) {
906 if (a->num_writers > 0)
907 continue; /* already set up */
909 a->wids = para_malloc(sizeof(int));
910 a->writer_lpr = para_malloc(sizeof(struct lls_parse_result *));
911 a->wids[0] = check_writer_arg_or_die(NULL, a->writer_lpr);
912 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
913 writer_name(a->wids[0]));
918 static int parse_receiver_args(void)
922 struct audio_format_info *a;
924 FOR_EACH_AUDIO_FORMAT(i)
925 afi[i].receiver_num = -1;
926 for (i = conf.receiver_given - 1; i >= 0; i--) {
929 ret = parse_stream_command(conf.receiver_arg[i], &arg);
933 FOR_EACH_AUDIO_FORMAT(j) {
935 if ((af_mask & (1 << j)) == 0) /* no match */
938 * If multiple receivers are given for this audio format, the
939 * last one wins and we have to free the previous receiver
940 * config here. Since we are iterating backwards, the winning
941 * receiver arg is in fact the first one given.
943 lls_free_parse_result(a->receiver_lpr, RECEIVER_CMD(a));
944 a->receiver_num = check_receiver_arg(arg, &a->receiver_lpr);
948 * Use the default receiver for those audio formats for which no
949 * receiver was specified.
951 FOR_EACH_AUDIO_FORMAT(i) {
953 if (a->receiver_num >= 0)
955 a->receiver_num = check_receiver_arg(NULL, &a->receiver_lpr);
957 FOR_EACH_AUDIO_FORMAT(i) {
959 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
960 audio_formats[i], lls_command_name(RECEIVER_CMD(a)));
967 static int init_default_filters(void)
971 FOR_EACH_AUDIO_FORMAT(i) {
972 struct audio_format_info *a = &afi[i];
973 const char *name = lls_command_name(RECEIVER_CMD(a));
978 continue; /* no default -- nothing to to */
980 * udp and dccp streams are fec-encoded, so add fecdec as the
983 if (strcmp(name, "udp") == 0 || strcmp(name, "dccp") == 0) {
984 tmp = para_strdup("fecdec");
990 /* add "dec" to audio format name */
991 tmp = make_message("%sdec", audio_formats[i]);
992 for (j = 0; filter_get(j); j++)
993 if (!strcmp(tmp, filter_name(j)))
996 ret = -E_UNSUPPORTED_FILTER;
999 tmp = para_strdup(filter_name(j));
1000 ret = add_filter(i, tmp);
1004 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1011 static int parse_filter_args(void)
1013 int i, j, ret, af_mask, num_matches;
1015 for (i = 0; i < conf.filter_given; i++) {
1017 ret = parse_stream_command(conf.filter_arg[i], &arg);
1022 FOR_EACH_AUDIO_FORMAT(j) {
1023 if ((af_mask & (1 << j)) == 0) /* no match */
1025 ret = add_filter(j, arg);
1030 if (num_matches == 0)
1031 PARA_WARNING_LOG("ignoring filter spec: %s\n",
1032 conf.filter_arg[i]);
1034 ret = init_default_filters(); /* use default values for the rest */
1039 static int parse_stream_args(void)
1043 ret = parse_receiver_args();
1046 ret = parse_filter_args();
1049 ret = parse_writer_args();
1055 /* does not unlink socket on errors */
1056 static void init_local_sockets(struct command_task *ct)
1058 if (conf.socket_given)
1059 socket_name = para_strdup(conf.socket_arg);
1061 char *hn = para_hostname();
1062 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1066 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1067 if (conf.force_given)
1068 unlink(socket_name);
1069 ct->fd[0] = create_local_socket(socket_name, 0);
1070 ct->fd[1] = create_local_socket(socket_name,
1071 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
1072 if (ct->fd[0] >= 0 || ct->fd[1] >= 0)
1074 PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd[1]));
1078 static int signal_post_select(struct sched *s, void *context)
1080 struct signal_task *st = context;
1083 ret = task_get_notification(st->task);
1086 signum = para_next_signal(&s->rfds);
1091 PARA_NOTICE_LOG("received signal %d\n", signum);
1092 task_notify_all(s, E_AUDIOD_SIGNAL);
1093 return -E_AUDIOD_SIGNAL;
1098 static void command_pre_select(struct sched *s, void *context)
1100 struct command_task *ct = context;
1103 for (i = 0; i < 2; i++)
1105 para_fd_set(ct->fd[i], &s->rfds, &s->max_fileno);
1108 static int command_post_select(struct sched *s, void *context)
1111 struct command_task *ct = context;
1112 static struct timeval last_status_dump;
1113 struct timeval tmp, delay;
1116 ret = task_get_notification(ct->task);
1119 for (i = 0; i < 2; i++) {
1122 ret = handle_connect(ct->fd[i], &s->rfds);
1124 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1125 if (ret == -E_AUDIOD_TERM) {
1126 task_notify_all(s, -ret);
1135 /* if last status dump was less than 500ms ago, do nothing */
1137 delay.tv_usec = 500 * 1000;
1138 tv_add(&last_status_dump, &delay, &tmp);
1139 if (tv_diff(now, &tmp, NULL) < 0)
1143 * If last status dump was more than 5s ago, force update. Otherwise,
1144 * update only those items that have changed.
1148 tv_add(&last_status_dump, &delay, &tmp);
1149 if (tv_diff(now, &tmp, NULL) > 0)
1152 audiod_status_dump(force);
1153 last_status_dump = *now;
1157 static void init_command_task(struct command_task *ct)
1159 init_local_sockets(ct); /* doesn't return on errors */
1161 ct->task = task_register(&(struct task_info) {
1163 .pre_select = command_pre_select,
1164 .post_select = command_post_select,
1169 static void close_stat_pipe(void)
1173 task_reap(&stat_task->ct->task);
1174 client_close(stat_task->ct);
1175 stat_task->ct = NULL;
1176 clear_and_dump_items();
1177 stat_task->length_seconds = 0;
1178 stat_task->offset_seconds = 0;
1179 stat_task->vss_status = 0;
1180 stat_task->current_audio_format_num = -1;
1181 audiod_status_dump(true);
1184 /* avoid busy loop if server is down */
1185 static void set_stat_task_restart_barrier(unsigned seconds)
1187 struct timeval delay = {seconds, 0};
1188 tv_add(now, &delay, &stat_task->restart_barrier);
1191 static bool must_close_slot(int slot_num)
1193 struct slot_info *s = &slot[slot_num];
1194 struct audio_format_info *a = afi + s->format;
1199 if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1201 for (i = 0; i < a->num_filters; i++)
1202 if (s->fns && task_status(s->fns[i].task) >= 0)
1204 if (a->num_writers > 0) {
1205 for (i = 0; i < a->num_writers; i++)
1206 if (s->wns && task_status(s->wns[i].task) >= 0)
1209 if (s->wns && task_status(s->wns[0].task) >= 0)
1215 static void close_slot(int slot_num)
1217 struct slot_info *s = slot + slot_num;
1219 PARA_INFO_LOG("closing slot %d\n", slot_num);
1222 close_receiver(slot_num);
1223 clear_slot(slot_num);
1226 static void close_unused_slots(void)
1232 if (must_close_slot(i)) {
1237 audiod_status_dump(true);
1241 * Cleanup all resources.
1243 * This performs various cleanups, removes the audiod socket and closes the
1244 * connection to para_server.
1246 static void audiod_cleanup(void)
1249 unlink(socket_name);
1251 close_unused_slots();
1252 audiod_cmdline_parser_free(&conf);
1253 close_stat_clients();
1254 free(uid_whitelist);
1258 * Check if any receivers/filters/writers need to be started and do so if
1261 static void start_stop_decoders(void)
1264 struct slot_info *sl;
1266 close_unused_slots();
1267 if (audiod_status != AUDIOD_ON ||
1268 !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1269 return notify_receivers(E_NOT_PLAYING);
1270 if (!must_start_decoder())
1272 ret = open_receiver(stat_task->current_audio_format_num);
1274 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1280 activate_grab_clients(&sched);
1281 btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1282 audiod_status_dump(true);
1285 static void status_pre_select(struct sched *s, void *context)
1287 struct status_task *st = context;
1288 int i, ret, cafn = stat_task->current_audio_format_num;
1290 if (must_start_decoder())
1293 if (must_close_slot(i))
1295 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1298 if (st->ct && audiod_status == AUDIOD_OFF)
1300 if (!st->ct && audiod_status != AUDIOD_OFF)
1301 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1303 sched_request_barrier(&afi[cafn].restart_barrier, s);
1305 * If para_server is playing we'd like to have a smooth time display
1306 * even if we are running in standby mode. So we request a timeout that
1307 * expires at the next full second.
1309 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1310 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1316 /* restart the client task if necessary */
1317 static int status_post_select(struct sched *s, void *context)
1319 struct status_task *st = context;
1322 ret = task_get_notification(st->task);
1325 if (audiod_status == AUDIOD_OFF) {
1328 if (task_status(st->ct->task) >= 0) {
1329 task_notify(st->ct->task, E_AUDIOD_OFF);
1333 st->clock_diff_count = conf.clock_diff_count_arg;
1340 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1345 if (st->ct->status != CL_EXECUTING)
1348 struct timeval diff;
1349 tv_diff(now, &st->last_status_read, &diff);
1350 if (diff.tv_sec > 61)
1351 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1354 btr_merge(st->btrn, st->min_iqs);
1355 sz = btr_next_buffer(st->btrn, &buf);
1356 ret = for_each_stat_item(buf, sz, update_item);
1358 task_notify(st->ct->task, -ret);
1362 btr_consume(st->btrn, sz - ret);
1363 st->last_status_read = *now;
1365 } else /* current status item crosses buffers */
1366 st->min_iqs = sz + 1;
1369 btr_drain(st->btrn);
1370 st->current_audio_format_num = -1;
1371 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1373 if (st->clock_diff_count) { /* get status only one time */
1374 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1376 PARA_INFO_LOG("clock diff count: %u\n", st->clock_diff_count);
1377 st->clock_diff_count--;
1378 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1379 set_stat_task_restart_barrier(2);
1382 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1384 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1385 set_stat_task_restart_barrier(5);
1387 free(stat_item_values[SI_BASENAME]);
1388 stat_item_values[SI_BASENAME] = para_strdup(
1389 "no connection to para_server");
1390 stat_client_write_item(SI_BASENAME);
1391 st->last_status_read = *now;
1393 start_stop_decoders();
1397 static void init_status_task(struct status_task *st)
1399 memset(st, 0, sizeof(struct status_task));
1400 st->sa_time_diff_sign = 1;
1401 st->clock_diff_count = conf.clock_diff_count_arg;
1402 st->current_audio_format_num = -1;
1403 st->btrn = btr_new_node(&(struct btr_node_description)
1404 EMBRACE(.name = "stat"));
1406 stat_task->task = task_register(&(struct task_info) {
1408 .pre_select = status_pre_select,
1409 .post_select = status_post_select,
1410 .context = stat_task,
1414 static void set_initial_status(void)
1416 audiod_status = AUDIOD_ON;
1417 if (!conf.mode_given)
1419 if (!strcmp(conf.mode_arg, "sb")) {
1420 audiod_status = AUDIOD_STANDBY;
1423 if (!strcmp(conf.mode_arg, "off")) {
1424 audiod_status = AUDIOD_OFF;
1427 if (strcmp(conf.mode_arg, "on"))
1428 PARA_WARNING_LOG("invalid mode\n");
1431 __noreturn static void print_help_and_die(void)
1433 struct ggo_help h = DEFINE_GGO_HELP(audiod);
1434 bool d = conf.detailed_help_given;
1437 flags = d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
1438 ggo_print_help(&h, flags);
1440 flags = d? GPH_MODULE_FLAGS_DETAILED : GPH_MODULE_FLAGS;
1441 print_receiver_helps(flags);
1442 print_filter_helps(flags);
1443 print_writer_helps(flags);
1448 * Lookup the given UID in the whitelist.
1450 * The whitelist is the array of arguments to the --user-allow opion. If the
1451 * option was not given, the array is empty, in which case the check succeeds.
1453 * \param uid User ID to look up.
1455 * \return True if --user-allow was not given, or if uid matches an element of
1458 bool uid_is_whitelisted(uid_t uid)
1462 if (!conf.user_allow_given)
1464 for (i = 0; i < conf.user_allow_given; i++)
1465 if (uid == uid_whitelist[i])
1471 * the main function of para_audiod
1473 * \param argc usual argument count
1474 * \param argv usual argument vector
1476 * \return EXIT_SUCCESS or EXIT_FAILURE
1478 * \sa para_audiod(1)
1480 int main(int argc, char *argv[])
1483 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1484 struct audiod_cmdline_parser_params params = {
1487 .check_required = 0,
1488 .check_ambiguity = 0,
1493 audiod_cmdline_parser_ext(argc, argv, &conf, ¶ms);
1494 daemon_set_loglevel(conf.loglevel_arg);
1495 version_handle_flag("audiod", conf.version_given);
1496 /* init receivers/filters/writers early to make help work */
1498 if (conf.help_given || conf.detailed_help_given)
1499 print_help_and_die();
1500 daemon_set_priority(conf.priority_arg);
1501 daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
1502 parse_config_or_die();
1503 if (daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
1504 conf.logfile_given)) {
1505 for (i = 0; i < conf.log_color_given; i++)
1506 daemon_set_log_color_or_die(conf.log_color_arg[i]);
1508 init_random_seed_or_die();
1509 daemon_set_flag(DF_LOG_TIME);
1510 daemon_set_flag(DF_LOG_HOSTNAME);
1511 daemon_set_flag(DF_LOG_LL);
1512 if (conf.log_timing_given)
1513 daemon_set_flag(DF_LOG_TIMING);
1514 if (conf.logfile_given) {
1515 daemon_set_logfile(conf.logfile_arg);
1516 daemon_open_log_or_die();
1518 ret = parse_stream_args();
1520 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1523 daemon_log_welcome("audiod");
1524 daemon_set_start_time();
1525 set_initial_status();
1528 setup_signal_handling();
1530 init_status_task(stat_task);
1531 init_command_task(cmd_task);
1533 if (conf.daemon_given)
1534 daemonize(false /* parent exits immediately */);
1536 signal_task->task = task_register(&(struct task_info) {
1538 .pre_select = signal_pre_select,
1539 .post_select = signal_post_select,
1540 .context = signal_task,
1543 sched.default_timeout.tv_sec = 2;
1544 sched.default_timeout.tv_usec = 999 * 1000;
1545 ret = schedule(&sched);
1547 sched_shutdown(&sched);
1548 signal_shutdown(signal_task);
1551 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1552 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;