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