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