simplify writer node group
[paraslash.git] / audiod.c
1 /*
2 * Copyright (C) 2005-2006 Andre Noll <noll@mathematik.tu-darmstadt.de>
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 "close_on_fork.h"
26 #include "sched.h"
27 #include "recv.h"
28 #include "filter.h"
29 #include "grab_client.cmdline.h"
30 #include "grab_client.h"
31
32 #include "error.h"
33 #include "audiod.h"
34 #include "net.h"
35 #include "daemon.h"
36 #include "string.h"
37 #include "fd.h"
38 #include "write.h"
39 #include "write_common.h"
40
41 /** define the array of error lists needed by para_audiod */
42 INIT_AUDIOD_ERRLISTS;
43 /** define the array containing all supported audio formats */
44 DEFINE_AUDIO_FORMAT_ARRAY;
45
46 /**
47 * the possible modes of operation
48 *
49 * - off: disconnect from para_server
50 * - on: receive status information from para_server and play the audio stream
51 * - sb: only receive status information but not the audio stream
52 */
53 enum {AUDIOD_OFF, AUDIOD_ON, AUDIOD_STANDBY};
54
55 /** defines how to handle one supported audio format */
56 struct audio_format_info {
57 /** pointer to the receiver for this audio format */
58 struct receiver *receiver;
59 /** the receiver configuration */
60 void *receiver_conf;
61 /** the number of filters that should be activated for this audio format */
62 unsigned int num_filters;
63 /** pointer to the array of filters to be activated */
64 struct filter **filters;
65 /** pointer to the array of filter configurations */
66 void **filter_conf;
67 /** the number of filters that should be activated for this audio format */
68 unsigned int num_writers;
69 /** pointer to the array of writers to be activated */
70 struct writer **writers;
71 /** pointer to the array of writer configurations */
72 void **writer_conf;
73 /** do not start receiver/filters/writer before this time */
74 struct timeval restart_barrier;
75 };
76
77 /**
78 * describes one instance of a receiver-filter-writer chain
79 *
80 * \sa receier_node, receiver, filter, filter_node, filter_chain, writer,
81 * writer_node, writer_node_group.
82 */
83 struct slot_info {
84 /** number of the audio format in this slot */
85 int format;
86 /** writer start time */
87 struct timeval wstime;
88 /** the receiver info associated with this slot */
89 struct receiver_node *receiver_node;
90 /** the active filter chain */
91 struct filter_chain *fc;
92 /** the active writer node group */
93 struct writer_node_group *wng;
94 };
95 static struct slot_info slot[MAX_STREAM_SLOTS];
96
97 extern const char *status_item_list[NUM_STAT_ITEMS];
98
99 static struct gengetopt_args_info conf;
100 static struct timeval server_stream_start, sa_time_diff;
101 static int playing, current_decoder = -1,
102 audiod_status = AUDIOD_ON, offset_seconds, length_seconds,
103 sa_time_diff_sign = 1;
104 static char *af_status, /* the audio format announced in server status */
105 *socket_name, *hostname;
106 static char *stat_item_values[NUM_STAT_ITEMS];
107 static FILE *logfile;
108 static const struct timeval restart_delay = {0, 200 * 1000};
109 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
110 static struct timeval *now;
111
112 static struct signal_task signal_task_struct, *sig_task = &signal_task_struct;
113
114 /**
115 * the task for handling audiod commands
116 *
117 * \sa struct task, struct sched
118 */
119 struct command_task {
120 /** the local listening socket */
121 int fd;
122 /** the associated task structure */
123 struct task task;
124 };
125
126 /**
127 * the task for audiod's child (para_client stat)
128 *
129 * \sa struct task, struct sched
130 */
131 struct status_task {
132 /** the output of the stat command is read from this fd */
133 int fd;
134 /** stat data is stored here */
135 char buf[STRINGSIZE];
136 /** number of bytes loaded in \a buf */
137 unsigned loaded;
138 /** the associated task structure */
139 struct task task;
140 /** do not restart client command until this time */
141 struct timeval restart_barrier;
142 };
143 static struct status_task status_task_struct, *stat_task = &status_task_struct;
144
145 struct signal_task {
146 int fd;
147 int signum;
148 struct task task;
149 };
150
151 /** defines one command of para_audiod */
152 struct audiod_command {
153 /** the name of the command */
154 const char *name;
155 /** pointer to the function that handles the command */
156 int (*handler)(int, int, char**);
157 /**
158 * if the command prefers to handle the full line (rather than the usual
159 * argv[] array), it stores a pointer to the corresponding line handling
160 * function here. In this case, the above \a handler pointer must be NULL.
161 */
162 int (*line_handler)(int, char*);
163 /** one-line description of the command */
164 const char *description;
165 /** summary of the command line options */
166 const char *synopsis;
167 /** the long help text */
168 const char *help;
169 };
170 static int com_grab(int, char *);
171 static int com_cycle(int, int, char **);
172 static int com_help(int, int, char **);
173 static int com_kill(int, int, char **);
174 static int com_off(int, int, char **);
175 static int com_on(int, int, char **);
176 static int com_sb(int, int, char **);
177 static int com_stat(int, int, char **);
178 static int com_tasks(int, int, char **);
179 static int com_term(int, int, char **);
180 static struct audiod_command cmds[] = {
181 {
182 .name = "cycle",
183 .handler = com_cycle,
184 .description = "switch to next mode",
185 .synopsis = "cycle",
186 .help =
187
188 "on -> standby -> off -> on\n"
189
190 },
191 {
192 .name = "grab",
193 .line_handler = com_grab,
194 .description = "grab the audio stream",
195 .synopsis = "-- grab [grab_options]",
196 .help =
197
198 "grab ('splice') the audio stream at any position in the filter \n"
199 "chain and send that data back to the client. Try\n"
200 "\t para_audioc -- grab -h\n"
201 "for the list of available options.\n"
202 },
203
204 {
205 .name = "help",
206 .handler = com_help,
207 .description = "display command list or help for given command",
208 .synopsis = "help [command]",
209 .help =
210
211 "When I was younger, so much younger than today, I never needed\n"
212 "anybody's help in any way. But now these days are gone, I'm not so\n"
213 "self assured. Now I find I've changed my mind and opened up the doors.\n"
214 "\n"
215 " -- Beatles: Help\n"
216
217 },
218 {
219 .name = "kill",
220 .handler = com_kill,
221 .description = "kill an active audiod task",
222 .synopsis = "kill task_id [task_id ...]",
223 .help =
224
225 "call sched_unregister() and the event_handler of the given task(s)\n"
226
227 },
228 {
229 .name = "off",
230 .handler = com_off,
231 .description = "deactivate para_audiod",
232 .synopsis = "off",
233 .help =
234
235 "Close connection to para_server and stop all decoders.\n"
236
237 },
238 {
239 .name = "on",
240 .handler = com_on,
241 .description = "activate para_audiod",
242 .synopsis = "on",
243 .help =
244
245 "Establish connection to para_server, retrieve para_server's current\n"
246 "status. If playing, start corresponding decoder. Otherwise stop\n"
247 "all decoders.\n"
248
249 },
250 {
251 .name = "sb",
252 .handler = com_sb,
253 .description = "enter standby mode",
254 .synopsis = "sb",
255 .help =
256
257 "Stop all decoders but leave connection to para_server open.\n"
258
259 },
260 {
261 .name = "stat",
262 .handler = com_stat,
263 .description = "print status information",
264 .synopsis = "stat [item1 ...]",
265 .help =
266
267 "Dump given status items (all if none given) to stdout.\n"
268
269 },
270 {
271 .name = "tasks",
272 .handler = com_tasks,
273 .description = "list current tasks",
274 .synopsis = "tasks",
275 .help =
276
277 "print the list of task ids together with the status of each task\n"
278
279 },
280 {
281 .name = "term",
282 .handler = com_term,
283 .description = "terminate audiod",
284 .synopsis = "term",
285 .help =
286
287 "Stop all decoders, shut down connection to para_server and exit.\n"
288
289 },
290 {
291 .name = NULL,
292 }
293 };
294
295 /** iterate over all slots */
296 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
297 /** iterate over all supported audio formats */
298 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
299 /** iterate over the array of all audiod commands */
300 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
301
302 /**
303 * get the audio format number
304 * \param name the name of the audio format
305 *
306 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
307 * \a name is not a supported audio format.
308 */
309 int get_audio_format_num(char *name)
310 {
311 int i;
312 FOR_EACH_AUDIO_FORMAT(i)
313 if (!strcmp(name, audio_formats[i]))
314 return i;
315 return -E_UNSUPPORTED_AUDIO_FORMAT;
316 }
317
318 /*
319 * log function. first argument is loglevel.
320 */
321 void para_log(int ll, const char* fmt,...)
322 {
323 va_list argp;
324 FILE *outfd;
325 struct tm *tm;
326 time_t t1;
327 char str[MAXLINE] = "";
328
329 if (ll < conf.loglevel_arg)
330 return;
331 outfd = logfile? logfile : stderr;
332 time(&t1);
333 tm = localtime(&t1);
334 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
335 fprintf(outfd, "%s %s ", str, hostname);
336 if (conf.loglevel_arg <= INFO)
337 fprintf(outfd, "%i ", ll);
338 va_start(argp, fmt);
339 vfprintf(outfd, fmt, argp);
340 va_end(argp);
341 }
342
343 static int client_write(int fd, const char *buf)
344 {
345 size_t len = strlen(buf);
346 return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
347 }
348
349 static char *get_time_string(struct timeval *newest_stime)
350 {
351 struct timeval diff, adj_stream_start, tmp;
352 int total = 0, use_server_time = 1;
353
354 if (!playing) {
355 if (length_seconds)
356 return NULL;
357 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
358 }
359 if (audiod_status == AUDIOD_OFF)
360 goto out;
361 if (sa_time_diff_sign > 0)
362 tv_diff(&server_stream_start, &sa_time_diff,
363 &adj_stream_start);
364 else
365 tv_add(&server_stream_start, &sa_time_diff,
366 &adj_stream_start);
367 tmp = adj_stream_start;
368 if (newest_stime && audiod_status == AUDIOD_ON) {
369 tv_diff(newest_stime, &adj_stream_start, &diff);
370 if (tv2ms(&diff) < 5000) {
371 tmp = *newest_stime;
372 use_server_time = 0;
373 }
374 }
375 tv_diff(now, &tmp, &diff);
376 total = diff.tv_sec + offset_seconds;
377 if (total > length_seconds)
378 total = length_seconds;
379 if (total < 0)
380 total = 0;
381 out:
382 return make_message(
383 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
384 status_item_list[SI_PLAY_TIME],
385 use_server_time? "~" : "",
386 total / 60,
387 total % 60,
388 (length_seconds - total) / 60,
389 (length_seconds - total) % 60,
390 length_seconds? (total * 100 + length_seconds / 2) /
391 length_seconds : 0,
392 length_seconds / 60,
393 length_seconds % 60
394 );
395 }
396
397 __malloc static char *audiod_status_string(void)
398 {
399 const char *status = (audiod_status == AUDIOD_ON)?
400 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
401 return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
402 }
403
404 static struct timeval *wstime(void)
405 {
406 int i;
407 struct timeval *max = NULL;
408 FOR_EACH_SLOT(i) {
409 struct slot_info *s = &slot[i];
410 if (!s->wng)
411 continue;
412 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
413 continue;
414 max = &s->wstime;
415 }
416 return max;
417 }
418 __malloc static char *decoder_flags(void)
419 {
420 int i;
421 char decoder_flags[MAX_STREAM_SLOTS + 1];
422
423 FOR_EACH_SLOT(i) {
424 struct slot_info *s = &slot[i];
425 char flag = '0';
426 if (s->receiver_node)
427 flag += 1;
428 if (s->wng)
429 flag += 2;
430 decoder_flags[i] = flag;
431 }
432 decoder_flags[MAX_STREAM_SLOTS] = '\0';
433 return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
434 decoder_flags);
435 }
436
437 static char *configfile_exists(void)
438 {
439 static char *config_file;
440
441 if (!config_file) {
442 char *home = para_homedir();
443 config_file = make_message("%s/.paraslash/audiod.conf", home);
444 free(home);
445 }
446 return file_exists(config_file)? config_file : NULL;
447 }
448
449 static void setup_signal_handling(void)
450 {
451 sig_task->fd = para_signal_init();
452 PARA_INFO_LOG("signal pipe: fd %d\n", sig_task->fd);
453 para_install_sighandler(SIGINT);
454 para_install_sighandler(SIGTERM);
455 para_install_sighandler(SIGCHLD);
456 para_install_sighandler(SIGHUP);
457 para_install_sighandler(SIGPIPE);
458 // signal(SIGPIPE, SIG_IGN);
459 }
460
461 static void audiod_status_dump(void)
462 {
463 static char *p_ts, *p_us, *p_as, *p_df;
464 struct timeval *t = wstime();
465 char *us, *tmp = get_time_string(t);
466
467 if (tmp && (!p_ts || strcmp(tmp, p_ts)))
468 stat_client_write(tmp, SI_PLAY_TIME);
469 free(p_ts);
470 p_ts = tmp;
471
472 us = uptime_str();
473 tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
474 free(us);
475 if (!p_us || strcmp(p_us, tmp))
476 stat_client_write(tmp, SI_AUDIOD_UPTIME);
477 free(p_us);
478 p_us = tmp;
479
480 tmp = audiod_status_string();
481 if (!p_as || strcmp(p_as, tmp))
482 stat_client_write(tmp, SI_AUDIOD_STATUS);
483 free(p_as);
484 p_as = tmp;
485
486 tmp = decoder_flags();
487 if (!p_df || strcmp(p_df, tmp))
488 stat_client_write(tmp, SI_DECODER_FLAGS);
489 free(p_df);
490 p_df = tmp;
491 }
492
493 static void clear_slot(int slot_num)
494 {
495 struct slot_info *s = &slot[slot_num];
496
497 PARA_INFO_LOG("clearing slot %d\n", slot_num);
498 memset(s, 0, sizeof(struct slot_info));
499 s->format = -1;
500 }
501
502 static void close_receiver(int slot_num)
503 {
504 struct slot_info *s = &slot[slot_num];
505 struct audio_format_info *a;
506
507 if (s->format < 0 || !s->receiver_node)
508 return;
509 a = &afi[s->format];
510 PARA_NOTICE_LOG("closing %s receiver in slot %d (eof = %d)\n",
511 audio_formats[s->format] , slot_num, s->receiver_node->eof);
512 // if (!s->receiver_node->eof)
513 // unregister_task(&s->receiver_node->task);
514 a->receiver->close(s->receiver_node);
515 free(s->receiver_node);
516 s->receiver_node = NULL;
517 /* set restart barrier */
518 tv_add(now, &restart_delay, &afi[s->format].restart_barrier);
519 }
520
521 static void kill_all_decoders(void)
522 {
523 int i;
524
525 FOR_EACH_SLOT(i) {
526 struct slot_info *s = &slot[i];
527 if (s->wng && !s->wng->eof) {
528 PARA_INFO_LOG("unregistering writer node group in slot %d\n",
529 i);
530 wng_unregister(s->wng);
531 s->wng->eof = 1;
532 }
533 if (s->fc && !s->fc->eof) {
534 PARA_INFO_LOG("unregistering filter chain in slot %d\n", i);
535 unregister_task(&s->fc->task);
536 s->fc->eof = 1;
537 }
538 if (s->receiver_node && !s->receiver_node->eof) {
539 PARA_INFO_LOG("unregistering receiver_node in slot %d\n", i);
540 unregister_task(&s->receiver_node->task);
541 s->receiver_node->eof = 1;
542 }
543 }
544 }
545
546 static int get_empty_slot(void)
547 {
548 int i;
549 struct slot_info *s;
550
551 FOR_EACH_SLOT(i) {
552 s = &slot[i];
553 if (s->format < 0) {
554 clear_slot(i);
555 return i;
556 }
557 if (s->wng || s->receiver_node || s->fc)
558 continue;
559 clear_slot(i);
560 return i;
561 }
562 return -E_NO_MORE_SLOTS;
563 }
564
565 static int decoder_running(int format)
566 {
567 int i, ret = 0;
568 struct slot_info *s;
569
570 FOR_EACH_SLOT(i) {
571 s = &slot[i];
572 if (s->format == format && s->receiver_node)
573 ret |= 1;
574 if (s->format == format && s->wng)
575 ret |= 2;
576 }
577 return ret;
578 }
579
580 static void close_stat_pipe(void)
581 {
582 int i;
583
584 if (stat_task->fd < 0)
585 return;
586 PARA_NOTICE_LOG("%s", "closing status pipe\n");
587 close(stat_task->fd);
588 del_close_on_fork_list(stat_task->fd);
589 stat_task->fd = -1;
590 // kill_all_decoders();
591 for (i = 0; i < NUM_STAT_ITEMS; i++) {
592 free(stat_item_values[i]);
593 stat_item_values[i] = NULL;
594 }
595 dump_empty_status();
596 length_seconds = 0;
597 offset_seconds = 0;
598 audiod_status_dump();
599 playing = 0;
600 stat_item_values[SI_STATUS_BAR] = make_message(
601 "%s:no connection to para_server\n",
602 status_item_list[SI_STATUS_BAR]);
603 stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
604 }
605
606 static void __noreturn clean_exit(int status, const char *msg)
607 {
608 PARA_EMERG_LOG("%s\n", msg);
609 if (socket_name)
610 unlink(socket_name);
611 if (stat_task->fd >= 0)
612 close_stat_pipe();
613 exit(status);
614 }
615
616 /**
617 * get the number of filters
618 *
619 * \param audio_format_num the number identifying the audio format
620 *
621 * \return the number of filters for the given audio format
622 *
623 * \sa struct filter;
624 */
625 int num_filters(int audio_format_num)
626 {
627 return afi[audio_format_num].num_filters;
628 }
629
630 static void filter_event_handler(struct task *t)
631 {
632 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
633 struct filter_chain *fc = t->private_data;
634 fc->eof = 1;
635 unregister_task(t);
636 }
637
638 static void open_filters(int slot_num)
639 {
640 struct slot_info *s = &slot[slot_num];
641 struct audio_format_info *a = &afi[s->format];
642 int nf = a->num_filters;
643 int i;
644
645 s->fc = NULL;
646 if (!nf)
647 return;
648 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
649 s->fc = para_calloc(sizeof(struct filter_chain));
650 INIT_LIST_HEAD(&s->fc->filters);
651 s->fc->inbuf = s->receiver_node->buf;
652 s->fc->in_loaded = &s->receiver_node->loaded;
653 s->fc->input_eof = &s->receiver_node->eof;
654 s->fc->task.pre_select = filter_pre_select;
655 s->fc->task.event_handler = filter_event_handler;
656 s->fc->task.private_data = s->fc;
657 s->fc->eof = 0;
658
659 s->receiver_node->output_eof = &s->fc->eof;
660 sprintf(s->fc->task.status, "filter chain");
661 for (i = 0; i < nf; i++) {
662 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
663 fn->conf = a->filter_conf[i];
664 fn->fc = s->fc;
665 fn->filter = a->filters[i];
666 INIT_LIST_HEAD(&fn->callbacks);
667 list_add_tail(&fn->node, &s->fc->filters);
668 fn->filter->open(fn);
669 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
670 audio_formats[s->format], i + 1, nf,
671 fn->filter->name, slot_num);
672 s->fc->outbuf = fn->buf;
673 s->fc->out_loaded = &fn->loaded;
674 }
675 register_task(&s->fc->task);
676 }
677
678 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
679 {
680 struct filter_node *fn;
681 int i, j;
682
683 FOR_EACH_SLOT(i) {
684 struct slot_info *s = &slot[i];
685 if (s->format < 0 || !s->fc)
686 continue;
687 if (slot_num >= 0 && slot_num != i)
688 continue;
689 if (format >= 0 && s->format != format)
690 continue;
691 if (num_filters(i) < filternum)
692 continue;
693 /* success */
694 j = 1;
695 list_for_each_entry(fn, &s->fc->filters, node)
696 if (filternum <= 0 || j++ == filternum)
697 break;
698 return fn;
699 }
700 return NULL;
701 }
702
703 static void wng_event_handler(struct task *t)
704 {
705 struct writer_node_group *wng = t->private_data;
706
707 PARA_INFO_LOG("%s\n", PARA_STRERROR(-t->ret));
708 wng->eof = 1;
709 wng_unregister(wng);
710 }
711
712 static void open_writers(int slot_num)
713 {
714 int ret, i;
715 struct slot_info *s = &slot[slot_num];
716 struct audio_format_info *a = &afi[s->format];
717
718 PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
719 if (!a->num_writers)
720 s->wng = setup_default_wng();
721 else
722 s->wng = wng_new(a->num_writers);
723 if (s->fc) {
724 s->wng->buf = s->fc->outbuf;
725 s->wng->loaded = s->fc->out_loaded;
726 s->wng->input_eof = &s->fc->eof;
727 s->wng->channels = &s->fc->channels;
728 s->wng->samplerate = &s->fc->samplerate;
729 s->fc->output_eof = &s->wng->eof;
730 PARA_INFO_LOG("samplerate: %d\n", *s->wng->samplerate);
731 } else {
732 s->wng->buf = s->receiver_node->buf;
733 s->wng->loaded = &s->receiver_node->loaded;
734 s->wng->input_eof = &s->receiver_node->eof;
735 }
736 s->wng->task.event_handler = wng_event_handler;
737 for (i = 0; i < a->num_writers; i++) {
738 s->wng->writer_nodes[i].conf = a->writer_conf[i];
739 s->wng->writer_nodes[i].writer = a->writers[i];
740 }
741 ret = wng_open(s->wng);
742 if (ret < 0) {
743 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
744 return;
745 }
746 s->wstime = *now;
747 current_decoder = slot_num;
748 activate_inactive_grab_clients(slot_num, s->format, &s->fc->filters);
749 }
750
751 static void rn_event_handler(struct task *t)
752 {
753 struct receiver_node *rn = t->private_data;
754
755 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
756 unregister_task(t);
757 rn->eof = 1;
758 }
759
760 static void open_receiver(int format)
761 {
762 struct audio_format_info *a = &afi[format];
763 struct slot_info *s;
764 int ret, slot_num;
765 struct receiver_node *rn;
766
767 slot_num = get_empty_slot();
768 if (slot_num < 0)
769 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
770 s = &slot[slot_num];
771 s->format = format;
772 s->receiver_node = para_calloc(sizeof(struct receiver_node));
773 rn = s->receiver_node;
774 rn->receiver = a->receiver;
775 rn->conf = a->receiver_conf;
776 ret = a->receiver->open(s->receiver_node);
777 if (ret < 0) {
778 PARA_ERROR_LOG("failed to open receiver (%s)\n",
779 PARA_STRERROR(-ret));
780 free(s->receiver_node);
781 s->receiver_node = NULL;
782 return;
783 }
784 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
785 audio_formats[s->format], a->receiver->name, slot_num);
786 rn->task.private_data = s->receiver_node;
787 rn->task.pre_select = a->receiver->pre_select;
788 rn->task.post_select = a->receiver->post_select;
789 rn->task.event_handler = rn_event_handler;
790 sprintf(rn->task.status, "%s receiver node", rn->receiver->name);
791 register_task(&rn->task);
792 }
793
794 static int is_frozen(int format)
795 {
796 struct audio_format_info *a = &afi[format];
797
798 return (tv_diff(now, &a->restart_barrier, NULL) > 0)? 0 : 1;
799 }
800
801 static void open_current_receiver(struct sched *s)
802 {
803 int i;
804
805 if (!af_status)
806 return;
807 i = get_audio_format_num(af_status);
808 if (i < 0)
809 return;
810 if (decoder_running(i) || is_frozen(i))
811 return;
812 open_receiver(i);
813 /*
814 * the receiver didn't get a chance to put his fd to the fd set.
815 * Make the upcoming select() return immediately to avoid a long
816 * timeout.
817 */
818 s->timeout.tv_sec = 0;
819 s->timeout.tv_usec = 1;
820 }
821
822 static void compute_time_diff(const struct timeval *status_time)
823 {
824 struct timeval tmp, diff;
825 static int count;
826 int sign;
827 const struct timeval max_deviation = {0, 500 * 1000};
828 const int time_smooth = 5;
829
830 sign = tv_diff(status_time, now, &diff);
831 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
832 // sign, sa_time_diff_sign);
833 if (!count) {
834 sa_time_diff_sign = sign;
835 sa_time_diff = diff;
836 count++;
837 return;
838 }
839 if (count > 5) {
840 int s = tv_diff(&diff, &sa_time_diff, &tmp);
841 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
842 PARA_WARNING_LOG("time diff jump: %lims\n",
843 s * tv2ms(&tmp));
844 }
845 count++;
846 sa_time_diff_sign = tv_convex_combination(
847 sa_time_diff_sign * time_smooth, &sa_time_diff,
848 count > 10? sign : sign * time_smooth, &diff,
849 &tmp);
850 sa_time_diff = tmp;
851 PARA_DEBUG_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
852 sign > 0? "+" : "-",
853 tv2ms(&diff),
854 sa_time_diff_sign ? "+" : "-",
855 tv2ms(&sa_time_diff)
856 );
857 }
858
859 static void check_stat_line(char *line)
860 {
861 int itemnum;
862 size_t ilen = 0;
863 long unsigned sec, usec;
864 char *tmp;
865
866 // PARA_INFO_LOG("line: %s\n", line);
867 if (!line)
868 return;
869 itemnum = stat_line_valid(line);
870 if (itemnum < 0) {
871 PARA_WARNING_LOG("invalid status line: %s\n", line);
872 return;
873 }
874 tmp = make_message("%s\n", line);
875 stat_client_write(tmp, itemnum);
876 free(tmp);
877 free(stat_item_values[itemnum]);
878 stat_item_values[itemnum] = para_strdup(line);
879 ilen = strlen(status_item_list[itemnum]);
880 switch (itemnum) {
881 case SI_STATUS:
882 playing = strstr(line, "playing")? 1 : 0;
883 break;
884 case SI_FORMAT:
885 free(af_status);
886 af_status = para_strdup(line + ilen + 1);
887 break;
888 case SI_OFFSET:
889 offset_seconds = atoi(line + ilen + 1);
890 break;
891 case SI_LENGTH:
892 length_seconds = atoi(line + ilen + 1);
893 break;
894 case SI_STREAM_START:
895 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
896 server_stream_start.tv_sec = sec;
897 server_stream_start.tv_usec = usec;
898 }
899 break;
900 case SI_CURRENT_TIME:
901 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
902 struct timeval tv = {sec, usec};
903 compute_time_diff(&tv);
904 }
905 break;
906 }
907 }
908
909 static void handle_signal(int sig)
910 {
911 switch (sig) {
912 case SIGCHLD:
913 for (;;) {
914 pid_t pid = para_reap_child();
915 if (pid <= 0)
916 return;
917 PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
918 }
919 case SIGINT:
920 case SIGTERM:
921 case SIGHUP:
922 PARA_EMERG_LOG("terminating on signal %d\n", sig);
923 clean_exit(EXIT_FAILURE, "caught deadly signal");
924 return;
925 }
926 }
927
928 static void try_to_close_slot(int slot_num)
929 {
930 struct slot_info *s = &slot[slot_num];
931
932 if (s->format < 0)
933 return;
934 if (s->receiver_node && !s->receiver_node->eof)
935 return;
936 if (s->fc && !s->fc->eof)
937 return;
938 if (s->wng && !s->wng->eof)
939 return;
940 PARA_INFO_LOG("closing slot %d \n", slot_num);
941 wng_close(s->wng);
942 close_filters(s->fc);
943 free(s->fc);
944 close_receiver(slot_num);
945 clear_slot(slot_num);
946 }
947
948 static void audiod_pre_select(struct sched *s, __a_unused struct task *t)
949 {
950 int i;
951
952 t->ret = 1;
953 now = &s->now;
954 if (audiod_status != AUDIOD_ON || !playing)
955 kill_all_decoders();
956 else if (playing)
957 open_current_receiver(s);
958 FOR_EACH_SLOT(i) {
959 struct slot_info *s = &slot[i];
960 struct audio_format_info *a;
961
962 if (s->format < 0)
963 continue;
964 a = &afi[s->format];
965 if (!s->receiver_node)
966 continue;
967 if (!a->num_filters) {
968 if (s->receiver_node->loaded && !s->wng)
969 open_writers(i);
970 continue;
971 }
972 if (s->receiver_node->loaded && !s->fc) {
973 open_filters(i);
974 continue;
975 }
976 if (s->fc && *s->fc->out_loaded && !s->wng)
977 open_writers(i);
978 }
979 }
980
981 static void audiod_post_select(struct sched *s, __a_unused struct task *t)
982 {
983 int i;
984
985 /* save away the current time for other users */
986 now = &s->now;
987 t->ret = 1;
988 FOR_EACH_SLOT(i)
989 try_to_close_slot(i);
990 }
991
992 static void init_audiod_task(struct task *t)
993 {
994 t->pre_select = audiod_pre_select;
995 t->post_select = audiod_post_select;
996 t->event_handler = NULL;
997 t->private_data = t;
998 sprintf(t->status, "audiod task");
999 }
1000
1001 static int parse_stream_command(const char *txt, char **cmd)
1002 {
1003 char *p = strchr(txt, ':');
1004 int i;
1005
1006 if (!p)
1007 return -E_MISSING_COLON;
1008 p++;
1009 FOR_EACH_AUDIO_FORMAT(i) {
1010 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1011 continue;
1012 *cmd = p;
1013 return i;
1014 }
1015 return -E_UNSUPPORTED_AUDIO_FORMAT;
1016 }
1017
1018 static int add_filter(int format, char *cmdline)
1019 {
1020 struct audio_format_info *a = &afi[format];
1021 int filter_num, nf = a->num_filters;
1022
1023 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1024 if (filter_num < 0)
1025 return filter_num;
1026 a->filters[nf] = &filters[filter_num];
1027 a->num_filters++;
1028 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1029 a->filters[nf]->name);
1030 return filter_num;
1031 }
1032
1033 static int init_writers(void)
1034 {
1035 int i, ret, nw;
1036 char *cmd;
1037 struct audio_format_info *a;
1038
1039 init_supported_writers();
1040 nw = PARA_MAX(1, conf.writer_given);
1041 PARA_INFO_LOG("maximal number of writers: %d\n", nw);
1042 FOR_EACH_AUDIO_FORMAT(i) {
1043 a = &afi[i];
1044 a->writer_conf = para_malloc(nw * sizeof(void *));
1045 a->writers = para_malloc(nw * sizeof(struct writer *));
1046 a->num_writers = 0;
1047 }
1048 for (i = 0; i < conf.writer_given; i++) {
1049 void *wconf;
1050 int writer_num;
1051 ret = parse_stream_command(conf.writer_arg[i], &cmd);
1052 if (ret < 0)
1053 goto out;
1054 a = &afi[ret];
1055 nw = a->num_writers;
1056 wconf = check_writer_arg(cmd, &writer_num);
1057 if (!wconf) {
1058 ret = writer_num;
1059 goto out;
1060 }
1061 a->writers[nw] = &writers[writer_num];
1062 a->writer_conf[nw] = wconf;
1063 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
1064 nw, writer_names[writer_num]);
1065 a->num_writers++;
1066 }
1067 ret = 1;
1068 out:
1069 return ret;
1070 }
1071
1072 static int init_receivers(void)
1073 {
1074 int i, ret, receiver_num;
1075 char *cmd = NULL;
1076 struct audio_format_info *a;
1077
1078 for (i = 0; receivers[i].name; i++) {
1079 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1080 receivers[i].init(&receivers[i]);
1081 }
1082 for (i = 0; i < conf.receiver_given; i++) {
1083 char *arg = conf.receiver_arg[i];
1084 char *recv = strchr(arg, ':');
1085 ret = -E_MISSING_COLON;
1086 if (!recv)
1087 goto out;
1088 *recv = '\0';
1089 recv++;
1090 ret = get_audio_format_num(arg);
1091 if (ret < 0)
1092 goto out;
1093 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1094 if (!afi[ret].receiver_conf) {
1095 ret = -E_RECV_SYNTAX;
1096 goto out;
1097 }
1098 afi[ret].receiver = &receivers[receiver_num];
1099 }
1100 /* use the first available receiver with no arguments
1101 * for those audio formats for which no receiver
1102 * was specified
1103 */
1104 cmd = para_strdup(receivers[0].name);
1105 FOR_EACH_AUDIO_FORMAT(i) {
1106 a = &afi[i];
1107 if (a->receiver_conf)
1108 continue;
1109 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1110 if (!a->receiver_conf)
1111 return -E_RECV_SYNTAX;
1112 a->receiver = &receivers[receiver_num];
1113 }
1114 ret = 1;
1115 out:
1116 free(cmd);
1117 return ret;
1118 }
1119
1120 static int init_default_filters(void)
1121 {
1122 int i, ret = 1;
1123
1124 FOR_EACH_AUDIO_FORMAT(i) {
1125 struct audio_format_info *a = &afi[i];
1126 char *tmp;
1127 int j;
1128
1129 if (a->num_filters)
1130 continue; /* no default -- nothing to to */
1131 /* add "dec" to audio format name */
1132 tmp = make_message("%sdec", audio_formats[i]);
1133 for (j = 0; filters[j].name; j++)
1134 if (!strcmp(tmp, filters[j].name))
1135 break;
1136 free(tmp);
1137 ret = -E_UNSUPPORTED_FILTER;
1138 if (!filters[j].name)
1139 goto out;
1140 tmp = para_strdup(filters[j].name);
1141 ret = add_filter(i, tmp);
1142 free(tmp);
1143 if (ret < 0)
1144 goto out;
1145 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1146 filters[j].name);
1147 }
1148 out:
1149 return ret;
1150 }
1151
1152 static int init_filters(void)
1153 {
1154 int i, ret, nf;
1155
1156 filter_init(filters);
1157 nf = PARA_MAX(1, conf.filter_given);
1158 PARA_INFO_LOG("maximal number of filters: %d\n", nf);
1159 FOR_EACH_AUDIO_FORMAT(i) {
1160 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
1161 afi[i].filters = para_malloc(nf * sizeof(struct filter *));
1162 }
1163 if (!conf.no_default_filters_given)
1164 return init_default_filters();
1165 for (i = 0; i < conf.filter_given; i++) {
1166 char *arg = conf.filter_arg[i];
1167 char *filter_name = strchr(arg, ':');
1168 ret = -E_MISSING_COLON;
1169 if (!filter_name)
1170 goto out;
1171 *filter_name = '\0';
1172 filter_name++;
1173 ret = get_audio_format_num(arg);
1174 if (ret < 0)
1175 goto out;
1176 ret = add_filter(ret, filter_name);
1177 if (ret < 0)
1178 goto out;
1179 }
1180 ret = init_default_filters(); /* use default values for the rest */
1181 out:
1182 return ret;
1183 }
1184
1185 static int init_stream_io(void)
1186 {
1187 int ret;
1188
1189 ret = init_writers();
1190 if (ret < 0)
1191 return ret;
1192 ret = init_receivers();
1193 if (ret < 0)
1194 return ret;
1195 ret = init_filters();
1196 if (ret < 0)
1197 return ret;
1198 return 1;
1199 }
1200
1201 static int dump_commands(int fd)
1202 {
1203 char *buf = para_strdup(""), *tmp = NULL;
1204 int i;
1205 ssize_t ret;
1206
1207 FOR_EACH_COMMAND(i) {
1208 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1209 cmds[i].description);
1210 free(buf);
1211 buf = tmp;
1212 }
1213 ret = client_write(fd, buf);
1214 free(buf);
1215 return ret;
1216 }
1217
1218 /*
1219 * command handlers don't close their fd on errors (ret < 0) so that
1220 * its caller can send an error message. Otherwise (ret >= 0) it's up
1221 * to each individual command to close the fd if necessary.
1222 */
1223
1224 static int com_help(int fd, int argc, char **argv)
1225 {
1226 int i, ret;
1227 char *buf;
1228 const char *dflt = "No such command. Available commands:\n";
1229
1230 if (argc < 2) {
1231 ret = dump_commands(fd);
1232 goto out;
1233 }
1234 FOR_EACH_COMMAND(i) {
1235 if (strcmp(cmds[i].name, argv[1]))
1236 continue;
1237 buf = make_message(
1238 "NAME\n\t%s -- %s\n"
1239 "SYNOPSIS\n\tpara_audioc %s\n"
1240 "DESCRIPTION\n%s\n",
1241 argv[1],
1242 cmds[i].description,
1243 cmds[i].synopsis,
1244 cmds[i].help
1245 );
1246 ret = client_write(fd, buf);
1247 free(buf);
1248 goto out;
1249 }
1250 ret = client_write(fd, dflt);
1251 if (ret > 0)
1252 ret = dump_commands(fd);
1253 out:
1254 if (ret >= 0)
1255 close(fd);
1256 return ret;
1257 }
1258
1259 static int com_tasks(int fd, __a_unused int argc, __a_unused char **argv)
1260 {
1261 char *tl = get_task_list();
1262 int ret = 1;
1263 if (tl)
1264 ret = client_write(fd, tl);
1265 free(tl);
1266 if (ret > 0)
1267 close(fd);
1268 return ret;
1269 }
1270
1271 static int com_kill(int fd, int argc, char **argv)
1272 {
1273 int i, ret = 1;
1274 if (argc < 2)
1275 return -E_AUDIOD_SYNTAX;
1276 for (i = 1; i < argc; i++) {
1277 ret = kill_task(argv[i]);
1278 if (ret < 0)
1279 break;
1280 }
1281 if (ret > 0)
1282 close(fd);
1283 return ret;
1284 }
1285
1286 static int com_stat(int fd, __a_unused int argc, __a_unused char **argv)
1287 {
1288 int i, ret;
1289 char *buf = NULL;
1290 long unsigned mask = ~0LU;
1291
1292 if (argc > 1) {
1293 mask = 0;
1294 for (i = 1; i < argc; i++) {
1295 ret = stat_item_valid(argv[i]);
1296 if (ret < 0)
1297 return ret;
1298 mask |= (1 << ret);
1299 }
1300 }
1301 PARA_INFO_LOG("mask: 0x%lx\n", mask);
1302 if (mask & (1 << SI_PLAY_TIME)) {
1303 struct timeval *t = wstime();
1304 char *ts = get_time_string(t);
1305 if (ts) {
1306 ret = client_write(fd, ts);
1307 if (ret < 0)
1308 goto out;
1309 free(ts);
1310 }
1311 }
1312 if (mask & (1 << SI_AUDIOD_UPTIME)) {
1313 char *tmp, *us = uptime_str();
1314 tmp = make_message("%s:%s\n",
1315 status_item_list[SI_AUDIOD_UPTIME], us);
1316 free(us);
1317 ret = client_write(fd, tmp);
1318 if (ret < 0)
1319 goto out;
1320 free(tmp);
1321 }
1322 if (mask & (1 << SI_AUDIOD_STATUS)) {
1323 char *s = audiod_status_string();
1324 ret = client_write(fd, s);
1325 if (ret < 0)
1326 goto out;
1327 free(s);
1328 }
1329 if (mask & (1 << SI_DECODER_FLAGS)) {
1330 char *df =decoder_flags();
1331 ret = client_write(fd, df);
1332 if (ret < 0)
1333 goto out;
1334 free(df);
1335 }
1336
1337 for (i = 0; i < NUM_STAT_ITEMS; i++) {
1338 char *tmp, *v;
1339 if (!((1 << i) & mask))
1340 continue;
1341 v = stat_item_values[i];
1342 tmp = make_message("%s%s%s", buf? buf: "",
1343 v? v : "", v? "\n" : "");
1344 free(buf);
1345 buf = tmp;
1346 }
1347 ret = client_write(fd, buf);
1348 out:
1349 if (ret > 0)
1350 ret = stat_client_add(fd, mask);
1351 free(buf);
1352 return ret;
1353 }
1354
1355 static int com_grab(int fd, char *cmdline)
1356 {
1357 struct grab_client *gc;
1358 struct filter_node *fn;
1359 int i, err;
1360 char *msg;
1361
1362 gc = grab_client_new(fd, cmdline, &err);
1363 if (!gc)
1364 goto err_out;
1365 fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1366 if (fn)
1367 activate_grab_client(gc, fn);
1368 return 1;
1369 err_out:
1370 if (err != -E_GC_HELP_GIVEN && err != -E_GC_VERSION_GIVEN)
1371 return err;
1372 if (err == -E_GC_HELP_GIVEN) {
1373 msg = make_message("%s\n\n", grab_client_args_info_usage);
1374 for (i = 0; grab_client_args_info_help[i]; i++) {
1375 char *tmp = make_message("%s%s\n", msg,
1376 grab_client_args_info_help[i]);
1377 free(msg);
1378 msg = tmp;
1379 }
1380 } else
1381 msg = make_message("%s %s\n",
1382 GRAB_CLIENT_CMDLINE_PARSER_PACKAGE,
1383 GRAB_CLIENT_CMDLINE_PARSER_VERSION);
1384 err = client_write(fd, msg);
1385 free(msg);
1386 if (err < 0)
1387 return err;
1388 close(fd);
1389 return 1;
1390 }
1391
1392 static int __noreturn com_term(int fd, __a_unused int argc, __a_unused char **argv)
1393 {
1394 close(fd);
1395 clean_exit(EXIT_SUCCESS, "terminating on user request");
1396 }
1397
1398 static int com_on(int fd, __a_unused int argc, __a_unused char **argv)
1399 {
1400 audiod_status = AUDIOD_ON;
1401 close(fd);
1402 return 1;
1403 }
1404
1405 static int com_off(int fd, __a_unused int argc, __a_unused char **argv)
1406 {
1407 audiod_status = AUDIOD_OFF;
1408 close(fd);
1409 return 1;
1410 }
1411
1412 static int com_sb(int fd, __a_unused int argc, __a_unused char **argv)
1413 {
1414 audiod_status = AUDIOD_STANDBY;
1415 close(fd);
1416 return 1;
1417 }
1418
1419 static int com_cycle(int fd, int argc, char **argv)
1420 {
1421 switch (audiod_status) {
1422 case AUDIOD_ON:
1423 return com_sb(fd, argc, argv);
1424 break;
1425 case AUDIOD_OFF:
1426 return com_on(fd, argc, argv);
1427 break;
1428 case AUDIOD_STANDBY:
1429 return com_off(fd, argc, argv);
1430 break;
1431 }
1432 close(fd);
1433 return 1;
1434 }
1435
1436 static int check_perms(uid_t uid)
1437 {
1438 int i;
1439
1440 if (!conf.user_allow_given)
1441 return 1;
1442 for (i = 0; i < conf.user_allow_given; i++)
1443 if (uid == conf.user_allow_arg[i])
1444 return 1;
1445 return -E_UCRED_PERM;
1446 }
1447
1448 static int handle_connect(int accept_fd)
1449 {
1450 int i, argc, ret, clifd = -1;
1451 char *cmd = NULL, *p, *buf = para_calloc(MAXLINE), **argv = NULL;
1452 struct sockaddr_un unix_addr;
1453
1454 ret = para_accept(accept_fd, &unix_addr, sizeof(struct sockaddr_un));
1455 if (ret < 0)
1456 goto out;
1457 clifd = ret;
1458 ret = recv_cred_buffer(clifd, buf, MAXLINE - 1);
1459 if (ret < 0)
1460 goto out;
1461 PARA_INFO_LOG("connection from user %i, buf: %s\n", ret, buf);
1462 ret = check_perms(ret);
1463 if (ret < 0)
1464 goto out;
1465 ret = -E_INVALID_AUDIOD_CMD;
1466 cmd = para_strdup(buf);
1467 p = strchr(cmd, '\n');
1468 if (!p)
1469 p = "";
1470 else {
1471 *p = '\0';
1472 p++;
1473 }
1474 for (i = 0; cmds[i].name; i++) {
1475 int j;
1476 if (strcmp(cmds[i].name, cmd))
1477 continue;
1478 if (cmds[i].handler) {
1479 argc = split_args(buf, &argv, "\n");
1480 PARA_INFO_LOG("argv[0]: %s, argc= %d\n", argv[0], argc);
1481 ret = cmds[i].handler(clifd, argc, argv);
1482 goto out;
1483 }
1484 for (j = 0; p[j]; j++)
1485 if (p[j] == '\n')
1486 p[j] = ' ';
1487 PARA_INFO_LOG("cmd: %s, options: %s\n", cmd, p);
1488 ret = cmds[i].line_handler(clifd, p);
1489 goto out;
1490 }
1491 ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1492 out:
1493 free(cmd);
1494 free(buf);
1495 free(argv);
1496 if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1497 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1498 client_write(clifd, tmp);
1499 free(tmp);
1500 close(clifd);
1501 }
1502 return ret;
1503 }
1504
1505 static int audiod_get_socket(void)
1506 {
1507 struct sockaddr_un unix_addr;
1508 int fd;
1509
1510 if (conf.socket_given)
1511 socket_name = para_strdup(conf.socket_arg);
1512 else {
1513 char *hn = para_hostname();
1514 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1515 hn);
1516 free(hn);
1517 }
1518 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1519 if (conf.force_given)
1520 unlink(socket_name);
1521 fd = create_pf_socket(socket_name, &unix_addr,
1522 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1523 if (fd < 0) {
1524 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1525 exit(EXIT_FAILURE); /* do not unlink socket */
1526 }
1527 if (listen(fd , 5) < 0) {
1528 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1529 exit(EXIT_FAILURE); /* do not unlink socket */
1530 }
1531 add_close_on_fork_list(fd);
1532 return fd;
1533 }
1534
1535 static int open_stat_pipe(void)
1536 {
1537 int ret, fd[3] = {-1, 1, 0};
1538 pid_t pid;
1539 ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1540 if (ret >= 0) {
1541 ret = fd[1];
1542 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1543 add_close_on_fork_list(ret);
1544 } else
1545 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1546 return ret;
1547 }
1548
1549 void signal_event_handler(struct task *t)
1550 {
1551 struct signal_task *st = t->private_data;
1552
1553 if (t->ret != -E_SIGNAL_CAUGHT)
1554 PARA_ERROR_LOG("%s (ignored)\n", PARA_STRERROR(-t->ret));
1555 else
1556 handle_signal(st->signum);
1557 }
1558
1559 void signal_pre_select(struct sched *s, struct task *t)
1560 {
1561 struct signal_task *st = t->private_data;
1562 t->ret = 1;
1563 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1564 }
1565
1566 void signal_post_select(struct sched *s, struct task *t)
1567 {
1568 struct signal_task *st = t->private_data;
1569 t->ret = 1;
1570 if (!FD_ISSET(st->fd, &s->rfds))
1571 return;
1572 t->ret = -E_SIGNAL_CAUGHT;
1573 st->signum = para_next_signal();
1574 }
1575
1576 void signal_setup_default(struct signal_task *st)
1577 {
1578 st->task.pre_select = signal_pre_select;
1579 st->task.post_select = signal_post_select;
1580 st->task.private_data = st;
1581 sprintf(st->task.status, "signal task");
1582 }
1583
1584 static void command_pre_select(struct sched *s, struct task *t)
1585 {
1586 struct command_task *ct = t->private_data;
1587 t->ret = 1;
1588 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
1589
1590 }
1591
1592 static void command_post_select(struct sched *s, struct task *t)
1593 {
1594 int ret;
1595 struct command_task *ct = t->private_data;
1596
1597 t->ret = 1; /* always successful */
1598 if (audiod_status != AUDIOD_OFF)
1599 audiod_status_dump();
1600 if (!FD_ISSET(ct->fd, &s->rfds))
1601 return;
1602 ret = handle_connect(ct->fd);
1603 if (ret < 0)
1604 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1605 }
1606
1607 static void init_command_task(struct command_task *ct)
1608 {
1609 ct->task.pre_select = command_pre_select;
1610 ct->task.post_select = command_post_select;
1611 ct->task.event_handler = NULL;
1612 ct->task.private_data = ct;
1613 ct->fd = audiod_get_socket(); /* doesn't return on errors */
1614 sprintf(ct->task.status, "command task");
1615 }
1616
1617 static void status_event_handler(__a_unused struct task *t)
1618 {
1619 struct timeval delay = {1, 0};
1620 int i;
1621 struct status_task *st = t->private_data;
1622
1623 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-t->ret));
1624 close_stat_pipe();
1625 /* avoid busy loop if server is down */
1626 tv_add(now, &delay, &st->restart_barrier);
1627 FOR_EACH_AUDIO_FORMAT(i)
1628 afi[i].restart_barrier = st->restart_barrier;
1629 }
1630
1631 static void status_pre_select(struct sched *s, struct task *t)
1632 {
1633 struct status_task *st = t->private_data;
1634 t->ret = 1;
1635 if (st->fd >= 0 && audiod_status == AUDIOD_OFF)
1636 close_stat_pipe();
1637 if (st->fd < 0 && audiod_status != AUDIOD_OFF
1638 && tv_diff(now, &st->restart_barrier, NULL) > 0) {
1639 st->fd = open_stat_pipe();
1640 st->loaded = 0;
1641 st->buf[0] = '\0';
1642 }
1643 if (st->fd >= 0 && audiod_status != AUDIOD_OFF)
1644 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
1645 }
1646
1647 static void status_post_select(struct sched *s, struct task *t)
1648 {
1649 struct status_task *st = t->private_data;
1650
1651 t->ret = 1;
1652 if (st->fd < 0 || !FD_ISSET(st->fd, &s->rfds))
1653 return;
1654 t->ret = read(st->fd, st->buf + st->loaded, STRINGSIZE - 1 - st->loaded);
1655 if (t->ret <= 0) {
1656 if (!t->ret)
1657 t->ret = -E_STATUS_EOF;
1658 return;
1659 }
1660 st->buf[t->ret + st->loaded] = '\0';
1661 st->loaded = for_each_line(st->buf, t->ret + st->loaded,
1662 &check_stat_line);
1663 }
1664
1665 static void init_status_task(struct status_task *st)
1666 {
1667 memset(st, 0, sizeof(struct status_task));
1668 st->task.pre_select = status_pre_select;
1669 st->task.post_select = status_post_select;
1670 st->task.event_handler = status_event_handler;
1671 st->task.private_data = st;
1672 st->fd = -1;
1673 sprintf(st->task.status, "status task");
1674 }
1675
1676 static void set_initial_status(void)
1677 {
1678 audiod_status = AUDIOD_ON;
1679 if (!conf.mode_given)
1680 return;
1681 if (!strcmp(conf.mode_arg, "sb")) {
1682 audiod_status = AUDIOD_STANDBY;
1683 return;
1684 }
1685 if (!strcmp(conf.mode_arg, "off")) {
1686 audiod_status = AUDIOD_OFF;
1687 return;
1688 }
1689 if (strcmp(conf.mode_arg, "on"))
1690 PARA_WARNING_LOG("%s", "invalid mode\n");
1691 }
1692
1693 int main(int argc, char *argv[])
1694 {
1695 char *cf;
1696 int ret, i;
1697 struct sched s;
1698 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1699 struct task audiod_task_struct, *audiod_task = &audiod_task_struct;
1700
1701 init_sched();
1702
1703 valid_fd_012();
1704 hostname = para_hostname();
1705 cmdline_parser(argc, argv, &conf);
1706 para_drop_privileges(conf.user_arg, conf.group_arg);
1707 cf = configfile_exists();
1708 if (cf) {
1709 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1710 PARA_EMERG_LOG("%s", "parse error in config file\n");
1711 exit(EXIT_FAILURE);
1712 }
1713 }
1714 if (conf.logfile_given)
1715 logfile = open_log(conf.logfile_arg);
1716 log_welcome("para_audiod", conf.loglevel_arg);
1717 i = init_stream_io();
1718 if (i < 0) {
1719 PARA_EMERG_LOG("init stream io error: %s\n", PARA_STRERROR(-i));
1720 exit(EXIT_FAILURE);
1721 }
1722 server_uptime(UPTIME_SET);
1723 set_initial_status();
1724 FOR_EACH_SLOT(i)
1725 clear_slot(i);
1726 init_grabbing();
1727 setup_signal_handling();
1728 signal_setup_default(sig_task);
1729 sig_task->task.event_handler = signal_event_handler;
1730
1731 init_status_task(stat_task);
1732 init_command_task(cmd_task);
1733 init_audiod_task(audiod_task);
1734
1735 if (conf.daemon_given)
1736 daemon_init();
1737
1738 register_task(&sig_task->task);
1739 register_task(&cmd_task->task);
1740 register_task(&stat_task->task);
1741 register_task(audiod_task);
1742 s.default_timeout.tv_sec = 3;
1743 s.default_timeout.tv_usec = 99 * 1000;
1744 ret = sched(&s);
1745
1746 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
1747 return EXIT_FAILURE;
1748 }