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