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>
21 #include "audiod.cmdline.h"
25 #include "buffer_tree.h"
28 #include "grab_client.h"
29 #include "client.cmdline.h"
37 #include "write_common.h"
41 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
42 /** define the array of error lists needed by para_audiod */
44 /** define the array containing all supported audio formats */
45 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
47 DEFINE_RECEIVER_ARRAY;
49 /** Defines how audiod handles one supported audio format. */
50 struct audio_format_info {
51 /** pointer to the receiver for this audio format */
52 struct receiver *receiver;
53 /** the receiver configuration */
55 /** the number of filters that should be activated for this audio format */
56 unsigned int num_filters;
57 /** Array of filter numbers to be activated. */
58 unsigned *filter_nums;
59 /** Pointer to the array of filter configurations. */
61 /** the number of filters that should be activated for this audio format */
62 unsigned int num_writers;
63 /** Array of writer numbers to be activated. */
65 /** pointer to the array of writer configurations */
67 /** do not start receiver/filters/writer before this time */
68 struct timeval restart_barrier;
71 /* Describes one instance of a receiver-filter-writer chain. */
73 /* Number of the audio format in this slot. */
75 /* The stream_start status item announced by para_server. */
76 struct timeval server_stream_start;
77 /* The offset status item announced by para_server. */
78 unsigned offset_seconds;
79 /* The seconds_total status item announced by para_server. */
80 unsigned seconds_total;
81 /* The receiver info associated with this slot. */
82 struct receiver_node *receiver_node;
83 /* The array of filter nodes. */
84 struct filter_node *fns;
85 /* The array of writers attached to the last filter. */
86 struct writer_node *wns;
89 /** Maximal number of simultaneous instances. */
90 #define MAX_STREAM_SLOTS 5
92 /** Iterate over all slots. */
93 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
96 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
97 * be associated with a receiver/filter/writer triple. This array holds all
98 * information on the status of these slots.
100 * \sa struct slot_info
102 struct slot_info slot[MAX_STREAM_SLOTS];
104 /** The vss status flags audiod is interested in. */
105 enum vss_status_flags {
106 /** Whether the 'N' flag is set. */
107 VSS_STATUS_FLAG_NEXT = 1,
108 /** The 'P' flag is set. */
109 VSS_STATUS_FLAG_PLAYING = 2,
113 * The scheduler instance of para_audiod.
115 * This is needed also in audiod_command.c (for the tasks command), so it can
116 * not be made static.
118 struct sched sched = {.max_fileno = 0};
120 /* The task for obtaining para_server's status (para_client stat). */
122 /** The associated task structure of audiod. */
124 /** Client data associated with the stat task. */
125 struct client_task *ct;
126 /** Do not restart client command until this time. */
127 struct timeval restart_barrier;
128 /** Last time we received status data from para_server. */
129 struct timeval last_status_read;
131 /** The offset value announced by para_server. */
133 /** The length of the current audio file as announced by para_server. */
135 /** The start of the current stream from the view of para_server. */
136 struct timeval server_stream_start;
137 /** The average time deviation between para_server and para_audiod. */
138 struct timeval sa_time_diff;
139 /** Whether client time is ahead of server time. */
140 int sa_time_diff_sign;
141 /** The 'P' and the 'N' flags as announced by para_server. */
142 enum vss_status_flags vss_status;
143 /** Number of times the clock difference is to be checked. */
144 unsigned clock_diff_count;
145 /** When to start the next check for clock difference. */
146 struct timeval clock_diff_barrier;
147 /** Number of the audio format as announced by para_server. */
148 int current_audio_format_num;
149 /* The status task btrn is the child of the client task. */
150 struct btr_node *btrn;
153 /** The array of status items sent by para_server. */
154 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
157 * the current mode of operation of which can be changed by the on/off/cycle
158 * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
160 int audiod_status = AUDIOD_ON;
163 * the gengetopt args_info struct that holds information on all command line
166 struct audiod_args_info conf;
168 static char *socket_name;
169 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
171 static struct signal_task *signal_task;
173 static struct status_task status_task_struct;
176 * the task that calls the status command of para_server
178 * \sa struct status_task
180 static struct status_task *stat_task = &status_task_struct;
183 * The task for handling audiod commands.
185 * We need two listening sockets for backward compability: on Linux systems
186 * fd[0] is an abstract socket (more precisely, a socket bound to an address in
187 * the abstract namespace), and fd[1] is the usual pathname socket. On other
188 * systems, fd[0] is negative, and only the pathname socket is used.
190 * For 0.5.x we accept connections on both sockets to make sure that old
191 * para_audioc versions can still connect. New versions use only the abstract
192 * socket. Hence after v0.6.0 we can go back to a single socket, either an
193 * abstract one (Linux) or a pathname socket (all other systems).
195 struct command_task {
196 /** The local listening sockets. */
198 /** the associated task structure */
202 /** iterate over all supported audio formats */
203 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
206 * Get the audio format number.
208 * \param name The name of the audio format.
210 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
211 * \a name is not a supported audio format.
213 static int get_audio_format_num(const char *name)
217 while (para_isspace(*name))
219 FOR_EACH_AUDIO_FORMAT(i)
220 if (!strcmp(name, audio_formats[i]))
222 return -E_UNSUPPORTED_AUDIO_FORMAT;
226 * Return the flags for the \a decoder_flags status item.
228 * Allocates a string which contains one octal digit per slot. Bit zero (value
229 * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
230 * have the analogous meaning for filter and writer, respectively.
232 * \return String that must be freed by the caller.
234 __malloc char *audiod_get_decoder_flags(void)
237 char flags[MAX_STREAM_SLOTS + 1];
240 struct slot_info *s = &slot[i];
242 if (s->receiver_node)
250 flags[MAX_STREAM_SLOTS] = '\0';
251 return para_strdup(flags);
254 static int get_matching_audio_format_nums(const char *re)
259 ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
263 FOR_EACH_AUDIO_FORMAT(i)
264 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
270 static int get_play_time_slot_num(void)
272 int i, oldest_slot = -1;
273 struct timeval oldest_wstime = {0, 0};
276 struct slot_info *s = &slot[i];
277 struct timeval wstime;
278 if (!s->wns || !s->wns[0].btrn)
280 btr_get_node_start(s->wns[0].btrn, &wstime);
281 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
283 oldest_wstime = wstime;
290 * Compute the play time based on information of the current slot.
292 * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
293 * from the status items received from para_server and the start time of the
294 * (first) writer of the current slot.
296 * It has to take into account that the stream was probably not started at
297 * the beginning of the file, that the clock between the server and the client
298 * host may differ and that playback of the stream was delayed, e.g. because
299 * the prebuffer filter is used in the filter configuration.
301 * If no writer is active, for example because para_audiod runs in standby
302 * mode, an approximation based only on the status items is computed and the
303 * returned string is prefixed with "~".
305 * \return A string that must be freed by the caller.
307 char *get_time_string(void)
309 int ret, seconds = 0, length;
310 struct timeval *tmp, sum, sss, /* server stream start */
311 rstime, /* receiver start time */
312 wstime, /* writer start time */
313 wtime, /* now - writer start */
314 rskip; /* receiver start - sss */
315 int slot_num = get_play_time_slot_num();
316 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
319 if (audiod_status == AUDIOD_OFF)
321 if (!(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)) {
322 if (stat_task->length_seconds) /* paused */
324 goto empty; /* stopped */
326 if (audiod_status == AUDIOD_ON && !s)
329 * Valid status items and playing, set length and tmp to the stream
330 * start. We use the slot info and fall back to the info from current
331 * status items if no slot info is available.
333 length = stat_task->length_seconds;
334 tmp = &stat_task->server_stream_start;
335 if (s && s->wns && s->wns[0].btrn) { /* writer active in this slot */
336 btr_get_node_start(s->wns[0].btrn, &wstime);
337 if (wstime.tv_sec != 0) { /* writer wrote something */
338 if (s->server_stream_start.tv_sec == 0) {
339 /* copy status info to slot */
340 s->server_stream_start = stat_task->server_stream_start;
341 s->offset_seconds = stat_task->offset_seconds;
342 s->seconds_total = stat_task->length_seconds;
344 length = s->seconds_total;
345 tmp = &s->server_stream_start;
348 if (stat_task->sa_time_diff_sign > 0)
349 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
351 tv_add(tmp, &stat_task->sa_time_diff, &sss);
352 if (!s || !s->wns || !s->wns[0].btrn) {
354 tv_diff(now, &sss, &diff);
355 seconds = diff.tv_sec + stat_task->offset_seconds;
358 tv_diff(now, &wstime, &wtime);
359 //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
360 seconds = s->offset_seconds;
361 if (s->receiver_node->btrn) {
362 btr_get_node_start(s->receiver_node->btrn, &rstime);
363 ret = tv_diff(&rstime, &sss, &rskip);
364 if (ret > 0) { /* audiod was started in the middle of the stream */
365 tv_add(&wtime, &rskip, &sum);
366 seconds += sum.tv_sec;
368 seconds += wtime.tv_sec;
370 seconds += wtime.tv_sec;
372 seconds = PARA_MIN(seconds, length);
373 seconds = PARA_MAX(seconds, 0);
375 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
379 (length - seconds) / 60,
380 (length - seconds) % 60,
381 length? (seconds * 100 + length / 2) / length : 0,
385 //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
388 return para_strdup(NULL);
391 static void parse_config_or_die(void)
395 struct audiod_cmdline_parser_params params = {
399 .check_ambiguity = 0,
403 if (conf.config_file_given)
404 config_file = para_strdup(conf.config_file_arg);
406 char *home = para_homedir();
407 config_file = make_message("%s/.paraslash/audiod.conf", home);
410 ret = file_exists(config_file);
411 if (conf.config_file_given && !ret) {
412 PARA_EMERG_LOG("can not read config file %s\n", config_file);
416 audiod_cmdline_parser_config_file(config_file, &conf, ¶ms);
417 daemon_set_loglevel(conf.loglevel_arg);
426 static void setup_signal_handling(void)
428 signal_task = signal_init_or_die();
429 para_install_sighandler(SIGINT);
430 para_install_sighandler(SIGTERM);
431 para_install_sighandler(SIGHUP);
432 para_sigaction(SIGPIPE, SIG_IGN);
435 static void clear_slot(int slot_num)
437 struct slot_info *s = &slot[slot_num];
439 PARA_INFO_LOG("clearing slot %d\n", slot_num);
440 memset(s, 0, sizeof(struct slot_info));
444 static void close_receiver(int slot_num)
446 struct slot_info *s = &slot[slot_num];
447 struct audio_format_info *a;
449 if (s->format < 0 || !s->receiver_node)
452 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
453 audio_formats[s->format], slot_num);
454 a->receiver->close(s->receiver_node);
455 btr_remove_node(&s->receiver_node->btrn);
456 task_reap(&s->receiver_node->task);
457 free(s->receiver_node);
458 s->receiver_node = NULL;
459 stat_task->current_audio_format_num = -1;
460 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
461 &a->restart_barrier);
464 static void writer_cleanup(struct writer_node *wn)
470 w = writers + wn->writer_num;
471 PARA_INFO_LOG("closing %s\n", writer_names[wn->writer_num]);
473 btr_remove_node(&wn->btrn);
474 task_reap(&wn->task);
477 static void close_writers(struct slot_info *s)
479 struct audio_format_info *a;
486 if (a->num_writers == 0)
487 writer_cleanup(s->wns);
489 for (i = 0; i < a->num_writers; i++)
490 writer_cleanup(s->wns + i);
496 static void close_filters(struct slot_info *s)
499 struct audio_format_info *a = afi + s->format;
500 if (a->num_filters == 0)
502 for (i = a->num_filters - 1; i >= 0; i--) {
503 struct filter_node *fn = s->fns + i;
508 f = filters + fn->filter_num;
511 btr_remove_node(&fn->btrn);
512 task_reap(&fn->task);
518 static void notify_receivers(int error)
523 struct slot_info *s = slot + i;
526 if (!s->receiver_node)
528 task_notify(s->receiver_node->task, error);
532 static int get_empty_slot(void)
543 if (s->wns || s->receiver_node || s->fns)
548 return -E_NO_MORE_SLOTS;
551 static void open_filters(struct slot_info *s)
553 struct audio_format_info *a = afi + s->format;
554 struct filter_node *fn;
555 int nf = a->num_filters;
556 struct btr_node *parent;
561 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
562 assert(s->fns == NULL);
563 s->fns = para_calloc(nf * sizeof(struct filter_node));
564 parent = s->receiver_node->btrn;
565 for (i = 0; i < nf; i++) {
567 struct filter *f = filters + a->filter_nums[i];
569 fn->filter_num = a->filter_nums[i];
570 fn->conf = a->filter_conf[i];
571 fn->btrn = btr_new_node(&(struct btr_node_description)
572 EMBRACE(.name = f->name, .parent = parent,
573 .handler = f->execute, .context = fn));
576 sprintf(buf, "%s (slot %d)", f->name, (int)(s - slot));
577 fn->task = task_register(&(struct task_info) {
579 .pre_select = f->pre_select,
580 .post_select = f->post_select,
584 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
585 audio_formats[s->format], i, nf, f->name, (int)(s - slot));
589 static void open_writers(struct slot_info *s)
592 struct audio_format_info *a = afi + s->format;
593 struct writer_node *wn;
594 struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
596 assert(s->wns == NULL);
597 s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
598 * sizeof(struct writer_node));
599 for (i = 0; i < a->num_writers; i++) {
601 wn->conf = a->writer_conf[i];
602 wn->writer_num = a->writer_nums[i];
603 register_writer_node(wn, parent, &sched);
604 PARA_NOTICE_LOG("%s writer started in slot %d\n",
605 writer_names[a->writer_nums[i]], (int)(s - slot));
609 /* returns slot num on success */
610 static int open_receiver(int format)
612 struct audio_format_info *a = &afi[format];
615 struct receiver *r = a->receiver;
616 struct receiver_node *rn;
618 tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
619 ret = get_empty_slot();
623 rn = para_calloc(sizeof(*rn));
625 rn->conf = a->receiver_conf;
626 rn->btrn = btr_new_node(&(struct btr_node_description)
627 EMBRACE(.name = r->name, .context = rn));
630 btr_remove_node(&rn->btrn);
636 s->receiver_node = rn;
637 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
638 audio_formats[format], r->name, slot_num);
639 rn->task = task_register(&(struct task_info) {
641 .pre_select = r->pre_select,
642 .post_select = r->post_select,
648 static bool receiver_running(void)
651 long unsigned ss1 = stat_task->server_stream_start.tv_sec;
654 struct slot_info *s = &slot[i];
655 long unsigned ss2 = s->server_stream_start.tv_sec;
657 if (!s->receiver_node)
659 if (task_status(s->receiver_node->task) >= 0)
668 * Return the root node of the current buffer tree.
670 * This is only used for stream grabbing.
672 * \return \p NULL if no slot is currently active. If more than one buffer tree
673 * exists, the node corresponding to the most recently started receiver is
676 struct btr_node *audiod_get_btr_root(void)
678 int i, newest_slot = -1;
679 struct timeval newest_rstime = {0, 0};
682 struct slot_info *s = &slot[i];
683 struct timeval rstime;
684 if (!s->receiver_node)
686 if (task_status(s->receiver_node->task) < 0)
688 btr_get_node_start(s->receiver_node->btrn, &rstime);
689 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
691 newest_rstime = rstime;
694 if (newest_slot == -1)
696 return slot[newest_slot].receiver_node->btrn;
699 /* whether a new instance of a decoder should be started. */
700 static bool must_start_decoder(void)
702 int cafn = stat_task->current_audio_format_num;
703 unsigned vs = stat_task->vss_status;
705 if (audiod_status != AUDIOD_ON)
711 if (vs & VSS_STATUS_FLAG_NEXT)
713 if (!(vs & VSS_STATUS_FLAG_PLAYING))
715 if (receiver_running())
717 if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
722 static void compute_time_diff(const struct timeval *status_time)
724 struct timeval tmp, diff;
725 static unsigned count;
726 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
727 const struct timeval max_deviation = {0, 500 * 1000};
728 const int time_smooth = 5;
730 sign = tv_diff(status_time, now, &diff);
731 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
732 // sign, sa_time_diff_sign);
734 sa_time_diff_sign = sign;
735 stat_task->sa_time_diff = diff;
740 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
741 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
742 PARA_WARNING_LOG("time diff jump: %lims\n",
746 sa_time_diff_sign = tv_convex_combination(
747 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
748 count > 10? sign : sign * time_smooth, &diff,
750 stat_task->sa_time_diff = tmp;
751 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
754 sa_time_diff_sign < 0? "-" : "+",
755 tv2ms(&stat_task->sa_time_diff)
758 stat_task->sa_time_diff_sign = sa_time_diff_sign;
761 static int update_item(int itemnum, char *buf)
763 long unsigned sec, usec;
765 if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
767 free(stat_item_values[itemnum]);
768 stat_item_values[itemnum] = para_strdup(buf);
769 stat_client_write_item(itemnum);
771 case SI_STATUS_FLAGS:
772 stat_task->vss_status = 0;
773 if (strchr(buf, 'N'))
774 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
775 if (strchr(buf, 'P'))
776 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
779 stat_task->offset_seconds = atoi(buf);
781 case SI_SECONDS_TOTAL:
782 stat_task->length_seconds = atoi(buf);
784 case SI_STREAM_START:
785 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
786 stat_task->server_stream_start.tv_sec = sec;
787 stat_task->server_stream_start.tv_usec = usec;
790 case SI_CURRENT_TIME:
791 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
792 struct timeval tv = {sec, usec};
793 compute_time_diff(&tv);
797 stat_task->current_audio_format_num
798 = get_audio_format_num(buf);
803 static int parse_stream_command(const char *txt, char **cmd)
806 char *re, *p = strchr(txt, ':');
809 return -E_MISSING_COLON;
812 re = malloc(len + 1);
813 strncpy(re, txt, len);
815 ret = get_matching_audio_format_nums(re);
820 static int add_filter(int format, char *cmdline)
822 struct audio_format_info *a = &afi[format];
823 int filter_num, nf = a->num_filters;
826 filter_num = check_filter_arg(cmdline, &cfg);
829 a->filter_conf = para_realloc(a->filter_conf,
830 (nf + 1) * sizeof(void *));
831 a->filter_nums = para_realloc(a->filter_nums,
832 (nf + 1) * sizeof(unsigned));
833 a->filter_nums[nf] = filter_num;
834 a->filter_conf[nf] = cfg;
836 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
837 filters[filter_num].name);
841 static int parse_writer_args(void)
845 struct audio_format_info *a;
847 for (i = 0; i < conf.writer_given; i++) {
849 int j, nw, writer_num, af_mask;
851 ret = parse_stream_command(conf.writer_arg[i], &cmd);
855 FOR_EACH_AUDIO_FORMAT(j) {
857 if ((af_mask & (1 << j)) == 0) /* no match */
859 wconf = check_writer_arg_or_die(cmd, &writer_num);
861 a->writer_nums = para_realloc(a->writer_nums, (nw + 1) * sizeof(int));
862 a->writer_conf = para_realloc(a->writer_conf, (nw + 1) * sizeof(void *));
863 a->writer_nums[nw] = writer_num;
864 a->writer_conf[nw] = wconf;
865 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
866 nw, writer_names[writer_num]);
870 /* Use default writer for audio formats which are not yet set up. */
871 FOR_EACH_AUDIO_FORMAT(i) {
875 if (a->num_writers > 0)
876 continue; /* already set up */
877 writer_conf = check_writer_arg_or_die(NULL, &writer_num);
878 a->writer_nums = para_malloc(sizeof(int));
879 a->writer_nums[0] = writer_num;
880 a->writer_conf = para_malloc(sizeof(void *));
881 a->writer_conf[0] = writer_conf;
883 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
884 writer_names[writer_num]);
889 static int parse_receiver_args(void)
891 int i, ret, receiver_num;
893 struct audio_format_info *a;
895 for (i = conf.receiver_given - 1; i >= 0; i--) {
899 ret = parse_stream_command(conf.receiver_arg[i], &arg);
903 FOR_EACH_AUDIO_FORMAT(j) {
905 if ((af_mask & (1 << j)) == 0) /* no match */
908 * If multiple receivers are given for this audio format, the
909 * last one wins and we have to free the previous receiver
910 * config here. Since we are iterating backwards, the winning
911 * receiver arg is in fact the first one given.
913 if (a->receiver_conf)
914 a->receiver->free_config(a->receiver_conf);
915 a->receiver_conf = check_receiver_arg(arg, &receiver_num);
916 ret = -E_RECV_SYNTAX;
917 if (!a->receiver_conf)
919 a->receiver = receivers + receiver_num;
923 * Use the first available receiver with no arguments for those audio
924 * formats for which no receiver was specified.
926 cmd = para_strdup(receivers[0].name);
927 FOR_EACH_AUDIO_FORMAT(i) {
929 if (a->receiver_conf)
931 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
932 if (!a->receiver_conf)
933 return -E_RECV_SYNTAX;
934 a->receiver = &receivers[receiver_num];
936 FOR_EACH_AUDIO_FORMAT(i) {
938 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
939 audio_formats[i], a->receiver->name);
947 static int init_default_filters(void)
951 FOR_EACH_AUDIO_FORMAT(i) {
952 struct audio_format_info *a = &afi[i];
957 continue; /* no default -- nothing to to */
959 * udp and dccp streams are fec-encoded, so add fecdec as the
962 if (strcmp(afi[i].receiver->name, "udp") == 0 ||
963 strcmp(afi[i].receiver->name, "dccp") == 0) {
964 tmp = para_strdup("fecdec");
970 /* add "dec" to audio format name */
971 tmp = make_message("%sdec", audio_formats[i]);
972 for (j = 0; filters[j].name; j++)
973 if (!strcmp(tmp, filters[j].name))
976 ret = -E_UNSUPPORTED_FILTER;
977 if (!filters[j].name)
979 tmp = para_strdup(filters[j].name);
980 ret = add_filter(i, tmp);
984 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
991 static int parse_filter_args(void)
993 int i, j, ret, af_mask, num_matches;
995 for (i = 0; i < conf.filter_given; i++) {
997 ret = parse_stream_command(conf.filter_arg[i], &arg);
1002 FOR_EACH_AUDIO_FORMAT(j) {
1003 if ((af_mask & (1 << j)) == 0) /* no match */
1005 ret = add_filter(j, arg);
1010 if (num_matches == 0)
1011 PARA_WARNING_LOG("ignoring filter spec: %s\n",
1012 conf.filter_arg[i]);
1014 ret = init_default_filters(); /* use default values for the rest */
1019 static int parse_stream_args(void)
1023 ret = parse_receiver_args();
1026 ret = parse_filter_args();
1029 ret = parse_writer_args();
1035 /* does not unlink socket on errors */
1036 static void init_local_sockets(struct command_task *ct)
1038 if (conf.socket_given)
1039 socket_name = para_strdup(conf.socket_arg);
1041 char *hn = para_hostname();
1042 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1046 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1047 if (conf.force_given)
1048 unlink(socket_name);
1049 ct->fd[0] = create_local_socket(socket_name, 0);
1050 ct->fd[1] = create_local_socket(socket_name,
1051 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1052 if (ct->fd[0] >= 0 || ct->fd[1] >= 0)
1054 PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd[1]));
1058 static int signal_post_select(struct sched *s, void *context)
1060 struct signal_task *st = context;
1063 ret = task_get_notification(st->task);
1066 signum = para_next_signal(&s->rfds);
1071 PARA_NOTICE_LOG("received signal %d\n", signum);
1072 task_notify_all(s, E_AUDIOD_SIGNAL);
1073 return -E_AUDIOD_SIGNAL;
1078 static void command_pre_select(struct sched *s, void *context)
1080 struct command_task *ct = context;
1083 for (i = 0; i < 2; i++)
1085 para_fd_set(ct->fd[i], &s->rfds, &s->max_fileno);
1088 static int command_post_select(struct sched *s, void *context)
1091 struct command_task *ct = context;
1092 static struct timeval last_status_dump;
1093 struct timeval tmp, delay;
1096 ret = task_get_notification(ct->task);
1099 for (i = 0; i < 2; i++) {
1102 ret = handle_connect(ct->fd[i], &s->rfds);
1104 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1105 if (ret == -E_AUDIOD_TERM) {
1106 task_notify_all(s, -ret);
1115 /* if last status dump was less than 500ms ago, do nothing */
1117 delay.tv_usec = 500 * 1000;
1118 tv_add(&last_status_dump, &delay, &tmp);
1119 if (tv_diff(now, &tmp, NULL) < 0)
1123 * If last status dump was more than 5s ago, force update. Otherwise,
1124 * update only those items that have changed.
1128 tv_add(&last_status_dump, &delay, &tmp);
1129 if (tv_diff(now, &tmp, NULL) > 0)
1132 audiod_status_dump(force);
1133 last_status_dump = *now;
1137 static void init_command_task(struct command_task *ct)
1139 init_local_sockets(ct); /* doesn't return on errors */
1141 ct->task = task_register(&(struct task_info) {
1143 .pre_select = command_pre_select,
1144 .post_select = command_post_select,
1149 static void close_stat_pipe(void)
1153 task_reap(&stat_task->ct->task);
1154 client_close(stat_task->ct);
1155 stat_task->ct = NULL;
1156 clear_and_dump_items();
1157 stat_task->length_seconds = 0;
1158 stat_task->offset_seconds = 0;
1159 stat_task->vss_status = 0;
1160 stat_task->current_audio_format_num = -1;
1161 audiod_status_dump(true);
1164 /* avoid busy loop if server is down */
1165 static void set_stat_task_restart_barrier(unsigned seconds)
1167 struct timeval delay = {seconds, 0};
1168 tv_add(now, &delay, &stat_task->restart_barrier);
1171 static bool must_close_slot(int slot_num)
1173 struct slot_info *s = &slot[slot_num];
1174 struct audio_format_info *a = afi + s->format;
1179 if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1181 for (i = 0; i < a->num_filters; i++)
1182 if (s->fns && task_status(s->fns[i].task) >= 0)
1184 if (a->num_writers > 0) {
1185 for (i = 0; i < a->num_writers; i++)
1186 if (s->wns && task_status(s->wns[i].task) >= 0)
1189 if (s->wns && task_status(s->wns[0].task) >= 0)
1195 static void close_slot(int slot_num)
1197 struct slot_info *s = slot + slot_num;
1199 PARA_INFO_LOG("closing slot %d\n", slot_num);
1202 close_receiver(slot_num);
1203 clear_slot(slot_num);
1206 static void close_unused_slots(void)
1211 if (must_close_slot(i))
1216 * Cleanup all resources.
1218 * This performs various cleanups, removes the audiod socket and closes the
1219 * connection to para_server.
1221 static void audiod_cleanup(void)
1224 unlink(socket_name);
1226 close_unused_slots();
1227 audiod_cmdline_parser_free(&conf);
1228 close_stat_clients();
1232 * Check if any receivers/filters/writers need to be started and do so if
1235 static void start_stop_decoders(void)
1238 struct slot_info *sl;
1240 close_unused_slots();
1241 if (audiod_status != AUDIOD_ON ||
1242 !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1243 return notify_receivers(E_NOT_PLAYING);
1244 if (!must_start_decoder())
1246 ret = open_receiver(stat_task->current_audio_format_num);
1248 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1254 activate_grab_clients(&sched);
1255 btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1258 static void status_pre_select(struct sched *s, void *context)
1260 struct status_task *st = context;
1261 int i, ret, cafn = stat_task->current_audio_format_num;
1263 if (must_start_decoder())
1266 if (must_close_slot(i))
1268 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1271 if (st->ct && audiod_status == AUDIOD_OFF)
1273 if (!st->ct && audiod_status != AUDIOD_OFF)
1274 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1276 sched_request_barrier(&afi[cafn].restart_barrier, s);
1278 * If para_server is playing we'd like to have a smooth time display
1279 * even if we are running in standby mode. So we request a timeout that
1280 * expires at the next full second.
1282 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1283 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1289 /* restart the client task if necessary */
1290 static int status_post_select(struct sched *s, void *context)
1292 struct status_task *st = context;
1295 ret = task_get_notification(st->task);
1298 if (audiod_status == AUDIOD_OFF) {
1301 if (task_status(st->ct->task) >= 0) {
1302 task_notify(st->ct->task, E_AUDIOD_OFF);
1306 st->clock_diff_count = conf.clock_diff_count_arg;
1313 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1318 if (st->ct->status != CL_EXECUTING)
1321 struct timeval diff;
1322 tv_diff(now, &st->last_status_read, &diff);
1323 if (diff.tv_sec > 61)
1324 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1327 btr_merge(st->btrn, st->min_iqs);
1328 sz = btr_next_buffer(st->btrn, &buf);
1329 ret = for_each_stat_item(buf, sz, update_item);
1331 task_notify(st->ct->task, -ret);
1335 btr_consume(st->btrn, sz - ret);
1336 st->last_status_read = *now;
1338 } else /* current status item crosses buffers */
1339 st->min_iqs = sz + 1;
1342 btr_drain(st->btrn);
1343 st->current_audio_format_num = -1;
1344 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1346 if (st->clock_diff_count) { /* get status only one time */
1347 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1349 PARA_INFO_LOG("clock diff count: %d\n", st->clock_diff_count);
1350 st->clock_diff_count--;
1351 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1352 set_stat_task_restart_barrier(2);
1355 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1357 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1358 set_stat_task_restart_barrier(5);
1360 free(stat_item_values[SI_BASENAME]);
1361 stat_item_values[SI_BASENAME] = para_strdup(
1362 "no connection to para_server");
1363 stat_client_write_item(SI_BASENAME);
1364 st->last_status_read = *now;
1366 start_stop_decoders();
1370 static void init_status_task(struct status_task *st)
1372 memset(st, 0, sizeof(struct status_task));
1373 st->sa_time_diff_sign = 1;
1374 st->clock_diff_count = conf.clock_diff_count_arg;
1375 st->current_audio_format_num = -1;
1376 st->btrn = btr_new_node(&(struct btr_node_description)
1377 EMBRACE(.name = "stat"));
1379 stat_task->task = task_register(&(struct task_info) {
1381 .pre_select = status_pre_select,
1382 .post_select = status_post_select,
1383 .context = stat_task,
1387 static void set_initial_status(void)
1389 audiod_status = AUDIOD_ON;
1390 if (!conf.mode_given)
1392 if (!strcmp(conf.mode_arg, "sb")) {
1393 audiod_status = AUDIOD_STANDBY;
1396 if (!strcmp(conf.mode_arg, "off")) {
1397 audiod_status = AUDIOD_OFF;
1400 if (strcmp(conf.mode_arg, "on"))
1401 PARA_WARNING_LOG("invalid mode\n");
1404 __noreturn static void print_help_and_die(void)
1406 struct ggo_help h = DEFINE_GGO_HELP(audiod);
1407 bool d = conf.detailed_help_given;
1410 flags = d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
1411 ggo_print_help(&h, flags);
1413 flags = d? GPH_MODULE_FLAGS_DETAILED : GPH_MODULE_FLAGS;
1414 print_receiver_helps(flags);
1415 print_filter_helps(flags);
1416 print_writer_helps(flags);
1421 * the main function of para_audiod
1423 * \param argc usual argument count
1424 * \param argv usual argument vector
1426 * \return EXIT_SUCCESS or EXIT_FAILURE
1428 * \sa para_audiod(1)
1430 int main(int argc, char *argv[])
1433 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1434 struct audiod_cmdline_parser_params params = {
1437 .check_required = 0,
1438 .check_ambiguity = 0,
1443 audiod_cmdline_parser_ext(argc, argv, &conf, ¶ms);
1444 daemon_set_loglevel(conf.loglevel_arg);
1445 version_handle_flag("audiod", conf.version_given);
1446 /* init receivers/filters/writers early to make help work */
1450 if (conf.help_given || conf.detailed_help_given)
1451 print_help_and_die();
1452 daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
1453 parse_config_or_die();
1454 daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
1455 conf.logfile_given, conf.log_color_arg, conf.log_color_given);
1456 init_random_seed_or_die();
1457 daemon_set_flag(DF_LOG_TIME);
1458 daemon_set_flag(DF_LOG_HOSTNAME);
1459 daemon_set_flag(DF_LOG_LL);
1460 if (conf.log_timing_given)
1461 daemon_set_flag(DF_LOG_TIMING);
1462 if (conf.logfile_given) {
1463 daemon_set_logfile(conf.logfile_arg);
1464 daemon_open_log_or_die();
1466 ret = parse_stream_args();
1468 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1471 daemon_log_welcome("para_audiod");
1472 daemon_set_start_time();
1473 set_initial_status();
1476 setup_signal_handling();
1478 init_status_task(stat_task);
1479 init_command_task(cmd_task);
1481 if (conf.daemon_given)
1482 daemonize(false /* parent exits immediately */);
1484 signal_task->task = task_register(&(struct task_info) {
1486 .pre_select = signal_pre_select,
1487 .post_select = signal_post_select,
1488 .context = signal_task,
1491 sched.default_timeout.tv_sec = 2;
1492 sched.default_timeout.tv_usec = 999 * 1000;
1493 ret = schedule(&sched);
1495 sched_shutdown(&sched);
1496 signal_shutdown(signal_task);
1499 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1500 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;