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>
45 #include "configuration.h"
54 #include <alsa/asoundlib.h>
56 #define BUFFER_SECONDS 5 /* How many seconds of input to
59 #define FRAMES 4096 /* Frame batch size */
61 #define NFDS 256 /* Max FDs to poll for */
63 /* Known tracks are kept in a linked list. We don't normally to have
64 * more than two - maybe three at the outside. */
66 struct track *next; /* next track */
67 int fd; /* input FD */
69 size_t start, used; /* start + bytes used */
70 int eof; /* input is at EOF */
71 int got_format; /* got format yet? */
72 ao_sample_format format; /* sample format */
73 unsigned long long played; /* number of frames played */
74 char *buffer; /* sample buffer */
75 size_t size; /* sample buffer size */
76 int slot; /* poll array slot */
77 } *tracks, *playing; /* all tracks + playing track */
79 static time_t last_report; /* when we last reported */
80 static int paused; /* pause status */
81 static snd_pcm_t *pcm; /* current pcm handle */
82 static ao_sample_format pcm_format; /* current format if aodev != 0 */
83 static size_t bpf; /* bytes per frame */
84 static struct pollfd fds[NFDS]; /* if we need more than that */
85 static int fdno; /* fd number */
86 static snd_pcm_uframes_t pcm_bufsize; /* buffer size */
87 static int forceplay; /* frames to force play */
89 static const struct option options[] = {
90 { "help", no_argument, 0, 'h' },
91 { "version", no_argument, 0, 'V' },
92 { "config", required_argument, 0, 'c' },
93 { "debug", no_argument, 0, 'd' },
94 { "no-debug", no_argument, 0, 'D' },
98 /* Display usage message and terminate. */
99 static void help(void) {
101 " disorder-speaker [OPTIONS]\n"
103 " --help, -h Display usage message\n"
104 " --version, -V Display version number\n"
105 " --config PATH, -c PATH Set configuration file\n"
106 " --debug, -d Turn on debugging\n"
108 "Speaker process for DisOrder. Not intended to be run\n"
114 /* Display version number and terminate. */
115 static void version(void) {
116 xprintf("disorder-speaker version %s\n", disorder_version_string);
121 /* Return the number of bytes per frame in FORMAT. */
122 static size_t bytes_per_frame(const ao_sample_format *format) {
123 return format->channels * format->bits / 8;
126 /* Find track ID, maybe creating it if not found. */
127 static struct track *findtrack(const char *id, int create) {
130 D(("findtrack %s %d", id, create));
131 for(t = tracks; t && strcmp(id, t->id); t = t->next)
134 t = xmalloc(sizeof *t);
139 /* The initial input buffer will be the sample format. */
140 t->buffer = (void *)&t->format;
141 t->size = sizeof t->format;
146 /* Remove track ID (but do not destroy it). */
147 static struct track *removetrack(const char *id) {
148 struct track *t, **tt;
150 D(("removetrack %s", id));
151 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
158 /* Destroy a track. */
159 static void destroy(struct track *t) {
160 D(("destroy %s", t->id));
161 if(t->fd != -1) xclose(t->fd);
162 if(t->buffer != (void *)&t->format) free(t->buffer);
166 /* Notice a new FD. */
167 static void acquire(struct track *t, int fd) {
168 D(("acquire %s %d", t->id, fd));
175 /* Read data into a sample buffer. Return 0 on success, -1 on EOF. */
176 static int fill(struct track *t) {
180 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
181 t->id, t->eof, t->used, t->size, t->got_format));
182 if(t->eof) return -1;
183 if(t->used < t->size) {
184 /* there is room left in the buffer */
185 where = (t->start + t->used) % t->size;
187 /* We are reading audio data, get as much as we can */
188 if(where >= t->start) left = t->size - where;
189 else left = t->start - where;
191 /* We are still waiting for the format, only get that */
192 left = sizeof (ao_sample_format) - t->used;
194 n = read(t->fd, t->buffer + where, left);
195 } while(n < 0 && errno == EINTR);
197 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
201 D(("fill %s: eof detected", t->id));
206 if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
207 assert(t->used == sizeof (ao_sample_format));
208 /* Check that our assumptions are met. */
209 if(t->format.bits & 7)
210 fatal(0, "bits per sample not a multiple of 8");
211 /* Make a new buffer for audio data. */
212 t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
213 t->buffer = xmalloc(t->size);
216 D(("got format for %s", t->id));
222 /* Return true if A and B denote identical libao formats, else false. */
223 static int formats_equal(const ao_sample_format *a,
224 const ao_sample_format *b) {
225 return (a->bits == b->bits
226 && a->rate == b->rate
227 && a->channels == b->channels
228 && a->byte_format == b->byte_format);
231 /* Close the sound device. */
232 static void idle(void) {
237 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
238 fatal(0, "error calling snd_pcm_nonblock: %d", err);
245 D(("released audio device"));
249 /* Abandon the current track */
250 static void abandon(void) {
251 struct speaker_message sm;
254 memset(&sm, 0, sizeof sm);
255 sm.type = SM_FINISHED;
256 strcpy(sm.id, playing->id);
257 speaker_send(1, &sm, 0);
258 removetrack(playing->id);
264 /* Make sure the sound device is open and has the right sample format. Return
265 * 0 on success and -1 on error. */
266 static int activate(void) {
268 snd_pcm_hw_params_t *hwparams;
269 snd_pcm_sw_params_t *swparams;
270 int sample_format = 0;
273 /* If we don't know the format yet we cannot start. */
274 if(!playing->got_format) {
275 D((" - not got format for %s", playing->id));
278 /* If we need to change format then close the current device. */
279 if(pcm && !formats_equal(&playing->format, &pcm_format))
283 if((err = snd_pcm_open(&pcm,
285 SND_PCM_STREAM_PLAYBACK,
286 SND_PCM_NONBLOCK))) {
287 error(0, "error from snd_pcm_open: %d", err);
290 snd_pcm_hw_params_alloca(&hwparams);
291 D(("set up hw params"));
292 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
293 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
294 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
295 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
296 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
297 switch(playing->format.bits) {
299 sample_format = SND_PCM_FORMAT_S8;
302 switch(playing->format.byte_format) {
303 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
304 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
305 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
306 error(0, "unrecognized byte format %d", playing->format.byte_format);
311 error(0, "unsupported sample size %d", playing->format.bits);
314 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
315 sample_format)) < 0) {
316 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
320 rate = playing->format.rate;
321 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
322 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
323 playing->format.rate, err);
326 if(rate != (unsigned)playing->format.rate)
327 info("want rate %d, got %u", playing->format.rate, rate);
328 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
329 playing->format.channels)) < 0) {
330 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
331 playing->format.channels, err);
334 pcm_bufsize = 3 * FRAMES;
335 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
337 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
339 if(pcm_bufsize != 3 * FRAMES)
340 info("asked for PCM buffer of %d frames, got %d",
341 3 * FRAMES, (int)pcm_bufsize);
342 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
343 fatal(0, "error calling snd_pcm_hw_params: %d", err);
344 D(("set up sw params"));
345 snd_pcm_sw_params_alloca(&swparams);
346 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
347 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
348 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
349 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
351 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
352 fatal(0, "error calling snd_pcm_sw_params: %d", err);
353 pcm_format = playing->format;
354 bpf = bytes_per_frame(&pcm_format);
355 D(("acquired audio device"));
361 /* We assume the error is temporary and that we'll retry in a bit. */
369 /* Check to see whether the current track has finished playing */
370 static void maybe_finished(void) {
373 && (!playing->got_format
374 || playing->used < bytes_per_frame(&playing->format)))
378 static void play(size_t frames) {
379 snd_pcm_sframes_t written_frames;
380 size_t avail_bytes, avail_frames, written_bytes;
387 forceplay = 0; /* Must have called abandon() */
390 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
391 playing->eof ? " EOF" : "",
392 playing->format.rate,
393 playing->format.bits,
394 playing->format.channels));
395 /* If we haven't got enough bytes yet wait until we have. Exception: when
397 if(playing->used < frames * bpf && !playing->eof) {
401 /* We have got enough data so don't force play again */
403 /* Figure out how many frames there are available to write */
404 if(playing->start + playing->used > playing->size)
405 avail_bytes = playing->size - playing->start;
407 avail_bytes = playing->used;
408 avail_frames = avail_bytes / bpf;
409 if(avail_frames > frames)
410 avail_frames = frames;
413 written_frames = snd_pcm_writei(pcm,
414 playing->buffer + playing->start,
416 D(("actually play %zu frames, wrote %d",
417 avail_frames, (int)written_frames));
418 if(written_frames < 0) {
419 switch(written_frames) {
420 case -EPIPE: /* underrun */
421 error(0, "snd_pcm_writei reports underrun");
422 if((err = snd_pcm_prepare(pcm)) < 0)
423 fatal(0, "error calling snd_pcm_prepare: %d", err);
428 fatal(0, "error calling snd_pcm_writei: %d", (int)written_frames);
431 written_bytes = written_frames * bpf;
432 playing->start += written_bytes;
433 playing->used -= written_bytes;
434 playing->played += written_frames;
435 /* If the pointer is at the end of the buffer (or the buffer is completely
436 * empty) wrap it back to the start. */
437 if(!playing->used || playing->start == playing->size)
439 frames -= written_frames;
442 /* Notify the server what we're up to. */
443 static void report(void) {
444 struct speaker_message sm;
446 if(playing && playing->buffer != (void *)&playing->format) {
447 memset(&sm, 0, sizeof sm);
448 sm.type = paused ? SM_PAUSED : SM_PLAYING;
449 strcpy(sm.id, playing->id);
450 sm.data = playing->played / playing->format.rate;
451 speaker_send(1, &sm, 0);
456 static int addfd(int fd, int events) {
459 fds[fdno].events = events;
465 int main(int argc, char **argv) {
466 int n, fd, stdin_slot, alsa_slots, alsa_nslots = -1, err;
467 unsigned short alsa_revents;
469 struct speaker_message sm;
473 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
474 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
478 case 'c': configfile = optarg; break;
479 case 'd': debugging = 1; break;
480 case 'D': debugging = 0; break;
481 default: fatal(0, "invalid option");
484 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
485 /* If stderr is a TTY then log there, otherwise to syslog. */
487 openlog(progname, LOG_PID, LOG_DAEMON);
488 log_default = &log_syslog;
490 if(config_read()) fatal(0, "cannot read configuration");
492 signal(SIGPIPE, SIG_IGN);
494 xnice(config->nice_speaker);
497 /* make sure we're not root, whatever the config says */
498 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
500 while(getppid() != 1) {
502 /* Always ready for commands from the main server. */
503 stdin_slot = addfd(0, POLLIN);
504 /* Try to read sample data for the currently playing track if there is
506 if(playing && !playing->eof && playing->used < playing->size) {
507 playing->slot = addfd(playing->fd, POLLIN);
510 /* If forceplay is set then wait until it succeeds before waiting on the
512 if(pcm && !forceplay) {
514 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
518 /* If any other tracks don't have a full buffer, try to read sample data
520 for(t = tracks; t; t = t->next)
522 if(!t->eof && t->used < t->size) {
523 t->slot = addfd(t->fd, POLLIN);
527 /* Wait up to a second before thinking about current state */
528 n = poll(fds, fdno, 1000);
530 if(errno == EINTR) continue;
531 fatal(errno, "error calling poll");
533 /* Play some sound before doing anything else */
534 if(alsa_slots != -1) {
535 if((err = snd_pcm_poll_descriptors_revents(pcm,
539 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
540 if(alsa_revents & POLLOUT)
543 /* Some attempt to play must have failed */
544 if(playing && !paused)
547 forceplay = 0; /* just in case */
549 /* Perhaps we have a command to process */
550 if(fds[stdin_slot].revents & POLLIN) {
551 n = speaker_recv(0, &sm, &fd);
555 D(("SM_PREPARE %s %d", sm.id, fd));
556 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
557 t = findtrack(sm.id, 1);
561 D(("SM_PLAY %s %d", sm.id, fd));
562 if(playing) fatal(0, "got SM_PLAY but already playing something");
563 t = findtrack(sm.id, 1);
564 if(fd != -1) acquire(t, fd);
584 D(("SM_CANCEL %s", sm.id));
585 t = removetrack(sm.id);
588 sm.type = SM_FINISHED;
589 strcpy(sm.id, playing->id);
590 speaker_send(1, &sm, 0);
595 error(0, "SM_CANCEL for unknown track %s", sm.id);
600 if(config_read()) error(0, "cannot read configuration");
601 info("reloaded configuration");
604 error(0, "unknown message type %d", sm.type);
607 /* Read in any buffered data */
608 for(t = tracks; t; t = t->next)
609 if(t->slot != -1 && (fds[t->slot].revents & POLLIN))
611 /* We might be able to play now */
612 if(pcm && forceplay && playing && !paused)
614 /* Maybe we finished playing a track somewhere in the above */
616 /* If we don't need the sound device for now then close it for the benefit
617 * of anyone else who wants it. */
618 if((!playing || paused) && pcm)
620 /* If we've not reported out state for a second do so now. */
621 if(time(0) > last_report)
624 info("stopped (parent terminated)");
628 int main(int attribute((unused)) argc, char **argv) {
631 fatal(0, "disorder-speaker not supported on this platform");