2 * This file is part of DisOrder
3 * Copyright (C) 2005-2009 Richard Kettlewell
4 * Portions (C) 2007 Mark Wooding
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 /** @file server/speaker.c
20 * @brief Speaker process
22 * This program is responsible for transmitting a single coherent audio stream
23 * to its destination (over the network, to some sound API, to some
24 * subprocess). It receives connections from decoders (or rather from the
25 * process that is about to become disorder-normalize) and plays them in the
28 * @b Model. mainloop() implements a select loop awaiting commands from the
29 * main server, new connections to the speaker socket, and audio data on those
30 * connections. Each connection starts with a queue ID (with a 32-bit
31 * native-endian length word), allowing it to be referred to in commands from
34 * Data read on connections is buffered, up to a limit (currently 1Mbyte per
35 * track). No attempt is made here to limit the number of tracks, it is
36 * assumed that the main server won't start outrageously many decoders.
38 * Audio is supplied from this buffer to the uaudio play callback. Playback is
39 * enabled when a track is to be played and disabled when the its last bytes
40 * have been return by the callback; pause and resume is implemneted the
41 * obvious way. If the callback finds itself required to play when there is no
42 * playing track it returns dead air.
44 * @b Encodings. The encodings supported depend entirely on the uaudio backend
45 * chosen. See @ref uaudio.h, etc.
47 * Inbound data is expected to match @c config->sample_format. In normal use
48 * this is arranged by the @c disorder-normalize program (see @ref
49 * server/normalize.c).
51 * @b Garbage @b Collection. This program deliberately does not use the
52 * garbage collector even though it might be convenient to do so. This is for
53 * two reasons. Firstly some sound APIs use thread threads and we do not want
54 * to have to deal with potential interactions between threading and garbage
55 * collection. Secondly this process needs to be able to respond quickly and
56 * this is not compatible with the collector hanging the program even
59 * @b Units. This program thinks at various times in three different units.
60 * Bytes are obvious. A sample is a single sample on a single channel. A
61 * frame is several samples on different channels at the same point in time.
62 * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
74 #include <sys/select.h>
83 #include "configuration.h"
88 #include "speaker-protocol.h"
94 /** @brief Maximum number of FDs to poll for */
97 /** @brief Track structure
99 * Known tracks are kept in a linked list. Usually there will be at most two
100 * of these but rearranging the queue can cause there to be more.
103 /** @brief Next track */
106 /** @brief Input file descriptor */
107 int fd; /* input FD */
109 /** @brief Track ID */
112 /** @brief Start position of data in buffer */
115 /** @brief Number of bytes of data in buffer */
118 /** @brief Set @c fd is at EOF */
121 /** @brief Total number of samples played */
122 unsigned long long played;
124 /** @brief Slot in @ref fds */
127 /** @brief Set when playable
129 * A track becomes playable whenever it fills its buffer or reaches EOF; it
130 * stops being playable when it entirely empties its buffer. Tracks start
131 * out life not playable.
135 /** @brief Input buffer
137 * 1Mbyte is enough for nearly 6s of 44100Hz 16-bit stereo
139 char buffer[1048576];
142 /** @brief Lock protecting data structures
144 * This lock protects values shared between the main thread and the callback.
145 * It is needed e.g. if changing @ref playing or if modifying buffer pointers.
146 * It is not needed to add a new track, to read values only modified in the
149 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
151 /** @brief Linked list of all prepared tracks */
152 static struct track *tracks;
154 /** @brief Playing track, or NULL
156 * This means the DESIRED playing track. It does not reflect any other state
157 * (e.g. activation of uaudio backend).
159 static struct track *playing;
161 /** @brief Array of file descriptors for poll() */
162 static struct pollfd fds[NFDS];
164 /** @brief Next free slot in @ref fds */
167 /** @brief Listen socket */
170 /** @brief Timestamp of last potential report to server */
171 static time_t last_report;
173 /** @brief Set when paused */
176 /** @brief Set when back end activated */
177 static int activated;
179 /** @brief Signal pipe back into the poll() loop */
180 static int sigpipe[2];
182 /** @brief Selected backend */
183 static const struct uaudio *backend;
185 static const struct option options[] = {
186 { "help", no_argument, 0, 'h' },
187 { "version", no_argument, 0, 'V' },
188 { "config", required_argument, 0, 'c' },
189 { "debug", no_argument, 0, 'd' },
190 { "no-debug", no_argument, 0, 'D' },
191 { "syslog", no_argument, 0, 's' },
192 { "no-syslog", no_argument, 0, 'S' },
196 /* Display usage message and terminate. */
197 static void help(void) {
199 " disorder-speaker [OPTIONS]\n"
201 " --help, -h Display usage message\n"
202 " --version, -V Display version number\n"
203 " --config PATH, -c PATH Set configuration file\n"
204 " --debug, -d Turn on debugging\n"
205 " --[no-]syslog Force logging\n"
207 "Speaker process for DisOrder. Not intended to be run\n"
213 /** @brief Find track @p id, maybe creating it if not found
214 * @param id Track ID to find
215 * @param create If nonzero, create track structure of @p id not found
216 * @return Pointer to track structure or NULL
218 static struct track *findtrack(const char *id, int create) {
221 D(("findtrack %s %d", id, create));
222 for(t = tracks; t && strcmp(id, t->id); t = t->next)
225 t = xmalloc(sizeof *t);
234 /** @brief Remove track @p id (but do not destroy it)
235 * @param id Track ID to remove
236 * @return Track structure or NULL if not found
238 static struct track *removetrack(const char *id) {
239 struct track *t, **tt;
241 D(("removetrack %s", id));
242 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
249 /** @brief Destroy a track
250 * @param t Track structure
252 static void destroy(struct track *t) {
253 D(("destroy %s", t->id));
259 /** @brief Read data into a sample buffer
260 * @param t Pointer to track
261 * @return 0 on success, -1 on EOF
263 * This is effectively the read callback on @c t->fd. It is called from the
264 * main loop whenever the track's file descriptor is readable, assuming the
265 * buffer has not reached the maximum allowed occupancy.
267 static int speaker_fill(struct track *t) {
271 D(("fill %s: eof=%d used=%zu",
272 t->id, t->eof, t->used));
275 pthread_mutex_lock(&lock);
276 if(t->used < sizeof t->buffer) {
277 /* there is room left in the buffer */
278 where = (t->start + t->used) % sizeof t->buffer;
279 /* Get as much data as we can */
280 if(where >= t->start)
281 left = (sizeof t->buffer) - where;
283 left = t->start - where;
284 pthread_mutex_unlock(&lock);
286 n = read(t->fd, t->buffer + where, left);
287 } while(n < 0 && errno == EINTR);
288 pthread_mutex_lock(&lock);
291 fatal(errno, "error reading sample stream");
294 D(("fill %s: eof detected", t->id));
296 /* A track always becomes playable at EOF; we're not going to see any
302 /* A track becomes playable when it (first) fills its buffer. For
303 * 44.1KHz 16-bit stereo this is ~6s of audio data. The latency will
304 * depend how long that takes to decode (hopefuly not very!) */
305 if(t->used == sizeof t->buffer)
310 pthread_mutex_unlock(&lock);
314 /** @brief Return nonzero if we want to play some audio
316 * We want to play audio if there is a current track; and it is not paused; and
317 * it is playable according to the rules for @ref track::playable.
319 static int playable(void) {
322 && playing->playable;
325 /** @brief Notify the server what we're up to */
326 static void report(void) {
327 struct speaker_message sm;
330 memset(&sm, 0, sizeof sm);
331 sm.type = paused ? SM_PAUSED : SM_PLAYING;
332 strcpy(sm.id, playing->id);
333 pthread_mutex_lock(&lock);
334 sm.data = playing->played / (uaudio_rate * uaudio_channels);
335 pthread_mutex_unlock(&lock);
336 speaker_send(1, &sm);
341 /** @brief Add a file descriptor to the set to poll() for
342 * @param fd File descriptor
343 * @param events Events to wait for e.g. @c POLLIN
344 * @return Slot number
346 static int addfd(int fd, int events) {
349 fds[fdno].events = events;
355 /** @brief Callback to return some sampled data
356 * @param buffer Where to put sample data
357 * @param max_samples How many samples to return
358 * @param userdata User data
359 * @return Number of samples written
361 * See uaudio_callback().
363 static size_t speaker_callback(void *buffer,
365 void attribute((unused)) *userdata) {
366 const size_t max_bytes = max_samples * uaudio_sample_size;
367 size_t provided_samples = 0;
369 pthread_mutex_lock(&lock);
370 /* TODO perhaps we should immediately go silent if we've been asked to pause
371 * or cancel the playing track (maybe block in the cancel case and see what
374 if(playing->used > 0) {
376 /* Compute size of largest contiguous chunk. We get called as often as
377 * necessary so there's no need for cleverness here. */
378 if(playing->start + playing->used > sizeof playing->buffer)
379 bytes = sizeof playing->buffer - playing->start;
381 bytes = playing->used;
382 /* Limit to what we were asked for */
383 if(bytes > max_bytes)
386 memcpy(buffer, playing->buffer + playing->start, bytes);
387 playing->start += bytes;
388 playing->used -= bytes;
389 /* Wrap around to start of buffer */
390 if(playing->start == sizeof playing->buffer)
392 /* See if we've reached the end of the track */
393 if(playing->used == 0 && playing->eof)
394 write(sigpipe[1], "", 1);
395 provided_samples = bytes / uaudio_sample_size;
396 playing->played += provided_samples;
399 /* If we couldn't provide anything at all, play dead air */
400 /* TODO maybe it would be better to block, in some cases? */
401 if(!provided_samples) {
402 memset(buffer, 0, max_bytes);
403 provided_samples = max_samples;
405 pthread_mutex_unlock(&lock);
406 return provided_samples;
409 /** @brief Main event loop */
410 static void mainloop(void) {
412 struct speaker_message sm;
413 int n, fd, stdin_slot, timeout, listen_slot, sigpipe_slot;
415 /* Keep going while our parent process is alive */
416 while(getppid() != 1) {
417 int force_report = 0;
420 /* By default we will wait up to a second before thinking about current
423 /* Always ready for commands from the main server. */
424 stdin_slot = addfd(0, POLLIN);
425 /* Also always ready for inbound connections */
426 listen_slot = addfd(listenfd, POLLIN);
427 /* Try to read sample data for the currently playing track if there is
432 && playing->used < (sizeof playing->buffer))
433 playing->slot = addfd(playing->fd, POLLIN);
436 /* If any other tracks don't have a full buffer, try to read sample data
437 * from them. We do this last of all, so that if we run out of slots,
438 * nothing important can't be monitored. */
439 for(t = tracks; t; t = t->next)
443 && t->used < sizeof t->buffer) {
444 t->slot = addfd(t->fd, POLLIN | POLLHUP);
448 sigpipe_slot = addfd(sigpipe[1], POLLIN);
449 /* Wait for something interesting to happen */
450 n = poll(fds, fdno, timeout);
452 if(errno == EINTR) continue;
453 fatal(errno, "error calling poll");
455 /* Perhaps a connection has arrived */
456 if(fds[listen_slot].revents & POLLIN) {
457 struct sockaddr_un addr;
458 socklen_t addrlen = sizeof addr;
462 if((fd = accept(listenfd, (struct sockaddr *)&addr, &addrlen)) >= 0) {
464 if(read(fd, &l, sizeof l) < 4) {
465 error(errno, "reading length from inbound connection");
467 } else if(l >= sizeof id) {
468 error(0, "id length too long");
470 } else if(read(fd, id, l) < (ssize_t)l) {
471 error(errno, "reading id from inbound connection");
475 D(("id %s fd %d", id, fd));
476 t = findtrack(id, 1/*create*/);
477 if (write(fd, "", 1) < 0) /* write an ack */
478 error(errno, "writing ack to inbound connection");
480 error(0, "%s: already got a connection", id);
484 t->fd = fd; /* yay */
488 error(errno, "accept");
490 /* Perhaps we have a command to process */
491 if(fds[stdin_slot].revents & POLLIN) {
492 /* There might (in theory) be several commands queued up, but in general
493 * this won't be the case, so we don't bother looping around to pick them
495 n = speaker_recv(0, &sm);
501 fatal(0, "got SM_PLAY but already playing something");
502 t = findtrack(sm.id, 1);
503 D(("SM_PLAY %s fd %d", t->id, t->fd));
505 error(0, "cannot play track because no connection arrived");
520 D(("SM_CANCEL %s", sm.id));
521 t = removetrack(sm.id);
523 pthread_mutex_lock(&lock);
525 /* scratching the playing track */
526 sm.type = SM_FINISHED;
529 /* Could be scratching the playing track before it's quite got
530 * going, or could be just removing a track from the queue. We
531 * log more because there's been a bug here recently than because
532 * it's particularly interesting; the log message will be removed
533 * if no further problems show up. */
534 info("SM_CANCEL for nonplaying track %s", sm.id);
535 sm.type = SM_STILLBORN;
537 strcpy(sm.id, t->id);
539 pthread_mutex_unlock(&lock);
541 /* Probably scratching the playing track well before it's got
542 * going, but could indicate a bug, so we log this as an error. */
543 sm.type = SM_UNKNOWN;
544 error(0, "SM_CANCEL for unknown track %s", sm.id);
546 speaker_send(1, &sm);
552 error(0, "cannot read configuration");
553 info("reloaded configuration");
556 error(0, "unknown message type %d", sm.type);
559 /* Read in any buffered data */
560 for(t = tracks; t; t = t->next)
563 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
565 /* Drain the signal pipe. We don't care about its contents, merely that it
566 * interrupted poll(). */
567 if(fds[sigpipe_slot].revents & POLLIN) {
570 read(sigpipe[0], buffer, sizeof buffer);
572 if(playing && playing->used == 0 && playing->eof) {
573 /* The playing track is done. Tell the server, and destroy it. */
574 memset(&sm, 0, sizeof sm);
575 sm.type = SM_FINISHED;
576 strcpy(sm.id, playing->id);
577 speaker_send(1, &sm);
578 removetrack(playing->id);
579 pthread_mutex_lock(&lock);
582 pthread_mutex_unlock(&lock);
583 /* The server will presumalby send as an SM_PLAY by return */
585 /* Impose any state change required by the above */
594 backend->deactivate();
597 /* If we've not reported our state for a second do so now. */
598 if(force_report || time(0) > last_report)
603 int main(int argc, char **argv) {
604 int n, logsyslog = !isatty(2);
605 struct sockaddr_un addr;
606 static const int one = 1;
607 struct speaker_message sm;
613 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
614 while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
617 case 'V': version("disorder-speaker");
618 case 'c': configfile = optarg; break;
619 case 'd': debugging = 1; break;
620 case 'D': debugging = 0; break;
621 case 'S': logsyslog = 0; break;
622 case 's': logsyslog = 1; break;
623 default: fatal(0, "invalid option");
626 if((d = getenv("DISORDER_DEBUG_SPEAKER"))) debugging = atoi(d);
628 openlog(progname, LOG_PID, LOG_DAEMON);
629 log_default = &log_syslog;
631 config_uaudio_apis = uaudio_apis;
632 if(config_read(1)) fatal(0, "cannot read configuration");
634 signal(SIGPIPE, SIG_IGN);
636 xnice(config->nice_speaker);
639 /* make sure we're not root, whatever the config says */
640 if(getuid() == 0 || geteuid() == 0)
641 fatal(0, "do not run as root");
642 /* Make sure we can't have more than NFDS files open (it would bust our
644 if(getrlimit(RLIMIT_NOFILE, rl) < 0)
645 fatal(errno, "getrlimit RLIMIT_NOFILE");
646 if(rl->rlim_cur > NFDS) {
648 if(setrlimit(RLIMIT_NOFILE, rl) < 0)
649 fatal(errno, "setrlimit to reduce RLIMIT_NOFILE to %lu",
650 (unsigned long)rl->rlim_cur);
651 info("set RLIM_NOFILE to %lu", (unsigned long)rl->rlim_cur);
653 info("RLIM_NOFILE is %lu", (unsigned long)rl->rlim_cur);
654 /* create a pipe between the backend callback and the poll() loop */
656 nonblock(sigpipe[0]);
657 /* set up audio backend */
658 uaudio_set_format(config->sample_format.rate,
659 config->sample_format.channels,
660 config->sample_format.bits,
661 config->sample_format.bits != 8);
662 /* TODO other parameters! */
663 backend = uaudio_find(config->api);
664 /* backend-specific initialization */
665 backend->start(speaker_callback, NULL);
666 /* create the socket directory */
667 byte_xasprintf(&dir, "%s/speaker", config->home);
668 unlink(dir); /* might be a leftover socket */
669 if(mkdir(dir, 0700) < 0 && errno != EEXIST)
670 fatal(errno, "error creating %s", dir);
671 /* set up the listen socket */
672 listenfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
673 memset(&addr, 0, sizeof addr);
674 addr.sun_family = AF_UNIX;
675 snprintf(addr.sun_path, sizeof addr.sun_path, "%s/speaker/socket",
677 if(unlink(addr.sun_path) < 0 && errno != ENOENT)
678 error(errno, "removing %s", addr.sun_path);
679 xsetsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
680 if(bind(listenfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
681 fatal(errno, "error binding socket to %s", addr.sun_path);
682 xlisten(listenfd, 128);
684 info("listening on %s", addr.sun_path);
685 memset(&sm, 0, sizeof sm);
687 speaker_send(1, &sm);
689 info("stopped (parent terminated)");