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