2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2006 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>
44 #include <alsa/asoundlib.h>
46 #include "configuration.h"
54 #define BUFFER_SECONDS 5 /* How many seconds of input to
57 #define FRAMES 4096 /* Frame batch size */
59 #define NFDS 256 /* Max FDs to poll for */
61 /* Known tracks are kept in a linked list. We don't normally to have
62 * more than two - maybe three at the outside. */
64 struct track *next; /* next track */
65 int fd; /* input FD */
67 size_t start, used; /* start + bytes used */
68 int eof; /* input is at EOF */
69 int got_format; /* got format yet? */
70 ao_sample_format format; /* sample format */
71 unsigned long long played; /* number of frames played */
72 char *buffer; /* sample buffer */
73 size_t size; /* sample buffer size */
74 int slot; /* poll array slot */
75 } *tracks, *playing; /* all tracks + playing track */
77 static time_t last_report; /* when we last reported */
78 static int paused; /* pause status */
79 static snd_pcm_t *pcm; /* current pcm handle */
80 static ao_sample_format pcm_format; /* current format if aodev != 0 */
81 static size_t bpf; /* bytes per frame */
82 static struct pollfd fds[NFDS]; /* if we need more than that */
83 static int fdno; /* fd number */
84 static snd_pcm_uframes_t pcm_bufsize; /* buffer size */
85 static int forceplay; /* frames to force play */
87 static const struct option options[] = {
88 { "help", no_argument, 0, 'h' },
89 { "version", no_argument, 0, 'V' },
90 { "config", required_argument, 0, 'c' },
91 { "debug", no_argument, 0, 'd' },
92 { "no-debug", no_argument, 0, 'D' },
96 /* Display usage message and terminate. */
97 static void help(void) {
99 " disorder-speaker [OPTIONS]\n"
101 " --help, -h Display usage message\n"
102 " --version, -V Display version number\n"
103 " --config PATH, -c PATH Set configuration file\n"
104 " --debug, -d Turn on debugging\n"
106 "Speaker process for DisOrder. Not intended to be run\n"
112 /* Display version number and terminate. */
113 static void version(void) {
114 xprintf("disorder-speaker version %s\n", disorder_version_string);
119 /* Return the number of bytes per frame in FORMAT. */
120 static size_t bytes_per_frame(const ao_sample_format *format) {
121 return format->channels * format->bits / 8;
124 /* Find track ID, maybe creating it if not found. */
125 static struct track *findtrack(const char *id, int create) {
128 D(("findtrack %s %d", id, create));
129 for(t = tracks; t && strcmp(id, t->id); t = t->next)
132 t = xmalloc(sizeof *t);
137 /* The initial input buffer will be the sample format. */
138 t->buffer = (void *)&t->format;
139 t->size = sizeof t->format;
144 /* Remove track ID (but do not destroy it). */
145 static struct track *removetrack(const char *id) {
146 struct track *t, **tt;
148 D(("removetrack %s", id));
149 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
156 /* Destroy a track. */
157 static void destroy(struct track *t) {
158 D(("destroy %s", t->id));
159 if(t->fd != -1) xclose(t->fd);
160 if(t->buffer != (void *)&t->format) free(t->buffer);
164 /* Notice a new FD. */
165 static void acquire(struct track *t, int fd) {
166 D(("acquire %s %d", t->id, fd));
173 /* Read data into a sample buffer. Return 0 on success, -1 on EOF. */
174 static int fill(struct track *t) {
178 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
179 t->id, t->eof, t->used, t->size, t->got_format));
180 if(t->eof) return -1;
181 if(t->used < t->size) {
182 /* there is room left in the buffer */
183 where = (t->start + t->used) % t->size;
185 /* We are reading audio data, get as much as we can */
186 if(where >= t->start) left = t->size - where;
187 else left = t->start - where;
189 /* We are still waiting for the format, only get that */
190 left = sizeof (ao_sample_format) - t->used;
192 n = read(t->fd, t->buffer + where, left);
193 } while(n < 0 && errno == EINTR);
195 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
199 D(("fill %s: eof detected", t->id));
204 if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
205 assert(t->used == sizeof (ao_sample_format));
206 /* Check that our assumptions are met. */
207 if(t->format.bits & 7)
208 fatal(0, "bits per sample not a multiple of 8");
209 /* Make a new buffer for audio data. */
210 t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
211 t->buffer = xmalloc(t->size);
214 D(("got format for %s", t->id));
220 /* Return true if A and B denote identical libao formats, else false. */
221 static int formats_equal(const ao_sample_format *a,
222 const ao_sample_format *b) {
223 return (a->bits == b->bits
224 && a->rate == b->rate
225 && a->channels == b->channels
226 && a->byte_format == b->byte_format);
229 /* Close the sound device. */
230 static void idle(void) {
235 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
236 fatal(0, "error calling snd_pcm_nonblock: %d", err);
243 D(("released audio device"));
247 /* Abandon the current track */
248 static void abandon(void) {
249 struct speaker_message sm;
252 memset(&sm, 0, sizeof sm);
253 sm.type = SM_FINISHED;
254 strcpy(sm.id, playing->id);
255 speaker_send(1, &sm, 0);
256 removetrack(playing->id);
262 /* Make sure the sound device is open and has the right sample format. Return
263 * 0 on success and -1 on error. */
264 static int activate(void) {
266 snd_pcm_hw_params_t *hwparams;
267 snd_pcm_sw_params_t *swparams;
268 int sample_format = 0;
271 /* If we don't know the format yet we cannot start. */
272 if(!playing->got_format) {
273 D((" - not got format for %s", playing->id));
276 /* If we need to change format then close the current device. */
277 if(pcm && !formats_equal(&playing->format, &pcm_format))
281 if((err = snd_pcm_open(&pcm,
283 SND_PCM_STREAM_PLAYBACK,
284 SND_PCM_NONBLOCK))) {
285 error(0, "error from snd_pcm_open: %d", err);
288 snd_pcm_hw_params_alloca(&hwparams);
289 D(("set up hw params"));
290 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
291 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
292 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
293 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
294 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
295 switch(playing->format.bits) {
297 sample_format = SND_PCM_FORMAT_S8;
300 switch(playing->format.byte_format) {
301 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
302 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
303 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
304 error(0, "unrecognized byte format %d", playing->format.byte_format);
309 error(0, "unsupported sample size %d", playing->format.bits);
312 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
313 sample_format)) < 0) {
314 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
318 rate = playing->format.rate;
319 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
320 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
321 playing->format.rate, err);
324 if(rate != (unsigned)playing->format.rate)
325 info("want rate %d, got %u", playing->format.rate, rate);
326 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
327 playing->format.channels)) < 0) {
328 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
329 playing->format.channels, err);
332 pcm_bufsize = 3 * FRAMES;
333 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
335 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
337 if(pcm_bufsize != 3 * FRAMES)
338 info("asked for PCM buffer of %d frames, got %d",
339 3 * FRAMES, (int)pcm_bufsize);
340 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
341 fatal(0, "error calling snd_pcm_hw_params: %d", err);
342 D(("set up sw params"));
343 snd_pcm_sw_params_alloca(&swparams);
344 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
345 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
346 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
347 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
349 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
350 fatal(0, "error calling snd_pcm_sw_params: %d", err);
351 pcm_format = playing->format;
352 bpf = bytes_per_frame(&pcm_format);
353 D(("acquired audio device"));
359 /* We assume the error is temporary and that we'll retry in a bit. */
367 /* Check to see whether the current track has finished playing */
368 static void maybe_finished(void) {
371 && (!playing->got_format
372 || playing->used < bytes_per_frame(&playing->format)))
376 static void play(size_t frames) {
377 snd_pcm_sframes_t written_frames;
378 size_t avail_bytes, avail_frames, written_bytes;
385 forceplay = 0; /* Must have called abandon() */
388 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
389 playing->eof ? " EOF" : "",
390 playing->format.rate,
391 playing->format.bits,
392 playing->format.channels));
393 /* If we haven't got enough bytes yet wait until we have. Exception: when
395 if(playing->used < frames * bpf && !playing->eof) {
399 /* We have got enough data so don't force play again */
401 /* Figure out how many frames there are available to write */
402 if(playing->start + playing->used > playing->size)
403 avail_bytes = playing->size - playing->start;
405 avail_bytes = playing->used;
406 avail_frames = avail_bytes / bpf;
407 if(avail_frames > frames)
408 avail_frames = frames;
411 written_frames = snd_pcm_writei(pcm,
412 playing->buffer + playing->start,
414 D(("actually play %zu frames, wrote %d",
415 avail_frames, (int)written_frames));
416 if(written_frames < 0) {
417 switch(written_frames) {
418 case -EPIPE: /* underrun */
419 error(0, "snd_pcm_writei reports underrun");
420 if((err = snd_pcm_prepare(pcm)) < 0)
421 fatal(0, "error calling snd_pcm_prepare: %d", err);
426 fatal(0, "error calling snd_pcm_writei: %d", (int)written_frames);
429 written_bytes = written_frames * bpf;
430 playing->start += written_bytes;
431 playing->used -= written_bytes;
432 playing->played += written_frames;
433 /* If the pointer is at the end of the buffer (or the buffer is completely
434 * empty) wrap it back to the start. */
435 if(!playing->used || playing->start == playing->size)
437 frames -= written_frames;
440 /* Notify the server what we're up to. */
441 static void report(void) {
442 struct speaker_message sm;
444 if(playing && playing->buffer != (void *)&playing->format) {
445 memset(&sm, 0, sizeof sm);
446 sm.type = paused ? SM_PAUSED : SM_PLAYING;
447 strcpy(sm.id, playing->id);
448 sm.data = playing->played / playing->format.rate;
449 speaker_send(1, &sm, 0);
454 static int addfd(int fd, int events) {
457 fds[fdno].events = events;
463 int main(int argc, char **argv) {
464 int n, fd, stdin_slot, alsa_slots, alsa_nslots = -1, err;
465 unsigned short alsa_revents;
467 struct speaker_message sm;
471 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
472 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
476 case 'c': configfile = optarg; break;
477 case 'd': debugging = 1; break;
478 case 'D': debugging = 0; break;
479 default: fatal(0, "invalid option");
482 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
483 /* If stderr is a TTY then log there, otherwise to syslog. */
485 openlog(progname, LOG_PID, LOG_DAEMON);
486 log_default = &log_syslog;
488 if(config_read()) fatal(0, "cannot read configuration");
490 signal(SIGPIPE, SIG_IGN);
492 xnice(config->nice_speaker);
495 /* make sure we're not root, whatever the config says */
496 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
498 while(getppid() != 1) {
500 /* Always ready for commands from the main server. */
501 stdin_slot = addfd(0, POLLIN);
502 /* Try to read sample data for the currently playing track if there is
504 if(playing && !playing->eof && playing->used < playing->size) {
505 playing->slot = addfd(playing->fd, POLLIN);
508 /* If forceplay is set then wait until it succeeds before waiting on the
510 if(pcm && !forceplay) {
512 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
516 /* If any other tracks don't have a full buffer, try to read sample data
518 for(t = tracks; t; t = t->next)
520 if(!t->eof && t->used < t->size) {
521 t->slot = addfd(t->fd, POLLIN);
525 /* Wait up to a second before thinking about current state */
526 n = poll(fds, fdno, 1000);
528 if(errno == EINTR) continue;
529 fatal(errno, "error calling poll");
531 /* Play some sound before doing anything else */
532 if(alsa_slots != -1) {
533 if((err = snd_pcm_poll_descriptors_revents(pcm,
537 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
538 if(alsa_revents & POLLOUT)
541 /* Some attempt to play must have failed */
542 if(playing && !paused)
545 forceplay = 0; /* just in case */
547 /* Perhaps we have a command to process */
548 if(fds[stdin_slot].revents & POLLIN) {
549 n = speaker_recv(0, &sm, &fd);
553 D(("SM_PREPARE %s %d", sm.id, fd));
554 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
555 t = findtrack(sm.id, 1);
559 D(("SM_PLAY %s %d", sm.id, fd));
560 if(playing) fatal(0, "got SM_PLAY but already playing something");
561 t = findtrack(sm.id, 1);
562 if(fd != -1) acquire(t, fd);
582 D(("SM_CANCEL %s", sm.id));
583 t = removetrack(sm.id);
586 sm.type = SM_FINISHED;
587 strcpy(sm.id, playing->id);
588 speaker_send(1, &sm, 0);
593 error(0, "SM_CANCEL for unknown track %s", sm.id);
598 if(config_read()) error(0, "cannot read configuration");
599 info("reloaded configuration");
602 error(0, "unknown message type %d", sm.type);
605 /* Read in any buffered data */
606 for(t = tracks; t; t = t->next)
607 if(t->slot != -1 && (fds[t->slot].revents & POLLIN))
609 /* We might be able to play now */
610 if(pcm && forceplay && playing && !paused)
612 /* Maybe we finished playing a track somewhere in the above */
614 /* If we don't need the sound device for now then close it for the benefit
615 * of anyone else who wants it. */
616 if((!playing || paused) && pcm)
618 /* If we've not reported out state for a second do so now. */
619 if(time(0) > last_report)
622 info("stopped (parent terminated)");