*
* This program is responsible for transmitting a single coherent audio stream
* to its destination (over the network, to some sound API, to some
- * subprocess). It receives connections from decoders via file descriptor
- * passing from the main server and plays them in the right order.
+ * subprocess). It receives connections from decoders (or rather from the
+ * process that is about to become disorder-normalize) and plays them in the
+ * right order.
*
* @b Encodings. For the <a href="http://www.alsa-project.org/">ALSA</a> API,
* 8- and 16- bit stereo and mono are supported, with any sample rate (within
* the limits that ALSA can deal with.)
*
- * When communicating with a subprocess, <a
- * href="http://sox.sourceforge.net/">sox</a> is invoked to convert the inbound
- * data to a single consistent format. The same applies for network (RTP)
- * play, though in that case currently only 44.1KHz 16-bit stereo is supported.
- *
- * The inbound data starts with a structure defining the data format. Note
- * that this is NOT portable between different platforms or even necessarily
- * between versions; the speaker is assumed to be built from the same source
- * and run on the same host as the main server.
+ * Inbound data is expected to match @c config->sample_format. In normal use
+ * this is arranged by the @c disorder-normalize program (see @ref
+ * server/normalize.c).
*
* @b Garbage @b Collection. This program deliberately does not use the
* garbage collector even though it might be convenient to do so. This is for
#include <time.h>
#include <fcntl.h>
#include <poll.h>
+#include <sys/un.h>
#include "configuration.h"
#include "syscalls.h"
struct track *playing;
/** @brief Number of bytes pre frame */
-size_t device_bpf;
+size_t bpf;
/** @brief Array of file descriptors for poll() */
struct pollfd fds[NFDS];
/** @brief Next free slot in @ref fds */
int fdno;
+/** @brief Listen socket */
+static int listenfd;
+
static time_t last_report; /* when we last reported */
static int paused; /* pause status */
/** @brief The current device state */
enum device_states device_state;
-/** @brief The current device sample format
- *
- * Only meaningful if @ref device_state = @ref device_open or perhaps @ref
- * device_error. For @ref FIXED_FORMAT backends, this should always match @c
- * config->sample_format.
- */
-ao_sample_format device_format;
-
/** @brief Set when idled
*
* This is set when the sound device is deliberately closed by idle().
}
/** @brief Return the number of bytes per frame in @p format */
-static size_t bytes_per_frame(const ao_sample_format *format) {
+static size_t bytes_per_frame(const struct stream_header *format) {
return format->channels * format->bits / 8;
}
strcpy(t->id, id);
t->fd = -1;
tracks = t;
- /* The initial input buffer will be the sample format. */
- t->buffer = (void *)&t->format;
- t->size = sizeof t->format;
}
return t;
}
static void destroy(struct track *t) {
D(("destroy %s", t->id));
if(t->fd != -1) xclose(t->fd);
- if(t->buffer != (void *)&t->format) free(t->buffer);
free(t);
}
-/** @brief Notice a new connection */
-static void acquire(struct track *t, int fd) {
- D(("acquire %s %d", t->id, fd));
- if(t->fd != -1)
- xclose(t->fd);
- t->fd = fd;
- nonblock(fd);
-}
-
-/** @brief Return true if A and B denote identical libao formats, else false */
-int formats_equal(const ao_sample_format *a,
- const ao_sample_format *b) {
- return (a->bits == b->bits
- && a->rate == b->rate
- && a->channels == b->channels
- && a->byte_format == b->byte_format);
-}
-
-/** @brief Compute arguments to sox */
-static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
- int n;
-
- *(*pp)++ = "-t.raw";
- *(*pp)++ = "-s";
- *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
- *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
- /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
- * deployed! */
- switch(config->sox_generation) {
- case 0:
- if(ao->bits != 8
- && ao->byte_format != AO_FMT_NATIVE
- && ao->byte_format != MACHINE_AO_FMT) {
- *(*pp)++ = "-x";
- }
- switch(ao->bits) {
- case 8: *(*pp)++ = "-b"; break;
- case 16: *(*pp)++ = "-w"; break;
- case 32: *(*pp)++ = "-l"; break;
- case 64: *(*pp)++ = "-d"; break;
- default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
- }
- break;
- case 1:
- switch(ao->byte_format) {
- case AO_FMT_NATIVE: break;
- case AO_FMT_BIG: *(*pp)++ = "-B"; break;
- case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
- }
- *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
- break;
- }
-}
-
-/** @brief Enable format translation
- *
- * If necessary, replaces a tracks inbound file descriptor with one connected
- * to a sox invocation, which performs the required translation.
- */
-static void enable_translation(struct track *t) {
- if((backend->flags & FIXED_FORMAT)
- && !formats_equal(&t->format, &config->sample_format)) {
- char argbuf[1024], *q = argbuf;
- const char *av[18], **pp = av;
- int soxpipe[2];
- pid_t soxkid;
-
- *pp++ = "sox";
- soxargs(&pp, &q, &t->format);
- *pp++ = "-";
- soxargs(&pp, &q, &config->sample_format);
- *pp++ = "-";
- *pp++ = 0;
- if(debugging) {
- for(pp = av; *pp; pp++)
- D(("sox arg[%d] = %s", pp - av, *pp));
- D(("end args"));
- }
- xpipe(soxpipe);
- soxkid = xfork();
- if(soxkid == 0) {
- signal(SIGPIPE, SIG_DFL);
- xdup2(t->fd, 0);
- xdup2(soxpipe[1], 1);
- fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
- close(soxpipe[0]);
- close(soxpipe[1]);
- close(t->fd);
- execvp("sox", (char **)av);
- _exit(1);
- }
- D(("forking sox for format conversion (kid = %d)", soxkid));
- close(t->fd);
- close(soxpipe[1]);
- t->fd = soxpipe[0];
- t->format = config->sample_format;
- }
-}
-
/** @brief Read data into a sample buffer
* @param t Pointer to track
* @return 0 on success, -1 on EOF
size_t where, left;
int n;
- D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
- t->id, t->eof, t->used, t->size, t->got_format));
+ D(("fill %s: eof=%d used=%zu",
+ t->id, t->eof, t->used));
if(t->eof) return -1;
- if(t->used < t->size) {
+ if(t->used < sizeof t->buffer) {
/* there is room left in the buffer */
- where = (t->start + t->used) % t->size;
- if(t->got_format) {
- /* We are reading audio data, get as much as we can */
- if(where >= t->start) left = t->size - where;
- else left = t->start - where;
- } else
- /* We are still waiting for the format, only get that */
- left = sizeof (ao_sample_format) - t->used;
+ where = (t->start + t->used) % sizeof t->buffer;
+ /* Get as much data as we can */
+ if(where >= t->start) left = (sizeof t->buffer) - where;
+ else left = t->start - where;
do {
n = read(t->fd, t->buffer + where, left);
} while(n < 0 && errno == EINTR);
return -1;
}
t->used += n;
- if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
- assert(t->used == sizeof (ao_sample_format));
- /* Check that our assumptions are met. */
- if(t->format.bits & 7)
- fatal(0, "bits per sample not a multiple of 8");
- /* If the input format is unsuitable, arrange to translate it */
- enable_translation(t);
- /* Make a new buffer for audio data. */
- t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
- t->buffer = xmalloc(t->size);
- t->used = 0;
- t->got_format = 1;
- D(("got format for %s", t->id));
- }
}
return 0;
}
memset(&sm, 0, sizeof sm);
sm.type = SM_FINISHED;
strcpy(sm.id, playing->id);
- speaker_send(1, &sm, 0);
+ speaker_send(1, &sm);
removetrack(playing->id);
destroy(playing);
playing = 0;
* 0 on success and -1 on error.
*/
static void activate(void) {
- /* If we don't know the format yet we cannot start. */
- if(!playing->got_format) {
- D((" - not got format for %s", playing->id));
- return;
- }
- if(backend->flags & FIXED_FORMAT)
- device_format = config->sample_format;
- if(backend->activate) {
+ if(backend->activate)
backend->activate();
- } else {
- assert(backend->flags & FIXED_FORMAT);
- /* ...otherwise device_format not set */
+ else
device_state = device_open;
- }
- if(device_state == device_open)
- device_bpf = bytes_per_frame(&device_format);
}
/** @brief Check whether the current track has finished
static void maybe_finished(void) {
if(playing
&& playing->eof
- && (!playing->got_format
- || playing->used < bytes_per_frame(&playing->format)))
+ && playing->used < bytes_per_frame(&config->sample_format))
abandon();
}
/* Make sure there's a track to play and it is not pasued */
if(!playing || paused)
return;
- /* Make sure the output device is open and has the right sample format */
- if(device_state != device_open
- || !formats_equal(&device_format, &playing->format)) {
+ /* Make sure the output device is open */
+ if(device_state != device_open) {
activate();
if(device_state != device_open)
return;
}
- D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / device_bpf,
+ D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
playing->eof ? " EOF" : "",
- playing->format.rate,
- playing->format.bits,
- playing->format.channels));
+ config->sample_format.rate,
+ config->sample_format.bits,
+ config->sample_format.channels));
/* Figure out how many frames there are available to write */
- if(playing->start + playing->used > playing->size)
+ if(playing->start + playing->used > sizeof playing->buffer)
/* The ring buffer is currently wrapped, only play up to the wrap point */
- avail_bytes = playing->size - playing->start;
+ avail_bytes = (sizeof playing->buffer) - playing->start;
else
/* The ring buffer is not wrapped, can play the lot */
avail_bytes = playing->used;
- avail_frames = avail_bytes / device_bpf;
+ avail_frames = avail_bytes / bpf;
/* Only play up to the requested amount */
if(avail_frames > frames)
avail_frames = frames;
return;
/* Play it, Sam */
written_frames = backend->play(avail_frames);
- written_bytes = written_frames * device_bpf;
+ written_bytes = written_frames * bpf;
/* written_bytes and written_frames had better both be set and correct by
* this point */
playing->start += written_bytes;
playing->played += written_frames;
/* If the pointer is at the end of the buffer (or the buffer is completely
* empty) wrap it back to the start. */
- if(!playing->used || playing->start == playing->size)
+ if(!playing->used || playing->start == (sizeof playing->buffer))
playing->start = 0;
frames -= written_frames;
return;
static void report(void) {
struct speaker_message sm;
- if(playing && playing->buffer != (void *)&playing->format) {
+ if(playing) {
memset(&sm, 0, sizeof sm);
sm.type = paused ? SM_PAUSED : SM_PLAYING;
strcpy(sm.id, playing->id);
- sm.data = playing->played / playing->format.rate;
- speaker_send(1, &sm, 0);
+ sm.data = playing->played / config->sample_format.rate;
+ speaker_send(1, &sm);
}
time(&last_report);
}
/** @brief Table of speaker backends */
static const struct speaker_backend *backends[] = {
-#if API_ALSA
+#if HAVE_ALSA_ASOUNDLIB_H
&alsa_backend,
#endif
&command_backend,
&network_backend,
+#if HAVE_COREAUDIO_AUDIOHARDWARE_H
+ &coreaudio_backend,
+#endif
+#if HAVE_SYS_SOUNDCARD_H
+ &oss_backend,
+#endif
0
};
static void mainloop(void) {
struct track *t;
struct speaker_message sm;
- int n, fd, stdin_slot, timeout;
+ int n, fd, stdin_slot, timeout, listen_slot;
while(getppid() != 1) {
fdno = 0;
timeout = 1000;
/* Always ready for commands from the main server. */
stdin_slot = addfd(0, POLLIN);
+ /* Also always ready for inbound connections */
+ listen_slot = addfd(listenfd, POLLIN);
/* Try to read sample data for the currently playing track if there is
* buffer space. */
- if(playing && !playing->eof && playing->used < playing->size)
+ if(playing
+ && playing->fd >= 0
+ && !playing->eof
+ && playing->used < (sizeof playing->buffer))
playing->slot = addfd(playing->fd, POLLIN);
else if(playing)
playing->slot = -1;
* instead, but the post-poll code will cope even if it's
* device_closed. */
if(device_state == device_open)
- backend->beforepoll();
+ backend->beforepoll(&timeout);
}
/* If any other tracks don't have a full buffer, try to read sample data
* from them. We do this last of all, so that if we run out of slots,
* nothing important can't be monitored. */
for(t = tracks; t; t = t->next)
if(t != playing) {
- if(!t->eof && t->used < t->size) {
+ if(t->fd >= 0
+ && !t->eof
+ && t->used < sizeof t->buffer) {
t->slot = addfd(t->fd, POLLIN | POLLHUP);
} else
t->slot = -1;
play(3 * FRAMES);
}
}
+ /* Perhaps a connection has arrived */
+ if(fds[listen_slot].revents & POLLIN) {
+ struct sockaddr_un addr;
+ socklen_t addrlen = sizeof addr;
+ uint32_t l;
+ char id[24];
+
+ if((fd = accept(listenfd, (struct sockaddr *)&addr, &addrlen)) >= 0) {
+ blocking(fd);
+ if(read(fd, &l, sizeof l) < 4) {
+ error(errno, "reading length from inbound connection");
+ xclose(fd);
+ } else if(l >= sizeof id) {
+ error(0, "id length too long");
+ xclose(fd);
+ } else if(read(fd, id, l) < (ssize_t)l) {
+ error(errno, "reading id from inbound connection");
+ xclose(fd);
+ } else {
+ id[l] = 0;
+ D(("id %s fd %d", id, fd));
+ t = findtrack(id, 1/*create*/);
+ write(fd, "", 1); /* write an ack */
+ if(t->fd != -1) {
+ error(0, "got a connection for a track that already has one");
+ xclose(fd);
+ } else {
+ nonblock(fd);
+ t->fd = fd; /* yay */
+ }
+ }
+ } else
+ error(errno, "accept");
+ }
/* Perhaps we have a command to process */
if(fds[stdin_slot].revents & POLLIN) {
/* There might (in theory) be several commands queued up, but in general
* this won't be the case, so we don't bother looping around to pick them
* all up. */
- n = speaker_recv(0, &sm, &fd);
+ n = speaker_recv(0, &sm);
+ /* TODO */
if(n > 0)
switch(sm.type) {
- case SM_PREPARE:
- D(("SM_PREPARE %s %d", sm.id, fd));
- if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
- t = findtrack(sm.id, 1);
- acquire(t, fd);
- break;
case SM_PLAY:
- D(("SM_PLAY %s %d", sm.id, fd));
if(playing) fatal(0, "got SM_PLAY but already playing something");
t = findtrack(sm.id, 1);
- if(fd != -1) acquire(t, fd);
+ D(("SM_PLAY %s fd %d", t->id, t->fd));
+ if(t->fd == -1)
+ error(0, "cannot play track because no connection arrived");
playing = t;
/* We attempt to play straight away rather than going round the loop.
* play() is clever enough to perform any activation that is
if(t == playing) {
sm.type = SM_FINISHED;
strcpy(sm.id, playing->id);
- speaker_send(1, &sm, 0);
+ speaker_send(1, &sm);
playing = 0;
}
destroy(t);
break;
case SM_RELOAD:
D(("SM_RELOAD"));
- if(config_read()) error(0, "cannot read configuration");
+ if(config_read(1)) error(0, "cannot read configuration");
info("reloaded configuration");
break;
default:
}
/* Read in any buffered data */
for(t = tracks; t; t = t->next)
- if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
+ if(t->fd != -1
+ && t->slot != -1
+ && (fds[t->slot].revents & (POLLIN | POLLHUP)))
fill(t);
/* Maybe we finished playing a track somewhere in the above */
maybe_finished();
int main(int argc, char **argv) {
int n;
+ struct sockaddr_un addr;
+ static const int one = 1;
+ struct speaker_message sm;
set_progname(argv);
if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
openlog(progname, LOG_PID, LOG_DAEMON);
log_default = &log_syslog;
}
- if(config_read()) fatal(0, "cannot read configuration");
+ if(config_read(1)) fatal(0, "cannot read configuration");
+ bpf = bytes_per_frame(&config->sample_format);
/* ignore SIGPIPE */
signal(SIGPIPE, SIG_IGN);
/* reap kids */
backend = backends[n];
/* backend-specific initialization */
backend->init();
+ /* set up the listen socket */
+ listenfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
+ memset(&addr, 0, sizeof addr);
+ addr.sun_family = AF_UNIX;
+ snprintf(addr.sun_path, sizeof addr.sun_path, "%s/speaker",
+ config->home);
+ if(unlink(addr.sun_path) < 0 && errno != ENOENT)
+ error(errno, "removing %s", addr.sun_path);
+ xsetsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ if(bind(listenfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
+ fatal(errno, "error binding socket to %s", addr.sun_path);
+ xlisten(listenfd, 128);
+ nonblock(listenfd);
+ info("listening on %s", addr.sun_path);
+ memset(&sm, 0, sizeof sm);
+ sm.type = SM_READY;
+ speaker_send(1, &sm);
mainloop();
info("stopped (parent terminated)");
exit(0);