2 * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file audiod.c The paraslash's audio daemon. */
9 #include <netinet/in.h>
10 #include <sys/socket.h>
12 #include <sys/types.h>
13 #include <arpa/inet.h>
22 #include "audiod.cmdline.h"
26 #include "buffer_tree.h"
29 #include "grab_client.h"
30 #include "client.cmdline.h"
38 #include "write_common.h"
42 /** Array of error strings. */
45 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
46 /** define the array containing all supported audio formats */
47 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
49 DEFINE_RECEIVER_ARRAY;
51 /** Defines how audiod handles one supported audio format. */
52 struct audio_format_info {
53 /** pointer to the receiver for this audio format */
54 struct receiver *receiver;
55 /** the receiver configuration */
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 /** Maximal number of simultaneous instances. */
92 #define MAX_STREAM_SLOTS 5
94 /** Iterate over all slots. */
95 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
98 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
99 * be associated with a receiver/filter/writer triple. This array holds all
100 * information on the status of these slots.
102 * \sa struct slot_info
104 struct slot_info slot[MAX_STREAM_SLOTS];
106 /** The vss status flags audiod is interested in. */
107 enum vss_status_flags {
108 /** Whether the 'N' flag is set. */
109 VSS_STATUS_FLAG_NEXT = 1,
110 /** The 'P' flag is set. */
111 VSS_STATUS_FLAG_PLAYING = 2,
115 * The scheduler instance of para_audiod.
117 * This is needed also in audiod_command.c (for the tasks command), so it can
118 * not be made static.
120 struct sched sched = {.max_fileno = 0};
122 /* The task for obtaining para_server's status (para_client stat). */
124 /** The associated task structure of audiod. */
126 /** Client data associated with the stat task. */
127 struct client_task *ct;
128 /** Do not restart client command until this time. */
129 struct timeval restart_barrier;
130 /** Last time we received status data from para_server. */
131 struct timeval last_status_read;
133 /** The offset value announced by para_server. */
135 /** The length of the current audio file as announced by para_server. */
137 /** The start of the current stream from the view of para_server. */
138 struct timeval server_stream_start;
139 /** The average time deviation between para_server and para_audiod. */
140 struct timeval sa_time_diff;
141 /** Whether client time is ahead of server time. */
142 int sa_time_diff_sign;
143 /** The 'P' and the 'N' flags as announced by para_server. */
144 enum vss_status_flags vss_status;
145 /** Number of times the clock difference is to be checked. */
146 unsigned clock_diff_count;
147 /** When to start the next check for clock difference. */
148 struct timeval clock_diff_barrier;
149 /** Number of the audio format as announced by para_server. */
150 int current_audio_format_num;
151 /* The status task btrn is the child of the client task. */
152 struct btr_node *btrn;
155 /** The array of status items sent by para_server. */
156 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
159 * the current mode of operation of which can be changed by the on/off/cycle
160 * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
162 int audiod_status = AUDIOD_ON;
165 * the gengetopt args_info struct that holds information on all command line
168 static struct audiod_args_info conf;
170 static char *socket_name;
171 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
173 static struct signal_task *signal_task;
175 static struct status_task status_task_struct;
177 static uid_t *uid_whitelist;
180 * the task that calls the status command of para_server
182 * \sa struct status_task
184 static struct status_task *stat_task = &status_task_struct;
187 * The task for handling audiod commands.
189 * We need two listening sockets for backward compability: on Linux systems
190 * fd[0] is an abstract socket (more precisely, a socket bound to an address in
191 * the abstract namespace), and fd[1] is the usual pathname socket. On other
192 * systems, fd[0] is negative, and only the pathname socket is used.
194 * For 0.5.x we accept connections on both sockets to make sure that old
195 * para_audioc versions can still connect. New versions use only the abstract
196 * socket. Hence after v0.6.0 we can go back to a single socket, either an
197 * abstract one (Linux) or a pathname socket (all other systems).
199 struct command_task {
200 /** The local listening sockets. */
202 /** the associated task structure */
206 /** iterate over all supported audio formats */
207 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
210 * Get the audio format number.
212 * \param name The name of the audio format.
214 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
215 * \a name is not a supported audio format.
217 static int get_audio_format_num(const char *name)
221 while (para_isspace(*name))
223 FOR_EACH_AUDIO_FORMAT(i)
224 if (!strcmp(name, audio_formats[i]))
226 return -E_UNSUPPORTED_AUDIO_FORMAT;
230 * Return the flags for the \a decoder_flags status item.
232 * Allocates a string which contains one octal digit per slot. Bit zero (value
233 * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
234 * have the analogous meaning for filter and writer, respectively.
236 * \return String that must be freed by the caller.
238 __malloc char *audiod_get_decoder_flags(void)
241 char flags[MAX_STREAM_SLOTS + 1];
244 struct slot_info *s = &slot[i];
246 if (s->receiver_node)
254 flags[MAX_STREAM_SLOTS] = '\0';
255 return para_strdup(flags);
258 static int get_matching_audio_format_nums(const char *re)
263 ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
267 FOR_EACH_AUDIO_FORMAT(i)
268 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
274 static int get_play_time_slot_num(void)
276 int i, oldest_slot = -1;
277 struct timeval oldest_wstime = {0, 0};
280 struct slot_info *s = &slot[i];
281 struct timeval wstime;
282 if (!s->wns || !s->wns[0].btrn)
284 btr_get_node_start(s->wns[0].btrn, &wstime);
285 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
287 oldest_wstime = wstime;
294 * Compute the play time based on information of the current slot.
296 * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
297 * from the status items received from para_server and the start time of the
298 * (first) writer of the current slot.
300 * It has to take into account that the stream was probably not started at
301 * the beginning of the file, that the clock between the server and the client
302 * host may differ and that playback of the stream was delayed, e.g. because
303 * the prebuffer filter is used in the filter configuration.
305 * If no writer is active, for example because para_audiod runs in standby
306 * mode, an approximation based only on the status items is computed and the
307 * returned string is prefixed with "~".
309 * \return A string that must be freed by the caller.
311 char *get_time_string(void)
313 int ret, seconds = 0, length = stat_task->length_seconds;
314 struct timeval *tmp, sum, sss, /* server stream start */
315 rstime, /* receiver start time */
316 wstime, /* writer start time */
317 wtime, /* now - writer start */
318 rskip; /* receiver start - sss */
319 int slot_num = get_play_time_slot_num();
320 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
321 bool writer_active = s && s->wns && s->wns[0].btrn;
324 if (audiod_status == AUDIOD_OFF)
326 if (stat_task->server_stream_start.tv_sec == 0) {
327 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
328 goto out; /* server is about to change file */
329 if (length > 0) /* paused */
331 goto empty; /* stopped */
334 * Valid status items and playing, set length and tmp to the stream
335 * start. We use the writer start time from the slot info and fall back
336 * to the info from current status items if no writer is active yet.
338 tmp = &stat_task->server_stream_start;
340 btr_get_node_start(s->wns[0].btrn, &wstime);
341 if (wstime.tv_sec != 0) { /* writer wrote something */
342 if (s->server_stream_start.tv_sec == 0) {
343 /* copy status info to slot */
344 s->server_stream_start = stat_task->server_stream_start;
345 s->offset_seconds = stat_task->offset_seconds;
346 s->seconds_total = stat_task->length_seconds;
348 length = s->seconds_total;
349 tmp = &s->server_stream_start;
352 if (stat_task->sa_time_diff_sign > 0)
353 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
355 tv_add(tmp, &stat_task->sa_time_diff, &sss);
356 if (!writer_active) {
358 tv_diff(now, &sss, &diff);
359 seconds = diff.tv_sec + stat_task->offset_seconds;
362 tv_diff(now, &wstime, &wtime);
363 //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
364 seconds = s->offset_seconds;
365 if (s->receiver_node->btrn) {
366 btr_get_node_start(s->receiver_node->btrn, &rstime);
367 ret = tv_diff(&rstime, &sss, &rskip);
368 if (ret > 0 && rskip.tv_sec > 2) {
369 /* audiod was started in the middle of the stream */
370 tv_add(&wtime, &rskip, &sum);
371 seconds += sum.tv_sec;
373 seconds += wtime.tv_sec;
375 seconds += wtime.tv_sec;
377 seconds = PARA_MIN(seconds, length);
378 seconds = PARA_MAX(seconds, 0);
380 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
384 (length - seconds) / 60,
385 (length - seconds) % 60,
386 length? (seconds * 100 + length / 2) / length : 0,
390 //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
393 return para_strdup(NULL);
396 static void parse_config_or_die(void)
400 struct audiod_cmdline_parser_params params = {
404 .check_ambiguity = 0,
408 if (conf.config_file_given)
409 config_file = para_strdup(conf.config_file_arg);
411 char *home = para_homedir();
412 config_file = make_message("%s/.paraslash/audiod.conf", home);
415 ret = file_exists(config_file);
416 if (conf.config_file_given && !ret) {
417 PARA_EMERG_LOG("can not read config file %s\n", config_file);
422 audiod_cmdline_parser_config_file(config_file, &conf, ¶ms);
423 daemon_set_loglevel(conf.loglevel_arg);
426 if (conf.user_allow_given > 0) {
427 uid_whitelist = para_malloc(conf.user_allow_given
429 for (i = 0; i < conf.user_allow_given; i++) {
432 ret = para_atoi32(conf.user_allow_arg[i], &val);
434 uid_whitelist[i] = val;
437 errno = 0; /* see getpwnam(3) */
438 pw = getpwnam(conf.user_allow_arg[i]);
440 PARA_EMERG_LOG("invalid username: %s\n",
441 conf.user_allow_arg[i]);
444 uid_whitelist[i] = pw->pw_uid;
452 static void setup_signal_handling(void)
454 signal_task = signal_init_or_die();
455 para_install_sighandler(SIGINT);
456 para_install_sighandler(SIGTERM);
457 para_install_sighandler(SIGHUP);
458 para_sigaction(SIGPIPE, SIG_IGN);
461 static void clear_slot(int slot_num)
463 struct slot_info *s = &slot[slot_num];
465 PARA_INFO_LOG("clearing slot %d\n", slot_num);
466 memset(s, 0, sizeof(struct slot_info));
470 static void close_receiver(int slot_num)
472 struct slot_info *s = &slot[slot_num];
473 struct audio_format_info *a;
475 if (s->format < 0 || !s->receiver_node)
478 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
479 audio_formats[s->format], slot_num);
480 a->receiver->close(s->receiver_node);
481 btr_remove_node(&s->receiver_node->btrn);
482 task_reap(&s->receiver_node->task);
483 free(s->receiver_node);
484 s->receiver_node = NULL;
485 stat_task->current_audio_format_num = -1;
486 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
487 &a->restart_barrier);
490 static void writer_cleanup(struct writer_node *wn)
496 w = writers + wn->writer_num;
497 PARA_INFO_LOG("closing %s\n", writer_names[wn->writer_num]);
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++) {
593 const struct filter *f = filter_get(a->filter_nums[i]);
595 fn->filter_num = a->filter_nums[i];
596 fn->conf = a->filter_conf[i];
597 fn->btrn = btr_new_node(&(struct btr_node_description)
598 EMBRACE(.name = f->name, .parent = parent,
599 .handler = f->execute, .context = fn));
603 sprintf(buf, "%s (slot %d)", f->name, (int)(s - slot));
604 fn->task = task_register(&(struct task_info) {
606 .pre_select = f->pre_select,
607 .post_select = f->post_select,
611 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
612 audio_formats[s->format], i, nf, f->name, (int)(s - slot));
616 static void open_writers(struct slot_info *s)
619 struct audio_format_info *a = afi + s->format;
620 struct writer_node *wn;
621 struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
623 assert(s->wns == NULL);
624 s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
625 * sizeof(struct writer_node));
626 for (i = 0; i < a->num_writers; i++) {
628 wn->conf = a->writer_conf[i];
629 wn->writer_num = a->writer_nums[i];
630 register_writer_node(wn, parent, &sched);
631 PARA_NOTICE_LOG("%s writer started in slot %d\n",
632 writer_names[a->writer_nums[i]], (int)(s - slot));
636 /* returns slot num on success */
637 static int open_receiver(int format)
639 struct audio_format_info *a = &afi[format];
642 struct receiver *r = a->receiver;
643 struct receiver_node *rn;
645 tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
646 ret = get_empty_slot();
650 rn = para_calloc(sizeof(*rn));
652 rn->conf = a->receiver_conf;
653 rn->btrn = btr_new_node(&(struct btr_node_description)
654 EMBRACE(.name = r->name, .context = rn));
657 btr_remove_node(&rn->btrn);
663 s->receiver_node = rn;
664 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
665 audio_formats[format], r->name, slot_num);
666 rn->task = task_register(&(struct task_info) {
668 .pre_select = r->pre_select,
669 .post_select = r->post_select,
675 static bool receiver_running(void)
678 long unsigned ss1 = stat_task->server_stream_start.tv_sec;
681 struct slot_info *s = &slot[i];
682 long unsigned ss2 = s->server_stream_start.tv_sec;
684 if (!s->receiver_node)
686 if (task_status(s->receiver_node->task) >= 0)
695 * Return the root node of the current buffer tree.
697 * This is only used for stream grabbing.
699 * \return \p NULL if no slot is currently active. If more than one buffer tree
700 * exists, the node corresponding to the most recently started receiver is
703 struct btr_node *audiod_get_btr_root(void)
705 int i, newest_slot = -1;
706 struct timeval newest_rstime = {0, 0};
709 struct slot_info *s = &slot[i];
710 struct timeval rstime;
711 if (!s->receiver_node)
713 if (task_status(s->receiver_node->task) < 0)
715 btr_get_node_start(s->receiver_node->btrn, &rstime);
716 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
718 newest_rstime = rstime;
721 if (newest_slot == -1)
723 return slot[newest_slot].receiver_node->btrn;
726 /* whether a new instance of a decoder should be started. */
727 static bool must_start_decoder(void)
729 int cafn = stat_task->current_audio_format_num;
730 unsigned vs = stat_task->vss_status;
732 if (audiod_status != AUDIOD_ON)
738 if (vs & VSS_STATUS_FLAG_NEXT)
740 if (!(vs & VSS_STATUS_FLAG_PLAYING))
742 if (receiver_running())
744 if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
749 static void compute_time_diff(const struct timeval *status_time)
751 struct timeval tmp, diff;
752 static unsigned count;
753 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
754 const struct timeval max_deviation = {0, 500 * 1000};
755 const int time_smooth = 5;
757 sign = tv_diff(status_time, now, &diff);
758 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
759 // sign, sa_time_diff_sign);
761 sa_time_diff_sign = sign;
762 stat_task->sa_time_diff = diff;
767 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
768 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
769 PARA_WARNING_LOG("time diff jump: %lums\n",
773 sa_time_diff_sign = tv_convex_combination(
774 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
775 count > 10? sign : sign * time_smooth, &diff,
777 stat_task->sa_time_diff = tmp;
778 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
781 sa_time_diff_sign < 0? "-" : "+",
782 tv2ms(&stat_task->sa_time_diff)
785 stat_task->sa_time_diff_sign = sa_time_diff_sign;
788 static int update_item(int itemnum, char *buf)
790 long unsigned sec, usec;
792 if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
794 free(stat_item_values[itemnum]);
795 stat_item_values[itemnum] = para_strdup(buf);
796 stat_client_write_item(itemnum);
798 case SI_STATUS_FLAGS:
799 stat_task->vss_status = 0;
800 if (strchr(buf, 'N'))
801 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
802 if (strchr(buf, 'P'))
803 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
806 stat_task->offset_seconds = atoi(buf);
808 case SI_SECONDS_TOTAL:
809 stat_task->length_seconds = atoi(buf);
811 case SI_STREAM_START:
812 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
813 stat_task->server_stream_start.tv_sec = sec;
814 stat_task->server_stream_start.tv_usec = usec;
817 case SI_CURRENT_TIME:
818 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
819 struct timeval tv = {sec, usec};
820 compute_time_diff(&tv);
824 stat_task->current_audio_format_num
825 = get_audio_format_num(buf);
830 static int parse_stream_command(const char *txt, char **cmd)
833 char *re, *p = strchr(txt, ':');
836 return -E_MISSING_COLON;
839 re = malloc(len + 1);
840 strncpy(re, txt, len);
842 ret = get_matching_audio_format_nums(re);
847 static int add_filter(int format, char *cmdline)
849 struct audio_format_info *a = &afi[format];
850 int filter_num, nf = a->num_filters;
853 filter_num = check_filter_arg(cmdline, &cfg);
856 a->filter_conf = para_realloc(a->filter_conf,
857 (nf + 1) * sizeof(void *));
858 a->filter_nums = para_realloc(a->filter_nums,
859 (nf + 1) * sizeof(unsigned));
860 a->filter_nums[nf] = filter_num;
861 a->filter_conf[nf] = cfg;
863 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
864 filter_get(filter_num)->name);
868 static int parse_writer_args(void)
872 struct audio_format_info *a;
874 for (i = 0; i < conf.writer_given; i++) {
876 int j, nw, writer_num, af_mask;
878 ret = parse_stream_command(conf.writer_arg[i], &cmd);
882 FOR_EACH_AUDIO_FORMAT(j) {
884 if ((af_mask & (1 << j)) == 0) /* no match */
886 wconf = check_writer_arg_or_die(cmd, &writer_num);
888 a->writer_nums = para_realloc(a->writer_nums, (nw + 1) * sizeof(int));
889 a->writer_conf = para_realloc(a->writer_conf, (nw + 1) * sizeof(void *));
890 a->writer_nums[nw] = writer_num;
891 a->writer_conf[nw] = wconf;
892 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
893 nw, writer_names[writer_num]);
897 /* Use default writer for audio formats which are not yet set up. */
898 FOR_EACH_AUDIO_FORMAT(i) {
902 if (a->num_writers > 0)
903 continue; /* already set up */
904 writer_conf = check_writer_arg_or_die(NULL, &writer_num);
905 a->writer_nums = para_malloc(sizeof(int));
906 a->writer_nums[0] = writer_num;
907 a->writer_conf = para_malloc(sizeof(void *));
908 a->writer_conf[0] = writer_conf;
910 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
911 writer_names[writer_num]);
916 static int parse_receiver_args(void)
918 int i, ret, receiver_num;
920 struct audio_format_info *a;
922 for (i = conf.receiver_given - 1; i >= 0; i--) {
926 ret = parse_stream_command(conf.receiver_arg[i], &arg);
930 FOR_EACH_AUDIO_FORMAT(j) {
932 if ((af_mask & (1 << j)) == 0) /* no match */
935 * If multiple receivers are given for this audio format, the
936 * last one wins and we have to free the previous receiver
937 * config here. Since we are iterating backwards, the winning
938 * receiver arg is in fact the first one given.
940 if (a->receiver_conf)
941 a->receiver->free_config(a->receiver_conf);
942 a->receiver_conf = check_receiver_arg(arg, &receiver_num);
943 ret = -E_RECV_SYNTAX;
944 if (!a->receiver_conf)
946 a->receiver = receivers + receiver_num;
950 * Use the first available receiver with no arguments for those audio
951 * formats for which no receiver was specified.
953 cmd = para_strdup(receivers[0].name);
954 FOR_EACH_AUDIO_FORMAT(i) {
956 if (a->receiver_conf)
958 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
959 if (!a->receiver_conf)
960 return -E_RECV_SYNTAX;
961 a->receiver = &receivers[receiver_num];
963 FOR_EACH_AUDIO_FORMAT(i) {
965 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
966 audio_formats[i], a->receiver->name);
974 static int init_default_filters(void)
978 FOR_EACH_AUDIO_FORMAT(i) {
979 struct audio_format_info *a = &afi[i];
984 continue; /* no default -- nothing to to */
986 * udp and dccp streams are fec-encoded, so add fecdec as the
989 if (strcmp(afi[i].receiver->name, "udp") == 0 ||
990 strcmp(afi[i].receiver->name, "dccp") == 0) {
991 tmp = para_strdup("fecdec");
997 /* add "dec" to audio format name */
998 tmp = make_message("%sdec", audio_formats[i]);
999 for (j = 0; filter_get(j); j++)
1000 if (!strcmp(tmp, filter_get(j)->name))
1003 ret = -E_UNSUPPORTED_FILTER;
1006 tmp = para_strdup(filter_get(j)->name);
1007 ret = add_filter(i, tmp);
1011 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1012 filter_get(j)->name);
1018 static int parse_filter_args(void)
1020 int i, j, ret, af_mask, num_matches;
1022 for (i = 0; i < conf.filter_given; i++) {
1024 ret = parse_stream_command(conf.filter_arg[i], &arg);
1029 FOR_EACH_AUDIO_FORMAT(j) {
1030 if ((af_mask & (1 << j)) == 0) /* no match */
1032 ret = add_filter(j, arg);
1037 if (num_matches == 0)
1038 PARA_WARNING_LOG("ignoring filter spec: %s\n",
1039 conf.filter_arg[i]);
1041 ret = init_default_filters(); /* use default values for the rest */
1046 static int parse_stream_args(void)
1050 ret = parse_receiver_args();
1053 ret = parse_filter_args();
1056 ret = parse_writer_args();
1062 /* does not unlink socket on errors */
1063 static void init_local_sockets(struct command_task *ct)
1065 if (conf.socket_given)
1066 socket_name = para_strdup(conf.socket_arg);
1068 char *hn = para_hostname();
1069 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1073 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1074 if (conf.force_given)
1075 unlink(socket_name);
1076 ct->fd[0] = create_local_socket(socket_name, 0);
1077 ct->fd[1] = create_local_socket(socket_name,
1078 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
1079 if (ct->fd[0] >= 0 || ct->fd[1] >= 0)
1081 PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd[1]));
1085 static int signal_post_select(struct sched *s, void *context)
1087 struct signal_task *st = context;
1090 ret = task_get_notification(st->task);
1093 signum = para_next_signal(&s->rfds);
1098 PARA_NOTICE_LOG("received signal %d\n", signum);
1099 task_notify_all(s, E_AUDIOD_SIGNAL);
1100 return -E_AUDIOD_SIGNAL;
1105 static void command_pre_select(struct sched *s, void *context)
1107 struct command_task *ct = context;
1110 for (i = 0; i < 2; i++)
1112 para_fd_set(ct->fd[i], &s->rfds, &s->max_fileno);
1115 static int command_post_select(struct sched *s, void *context)
1118 struct command_task *ct = context;
1119 static struct timeval last_status_dump;
1120 struct timeval tmp, delay;
1123 ret = task_get_notification(ct->task);
1126 for (i = 0; i < 2; i++) {
1129 ret = handle_connect(ct->fd[i], &s->rfds);
1131 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1132 if (ret == -E_AUDIOD_TERM) {
1133 task_notify_all(s, -ret);
1142 /* if last status dump was less than 500ms ago, do nothing */
1144 delay.tv_usec = 500 * 1000;
1145 tv_add(&last_status_dump, &delay, &tmp);
1146 if (tv_diff(now, &tmp, NULL) < 0)
1150 * If last status dump was more than 5s ago, force update. Otherwise,
1151 * update only those items that have changed.
1155 tv_add(&last_status_dump, &delay, &tmp);
1156 if (tv_diff(now, &tmp, NULL) > 0)
1159 audiod_status_dump(force);
1160 last_status_dump = *now;
1164 static void init_command_task(struct command_task *ct)
1166 init_local_sockets(ct); /* doesn't return on errors */
1168 ct->task = task_register(&(struct task_info) {
1170 .pre_select = command_pre_select,
1171 .post_select = command_post_select,
1176 static void close_stat_pipe(void)
1180 task_reap(&stat_task->ct->task);
1181 client_close(stat_task->ct);
1182 stat_task->ct = NULL;
1183 clear_and_dump_items();
1184 stat_task->length_seconds = 0;
1185 stat_task->offset_seconds = 0;
1186 stat_task->vss_status = 0;
1187 stat_task->current_audio_format_num = -1;
1188 audiod_status_dump(true);
1191 /* avoid busy loop if server is down */
1192 static void set_stat_task_restart_barrier(unsigned seconds)
1194 struct timeval delay = {seconds, 0};
1195 tv_add(now, &delay, &stat_task->restart_barrier);
1198 static bool must_close_slot(int slot_num)
1200 struct slot_info *s = &slot[slot_num];
1201 struct audio_format_info *a = afi + s->format;
1206 if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1208 for (i = 0; i < a->num_filters; i++)
1209 if (s->fns && task_status(s->fns[i].task) >= 0)
1211 if (a->num_writers > 0) {
1212 for (i = 0; i < a->num_writers; i++)
1213 if (s->wns && task_status(s->wns[i].task) >= 0)
1216 if (s->wns && task_status(s->wns[0].task) >= 0)
1222 static void close_slot(int slot_num)
1224 struct slot_info *s = slot + slot_num;
1226 PARA_INFO_LOG("closing slot %d\n", slot_num);
1229 close_receiver(slot_num);
1230 clear_slot(slot_num);
1233 static void close_unused_slots(void)
1239 if (must_close_slot(i)) {
1244 audiod_status_dump(true);
1248 * Cleanup all resources.
1250 * This performs various cleanups, removes the audiod socket and closes the
1251 * connection to para_server.
1253 static void audiod_cleanup(void)
1256 unlink(socket_name);
1258 close_unused_slots();
1259 audiod_cmdline_parser_free(&conf);
1260 close_stat_clients();
1261 free(uid_whitelist);
1265 * Check if any receivers/filters/writers need to be started and do so if
1268 static void start_stop_decoders(void)
1271 struct slot_info *sl;
1273 close_unused_slots();
1274 if (audiod_status != AUDIOD_ON ||
1275 !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1276 return notify_receivers(E_NOT_PLAYING);
1277 if (!must_start_decoder())
1279 ret = open_receiver(stat_task->current_audio_format_num);
1281 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1287 activate_grab_clients(&sched);
1288 btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1289 audiod_status_dump(true);
1292 static void status_pre_select(struct sched *s, void *context)
1294 struct status_task *st = context;
1295 int i, ret, cafn = stat_task->current_audio_format_num;
1297 if (must_start_decoder())
1300 if (must_close_slot(i))
1302 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1305 if (st->ct && audiod_status == AUDIOD_OFF)
1307 if (!st->ct && audiod_status != AUDIOD_OFF)
1308 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1310 sched_request_barrier(&afi[cafn].restart_barrier, s);
1312 * If para_server is playing we'd like to have a smooth time display
1313 * even if we are running in standby mode. So we request a timeout that
1314 * expires at the next full second.
1316 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1317 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1323 /* restart the client task if necessary */
1324 static int status_post_select(struct sched *s, void *context)
1326 struct status_task *st = context;
1329 ret = task_get_notification(st->task);
1332 if (audiod_status == AUDIOD_OFF) {
1335 if (task_status(st->ct->task) >= 0) {
1336 task_notify(st->ct->task, E_AUDIOD_OFF);
1340 st->clock_diff_count = conf.clock_diff_count_arg;
1347 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1352 if (st->ct->status != CL_EXECUTING)
1355 struct timeval diff;
1356 tv_diff(now, &st->last_status_read, &diff);
1357 if (diff.tv_sec > 61)
1358 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1361 btr_merge(st->btrn, st->min_iqs);
1362 sz = btr_next_buffer(st->btrn, &buf);
1363 ret = for_each_stat_item(buf, sz, update_item);
1365 task_notify(st->ct->task, -ret);
1369 btr_consume(st->btrn, sz - ret);
1370 st->last_status_read = *now;
1372 } else /* current status item crosses buffers */
1373 st->min_iqs = sz + 1;
1376 btr_drain(st->btrn);
1377 st->current_audio_format_num = -1;
1378 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1380 if (st->clock_diff_count) { /* get status only one time */
1381 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1383 PARA_INFO_LOG("clock diff count: %u\n", st->clock_diff_count);
1384 st->clock_diff_count--;
1385 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1386 set_stat_task_restart_barrier(2);
1389 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1391 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1392 set_stat_task_restart_barrier(5);
1394 free(stat_item_values[SI_BASENAME]);
1395 stat_item_values[SI_BASENAME] = para_strdup(
1396 "no connection to para_server");
1397 stat_client_write_item(SI_BASENAME);
1398 st->last_status_read = *now;
1400 start_stop_decoders();
1404 static void init_status_task(struct status_task *st)
1406 memset(st, 0, sizeof(struct status_task));
1407 st->sa_time_diff_sign = 1;
1408 st->clock_diff_count = conf.clock_diff_count_arg;
1409 st->current_audio_format_num = -1;
1410 st->btrn = btr_new_node(&(struct btr_node_description)
1411 EMBRACE(.name = "stat"));
1413 stat_task->task = task_register(&(struct task_info) {
1415 .pre_select = status_pre_select,
1416 .post_select = status_post_select,
1417 .context = stat_task,
1421 static void set_initial_status(void)
1423 audiod_status = AUDIOD_ON;
1424 if (!conf.mode_given)
1426 if (!strcmp(conf.mode_arg, "sb")) {
1427 audiod_status = AUDIOD_STANDBY;
1430 if (!strcmp(conf.mode_arg, "off")) {
1431 audiod_status = AUDIOD_OFF;
1434 if (strcmp(conf.mode_arg, "on"))
1435 PARA_WARNING_LOG("invalid mode\n");
1438 __noreturn static void print_help_and_die(void)
1440 struct ggo_help h = DEFINE_GGO_HELP(audiod);
1441 bool d = conf.detailed_help_given;
1444 flags = d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
1445 ggo_print_help(&h, flags);
1447 flags = d? GPH_MODULE_FLAGS_DETAILED : GPH_MODULE_FLAGS;
1448 print_receiver_helps(flags);
1449 print_filter_helps(flags);
1450 print_writer_helps(flags);
1455 * Lookup the given UID in the whitelist.
1457 * The whitelist is the array of arguments to the --user-allow opion. If the
1458 * option was not given, the array is empty, in which case the check succeeds.
1460 * \param uid User ID to look up.
1462 * \return True if --user-allow was not given, or if uid matches an element of
1465 bool uid_is_whitelisted(uid_t uid)
1469 if (!conf.user_allow_given)
1471 for (i = 0; i < conf.user_allow_given; i++)
1472 if (uid == uid_whitelist[i])
1478 * the main function of para_audiod
1480 * \param argc usual argument count
1481 * \param argv usual argument vector
1483 * \return EXIT_SUCCESS or EXIT_FAILURE
1485 * \sa para_audiod(1)
1487 int main(int argc, char *argv[])
1490 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1491 struct audiod_cmdline_parser_params params = {
1494 .check_required = 0,
1495 .check_ambiguity = 0,
1500 audiod_cmdline_parser_ext(argc, argv, &conf, ¶ms);
1501 daemon_set_loglevel(conf.loglevel_arg);
1502 version_handle_flag("audiod", conf.version_given);
1503 /* init receivers/filters/writers early to make help work */
1507 if (conf.help_given || conf.detailed_help_given)
1508 print_help_and_die();
1509 daemon_set_priority(conf.priority_arg);
1510 daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
1511 parse_config_or_die();
1512 if (daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
1513 conf.logfile_given)) {
1514 for (i = 0; i < conf.log_color_given; i++)
1515 daemon_set_log_color_or_die(conf.log_color_arg[i]);
1517 init_random_seed_or_die();
1518 daemon_set_flag(DF_LOG_TIME);
1519 daemon_set_flag(DF_LOG_HOSTNAME);
1520 daemon_set_flag(DF_LOG_LL);
1521 if (conf.log_timing_given)
1522 daemon_set_flag(DF_LOG_TIMING);
1523 if (conf.logfile_given) {
1524 daemon_set_logfile(conf.logfile_arg);
1525 daemon_open_log_or_die();
1527 ret = parse_stream_args();
1529 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1532 daemon_log_welcome("audiod");
1533 daemon_set_start_time();
1534 set_initial_status();
1537 setup_signal_handling();
1539 init_status_task(stat_task);
1540 init_command_task(cmd_task);
1542 if (conf.daemon_given)
1543 daemonize(false /* parent exits immediately */);
1545 signal_task->task = task_register(&(struct task_info) {
1547 .pre_select = signal_pre_select,
1548 .post_select = signal_post_select,
1549 .context = signal_task,
1552 sched.default_timeout.tv_sec = 2;
1553 sched.default_timeout.tv_usec = 999 * 1000;
1554 ret = schedule(&sched);
1556 sched_shutdown(&sched);
1557 signal_shutdown(signal_task);
1560 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1561 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;