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