2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2006, 2007 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 /* This program deliberately does not use the garbage collector even though it
22 * might be convenient to do so. This is for two reasons. Firstly some libao
23 * drivers are implemented using threads and we do not want to have to deal
24 * with potential interactions between threading and garbage collection.
25 * Secondly this process needs to be able to respond quickly and this is not
26 * compatible with the collector hanging the program even relatively
42 #include <sys/select.h>
48 #include "configuration.h"
57 #include <alsa/asoundlib.h>
60 #ifdef WORDS_BIGENDIAN
61 # define MACHINE_AO_FMT AO_FMT_BIG
63 # define MACHINE_AO_FMT AO_FMT_LITTLE
66 #define BUFFER_SECONDS 5 /* How many seconds of input to
69 #define FRAMES 4096 /* Frame batch size */
71 #define NFDS 256 /* Max FDs to poll for */
73 /* Known tracks are kept in a linked list. We don't normally to have
74 * more than two - maybe three at the outside. */
76 struct track *next; /* next track */
77 int fd; /* input FD */
79 size_t start, used; /* start + bytes used */
80 int eof; /* input is at EOF */
81 int got_format; /* got format yet? */
82 ao_sample_format format; /* sample format */
83 unsigned long long played; /* number of frames played */
84 char *buffer; /* sample buffer */
85 size_t size; /* sample buffer size */
86 int slot; /* poll array slot */
87 } *tracks, *playing; /* all tracks + playing track */
89 static time_t last_report; /* when we last reported */
90 static int paused; /* pause status */
91 static ao_sample_format pcm_format; /* current format if aodev != 0 */
92 static size_t bpf; /* bytes per frame */
93 static struct pollfd fds[NFDS]; /* if we need more than that */
94 static int fdno; /* fd number */
95 static size_t bufsize; /* buffer size */
97 static snd_pcm_t *pcm; /* current pcm handle */
98 static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
100 static int ready; /* ready to send audio */
101 static int forceplay; /* frames to force play */
102 static int kidfd = -1; /* child process input */
104 static const struct option options[] = {
105 { "help", no_argument, 0, 'h' },
106 { "version", no_argument, 0, 'V' },
107 { "config", required_argument, 0, 'c' },
108 { "debug", no_argument, 0, 'd' },
109 { "no-debug", no_argument, 0, 'D' },
113 /* Display usage message and terminate. */
114 static void help(void) {
116 " disorder-speaker [OPTIONS]\n"
118 " --help, -h Display usage message\n"
119 " --version, -V Display version number\n"
120 " --config PATH, -c PATH Set configuration file\n"
121 " --debug, -d Turn on debugging\n"
123 "Speaker process for DisOrder. Not intended to be run\n"
129 /* Display version number and terminate. */
130 static void version(void) {
131 xprintf("disorder-speaker version %s\n", disorder_version_string);
136 /* Return the number of bytes per frame in FORMAT. */
137 static size_t bytes_per_frame(const ao_sample_format *format) {
138 return format->channels * format->bits / 8;
141 /* Find track ID, maybe creating it if not found. */
142 static struct track *findtrack(const char *id, int create) {
145 D(("findtrack %s %d", id, create));
146 for(t = tracks; t && strcmp(id, t->id); t = t->next)
149 t = xmalloc(sizeof *t);
154 /* The initial input buffer will be the sample format. */
155 t->buffer = (void *)&t->format;
156 t->size = sizeof t->format;
161 /* Remove track ID (but do not destroy it). */
162 static struct track *removetrack(const char *id) {
163 struct track *t, **tt;
165 D(("removetrack %s", id));
166 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
173 /* Destroy a track. */
174 static void destroy(struct track *t) {
175 D(("destroy %s", t->id));
176 if(t->fd != -1) xclose(t->fd);
177 if(t->buffer != (void *)&t->format) free(t->buffer);
181 /* Notice a new FD. */
182 static void acquire(struct track *t, int fd) {
183 D(("acquire %s %d", t->id, fd));
190 /* Read data into a sample buffer. Return 0 on success, -1 on EOF. */
191 static int fill(struct track *t) {
195 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
196 t->id, t->eof, t->used, t->size, t->got_format));
197 if(t->eof) return -1;
198 if(t->used < t->size) {
199 /* there is room left in the buffer */
200 where = (t->start + t->used) % t->size;
202 /* We are reading audio data, get as much as we can */
203 if(where >= t->start) left = t->size - where;
204 else left = t->start - where;
206 /* We are still waiting for the format, only get that */
207 left = sizeof (ao_sample_format) - t->used;
209 n = read(t->fd, t->buffer + where, left);
210 } while(n < 0 && errno == EINTR);
212 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
216 D(("fill %s: eof detected", t->id));
221 if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
222 assert(t->used == sizeof (ao_sample_format));
223 /* Check that our assumptions are met. */
224 if(t->format.bits & 7)
225 fatal(0, "bits per sample not a multiple of 8");
226 /* Make a new buffer for audio data. */
227 t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
228 t->buffer = xmalloc(t->size);
231 D(("got format for %s", t->id));
237 /* Return true if A and B denote identical libao formats, else false. */
238 static int formats_equal(const ao_sample_format *a,
239 const ao_sample_format *b) {
240 return (a->bits == b->bits
241 && a->rate == b->rate
242 && a->channels == b->channels
243 && a->byte_format == b->byte_format);
246 /* Close the sound device. */
247 static void idle(void) {
253 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
254 fatal(0, "error calling snd_pcm_nonblock: %d", err);
261 D(("released audio device"));
267 /* Abandon the current track */
268 static void abandon(void) {
269 struct speaker_message sm;
272 memset(&sm, 0, sizeof sm);
273 sm.type = SM_FINISHED;
274 strcpy(sm.id, playing->id);
275 speaker_send(1, &sm, 0);
276 removetrack(playing->id);
283 static void log_params(snd_pcm_hw_params_t *hwparams,
284 snd_pcm_sw_params_t *swparams) {
288 return; /* too verbose */
293 snd_pcm_sw_params_get_silence_size(swparams, &f);
294 info("sw silence_size=%lu", (unsigned long)f);
295 snd_pcm_sw_params_get_silence_threshold(swparams, &f);
296 info("sw silence_threshold=%lu", (unsigned long)f);
297 snd_pcm_sw_params_get_sleep_min(swparams, &u);
298 info("sw sleep_min=%lu", (unsigned long)u);
299 snd_pcm_sw_params_get_start_threshold(swparams, &f);
300 info("sw start_threshold=%lu", (unsigned long)f);
301 snd_pcm_sw_params_get_stop_threshold(swparams, &f);
302 info("sw stop_threshold=%lu", (unsigned long)f);
303 snd_pcm_sw_params_get_xfer_align(swparams, &f);
304 info("sw xfer_align=%lu", (unsigned long)f);
309 static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
314 *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
315 *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
316 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
318 switch(config->sox_generation) {
321 && ao->byte_format != AO_FMT_NATIVE
322 && ao->byte_format != MACHINE_AO_FMT) {
326 case 8: *(*pp)++ = "-b"; break;
327 case 16: *(*pp)++ = "-w"; break;
328 case 32: *(*pp)++ = "-l"; break;
329 case 64: *(*pp)++ = "-d"; break;
330 default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
334 switch(ao->byte_format) {
335 case AO_FMT_NATIVE: break;
336 case AO_FMT_BIG: *(*pp)++ = "-B"; break;
337 case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
339 *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
344 /* Make sure the sound device is open and has the right sample format. Return
345 * 0 on success and -1 on error. */
346 static int activate(void) {
347 /* If we don't know the format yet we cannot start. */
348 if(!playing->got_format) {
349 D((" - not got format for %s", playing->id));
353 if(!formats_equal(&playing->format, &config->sample_format)) {
354 char argbuf[1024], *q = argbuf;
355 const char *av[18], **pp = av;
359 soxargs(&pp, &q, &playing->format);
361 soxargs(&pp, &q, &config->sample_format);
365 for(pp = av; *pp; pp++)
366 D(("sox arg[%d] = %s", pp - av, *pp));
372 xdup2(playing->fd, 0);
373 xdup2(soxpipe[1], 1);
374 fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
378 execvp("sox", (char **)av);
381 D(("forking sox for format conversion (kid = %d)", soxkid));
384 playing->fd = soxpipe[0];
385 playing->format = config->sample_format;
389 pcm_format = config->sample_format;
390 bufsize = 3 * FRAMES;
391 bpf = bytes_per_frame(&config->sample_format);
392 D(("acquired audio device"));
398 /* If we need to change format then close the current device. */
399 if(pcm && !formats_equal(&playing->format, &pcm_format))
402 snd_pcm_hw_params_t *hwparams;
403 snd_pcm_sw_params_t *swparams;
404 snd_pcm_uframes_t pcm_bufsize;
406 int sample_format = 0;
410 if((err = snd_pcm_open(&pcm,
412 SND_PCM_STREAM_PLAYBACK,
413 SND_PCM_NONBLOCK))) {
414 error(0, "error from snd_pcm_open: %d", err);
417 snd_pcm_hw_params_alloca(&hwparams);
418 D(("set up hw params"));
419 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
420 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
421 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
422 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
423 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
424 switch(playing->format.bits) {
426 sample_format = SND_PCM_FORMAT_S8;
429 switch(playing->format.byte_format) {
430 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
431 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
432 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
433 error(0, "unrecognized byte format %d", playing->format.byte_format);
438 error(0, "unsupported sample size %d", playing->format.bits);
441 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
442 sample_format)) < 0) {
443 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
447 rate = playing->format.rate;
448 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
449 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
450 playing->format.rate, err);
453 if(rate != (unsigned)playing->format.rate)
454 info("want rate %d, got %u", playing->format.rate, rate);
455 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
456 playing->format.channels)) < 0) {
457 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
458 playing->format.channels, err);
461 bufsize = 3 * FRAMES;
462 pcm_bufsize = bufsize;
463 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
465 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
467 if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
468 info("asked for PCM buffer of %d frames, got %d",
469 3 * FRAMES, (int)pcm_bufsize);
470 last_pcm_bufsize = pcm_bufsize;
471 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
472 fatal(0, "error calling snd_pcm_hw_params: %d", err);
473 D(("set up sw params"));
474 snd_pcm_sw_params_alloca(&swparams);
475 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
476 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
477 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
478 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
480 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
481 fatal(0, "error calling snd_pcm_sw_params: %d", err);
482 pcm_format = playing->format;
483 bpf = bytes_per_frame(&pcm_format);
484 D(("acquired audio device"));
485 log_params(hwparams, swparams);
492 /* We assume the error is temporary and that we'll retry in a bit. */
501 /* Check to see whether the current track has finished playing */
502 static void maybe_finished(void) {
505 && (!playing->got_format
506 || playing->used < bytes_per_frame(&playing->format)))
510 static void fork_kid(void) {
513 if(kidfd != -1) close(kidfd);
520 execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
521 fatal(errno, "error execing /bin/sh");
525 D(("forked kid %d, fd = %d", kid, kidfd));
528 static void play(size_t frames) {
529 size_t avail_bytes, written_frames;
530 ssize_t written_bytes;
536 forceplay = 0; /* Must have called abandon() */
539 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
540 playing->eof ? " EOF" : "",
541 playing->format.rate,
542 playing->format.bits,
543 playing->format.channels));
544 /* If we haven't got enough bytes yet wait until we have. Exception: when
546 if(playing->used < frames * bpf && !playing->eof) {
550 /* We have got enough data so don't force play again */
552 /* Figure out how many frames there are available to write */
553 if(playing->start + playing->used > playing->size)
554 avail_bytes = playing->size - playing->start;
556 avail_bytes = playing->used;
560 snd_pcm_sframes_t pcm_written_frames;
564 avail_frames = avail_bytes / bpf;
565 if(avail_frames > frames)
566 avail_frames = frames;
569 pcm_written_frames = snd_pcm_writei(pcm,
570 playing->buffer + playing->start,
572 D(("actually play %zu frames, wrote %d",
573 avail_frames, (int)pcm_written_frames));
574 if(pcm_written_frames < 0) {
575 switch(pcm_written_frames) {
576 case -EPIPE: /* underrun */
577 error(0, "snd_pcm_writei reports underrun");
578 if((err = snd_pcm_prepare(pcm)) < 0)
579 fatal(0, "error calling snd_pcm_prepare: %d", err);
584 fatal(0, "error calling snd_pcm_writei: %d",
585 (int)pcm_written_frames);
588 written_frames = pcm_written_frames;
589 written_bytes = written_frames * bpf;
594 if(avail_bytes > frames * bpf)
595 avail_bytes = frames * bpf;
596 written_bytes = write(kidfd, playing->buffer + playing->start,
598 D(("actually play %zu bytes, wrote %d",
599 avail_bytes, (int)written_bytes));
600 if(written_bytes < 0) {
603 error(0, "hmm, kid died; trying another");
610 written_frames = written_bytes / bpf; /* good enough */
612 playing->start += written_bytes;
613 playing->used -= written_bytes;
614 playing->played += written_frames;
615 /* If the pointer is at the end of the buffer (or the buffer is completely
616 * empty) wrap it back to the start. */
617 if(!playing->used || playing->start == playing->size)
619 frames -= written_frames;
622 /* Notify the server what we're up to. */
623 static void report(void) {
624 struct speaker_message sm;
626 if(playing && playing->buffer != (void *)&playing->format) {
627 memset(&sm, 0, sizeof sm);
628 sm.type = paused ? SM_PAUSED : SM_PLAYING;
629 strcpy(sm.id, playing->id);
630 sm.data = playing->played / playing->format.rate;
631 speaker_send(1, &sm, 0);
636 static void reap(int __attribute__((unused)) sig) {
641 kid = waitpid(-1, &st, WNOHANG);
643 signal(SIGCHLD, reap);
646 static int addfd(int fd, int events) {
649 fds[fdno].events = events;
655 int main(int argc, char **argv) {
656 int n, fd, stdin_slot, alsa_slots, kid_slot;
658 struct speaker_message sm;
660 int alsa_nslots = -1, err;
665 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
666 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
670 case 'c': configfile = optarg; break;
671 case 'd': debugging = 1; break;
672 case 'D': debugging = 0; break;
673 default: fatal(0, "invalid option");
676 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
677 /* If stderr is a TTY then log there, otherwise to syslog. */
679 openlog(progname, LOG_PID, LOG_DAEMON);
680 log_default = &log_syslog;
682 if(config_read()) fatal(0, "cannot read configuration");
684 signal(SIGPIPE, SIG_IGN);
686 signal(SIGCHLD, reap);
688 xnice(config->nice_speaker);
691 /* make sure we're not root, whatever the config says */
692 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
694 if(config->speaker_command)
700 fatal(0, "invoked speaker but no speaker_command and no known sound API");
703 while(getppid() != 1) {
705 /* Always ready for commands from the main server. */
706 stdin_slot = addfd(0, POLLIN);
707 /* Try to read sample data for the currently playing track if there is
709 if(playing && !playing->eof && playing->used < playing->size) {
710 playing->slot = addfd(playing->fd, POLLIN);
713 /* If forceplay is set then wait until it succeeds before waiting on the
717 if(ready && !forceplay) {
719 kid_slot = addfd(kidfd, POLLOUT);
727 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
729 || !(fds[alsa_slots].events & POLLOUT))
730 && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
731 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
732 if((err = snd_pcm_prepare(pcm)))
733 fatal(0, "error calling snd_pcm_prepare: %d", err);
736 } while(retry-- > 0);
742 /* If any other tracks don't have a full buffer, try to read sample data
744 for(t = tracks; t; t = t->next)
746 if(!t->eof && t->used < t->size) {
747 t->slot = addfd(t->fd, POLLIN | POLLHUP);
751 /* Wait up to a second before thinking about current state */
752 n = poll(fds, fdno, 1000);
754 if(errno == EINTR) continue;
755 fatal(errno, "error calling poll");
757 /* Play some sound before doing anything else */
758 if(alsa_slots != -1) {
760 unsigned short alsa_revents;
762 if((err = snd_pcm_poll_descriptors_revents(pcm,
766 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
767 if(alsa_revents & (POLLOUT | POLLERR))
770 } else if(kid_slot != -1) {
771 if(fds[kid_slot].revents & (POLLOUT | POLLERR))
774 /* Some attempt to play must have failed */
775 if(playing && !paused)
778 forceplay = 0; /* just in case */
780 /* Perhaps we have a command to process */
781 if(fds[stdin_slot].revents & POLLIN) {
782 n = speaker_recv(0, &sm, &fd);
786 D(("SM_PREPARE %s %d", sm.id, fd));
787 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
788 t = findtrack(sm.id, 1);
792 D(("SM_PLAY %s %d", sm.id, fd));
793 if(playing) fatal(0, "got SM_PLAY but already playing something");
794 t = findtrack(sm.id, 1);
795 if(fd != -1) acquire(t, fd);
815 D(("SM_CANCEL %s", sm.id));
816 t = removetrack(sm.id);
819 sm.type = SM_FINISHED;
820 strcpy(sm.id, playing->id);
821 speaker_send(1, &sm, 0);
826 error(0, "SM_CANCEL for unknown track %s", sm.id);
831 if(config_read()) error(0, "cannot read configuration");
832 info("reloaded configuration");
835 error(0, "unknown message type %d", sm.type);
838 /* Read in any buffered data */
839 for(t = tracks; t; t = t->next)
840 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
842 /* We might be able to play now */
843 if(ready && forceplay && playing && !paused)
845 /* Maybe we finished playing a track somewhere in the above */
847 /* If we don't need the sound device for now then close it for the benefit
848 * of anyone else who wants it. */
849 if((!playing || paused) && ready)
851 /* If we've not reported out state for a second do so now. */
852 if(time(0) > last_report)
855 info("stopped (parent terminated)");