audiod: Invalidate the current audio format when closing the receiver.
[paraslash.git] / audiod.c
1 /*
2 * Copyright (C) 2005-2009 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file audiod.c the paraslash's audio daemon */
8 #include <sys/types.h>
9 #include <dirent.h>
10 #include <signal.h>
11
12 #include "para.h"
13 #include "error.h"
14 #include "audiod.cmdline.h"
15 #include "list.h"
16 #include "sched.h"
17 #include "ggo.h"
18 #include "recv.h"
19 #include "filter.h"
20 #include "grab_client.cmdline.h"
21 #include "grab_client.h"
22 #include "client.cmdline.h"
23 #include "client.h"
24 #include "audiod.h"
25 #include "net.h"
26 #include "daemon.h"
27 #include "string.h"
28 #include "fd.h"
29 #include "write.h"
30 #include "write_common.h"
31 #include "signal.h"
32
33 /** define the array of error lists needed by para_audiod */
34 INIT_AUDIOD_ERRLISTS;
35 /** define the array containing all supported audio formats */
36 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
37
38 /** Defines how audiod handles one supported audio format. */
39 struct audio_format_info {
40 /** pointer to the receiver for this audio format */
41 struct receiver *receiver;
42 /** the receiver configuration */
43 void *receiver_conf;
44 /** the number of filters that should be activated for this audio format */
45 unsigned int num_filters;
46 /** Array of filter numbers to be activated. */
47 unsigned *filter_nums;
48 /** Pointer to the array of filter configurations. */
49 void **filter_conf;
50 /** the number of filters that should be activated for this audio format */
51 unsigned int num_writers;
52 /** Array of writer numbers to be activated. */
53 int *writer_nums;
54 /** pointer to the array of writer configurations */
55 void **writer_conf;
56 /** do not start receiver/filters/writer before this time */
57 struct timeval restart_barrier;
58 };
59
60 /**
61 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
62 * be associated with a receiver/filter/writer triple. This array holds all
63 * information on the status of these slots.
64 *
65 * \sa struct slot_info
66 * */
67 struct slot_info slot[MAX_STREAM_SLOTS];
68
69 /** The vss status flags audiod is interested in. */
70 enum vss_status_flags {
71 /** Whether the 'N' flag is set. */
72 VSS_STATUS_FLAG_NEXT = 1,
73 /** The 'P' flag is set. */
74 VSS_STATUS_FLAG_PLAYING = 2,
75 };
76
77 /**
78 * The task for obtaining para_server's status (para_client stat).
79 *
80 * \sa struct task, struct sched.
81 */
82 struct status_task {
83 /** The associated task structure of audiod. */
84 struct task task;
85 /** Client data associated with the stat task. */
86 struct client_task *ct;
87 /** Do not restart client command until this time. */
88 struct timeval restart_barrier;
89 /** Last time we received status data from para_server. */
90 struct timeval last_status_read;
91 /** The offset value announced by para_server. */
92 int offset_seconds;
93 /** The length of the current audio file as announced by para_server. */
94 int length_seconds;
95 /** The start of the current stream from the view of para_server. */
96 struct timeval server_stream_start;
97 /** The average time deviation between para_server and para_audiod. */
98 struct timeval sa_time_diff;
99 /** Whether client time is ahead of server time. */
100 int sa_time_diff_sign;
101 /** The 'P' and the 'N' flags as announced by para_server. */
102 enum vss_status_flags vss_status;
103 /** Number of times the clock difference is to be checked. */
104 unsigned clock_diff_count;
105 /** When to start the next check for clock difference. */
106 struct timeval clock_diff_barrier;
107 /** Number of the audio format as announced by para_server. */
108 int current_audio_format_num;
109 };
110
111 /** The array of status items sent by para_server. */
112 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
113
114 /**
115 * the current mode of operation of which can be changed by the on/off/cycle
116 * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
117 */
118 int audiod_status = AUDIOD_ON;
119
120 /**
121 * the gengetopt args_info struct that holds information on all command line
122 * arguments
123 */
124 struct audiod_args_info conf;
125
126 static char *socket_name;
127 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
128
129 static struct signal_task signal_task_struct, *sig_task = &signal_task_struct;
130
131 static struct status_task status_task_struct;
132
133 /**
134 * the task that calls the status command of para_server
135 *
136 * \sa struct status_task
137 */
138 static struct status_task *stat_task = &status_task_struct;
139 static struct timeval initial_delay_barrier;
140
141 /**
142 * the task for handling audiod commands
143 *
144 * \sa struct task, struct sched
145 */
146 struct command_task {
147 /** the local listening socket */
148 int fd;
149 /** the associated task structure */
150 struct task task;
151 };
152
153 /** iterate over all supported audio formats */
154 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
155
156 /**
157 * get the audio format number
158 * \param name the name of the audio format
159 *
160 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
161 * \a name is not a supported audio format.
162 */
163 int get_audio_format_num(char *name)
164 {
165 int i;
166
167 while (para_isspace(*name))
168 name++;
169 FOR_EACH_AUDIO_FORMAT(i)
170 if (!strcmp(name, audio_formats[i]))
171 return i;
172 return -E_UNSUPPORTED_AUDIO_FORMAT;
173 }
174
175 char *get_time_string(int slot_num)
176 {
177 int ret, seconds = 0, length;
178 struct timeval *tmp, sum, sss, /* server stream start */
179 wtime, /* now - writer start */
180 rskip; /* receiver start - sss */
181 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
182
183 if (audiod_status == AUDIOD_OFF)
184 goto empty;
185 if (!(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)) {
186 if (stat_task->length_seconds) /* paused */
187 return NULL;
188 goto empty; /* stopped */
189 }
190 if (audiod_status == AUDIOD_ON && !s)
191 goto empty;
192 /* valid status items and playing */
193 if (s) { /* writer active in this slot */
194 length = s->seconds_total;
195 tmp = &s->server_stream_start;
196 } else { /* standby mode, rely on status items */
197 length = stat_task->length_seconds;
198 tmp = &stat_task->server_stream_start;
199 }
200 if (stat_task->sa_time_diff_sign > 0)
201 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
202 else
203 tv_add(tmp, &stat_task->sa_time_diff, &sss);
204 if (!s) {
205 struct timeval diff;
206 tv_diff(now, &sss, &diff);
207 seconds = diff.tv_sec + stat_task->offset_seconds;
208 goto out;
209 }
210 tv_diff(now, &s->wstime, &wtime);
211 seconds = s->offset_seconds;
212 ret = tv_diff(&s->rstime, &sss, &rskip);
213 if (ret > 0) { /* audiod was started in the middle of the stream */
214 tv_add(&wtime, &rskip, &sum);
215 seconds += sum.tv_sec;
216 } else
217 seconds += wtime.tv_sec;
218 out:
219 seconds = PARA_MIN(seconds, length);
220 seconds = PARA_MAX(seconds, 0);
221 return make_message(
222 "%s: %s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
223 status_item_list[SI_PLAY_TIME],
224 s? "" : "~",
225 seconds / 60,
226 seconds % 60,
227 (length - seconds) / 60,
228 (length - seconds) % 60,
229 length? (seconds * 100 + length / 2) / length : 0,
230 length / 60,
231 length % 60
232 );
233 empty:
234 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
235 }
236
237 static int want_colors(void)
238 {
239 if (conf.color_arg == color_arg_no)
240 return 0;
241 if (conf.color_arg == color_arg_yes)
242 return 1;
243 if (conf.logfile_given)
244 return 0;
245 return isatty(STDERR_FILENO);
246 }
247
248 static void parse_config_or_die(void)
249 {
250 int ret;
251 char *config_file;
252 struct audiod_cmdline_parser_params params = {
253 .override = 0,
254 .initialize = 0,
255 .check_required = 1,
256 .check_ambiguity = 0,
257 .print_errors = 1
258 };
259
260 if (conf.config_file_given)
261 config_file = para_strdup(conf.config_file_arg);
262 else {
263 char *home = para_homedir();
264 config_file = make_message("%s/.paraslash/audiod.conf", home);
265 free(home);
266 }
267 ret = file_exists(config_file);
268 if (conf.config_file_given && !ret) {
269 PARA_EMERG_LOG("can not read config file %s\n", config_file);
270 goto err;
271 }
272 if (ret)
273 audiod_cmdline_parser_config_file(config_file, &conf, &params);
274 free(config_file);
275 daemon_set_loglevel(conf.loglevel_arg);
276 return;
277 err:
278 free(config_file);
279 exit(EXIT_FAILURE);
280 }
281
282 static void setup_signal_handling(void)
283 {
284 sig_task->fd = para_signal_init();
285 PARA_INFO_LOG("signal pipe: fd %d\n", sig_task->fd);
286 para_install_sighandler(SIGINT);
287 para_install_sighandler(SIGTERM);
288 para_install_sighandler(SIGHUP);
289 para_sigaction(SIGPIPE, SIG_IGN);
290 }
291
292 static void clear_slot(int slot_num)
293 {
294 struct slot_info *s = &slot[slot_num];
295
296 PARA_INFO_LOG("clearing slot %d\n", slot_num);
297 memset(s, 0, sizeof(struct slot_info));
298 s->format = -1;
299 }
300
301 static void close_receiver(int slot_num)
302 {
303 struct slot_info *s = &slot[slot_num];
304 struct audio_format_info *a;
305
306 if (s->format < 0 || !s->receiver_node)
307 return;
308 a = &afi[s->format];
309 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
310 audio_formats[s->format], slot_num);
311 a->receiver->close(s->receiver_node);
312 free(s->receiver_node);
313 s->receiver_node = NULL;
314 stat_task->current_audio_format_num = -1;
315 }
316
317 static void kill_all_decoders(int error)
318 {
319 int i;
320
321 FOR_EACH_SLOT(i) {
322 struct slot_info *s = &slot[i];
323 if (s->wng && s->wng->task.error >= 0) {
324 PARA_INFO_LOG("deactivating wng in slot %d\n",
325 i);
326 s->wng->task.error = error;
327 }
328 if (s->fc && s->fc->task.error >= 0) {
329 PARA_INFO_LOG("deactivatimg filter chain in slot %d\n", i);
330 s->fc->task.error = error;
331 }
332 if (s->receiver_node && s->receiver_node->task.error >= 0) {
333 PARA_INFO_LOG("deactivating receiver_node in slot %d\n", i);
334 s->receiver_node->task.error = error;
335 }
336 }
337 }
338
339 static int get_empty_slot(void)
340 {
341 int i;
342 struct slot_info *s;
343
344 FOR_EACH_SLOT(i) {
345 s = &slot[i];
346 if (s->format < 0) {
347 clear_slot(i);
348 return i;
349 }
350 if (s->wng || s->receiver_node || s->fc)
351 continue;
352 clear_slot(i);
353 return i;
354 }
355 return -E_NO_MORE_SLOTS;
356 }
357
358 /**
359 * get the number of filters
360 *
361 * \param audio_format_num the number identifying the audio format
362 *
363 * \return the number of filters for the given audio format
364 *
365 * \sa struct filter;
366 */
367 int num_filters(int audio_format_num)
368 {
369 return afi[audio_format_num].num_filters;
370 }
371
372 static void open_filters(int slot_num)
373 {
374 struct slot_info *s = &slot[slot_num];
375 struct audio_format_info *a = &afi[s->format];
376 struct filter_node *fn;
377 int nf = a->num_filters;
378 int i;
379
380 s->fc = NULL;
381 if (!nf)
382 return;
383 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
384 s->fc = para_calloc(sizeof(struct filter_chain));
385 s->fc->filter_nodes = para_malloc(nf * sizeof(struct filter_node));
386 s->fc->inbufp = &s->receiver_node->buf;
387 s->fc->in_loaded = &s->receiver_node->loaded;
388 s->fc->input_error = &s->receiver_node->task.error;
389 s->fc->task.pre_select = NULL;
390 s->fc->task.post_select = filter_post_select;
391 s->fc->task.error = 0;
392 s->fc->num_filters = nf;
393
394 s->receiver_node->output_error = &s->fc->task.error;
395 sprintf(s->fc->task.status, "filter chain");
396 FOR_EACH_FILTER_NODE(fn, s->fc, i) {
397 struct filter *f = filters + a->filter_nums[i];
398 fn->filter_num = a->filter_nums[i];
399 fn->conf = a->filter_conf[i];
400 fn->fc = s->fc;
401 fn->loaded = 0;
402 INIT_LIST_HEAD(&fn->callbacks);
403 f->open(fn);
404 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
405 audio_formats[s->format], i, nf, f->name, slot_num);
406 s->fc->outbufp = &fn->buf;
407 s->fc->out_loaded = &fn->loaded;
408 }
409 register_task(&s->fc->task);
410 }
411
412 static void open_writers(int slot_num)
413 {
414 int ret, i;
415 struct slot_info *s = &slot[slot_num];
416 struct audio_format_info *a = &afi[s->format];
417
418 PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
419 if (!a->num_writers)
420 s->wng = setup_default_wng();
421 else
422 s->wng = wng_new(a->num_writers);
423 if (s->fc) {
424 s->wng->bufp = s->fc->outbufp;
425 s->wng->loaded = s->fc->out_loaded;
426 s->wng->input_error = &s->fc->task.error;
427 s->wng->channels = &s->fc->channels;
428 s->wng->samplerate = &s->fc->samplerate;
429 s->fc->output_error = &s->wng->task.error;
430 PARA_INFO_LOG("samplerate: %d\n", *s->wng->samplerate);
431 } else {
432 s->wng->bufp = &s->receiver_node->buf;
433 s->wng->loaded = &s->receiver_node->loaded;
434 s->wng->input_error = &s->receiver_node->task.error;
435 }
436 for (i = 0; i < a->num_writers; i++) {
437 s->wng->writer_nodes[i].conf = a->writer_conf[i];
438 s->wng->writer_nodes[i].writer_num = a->writer_nums[i];
439 }
440 ret = wng_open(s->wng);
441 if (ret < 0)
442 return;
443 s->wstime = *now;
444 s->server_stream_start = stat_task->server_stream_start.tv_sec?
445 stat_task->server_stream_start : *now;
446 s->offset_seconds = stat_task->offset_seconds;
447 s->seconds_total = stat_task->length_seconds;
448 activate_inactive_grab_clients(slot_num, s->format, s->fc);
449 }
450
451 static int open_receiver(int format)
452 {
453 struct audio_format_info *a = &afi[format];
454 struct slot_info *s;
455 int ret, slot_num;
456 struct receiver_node *rn;
457 const struct timeval restart_delay = {2, 0};
458
459 ret = get_empty_slot();
460 if (ret < 0)
461 goto err;
462 slot_num = ret;
463 s = &slot[slot_num];
464 s->format = format;
465 s->receiver_node = para_calloc(sizeof(struct receiver_node));
466 rn = s->receiver_node;
467 rn->receiver = a->receiver;
468 rn->conf = a->receiver_conf;
469 ret = a->receiver->open(s->receiver_node);
470 if (ret < 0) {
471 free(s->receiver_node);
472 s->receiver_node = NULL;
473 goto err;
474 }
475 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
476 audio_formats[s->format], a->receiver->name, slot_num);
477 rn->task.pre_select = a->receiver->pre_select;
478 rn->task.post_select = a->receiver->post_select;
479 s->rstime = *now;
480 sprintf(rn->task.status, "%s receiver node", rn->receiver->name);
481 register_task(&rn->task);
482 ret = 1;
483 err:
484 if (ret < 0)
485 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
486 tv_add(now, &restart_delay, &afi[format].restart_barrier);
487 return ret;
488 }
489
490 /* return: 0: Not running, 1: Running, -1: Running but eof (or error) */
491 static int receiver_running(int format)
492 {
493 int i, ret = 0;
494
495 FOR_EACH_SLOT(i) {
496 struct slot_info *s = &slot[i];
497 if (s->format != format)
498 continue;
499 if (!s->receiver_node)
500 continue;
501 if (s->receiver_node->task.error >= 0)
502 return 1;
503 ret = -1;
504 }
505 return ret;
506 }
507
508 static void open_current_receiver(struct sched *s)
509 {
510 struct timeval diff;
511 int ret, cafn = stat_task->current_audio_format_num;
512
513 if (cafn < 0 || !stat_task->ct)
514 return;
515 /* Do nothing if the 'N' flag is set or the 'P' flag is unset */
516 if (stat_task->vss_status != VSS_STATUS_FLAG_PLAYING)
517 return;
518 ret = receiver_running(cafn);
519 if (ret > 0) /* already running and not eof */
520 return;
521 if (ret < 0) { /* eof */
522 /*
523 * para_server uses a zero start time during the announcement
524 * period, i.e. before it sends the first chunk. Wait until
525 * this period begins to avoid restarting the receiver that
526 * belongs to the file just completed.
527 */
528 if (stat_task->server_stream_start.tv_sec)
529 return;
530 }
531 if (tv_diff(now, &afi[cafn].restart_barrier, &diff) < 0) {
532 /* avoid busy loop */
533 s->timeout = diff;
534 return;
535 }
536 /* start a new receiver */
537 open_receiver(cafn);
538 }
539
540 static unsigned compute_time_diff(const struct timeval *status_time)
541 {
542 struct timeval tmp, diff;
543 static unsigned count;
544 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
545 const struct timeval max_deviation = {0, 500 * 1000};
546 const int time_smooth = 5;
547
548 if (!status_time)
549 return count;
550 sign = tv_diff(status_time, now, &diff);
551 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
552 // sign, sa_time_diff_sign);
553 if (!count) {
554 sa_time_diff_sign = sign;
555 stat_task->sa_time_diff = diff;
556 count++;
557 goto out;
558 }
559 if (count > 5) {
560 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
561 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
562 PARA_WARNING_LOG("time diff jump: %lims\n",
563 s * tv2ms(&tmp));
564 }
565 count++;
566 sa_time_diff_sign = tv_convex_combination(
567 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
568 count > 10? sign : sign * time_smooth, &diff,
569 &tmp);
570 stat_task->sa_time_diff = tmp;
571 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
572 sign > 0? "+" : "-",
573 tv2ms(&diff),
574 sa_time_diff_sign ? "+" : "-",
575 tv2ms(&stat_task->sa_time_diff)
576 );
577 out:
578 stat_task->sa_time_diff_sign = sa_time_diff_sign;
579 return count;
580 }
581
582 static int check_stat_line(char *line, __a_unused void *data)
583 {
584 int itemnum;
585 size_t ilen = 0;
586 long unsigned sec, usec;
587 char *tmp;
588
589 //PARA_INFO_LOG("line: %s\n", line);
590 if (!line)
591 return 1;
592 itemnum = stat_line_valid(line);
593 if (itemnum < 0) {
594 PARA_WARNING_LOG("invalid status line: %s\n", line);
595 return 1;
596 }
597 if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
598 return 1;
599 tmp = make_message("%s\n", line);
600 stat_client_write(tmp, itemnum);
601 free(tmp);
602 free(stat_item_values[itemnum]);
603 stat_item_values[itemnum] = para_strdup(line);
604 ilen = strlen(status_item_list[itemnum]);
605 switch (itemnum) {
606 case SI_STATUS_FLAGS:
607 stat_task->vss_status = 0;
608 if (strchr(line, 'N'))
609 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
610 if (strchr(line, 'P'))
611 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
612 break;
613 case SI_OFFSET:
614 stat_task->offset_seconds = atoi(line + ilen + 1);
615 break;
616 case SI_SECONDS_TOTAL:
617 stat_task->length_seconds = atoi(line + ilen + 1);
618 break;
619 case SI_STREAM_START:
620 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
621 struct timeval a_start, delay;
622 delay.tv_sec = conf.stream_delay_arg / 1000;
623 delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
624 stat_task->server_stream_start.tv_sec = sec;
625 stat_task->server_stream_start.tv_usec = usec;
626 if (compute_time_diff(NULL) > 2) {
627 if (stat_task->sa_time_diff_sign < 0)
628 tv_add(&stat_task->server_stream_start,
629 &stat_task->sa_time_diff, &a_start);
630 else
631 tv_diff(&stat_task->server_stream_start,
632 &stat_task->sa_time_diff, &a_start);
633 tv_add(&a_start, &delay, &initial_delay_barrier);
634 }
635 }
636 break;
637 case SI_CURRENT_TIME:
638 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
639 struct timeval tv = {sec, usec};
640 compute_time_diff(&tv);
641 }
642 break;
643 case SI_FORMAT:
644 stat_task->current_audio_format_num = get_audio_format_num(
645 line + ilen + 1);
646 }
647 return 1;
648 }
649
650 static int parse_stream_command(const char *txt, char **cmd)
651 {
652 char *p = strchr(txt, ':');
653 int i;
654
655 if (!p)
656 return -E_MISSING_COLON;
657 p++;
658 FOR_EACH_AUDIO_FORMAT(i) {
659 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
660 continue;
661 *cmd = p;
662 return i;
663 }
664 return -E_UNSUPPORTED_AUDIO_FORMAT;
665 }
666
667 static int add_filter(int format, char *cmdline)
668 {
669 struct audio_format_info *a = &afi[format];
670 int filter_num, nf = a->num_filters;
671
672 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
673 if (filter_num < 0)
674 return filter_num;
675 a->filter_nums[nf] = filter_num;
676 a->num_filters++;
677 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
678 filters[filter_num].name);
679 return filter_num;
680 }
681
682 static int parse_writer_args(void)
683 {
684 int i, ret, nw;
685 char *cmd;
686 struct audio_format_info *a;
687
688 nw = PARA_MAX(1U, conf.writer_given);
689 PARA_INFO_LOG("maximal number of writers: %d\n", nw);
690 FOR_EACH_AUDIO_FORMAT(i) {
691 a = &afi[i];
692 a->writer_conf = para_malloc(nw * sizeof(void *));
693 a->writer_nums = para_malloc(nw * sizeof(int));
694 a->num_writers = 0;
695 }
696 for (i = 0; i < conf.writer_given; i++) {
697 void *wconf;
698 int writer_num;
699 ret = parse_stream_command(conf.writer_arg[i], &cmd);
700 if (ret < 0)
701 goto out;
702 a = &afi[ret];
703 nw = a->num_writers;
704 wconf = check_writer_arg(cmd, &writer_num);
705 if (!wconf) {
706 ret = writer_num;
707 goto out;
708 }
709 a->writer_nums[nw] = writer_num;
710 a->writer_conf[nw] = wconf;
711 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
712 nw, writer_names[writer_num]);
713 a->num_writers++;
714 }
715 ret = 1;
716 out:
717 return ret;
718 }
719
720 static int parse_receiver_args(void)
721 {
722 int i, ret, receiver_num;
723 char *cmd = NULL;
724 struct audio_format_info *a;
725
726 for (i = conf.receiver_given - 1; i >= 0; i--) {
727 char *arg = conf.receiver_arg[i];
728 char *recv_arg = strchr(arg, ':');
729 ret = -E_MISSING_COLON;
730 if (!recv_arg)
731 goto out;
732 *recv_arg = '\0';
733 recv_arg++;
734 ret = get_audio_format_num(arg);
735 if (ret < 0)
736 goto out;
737 afi[ret].receiver_conf = check_receiver_arg(recv_arg, &receiver_num);
738 if (!afi[ret].receiver_conf) {
739 ret = -E_RECV_SYNTAX;
740 goto out;
741 }
742 afi[ret].receiver = &receivers[receiver_num];
743 }
744 /* use the first available receiver with no arguments
745 * for those audio formats for which no receiver
746 * was specified
747 */
748 cmd = para_strdup(receivers[0].name);
749 FOR_EACH_AUDIO_FORMAT(i) {
750 a = &afi[i];
751 if (a->receiver_conf)
752 continue;
753 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
754 if (!a->receiver_conf)
755 return -E_RECV_SYNTAX;
756 a->receiver = &receivers[receiver_num];
757 }
758 ret = 1;
759 out:
760 free(cmd);
761 return ret;
762 }
763
764 static int init_default_filters(void)
765 {
766 int i, ret = 1;
767
768 FOR_EACH_AUDIO_FORMAT(i) {
769 struct audio_format_info *a = &afi[i];
770 char *tmp;
771 int j;
772
773 if (a->num_filters)
774 continue; /* no default -- nothing to to */
775 /* add "dec" to audio format name */
776 tmp = make_message("%sdec", audio_formats[i]);
777 for (j = 0; filters[j].name; j++)
778 if (!strcmp(tmp, filters[j].name))
779 break;
780 free(tmp);
781 ret = -E_UNSUPPORTED_FILTER;
782 if (!filters[j].name)
783 goto out;
784 tmp = para_strdup(filters[j].name);
785 ret = add_filter(i, tmp);
786 free(tmp);
787 if (ret < 0)
788 goto out;
789 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
790 filters[j].name);
791 }
792 out:
793 return ret;
794 }
795
796 static int parse_filter_args(void)
797 {
798 int i, ret, nf;
799
800 nf = PARA_MAX(1U, conf.filter_given);
801 PARA_INFO_LOG("maximal number of filters: %d\n", nf);
802 FOR_EACH_AUDIO_FORMAT(i) {
803 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
804 afi[i].filter_nums = para_malloc(nf * sizeof(unsigned));
805 }
806 if (!conf.no_default_filters_given)
807 return init_default_filters();
808 for (i = 0; i < conf.filter_given; i++) {
809 char *arg = conf.filter_arg[i];
810 char *filter_name = strchr(arg, ':');
811 ret = -E_MISSING_COLON;
812 if (!filter_name)
813 goto out;
814 *filter_name = '\0';
815 filter_name++;
816 ret = get_audio_format_num(arg);
817 if (ret < 0)
818 goto out;
819 ret = add_filter(ret, filter_name);
820 if (ret < 0)
821 goto out;
822 }
823 ret = init_default_filters(); /* use default values for the rest */
824 out:
825 return ret;
826 }
827
828 static int parse_stream_args(void)
829 {
830 int ret;
831
832 ret = parse_receiver_args();
833 if (ret < 0)
834 return ret;
835 ret = parse_filter_args();
836 if (ret < 0)
837 return ret;
838 ret = parse_writer_args();
839 if (ret < 0)
840 return ret;
841 return 1;
842 }
843
844 /* does not unlink socket on errors */
845 static int audiod_get_socket(void)
846 {
847 struct sockaddr_un unix_addr;
848 int ret, fd;
849
850 if (conf.socket_given)
851 socket_name = para_strdup(conf.socket_arg);
852 else {
853 char *hn = para_hostname();
854 socket_name = make_message("/var/paraslash/audiod_socket.%s",
855 hn);
856 free(hn);
857 }
858 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
859 if (conf.force_given)
860 unlink(socket_name);
861 ret = create_local_socket(socket_name, &unix_addr,
862 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
863 if (ret < 0)
864 goto err;
865 fd = ret;
866 if (listen(fd , 5) < 0) {
867 ret = -ERRNO_TO_PARA_ERROR(errno);
868 goto err;
869 }
870 ret = mark_fd_nonblocking(fd);
871 if (ret < 0)
872 goto err;
873 return fd;
874 err:
875 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
876 exit(EXIT_FAILURE);
877 }
878
879 static void signal_pre_select(struct sched *s, struct task *t)
880 {
881 struct signal_task *st = container_of(t, struct signal_task, task);
882 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
883 }
884
885 static void signal_post_select(struct sched *s, struct task *t)
886 {
887 struct signal_task *st = container_of(t, struct signal_task, task);
888
889 if (!FD_ISSET(st->fd, &s->rfds))
890 return;
891
892 st->signum = para_next_signal();
893 switch (st->signum) {
894 case SIGINT:
895 case SIGTERM:
896 case SIGHUP:
897 PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
898 clean_exit(EXIT_FAILURE, "caught deadly signal");
899 }
900 }
901
902 static void signal_setup_default(struct signal_task *st)
903 {
904 st->task.pre_select = signal_pre_select;
905 st->task.post_select = signal_post_select;
906 sprintf(st->task.status, "signal task");
907 }
908
909 static void command_pre_select(struct sched *s, struct task *t)
910 {
911 struct command_task *ct = container_of(t, struct command_task, task);
912 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
913 }
914
915 static void command_post_select(struct sched *s, struct task *t)
916 {
917 int ret;
918 struct command_task *ct = container_of(t, struct command_task, task);
919
920 audiod_status_dump();
921 if (!FD_ISSET(ct->fd, &s->rfds))
922 return;
923 ret = handle_connect(ct->fd);
924 if (ret < 0)
925 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
926 }
927
928 static void init_command_task(struct command_task *ct)
929 {
930 ct->task.pre_select = command_pre_select;
931 ct->task.post_select = command_post_select;
932 ct->task.error = 0;
933 ct->fd = audiod_get_socket(); /* doesn't return on errors */
934 sprintf(ct->task.status, "command task");
935 }
936
937 static void close_stat_pipe(void)
938 {
939 int i;
940
941 if (!stat_task->ct)
942 return;
943 client_close(stat_task->ct);
944 stat_task->ct = NULL;
945 FOR_EACH_STATUS_ITEM(i) {
946 free(stat_item_values[i]);
947 stat_item_values[i] = NULL;
948 }
949 dump_empty_status();
950 stat_task->length_seconds = 0;
951 stat_task->offset_seconds = 0;
952 stat_task->vss_status = 0;
953 stat_task->current_audio_format_num = -1;
954 audiod_status_dump();
955 }
956
957 /**
958 * close the connection to para_server and exit
959 *
960 * \param status the exit status which is passed to exit(3)
961 * \param msg the log message
962 *
963 * Log \a msg with loglevel \p EMERG, close the connection to para_server if
964 * open, and call \p exit(status). \a status should be either EXIT_SUCCESS or
965 * EXIT_FAILURE.
966 *
967 * \sa exit(3)
968 */
969 void __noreturn clean_exit(int status, const char *msg)
970 {
971 PARA_EMERG_LOG("%s\n", msg);
972 if (socket_name)
973 unlink(socket_name);
974 close_stat_pipe();
975 exit(status);
976 }
977
978 /* avoid busy loop if server is down */
979 static void set_stat_task_restart_barrier(unsigned seconds)
980 {
981 struct timeval delay = {seconds, 0};
982 tv_add(now, &delay, &stat_task->restart_barrier);
983 }
984
985 static void try_to_close_slot(int slot_num)
986 {
987 struct slot_info *s = &slot[slot_num];
988
989 if (s->format < 0)
990 return;
991 if (s->receiver_node && s->receiver_node->task.error != -E_TASK_UNREGISTERED)
992 return;
993 if (s->fc && s->fc->task.error != -E_TASK_UNREGISTERED)
994 return;
995 if (s->wng && s->wng->task.error != -E_TASK_UNREGISTERED)
996 return;
997 PARA_INFO_LOG("closing slot %d\n", slot_num);
998 wng_close(s->wng);
999 close_filters(s->fc);
1000 free(s->fc);
1001 close_receiver(slot_num);
1002 clear_slot(slot_num);
1003 }
1004
1005 /*
1006 * Check if any receivers/filters/writers need to be started and do so if
1007 * necessary.
1008 */
1009 static void start_stop_decoders(struct sched *s)
1010 {
1011 int i;
1012
1013 FOR_EACH_SLOT(i)
1014 try_to_close_slot(i);
1015 if (audiod_status != AUDIOD_ON ||
1016 !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1017 return kill_all_decoders(-E_NOT_PLAYING);
1018 open_current_receiver(s);
1019 FOR_EACH_SLOT(i) {
1020 struct slot_info *sl = &slot[i];
1021 struct audio_format_info *a;
1022 struct timeval diff;
1023
1024 if (sl->format < 0)
1025 continue;
1026 a = &afi[sl->format];
1027 if (!sl->receiver_node)
1028 continue;
1029 if ((!a->num_filters || sl->fc) && sl->wng)
1030 continue; /* everything already started */
1031 if (!a->num_filters) {
1032 if (sl->receiver_node->loaded && !sl->wng) {
1033 open_writers(i);
1034 }
1035 continue;
1036 }
1037 if (sl->receiver_node->loaded && !sl->fc) {
1038 open_filters(i);
1039 continue;
1040 }
1041 if (sl->wng || !sl->fc || !*sl->fc->out_loaded)
1042 continue;
1043 if (tv_diff(now, &initial_delay_barrier, &diff) > 0) {
1044 open_writers(i);
1045 continue;
1046 }
1047 PARA_INFO_LOG("initial delay: %lu ms left\n", tv2ms(&diff));
1048 if (tv_diff(&s->timeout, &diff, NULL) > 0) {
1049 s->timeout = diff;
1050 }
1051 }
1052 }
1053
1054
1055 /* restart the client task if necessary */
1056 static void status_pre_select(struct sched *s, struct task *t)
1057 {
1058 struct status_task *st = container_of(t, struct status_task, task);
1059
1060 if (audiod_status == AUDIOD_OFF) {
1061 if (!st->ct)
1062 goto out;
1063 if (st->ct->task.error >= 0) {
1064 st->ct->task.error = -E_AUDIOD_OFF;
1065 goto out;
1066 }
1067 if (st->ct->task.error != -E_TASK_UNREGISTERED)
1068 goto out;
1069 close_stat_pipe();
1070 st->clock_diff_count = conf.clock_diff_count_arg;
1071 goto out;
1072 }
1073 if (st->ct) {
1074 unsigned bytes_left;
1075 if (st->ct->task.error < 0) {
1076 if (st->ct->task.error != -E_TASK_UNREGISTERED)
1077 goto out;
1078 close_stat_pipe();
1079 goto out;
1080 }
1081 if (st->ct->status != CL_RECEIVING)
1082 goto out;
1083 bytes_left = for_each_line(st->ct->buf, st->ct->loaded,
1084 &check_stat_line, NULL);
1085 if (st->ct->loaded != bytes_left) {
1086 st->last_status_read = *now;
1087 st->ct->loaded = bytes_left;
1088 } else {
1089 struct timeval diff;
1090 tv_diff(now, &st->last_status_read, &diff);
1091 if (diff.tv_sec > 61)
1092 st->ct->task.error = -E_STATUS_TIMEOUT;
1093 }
1094 goto out;
1095 }
1096 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1097 goto out;
1098 if (st->clock_diff_count) { /* get status only one time */
1099 char *argv[] = {"audiod", "stat", "1", NULL};
1100 int argc = 3;
1101 PARA_INFO_LOG("clock diff count: %d\n", st->clock_diff_count);
1102 st->clock_diff_count--;
1103 client_open(argc, argv, &st->ct, NULL);
1104 set_stat_task_restart_barrier(2);
1105
1106 } else {
1107 char *argv[] = {"audiod", "stat", NULL};
1108 int argc = 2;
1109 client_open(argc, argv, &st->ct, NULL);
1110 set_stat_task_restart_barrier(5);
1111 }
1112 free(stat_item_values[SI_BASENAME]);
1113 stat_item_values[SI_BASENAME] = make_message(
1114 "%s: no connection to para_server\n",
1115 status_item_list[SI_BASENAME]);
1116 stat_client_write(stat_item_values[SI_BASENAME],
1117 SI_BASENAME);
1118 st->last_status_read = *now;
1119 out:
1120 start_stop_decoders(s);
1121 }
1122
1123 static void init_status_task(struct status_task *st)
1124 {
1125 memset(st, 0, sizeof(struct status_task));
1126 st->task.pre_select = status_pre_select;
1127 st->sa_time_diff_sign = 1;
1128 st->clock_diff_count = conf.clock_diff_count_arg;
1129 st->current_audio_format_num = -1;
1130 sprintf(st->task.status, "status task");
1131 }
1132
1133 static void set_initial_status(void)
1134 {
1135 audiod_status = AUDIOD_ON;
1136 if (!conf.mode_given)
1137 return;
1138 if (!strcmp(conf.mode_arg, "sb")) {
1139 audiod_status = AUDIOD_STANDBY;
1140 return;
1141 }
1142 if (!strcmp(conf.mode_arg, "off")) {
1143 audiod_status = AUDIOD_OFF;
1144 return;
1145 }
1146 if (strcmp(conf.mode_arg, "on"))
1147 PARA_WARNING_LOG("invalid mode\n");
1148 }
1149
1150 __noreturn static void print_help_and_die(void)
1151 {
1152 int d = conf.detailed_help_given;
1153 const char **p = d? audiod_args_info_detailed_help
1154 : audiod_args_info_help;
1155
1156 printf_or_die("%s\n\n", AUDIOD_CMDLINE_PARSER_PACKAGE "-"
1157 AUDIOD_CMDLINE_PARSER_VERSION);
1158 printf_or_die("%s\n\n", audiod_args_info_usage);
1159 for (; *p; p++)
1160 printf_or_die("%s\n", *p);
1161 print_receiver_helps(d);
1162 print_filter_helps(d);
1163 print_writer_helps(d);
1164 exit(0);
1165 }
1166
1167 static void init_colors_or_die(void)
1168 {
1169 int ret, i;
1170
1171 if (!want_colors())
1172 return;
1173 daemon_set_default_log_colors();
1174 daemon_set_flag(DF_COLOR_LOG);
1175 for (i = 0; i < conf.log_color_given; i++) {
1176 ret = daemon_set_log_color(conf.log_color_arg[i]);
1177 if (ret < 0)
1178 exit(EXIT_FAILURE);
1179 }
1180 }
1181
1182 /**
1183 * the main function of para_audiod
1184 *
1185 * \param argc usual argument count
1186 * \param argv usual argument vector
1187 *
1188 * \return EXIT_SUCCESS or EXIT_FAILURE
1189 *
1190 * \sa para_audiod(1)
1191 * */
1192 int main(int argc, char *argv[])
1193 {
1194 int ret, i;
1195 static struct sched s;
1196 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1197 struct audiod_cmdline_parser_params params = {
1198 .override = 0,
1199 .initialize = 1,
1200 .check_required = 0,
1201 .check_ambiguity = 0,
1202 .print_errors = 1
1203 };
1204
1205 valid_fd_012();
1206 if (audiod_cmdline_parser_ext(argc, argv, &conf, &params))
1207 exit(EXIT_FAILURE);
1208 HANDLE_VERSION_FLAG("audiod", conf);
1209 /* init receivers/filters/writers early to make help work */
1210 recv_init();
1211 filter_init();
1212 writer_init();
1213 if (conf.help_given || conf.detailed_help_given)
1214 print_help_and_die();
1215 drop_privileges_or_die(conf.user_arg, conf.group_arg);
1216 parse_config_or_die();
1217 init_colors_or_die();
1218 daemon_set_flag(DF_LOG_TIME);
1219 daemon_set_flag(DF_LOG_HOSTNAME);
1220 daemon_set_flag(DF_LOG_LL);
1221 if (conf.logfile_given) {
1222 daemon_set_logfile(conf.logfile_arg);
1223 daemon_open_log_or_die();
1224 }
1225 ret = parse_stream_args();
1226 if (ret < 0) {
1227 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1228 exit(EXIT_FAILURE);
1229 }
1230 log_welcome("para_audiod");
1231 server_uptime(UPTIME_SET);
1232 set_initial_status();
1233 FOR_EACH_SLOT(i)
1234 clear_slot(i);
1235 init_grabbing();
1236 setup_signal_handling();
1237 signal_setup_default(sig_task);
1238
1239 init_status_task(stat_task);
1240 init_command_task(cmd_task);
1241
1242 if (conf.daemon_given)
1243 daemonize();
1244
1245 register_task(&sig_task->task);
1246 register_task(&cmd_task->task);
1247 register_task(&stat_task->task);
1248 s.default_timeout.tv_sec = 0;
1249 s.default_timeout.tv_usec = 99 * 1000;
1250 ret = schedule(&s);
1251
1252 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1253 return EXIT_FAILURE;
1254 }