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
20 /** @file server/speaker.c
21 * @brief Speaker process
23 * This program is responsible for transmitting a single coherent audio stream
24 * to its destination (over the network, to some sound API, to some
25 * subprocess). It receives connections from decoders via file descriptor
26 * passing from the main server and plays them in the right order.
28 * @b Encodings. For the <a href="http://www.alsa-project.org/">ALSA</a> API,
29 * 8- and 16- bit stereo and mono are supported, with any sample rate (within
30 * the limits that ALSA can deal with.)
32 * Inbound data is expected to match @c config->sample_format. In normal use
33 * this is arranged by the @c disorder-normalize program (see @ref
34 * server/normalize.c).
36 * @b Garbage @b Collection. This program deliberately does not use the
37 * garbage collector even though it might be convenient to do so. This is for
38 * two reasons. Firstly some sound APIs use thread threads and we do not want
39 * to have to deal with potential interactions between threading and garbage
40 * collection. Secondly this process needs to be able to respond quickly and
41 * this is not compatible with the collector hanging the program even
44 * @b Units. This program thinks at various times in three different units.
45 * Bytes are obvious. A sample is a single sample on a single channel. A
46 * frame is several samples on different channels at the same point in time.
47 * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
64 #include <sys/select.h>
70 #include "configuration.h"
75 #include "speaker-protocol.h"
79 /** @brief Linked list of all prepared tracks */
82 /** @brief Playing track, or NULL */
83 struct track *playing;
85 /** @brief Number of bytes pre frame */
88 /** @brief Array of file descriptors for poll() */
89 struct pollfd fds[NFDS];
91 /** @brief Next free slot in @ref fds */
94 static time_t last_report; /* when we last reported */
95 static int paused; /* pause status */
97 /** @brief The current device state */
98 enum device_states device_state;
100 /** @brief Set when idled
102 * This is set when the sound device is deliberately closed by idle().
106 /** @brief Selected backend */
107 static const struct speaker_backend *backend;
109 static const struct option options[] = {
110 { "help", no_argument, 0, 'h' },
111 { "version", no_argument, 0, 'V' },
112 { "config", required_argument, 0, 'c' },
113 { "debug", no_argument, 0, 'd' },
114 { "no-debug", no_argument, 0, 'D' },
118 /* Display usage message and terminate. */
119 static void help(void) {
121 " disorder-speaker [OPTIONS]\n"
123 " --help, -h Display usage message\n"
124 " --version, -V Display version number\n"
125 " --config PATH, -c PATH Set configuration file\n"
126 " --debug, -d Turn on debugging\n"
128 "Speaker process for DisOrder. Not intended to be run\n"
134 /* Display version number and terminate. */
135 static void version(void) {
136 xprintf("disorder-speaker version %s\n", disorder_version_string);
141 /** @brief Return the number of bytes per frame in @p format */
142 static size_t bytes_per_frame(const struct stream_header *format) {
143 return format->channels * format->bits / 8;
146 /** @brief Find track @p id, maybe creating it if not found */
147 static struct track *findtrack(const char *id, int create) {
150 D(("findtrack %s %d", id, create));
151 for(t = tracks; t && strcmp(id, t->id); t = t->next)
154 t = xmalloc(sizeof *t);
163 /** @brief Remove track @p id (but do not destroy it) */
164 static struct track *removetrack(const char *id) {
165 struct track *t, **tt;
167 D(("removetrack %s", id));
168 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
175 /** @brief Destroy a track */
176 static void destroy(struct track *t) {
177 D(("destroy %s", t->id));
178 if(t->fd != -1) xclose(t->fd);
182 /** @brief Notice a new connection */
183 static void acquire(struct track *t, int fd) {
184 D(("acquire %s %d", t->id, fd));
191 /** @brief Read data into a sample buffer
192 * @param t Pointer to track
193 * @return 0 on success, -1 on EOF
195 * This is effectively the read callback on @c t->fd. It is called from the
196 * main loop whenever the track's file descriptor is readable, assuming the
197 * buffer has not reached the maximum allowed occupancy.
199 static int fill(struct track *t) {
203 D(("fill %s: eof=%d used=%zu",
204 t->id, t->eof, t->used));
205 if(t->eof) return -1;
206 if(t->used < sizeof t->buffer) {
207 /* there is room left in the buffer */
208 where = (t->start + t->used) % sizeof t->buffer;
209 /* Get as much data as we can */
210 if(where >= t->start) left = (sizeof t->buffer) - where;
211 else left = t->start - where;
213 n = read(t->fd, t->buffer + where, left);
214 } while(n < 0 && errno == EINTR);
216 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
220 D(("fill %s: eof detected", t->id));
229 /** @brief Close the sound device
231 * This is called to deactivate the output device when pausing, and also by the
232 * ALSA backend when changing encoding (in which case the sound device will be
233 * immediately reactivated).
235 static void idle(void) {
237 if(backend->deactivate)
238 backend->deactivate();
240 device_state = device_closed;
244 /** @brief Abandon the current track */
246 struct speaker_message sm;
249 memset(&sm, 0, sizeof sm);
250 sm.type = SM_FINISHED;
251 strcpy(sm.id, playing->id);
252 speaker_send(1, &sm, 0);
253 removetrack(playing->id);
258 /** @brief Enable sound output
260 * Makes sure the sound device is open and has the right sample format. Return
261 * 0 on success and -1 on error.
263 static void activate(void) {
264 if(backend->activate)
267 device_state = device_open;
270 /** @brief Check whether the current track has finished
272 * The current track is determined to have finished either if the input stream
273 * eded before the format could be determined (i.e. it is malformed) or the
274 * input is at end of file and there is less than a frame left unplayed. (So
275 * it copes with decoders that crash mid-frame.)
277 static void maybe_finished(void) {
280 && playing->used < bytes_per_frame(&config->sample_format))
284 /** @brief Play up to @p frames frames of audio
286 * It is always safe to call this function.
287 * - If @ref playing is 0 then it will just return
288 * - If @ref paused is non-0 then it will just return
289 * - If @ref device_state != @ref device_open then it will call activate() and
290 * return if it it fails.
291 * - If there is not enough audio to play then it play what is available.
293 * If there are not enough frames to play then whatever is available is played
294 * instead. It is up to mainloop() to ensure that play() is not called when
295 * unreasonably only an small amounts of data is available to play.
297 static void play(size_t frames) {
298 size_t avail_frames, avail_bytes, written_frames;
299 ssize_t written_bytes;
301 /* Make sure there's a track to play and it is not pasued */
302 if(!playing || paused)
304 /* Make sure the output device is open */
305 if(device_state != device_open) {
307 if(device_state != device_open)
310 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
311 playing->eof ? " EOF" : "",
312 config->sample_format.rate,
313 config->sample_format.bits,
314 config->sample_format.channels));
315 /* Figure out how many frames there are available to write */
316 if(playing->start + playing->used > sizeof playing->buffer)
317 /* The ring buffer is currently wrapped, only play up to the wrap point */
318 avail_bytes = (sizeof playing->buffer) - playing->start;
320 /* The ring buffer is not wrapped, can play the lot */
321 avail_bytes = playing->used;
322 avail_frames = avail_bytes / bpf;
323 /* Only play up to the requested amount */
324 if(avail_frames > frames)
325 avail_frames = frames;
329 written_frames = backend->play(avail_frames);
330 written_bytes = written_frames * bpf;
331 /* written_bytes and written_frames had better both be set and correct by
333 playing->start += written_bytes;
334 playing->used -= written_bytes;
335 playing->played += written_frames;
336 /* If the pointer is at the end of the buffer (or the buffer is completely
337 * empty) wrap it back to the start. */
338 if(!playing->used || playing->start == (sizeof playing->buffer))
340 frames -= written_frames;
344 /* Notify the server what we're up to. */
345 static void report(void) {
346 struct speaker_message sm;
349 memset(&sm, 0, sizeof sm);
350 sm.type = paused ? SM_PAUSED : SM_PLAYING;
351 strcpy(sm.id, playing->id);
352 sm.data = playing->played / config->sample_format.rate;
353 speaker_send(1, &sm, 0);
358 static void reap(int __attribute__((unused)) sig) {
363 cmdpid = waitpid(-1, &st, WNOHANG);
365 signal(SIGCHLD, reap);
368 int addfd(int fd, int events) {
371 fds[fdno].events = events;
377 /** @brief Table of speaker backends */
378 static const struct speaker_backend *backends[] = {
387 /** @brief Return nonzero if we want to play some audio
389 * We want to play audio if there is a current track; and it is not paused; and
390 * there are at least @ref FRAMES frames of audio to play, or we are in sight
391 * of the end of the current track.
393 static int playable(void) {
396 && (playing->used >= FRAMES || playing->eof);
399 /** @brief Main event loop */
400 static void mainloop(void) {
402 struct speaker_message sm;
403 int n, fd, stdin_slot, timeout;
405 while(getppid() != 1) {
407 /* By default we will wait up to a second before thinking about current
410 /* Always ready for commands from the main server. */
411 stdin_slot = addfd(0, POLLIN);
412 /* Try to read sample data for the currently playing track if there is
414 if(playing && !playing->eof && playing->used < (sizeof playing->buffer))
415 playing->slot = addfd(playing->fd, POLLIN);
419 /* We want to play some audio. If the device is closed then we attempt
421 if(device_state == device_closed)
423 /* If the device is (now) open then we will wait up until it is ready for
424 * more. If something went wrong then we should have device_error
425 * instead, but the post-poll code will cope even if it's
427 if(device_state == device_open)
428 backend->beforepoll();
430 /* If any other tracks don't have a full buffer, try to read sample data
431 * from them. We do this last of all, so that if we run out of slots,
432 * nothing important can't be monitored. */
433 for(t = tracks; t; t = t->next)
435 if(!t->eof && t->used < sizeof t->buffer) {
436 t->slot = addfd(t->fd, POLLIN | POLLHUP);
440 /* Wait for something interesting to happen */
441 n = poll(fds, fdno, timeout);
443 if(errno == EINTR) continue;
444 fatal(errno, "error calling poll");
446 /* Play some sound before doing anything else */
448 /* We want to play some audio */
449 if(device_state == device_open) {
453 /* We must be in _closed or _error, and it should be the latter, but we
456 * We most likely timed out, so now is a good time to retry. play()
457 * knows to re-activate the device if necessary.
462 /* Perhaps we have a command to process */
463 if(fds[stdin_slot].revents & POLLIN) {
464 /* There might (in theory) be several commands queued up, but in general
465 * this won't be the case, so we don't bother looping around to pick them
467 n = speaker_recv(0, &sm, &fd);
471 D(("SM_PREPARE %s %d", sm.id, fd));
472 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
473 t = findtrack(sm.id, 1);
477 D(("SM_PLAY %s %d", sm.id, fd));
478 if(playing) fatal(0, "got SM_PLAY but already playing something");
479 t = findtrack(sm.id, 1);
480 if(fd != -1) acquire(t, fd);
482 /* We attempt to play straight away rather than going round the loop.
483 * play() is clever enough to perform any activation that is
497 /* As for SM_PLAY we attempt to play straight away. */
504 D(("SM_CANCEL %s", sm.id));
505 t = removetrack(sm.id);
508 sm.type = SM_FINISHED;
509 strcpy(sm.id, playing->id);
510 speaker_send(1, &sm, 0);
515 error(0, "SM_CANCEL for unknown track %s", sm.id);
520 if(config_read()) error(0, "cannot read configuration");
521 info("reloaded configuration");
524 error(0, "unknown message type %d", sm.type);
527 /* Read in any buffered data */
528 for(t = tracks; t; t = t->next)
529 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
531 /* Maybe we finished playing a track somewhere in the above */
533 /* If we don't need the sound device for now then close it for the benefit
534 * of anyone else who wants it. */
535 if((!playing || paused) && device_state == device_open)
537 /* If we've not reported out state for a second do so now. */
538 if(time(0) > last_report)
543 int main(int argc, char **argv) {
547 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
548 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
552 case 'c': configfile = optarg; break;
553 case 'd': debugging = 1; break;
554 case 'D': debugging = 0; break;
555 default: fatal(0, "invalid option");
558 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
559 /* If stderr is a TTY then log there, otherwise to syslog. */
561 openlog(progname, LOG_PID, LOG_DAEMON);
562 log_default = &log_syslog;
564 if(config_read()) fatal(0, "cannot read configuration");
565 bpf = bytes_per_frame(&config->sample_format);
567 signal(SIGPIPE, SIG_IGN);
569 signal(SIGCHLD, reap);
571 xnice(config->nice_speaker);
574 /* make sure we're not root, whatever the config says */
575 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
576 /* identify the backend used to play */
577 for(n = 0; backends[n]; ++n)
578 if(backends[n]->backend == config->speaker_backend)
581 fatal(0, "unsupported backend %d", config->speaker_backend);
582 backend = backends[n];
583 /* backend-specific initialization */
586 info("stopped (parent terminated)");