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