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 processs
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 * For the <a href="http://www.alsa-project.org/">ALSA</a> API, 8- and 16- bit
29 * stereo and mono are supported, with any sample rate (within the limits that
30 * ALSA can deal with.)
32 * When communicating with a subprocess, <a
33 * href="http://sox.sourceforge.net/">sox</a> is invoked to convert the inbound
34 * data to a single consistent format. The same applies for network (RTP)
35 * play, though in that case currently only 44.1KHz 16-bit stereo is supported.
37 * The inbound data starts with a structure defining the data format. Note
38 * that this is NOT portable between different platforms or even necessarily
39 * between versions; the speaker is assumed to be built from the same source
40 * and run on the same host as the main server.
42 * This program deliberately does not use the garbage collector even though it
43 * might be convenient to do so. This is for two reasons. Firstly some sound
44 * APIs use thread threads and we do not want to have to deal with potential
45 * interactions between threading and garbage collection. Secondly this
46 * process needs to be able to respond quickly and this is not compatible with
47 * the collector hanging the program even relatively briefly.
63 #include <sys/select.h>
68 #include <sys/socket.h>
73 #include "configuration.h"
85 #include <alsa/asoundlib.h>
88 #ifdef WORDS_BIGENDIAN
89 # define MACHINE_AO_FMT AO_FMT_BIG
91 # define MACHINE_AO_FMT AO_FMT_LITTLE
94 /** @brief How many seconds of input to buffer
96 * While any given connection has this much audio buffered, no more reads will
97 * be issued for that connection. The decoder will have to wait.
99 #define BUFFER_SECONDS 5
101 #define FRAMES 4096 /* Frame batch size */
103 /** @brief Bytes to send per network packet
105 * Don't make this too big or arithmetic will start to overflow.
107 #define NETWORK_BYTES 1024
109 /** @brief Maximum RTP playahead (seconds) */
112 /** @brief Maximum number of FDs to poll for */
115 /** @brief Track structure
117 * Known tracks are kept in a linked list. Usually there will be at most two
118 * of these but rearranging the queue can cause there to be more.
120 static struct track {
121 struct track *next; /* next track */
122 int fd; /* input FD */
123 char id[24]; /* ID */
124 size_t start, used; /* start + bytes used */
125 int eof; /* input is at EOF */
126 int got_format; /* got format yet? */
127 ao_sample_format format; /* sample format */
128 unsigned long long played; /* number of frames played */
129 char *buffer; /* sample buffer */
130 size_t size; /* sample buffer size */
131 int slot; /* poll array slot */
132 } *tracks, *playing; /* all tracks + playing track */
134 static time_t last_report; /* when we last reported */
135 static int paused; /* pause status */
136 static ao_sample_format pcm_format; /* current format if aodev != 0 */
137 static size_t bpf; /* bytes per frame */
138 static struct pollfd fds[NFDS]; /* if we need more than that */
139 static int fdno; /* fd number */
140 static size_t bufsize; /* buffer size */
142 static snd_pcm_t *pcm; /* current pcm handle */
143 static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
145 static int ready; /* ready to send audio */
146 static int forceplay; /* frames to force play */
147 static int cmdfd = -1; /* child process input */
148 static int bfd = -1; /* broadcast FD */
149 static uint32_t rtp_time; /* RTP timestamp */
150 static struct timeval rtp_time_real; /* corresponding real time */
151 static uint16_t rtp_seq; /* frame sequence number */
152 static uint32_t rtp_id; /* RTP SSRC */
153 static int idled; /* set when idled */
154 static int audio_errors; /* audio error counter */
156 static const struct option options[] = {
157 { "help", no_argument, 0, 'h' },
158 { "version", no_argument, 0, 'V' },
159 { "config", required_argument, 0, 'c' },
160 { "debug", no_argument, 0, 'd' },
161 { "no-debug", no_argument, 0, 'D' },
165 /* Display usage message and terminate. */
166 static void help(void) {
168 " disorder-speaker [OPTIONS]\n"
170 " --help, -h Display usage message\n"
171 " --version, -V Display version number\n"
172 " --config PATH, -c PATH Set configuration file\n"
173 " --debug, -d Turn on debugging\n"
175 "Speaker process for DisOrder. Not intended to be run\n"
181 /* Display version number and terminate. */
182 static void version(void) {
183 xprintf("disorder-speaker version %s\n", disorder_version_string);
188 /** @brief Return the number of bytes per frame in @p format */
189 static size_t bytes_per_frame(const ao_sample_format *format) {
190 return format->channels * format->bits / 8;
193 /** @brief Find track @p id, maybe creating it if not found */
194 static struct track *findtrack(const char *id, int create) {
197 D(("findtrack %s %d", id, create));
198 for(t = tracks; t && strcmp(id, t->id); t = t->next)
201 t = xmalloc(sizeof *t);
206 /* The initial input buffer will be the sample format. */
207 t->buffer = (void *)&t->format;
208 t->size = sizeof t->format;
213 /** @brief Remove track @p id (but do not destroy it) */
214 static struct track *removetrack(const char *id) {
215 struct track *t, **tt;
217 D(("removetrack %s", id));
218 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
225 /** @brief Destroy a track */
226 static void destroy(struct track *t) {
227 D(("destroy %s", t->id));
228 if(t->fd != -1) xclose(t->fd);
229 if(t->buffer != (void *)&t->format) free(t->buffer);
233 /** @brief Notice a new connection */
234 static void acquire(struct track *t, int fd) {
235 D(("acquire %s %d", t->id, fd));
242 /** @brief Return true if A and B denote identical libao formats, else false */
243 static int formats_equal(const ao_sample_format *a,
244 const ao_sample_format *b) {
245 return (a->bits == b->bits
246 && a->rate == b->rate
247 && a->channels == b->channels
248 && a->byte_format == b->byte_format);
251 /** @brief Compute arguments to sox */
252 static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
257 *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
258 *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
259 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
261 switch(config->sox_generation) {
264 && ao->byte_format != AO_FMT_NATIVE
265 && ao->byte_format != MACHINE_AO_FMT) {
269 case 8: *(*pp)++ = "-b"; break;
270 case 16: *(*pp)++ = "-w"; break;
271 case 32: *(*pp)++ = "-l"; break;
272 case 64: *(*pp)++ = "-d"; break;
273 default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
277 switch(ao->byte_format) {
278 case AO_FMT_NATIVE: break;
279 case AO_FMT_BIG: *(*pp)++ = "-B"; break;
280 case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
282 *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
287 /** @brief Enable format translation
289 * If necessary, replaces a tracks inbound file descriptor with one connected
290 * to a sox invocation, which performs the required translation.
292 static void enable_translation(struct track *t) {
293 switch(config->speaker_backend) {
294 case BACKEND_COMMAND:
295 case BACKEND_NETWORK:
296 /* These backends need a specific sample format */
302 if(!formats_equal(&t->format, &config->sample_format)) {
303 char argbuf[1024], *q = argbuf;
304 const char *av[18], **pp = av;
309 soxargs(&pp, &q, &t->format);
311 soxargs(&pp, &q, &config->sample_format);
315 for(pp = av; *pp; pp++)
316 D(("sox arg[%d] = %s", pp - av, *pp));
322 signal(SIGPIPE, SIG_DFL);
324 xdup2(soxpipe[1], 1);
325 fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
329 execvp("sox", (char **)av);
332 D(("forking sox for format conversion (kid = %d)", soxkid));
336 t->format = config->sample_format;
341 /** @brief Read data into a sample buffer
342 * @param t Pointer to track
343 * @return 0 on success, -1 on EOF
345 * This is effectively the read callback on @c t->fd.
347 static int fill(struct track *t) {
351 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
352 t->id, t->eof, t->used, t->size, t->got_format));
353 if(t->eof) return -1;
354 if(t->used < t->size) {
355 /* there is room left in the buffer */
356 where = (t->start + t->used) % t->size;
358 /* We are reading audio data, get as much as we can */
359 if(where >= t->start) left = t->size - where;
360 else left = t->start - where;
362 /* We are still waiting for the format, only get that */
363 left = sizeof (ao_sample_format) - t->used;
365 n = read(t->fd, t->buffer + where, left);
366 } while(n < 0 && errno == EINTR);
368 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
372 D(("fill %s: eof detected", t->id));
377 if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
378 assert(t->used == sizeof (ao_sample_format));
379 /* Check that our assumptions are met. */
380 if(t->format.bits & 7)
381 fatal(0, "bits per sample not a multiple of 8");
382 /* If the input format is unsuitable, arrange to translate it */
383 enable_translation(t);
384 /* Make a new buffer for audio data. */
385 t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
386 t->buffer = xmalloc(t->size);
389 D(("got format for %s", t->id));
395 /** @brief Close the sound device */
396 static void idle(void) {
399 if(config->speaker_backend == BACKEND_ALSA && pcm) {
402 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
403 fatal(0, "error calling snd_pcm_nonblock: %d", err);
410 D(("released audio device"));
417 /** @brief Abandon the current track */
418 static void abandon(void) {
419 struct speaker_message sm;
422 memset(&sm, 0, sizeof sm);
423 sm.type = SM_FINISHED;
424 strcpy(sm.id, playing->id);
425 speaker_send(1, &sm, 0);
426 removetrack(playing->id);
433 /** @brief Log ALSA parameters */
434 static void log_params(snd_pcm_hw_params_t *hwparams,
435 snd_pcm_sw_params_t *swparams) {
439 return; /* too verbose */
444 snd_pcm_sw_params_get_silence_size(swparams, &f);
445 info("sw silence_size=%lu", (unsigned long)f);
446 snd_pcm_sw_params_get_silence_threshold(swparams, &f);
447 info("sw silence_threshold=%lu", (unsigned long)f);
448 snd_pcm_sw_params_get_sleep_min(swparams, &u);
449 info("sw sleep_min=%lu", (unsigned long)u);
450 snd_pcm_sw_params_get_start_threshold(swparams, &f);
451 info("sw start_threshold=%lu", (unsigned long)f);
452 snd_pcm_sw_params_get_stop_threshold(swparams, &f);
453 info("sw stop_threshold=%lu", (unsigned long)f);
454 snd_pcm_sw_params_get_xfer_align(swparams, &f);
455 info("sw xfer_align=%lu", (unsigned long)f);
460 /** @brief Enable sound output
462 * Makes sure the sound device is open and has the right sample format. Return
463 * 0 on success and -1 on error.
465 static int activate(void) {
466 /* If we don't know the format yet we cannot start. */
467 if(!playing->got_format) {
468 D((" - not got format for %s", playing->id));
471 switch(config->speaker_backend) {
472 case BACKEND_COMMAND:
473 case BACKEND_NETWORK:
475 pcm_format = config->sample_format;
476 bufsize = 3 * FRAMES;
477 bpf = bytes_per_frame(&config->sample_format);
478 D(("acquired audio device"));
484 /* If we need to change format then close the current device. */
485 if(pcm && !formats_equal(&playing->format, &pcm_format))
488 snd_pcm_hw_params_t *hwparams;
489 snd_pcm_sw_params_t *swparams;
490 snd_pcm_uframes_t pcm_bufsize;
492 int sample_format = 0;
496 if((err = snd_pcm_open(&pcm,
498 SND_PCM_STREAM_PLAYBACK,
499 SND_PCM_NONBLOCK))) {
500 error(0, "error from snd_pcm_open: %d", err);
503 snd_pcm_hw_params_alloca(&hwparams);
504 D(("set up hw params"));
505 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
506 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
507 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
508 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
509 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
510 switch(playing->format.bits) {
512 sample_format = SND_PCM_FORMAT_S8;
515 switch(playing->format.byte_format) {
516 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
517 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
518 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
519 error(0, "unrecognized byte format %d", playing->format.byte_format);
524 error(0, "unsupported sample size %d", playing->format.bits);
527 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
528 sample_format)) < 0) {
529 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
533 rate = playing->format.rate;
534 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
535 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
536 playing->format.rate, err);
539 if(rate != (unsigned)playing->format.rate)
540 info("want rate %d, got %u", playing->format.rate, rate);
541 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
542 playing->format.channels)) < 0) {
543 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
544 playing->format.channels, err);
547 bufsize = 3 * FRAMES;
548 pcm_bufsize = bufsize;
549 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
551 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
553 if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
554 info("asked for PCM buffer of %d frames, got %d",
555 3 * FRAMES, (int)pcm_bufsize);
556 last_pcm_bufsize = pcm_bufsize;
557 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
558 fatal(0, "error calling snd_pcm_hw_params: %d", err);
559 D(("set up sw params"));
560 snd_pcm_sw_params_alloca(&swparams);
561 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
562 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
563 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
564 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
566 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
567 fatal(0, "error calling snd_pcm_sw_params: %d", err);
568 pcm_format = playing->format;
569 bpf = bytes_per_frame(&pcm_format);
570 D(("acquired audio device"));
571 log_params(hwparams, swparams);
578 /* We assume the error is temporary and that we'll retry in a bit. */
590 /* Check to see whether the current track has finished playing */
591 static void maybe_finished(void) {
594 && (!playing->got_format
595 || playing->used < bytes_per_frame(&playing->format)))
599 static void fork_cmd(void) {
602 if(cmdfd != -1) close(cmdfd);
606 signal(SIGPIPE, SIG_DFL);
610 execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
611 fatal(errno, "error execing /bin/sh");
615 D(("forked cmd %d, fd = %d", cmdpid, cmdfd));
618 static void play(size_t frames) {
619 size_t avail_bytes, write_bytes, written_frames;
620 ssize_t written_bytes;
621 struct rtp_header header;
628 forceplay = 0; /* Must have called abandon() */
631 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
632 playing->eof ? " EOF" : "",
633 playing->format.rate,
634 playing->format.bits,
635 playing->format.channels));
636 /* If we haven't got enough bytes yet wait until we have. Exception: when
638 if(playing->used < frames * bpf && !playing->eof) {
642 /* We have got enough data so don't force play again */
644 /* Figure out how many frames there are available to write */
645 if(playing->start + playing->used > playing->size)
646 avail_bytes = playing->size - playing->start;
648 avail_bytes = playing->used;
650 switch(config->speaker_backend) {
653 snd_pcm_sframes_t pcm_written_frames;
657 avail_frames = avail_bytes / bpf;
658 if(avail_frames > frames)
659 avail_frames = frames;
662 pcm_written_frames = snd_pcm_writei(pcm,
663 playing->buffer + playing->start,
665 D(("actually play %zu frames, wrote %d",
666 avail_frames, (int)pcm_written_frames));
667 if(pcm_written_frames < 0) {
668 switch(pcm_written_frames) {
669 case -EPIPE: /* underrun */
670 error(0, "snd_pcm_writei reports underrun");
671 if((err = snd_pcm_prepare(pcm)) < 0)
672 fatal(0, "error calling snd_pcm_prepare: %d", err);
677 fatal(0, "error calling snd_pcm_writei: %d",
678 (int)pcm_written_frames);
681 written_frames = pcm_written_frames;
682 written_bytes = written_frames * bpf;
686 case BACKEND_COMMAND:
687 if(avail_bytes > frames * bpf)
688 avail_bytes = frames * bpf;
689 written_bytes = write(cmdfd, playing->buffer + playing->start,
691 D(("actually play %zu bytes, wrote %d",
692 avail_bytes, (int)written_bytes));
693 if(written_bytes < 0) {
696 error(0, "hmm, command died; trying another");
703 written_frames = written_bytes / bpf; /* good enough */
705 case BACKEND_NETWORK:
706 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
707 * AVT profile (RFC3551). */
708 if(rtp_time_real.tv_sec == 0)
709 xgettimeofday(&rtp_time_real, 0);
712 xgettimeofday(&now, 0);
713 /* There's been a gap. Fix up the RTP time accordingly. */
714 const long offset = (((now.tv_sec + now.tv_usec /1000000.0)
715 - (rtp_time_real.tv_sec + rtp_time_real.tv_usec / 1000000.0))
716 * playing->format.rate * playing->format.channels);
718 info("offset RTP timestamp by %ld", offset);
723 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
724 header.seq = htons(rtp_seq++);
725 header.timestamp = htonl(rtp_time);
726 header.ssrc = rtp_id;
727 header.mpt = (idled ? 0x80 : 0x00) | 10;
728 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
729 * the sample rate (in a library somewhere so that configuration.c can rule
730 * out invalid rates).
733 if(avail_bytes > NETWORK_BYTES - sizeof header) {
734 avail_bytes = NETWORK_BYTES - sizeof header;
735 avail_bytes -= avail_bytes % bpf;
737 /* "The RTP clock rate used for generating the RTP timestamp is independent
738 * of the number of channels and the encoding; it equals the number of
739 * sampling periods per second. For N-channel encodings, each sampling
740 * period (say, 1/8000 of a second) generates N samples. (This terminology
741 * is standard, but somewhat confusing, as the total number of samples
742 * generated per second is then the sampling rate times the channel
745 write_bytes = avail_bytes;
747 while(write_bytes > 0 && (uint32_t)(playing->buffer + playing->start + write_bytes - 4) == 0)
751 vec[0].iov_base = (void *)&header;
752 vec[0].iov_len = sizeof header;
753 vec[1].iov_base = playing->buffer + playing->start;
754 vec[1].iov_len = avail_bytes;
757 char buffer[3 * sizeof header + 1];
759 const uint8_t *ptr = (void *)&header;
761 for(n = 0; n < sizeof header; ++n)
762 sprintf(&buffer[3 * n], "%02x ", *ptr++);
767 written_bytes = writev(bfd,
770 } while(written_bytes < 0 && errno == EINTR);
771 if(written_bytes < 0) {
772 error(errno, "error transmitting audio data");
774 if(audio_errors == 10)
775 fatal(0, "too many audio errors");
780 written_bytes = avail_bytes;
781 written_frames = written_bytes / bpf;
782 /* Advance RTP's notion of the time */
783 rtp_time += written_frames * playing->format.channels;
784 /* Advance the corresponding real time */
785 assert(NETWORK_BYTES <= 2000); /* else risk overflowing 32 bits */
786 rtp_time_real.tv_usec += written_frames * 1000000 / playing->format.rate;
787 if(rtp_time_real.tv_usec >= 1000000) {
788 ++rtp_time_real.tv_sec;
789 rtp_time_real.tv_usec -= 1000000;
791 assert(rtp_time_real.tv_usec < 1000000);
796 /* written_bytes and written_frames had better both be set and correct by
798 playing->start += written_bytes;
799 playing->used -= written_bytes;
800 playing->played += written_frames;
801 /* If the pointer is at the end of the buffer (or the buffer is completely
802 * empty) wrap it back to the start. */
803 if(!playing->used || playing->start == playing->size)
805 frames -= written_frames;
808 /* Notify the server what we're up to. */
809 static void report(void) {
810 struct speaker_message sm;
812 if(playing && playing->buffer != (void *)&playing->format) {
813 memset(&sm, 0, sizeof sm);
814 sm.type = paused ? SM_PAUSED : SM_PLAYING;
815 strcpy(sm.id, playing->id);
816 sm.data = playing->played / playing->format.rate;
817 speaker_send(1, &sm, 0);
822 static void reap(int __attribute__((unused)) sig) {
827 cmdpid = waitpid(-1, &st, WNOHANG);
829 signal(SIGCHLD, reap);
832 static int addfd(int fd, int events) {
835 fds[fdno].events = events;
841 int main(int argc, char **argv) {
842 int n, fd, stdin_slot, alsa_slots, cmdfd_slot, bfd_slot, poke, timeout;
843 struct timeval now, delta;
845 struct speaker_message sm;
846 struct addrinfo *res, *sres;
847 static const struct addrinfo pref = {
857 static const struct addrinfo prefbind = {
867 static const int one = 1;
868 char *sockname, *ssockname;
870 int alsa_nslots = -1, err;
874 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
875 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
879 case 'c': configfile = optarg; break;
880 case 'd': debugging = 1; break;
881 case 'D': debugging = 0; break;
882 default: fatal(0, "invalid option");
885 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
886 /* If stderr is a TTY then log there, otherwise to syslog. */
888 openlog(progname, LOG_PID, LOG_DAEMON);
889 log_default = &log_syslog;
891 if(config_read()) fatal(0, "cannot read configuration");
893 signal(SIGPIPE, SIG_IGN);
895 signal(SIGCHLD, reap);
897 xnice(config->nice_speaker);
900 /* make sure we're not root, whatever the config says */
901 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
902 switch(config->speaker_backend) {
904 info("selected ALSA backend");
905 case BACKEND_COMMAND:
906 info("selected command backend");
909 case BACKEND_NETWORK:
910 res = get_address(&config->broadcast, &pref, &sockname);
912 if(config->broadcast_from.n) {
913 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
917 if((bfd = socket(res->ai_family,
919 res->ai_protocol)) < 0)
920 fatal(errno, "error creating broadcast socket");
921 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
922 fatal(errno, "error settting SO_BROADCAST on broadcast socket");
923 /* We might well want to set additional broadcast- or multicast-related
925 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
926 fatal(errno, "error binding broadcast socket to %s", ssockname);
927 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
928 fatal(errno, "error connecting broadcast socket to %s", sockname);
930 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
931 info("selected network backend, sending to %s", sockname);
932 if(config->sample_format.byte_format != AO_FMT_BIG) {
933 info("forcing big-endian sample format");
934 config->sample_format.byte_format = AO_FMT_BIG;
938 fatal(0, "unknown backend %d", config->speaker_backend);
940 while(getppid() != 1) {
942 /* Always ready for commands from the main server. */
943 stdin_slot = addfd(0, POLLIN);
944 /* Try to read sample data for the currently playing track if there is
946 if(playing && !playing->eof && playing->used < playing->size) {
947 playing->slot = addfd(playing->fd, POLLIN);
950 /* If forceplay is set then wait until it succeeds before waiting on the
955 /* By default we will wait up to a second before thinking about current
958 if(ready && !forceplay) {
959 switch(config->speaker_backend) {
960 case BACKEND_COMMAND:
961 /* We send sample data to the subprocess as fast as it can accept it.
962 * This isn't ideal as pause latency can be very high as a result. */
964 cmdfd_slot = addfd(cmdfd, POLLOUT);
966 case BACKEND_NETWORK:
967 /* We want to keep the notional playing point somewhere in the near
968 * future. If it's too near then clients that attempt even the
969 * slightest amount of read-ahead will never catch up, and those that
970 * don't will skip whenever there's a trivial network delay. If it's
971 * too far ahead then pause latency will be too high.
973 xgettimeofday(&now, 0);
974 delta = tvsub(rtp_time_real, now);
975 if(delta.tv_sec < RTP_AHEAD) {
976 D(("delta = %ld.%06ld", (long)delta.tv_sec, (long)delta.tv_usec));
977 bfd_slot = addfd(bfd, POLLOUT);
979 rtp_time_real = now; /* catch up */
984 /* We send sample data to ALSA as fast as it can accept it, relying on
985 * the fact that it has a relatively small buffer to minimize pause
992 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
994 || !(fds[alsa_slots].events & POLLOUT))
995 && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
996 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
997 if((err = snd_pcm_prepare(pcm)))
998 fatal(0, "error calling snd_pcm_prepare: %d", err);
1001 } while(retry-- > 0);
1002 if(alsa_nslots >= 0)
1003 fdno += alsa_nslots;
1008 assert(!"unknown backend");
1011 /* If any other tracks don't have a full buffer, try to read sample data
1013 for(t = tracks; t; t = t->next)
1015 if(!t->eof && t->used < t->size) {
1016 t->slot = addfd(t->fd, POLLIN | POLLHUP);
1020 /* Wait for something interesting to happen */
1021 n = poll(fds, fdno, timeout);
1023 if(errno == EINTR) continue;
1024 fatal(errno, "error calling poll");
1026 /* Play some sound before doing anything else */
1028 switch(config->speaker_backend) {
1031 if(alsa_slots != -1) {
1032 unsigned short alsa_revents;
1034 if((err = snd_pcm_poll_descriptors_revents(pcm,
1037 &alsa_revents)) < 0)
1038 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
1039 if(alsa_revents & (POLLOUT | POLLERR))
1045 case BACKEND_COMMAND:
1046 if(cmdfd_slot != -1) {
1047 if(fds[cmdfd_slot].revents & (POLLOUT | POLLERR))
1052 case BACKEND_NETWORK:
1053 if(bfd_slot != -1) {
1054 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
1061 /* Some attempt to play must have failed */
1062 if(playing && !paused)
1065 forceplay = 0; /* just in case */
1067 /* Perhaps we have a command to process */
1068 if(fds[stdin_slot].revents & POLLIN) {
1069 n = speaker_recv(0, &sm, &fd);
1073 D(("SM_PREPARE %s %d", sm.id, fd));
1074 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
1075 t = findtrack(sm.id, 1);
1079 D(("SM_PLAY %s %d", sm.id, fd));
1080 if(playing) fatal(0, "got SM_PLAY but already playing something");
1081 t = findtrack(sm.id, 1);
1082 if(fd != -1) acquire(t, fd);
1102 D(("SM_CANCEL %s", sm.id));
1103 t = removetrack(sm.id);
1106 sm.type = SM_FINISHED;
1107 strcpy(sm.id, playing->id);
1108 speaker_send(1, &sm, 0);
1113 error(0, "SM_CANCEL for unknown track %s", sm.id);
1118 if(config_read()) error(0, "cannot read configuration");
1119 info("reloaded configuration");
1122 error(0, "unknown message type %d", sm.type);
1125 /* Read in any buffered data */
1126 for(t = tracks; t; t = t->next)
1127 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
1129 /* We might be able to play now */
1130 if(ready && forceplay && playing && !paused)
1132 /* Maybe we finished playing a track somewhere in the above */
1134 /* If we don't need the sound device for now then close it for the benefit
1135 * of anyone else who wants it. */
1136 if((!playing || paused) && ready)
1138 /* If we've not reported out state for a second do so now. */
1139 if(time(0) > last_report)
1142 info("stopped (parent terminated)");
1151 indent-tabs-mode:nil