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>
47 #include <sys/socket.h>
52 #include "configuration.h"
64 #include <alsa/asoundlib.h>
67 #ifdef WORDS_BIGENDIAN
68 # define MACHINE_AO_FMT AO_FMT_BIG
70 # define MACHINE_AO_FMT AO_FMT_LITTLE
73 #define BUFFER_SECONDS 5 /* How many seconds of input to
76 #define FRAMES 4096 /* Frame batch size */
78 #define NETWORK_BYTES 1024 /* Bytes to send per network packet */
79 /* (don't make this too big or arithmetic will start to overflow) */
81 #define RTP_AHEAD 2 /* Max RTP playahead (seconds) */
83 #define NFDS 256 /* Max FDs to poll for */
85 /* Known tracks are kept in a linked list. We don't normally to have
86 * more than two - maybe three at the outside. */
88 struct track *next; /* next track */
89 int fd; /* input FD */
91 size_t start, used; /* start + bytes used */
92 int eof; /* input is at EOF */
93 int got_format; /* got format yet? */
94 ao_sample_format format; /* sample format */
95 unsigned long long played; /* number of frames played */
96 char *buffer; /* sample buffer */
97 size_t size; /* sample buffer size */
98 int slot; /* poll array slot */
99 } *tracks, *playing; /* all tracks + playing track */
101 static time_t last_report; /* when we last reported */
102 static int paused; /* pause status */
103 static ao_sample_format pcm_format; /* current format if aodev != 0 */
104 static size_t bpf; /* bytes per frame */
105 static struct pollfd fds[NFDS]; /* if we need more than that */
106 static int fdno; /* fd number */
107 static size_t bufsize; /* buffer size */
109 static snd_pcm_t *pcm; /* current pcm handle */
110 static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
112 static int ready; /* ready to send audio */
113 static int forceplay; /* frames to force play */
114 static int cmdfd = -1; /* child process input */
115 static int bfd = -1; /* broadcast FD */
116 static uint32_t rtp_time; /* RTP timestamp */
117 static struct timeval rtp_time_real; /* corresponding real time */
118 static uint16_t rtp_seq; /* frame sequence number */
119 static uint32_t rtp_id; /* RTP SSRC */
120 static int idled; /* set when idled */
121 static int audio_errors; /* audio error counter */
123 static const struct option options[] = {
124 { "help", no_argument, 0, 'h' },
125 { "version", no_argument, 0, 'V' },
126 { "config", required_argument, 0, 'c' },
127 { "debug", no_argument, 0, 'd' },
128 { "no-debug", no_argument, 0, 'D' },
132 /* Display usage message and terminate. */
133 static void help(void) {
135 " disorder-speaker [OPTIONS]\n"
137 " --help, -h Display usage message\n"
138 " --version, -V Display version number\n"
139 " --config PATH, -c PATH Set configuration file\n"
140 " --debug, -d Turn on debugging\n"
142 "Speaker process for DisOrder. Not intended to be run\n"
148 /* Display version number and terminate. */
149 static void version(void) {
150 xprintf("disorder-speaker version %s\n", disorder_version_string);
155 /* Return the number of bytes per frame in FORMAT. */
156 static size_t bytes_per_frame(const ao_sample_format *format) {
157 return format->channels * format->bits / 8;
160 /* Find track ID, maybe creating it if not found. */
161 static struct track *findtrack(const char *id, int create) {
164 D(("findtrack %s %d", id, create));
165 for(t = tracks; t && strcmp(id, t->id); t = t->next)
168 t = xmalloc(sizeof *t);
173 /* The initial input buffer will be the sample format. */
174 t->buffer = (void *)&t->format;
175 t->size = sizeof t->format;
180 /* Remove track ID (but do not destroy it). */
181 static struct track *removetrack(const char *id) {
182 struct track *t, **tt;
184 D(("removetrack %s", id));
185 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
192 /* Destroy a track. */
193 static void destroy(struct track *t) {
194 D(("destroy %s", t->id));
195 if(t->fd != -1) xclose(t->fd);
196 if(t->buffer != (void *)&t->format) free(t->buffer);
200 /* Notice a new FD. */
201 static void acquire(struct track *t, int fd) {
202 D(("acquire %s %d", t->id, fd));
209 /* Read data into a sample buffer. Return 0 on success, -1 on EOF. */
210 static int fill(struct track *t) {
214 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
215 t->id, t->eof, t->used, t->size, t->got_format));
216 if(t->eof) return -1;
217 if(t->used < t->size) {
218 /* there is room left in the buffer */
219 where = (t->start + t->used) % t->size;
221 /* We are reading audio data, get as much as we can */
222 if(where >= t->start) left = t->size - where;
223 else left = t->start - where;
225 /* We are still waiting for the format, only get that */
226 left = sizeof (ao_sample_format) - t->used;
228 n = read(t->fd, t->buffer + where, left);
229 } while(n < 0 && errno == EINTR);
231 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
235 D(("fill %s: eof detected", t->id));
240 if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
241 assert(t->used == sizeof (ao_sample_format));
242 /* Check that our assumptions are met. */
243 if(t->format.bits & 7)
244 fatal(0, "bits per sample not a multiple of 8");
245 /* Make a new buffer for audio data. */
246 t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
247 t->buffer = xmalloc(t->size);
250 D(("got format for %s", t->id));
256 /* Return true if A and B denote identical libao formats, else false. */
257 static int formats_equal(const ao_sample_format *a,
258 const ao_sample_format *b) {
259 return (a->bits == b->bits
260 && a->rate == b->rate
261 && a->channels == b->channels
262 && a->byte_format == b->byte_format);
265 /* Close the sound device. */
266 static void idle(void) {
269 if(config->speaker_backend == BACKEND_ALSA && pcm) {
272 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
273 fatal(0, "error calling snd_pcm_nonblock: %d", err);
280 D(("released audio device"));
287 /* Abandon the current track */
288 static void abandon(void) {
289 struct speaker_message sm;
292 memset(&sm, 0, sizeof sm);
293 sm.type = SM_FINISHED;
294 strcpy(sm.id, playing->id);
295 speaker_send(1, &sm, 0);
296 removetrack(playing->id);
303 static void log_params(snd_pcm_hw_params_t *hwparams,
304 snd_pcm_sw_params_t *swparams) {
308 return; /* too verbose */
313 snd_pcm_sw_params_get_silence_size(swparams, &f);
314 info("sw silence_size=%lu", (unsigned long)f);
315 snd_pcm_sw_params_get_silence_threshold(swparams, &f);
316 info("sw silence_threshold=%lu", (unsigned long)f);
317 snd_pcm_sw_params_get_sleep_min(swparams, &u);
318 info("sw sleep_min=%lu", (unsigned long)u);
319 snd_pcm_sw_params_get_start_threshold(swparams, &f);
320 info("sw start_threshold=%lu", (unsigned long)f);
321 snd_pcm_sw_params_get_stop_threshold(swparams, &f);
322 info("sw stop_threshold=%lu", (unsigned long)f);
323 snd_pcm_sw_params_get_xfer_align(swparams, &f);
324 info("sw xfer_align=%lu", (unsigned long)f);
329 static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
334 *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
335 *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
336 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
338 switch(config->sox_generation) {
341 && ao->byte_format != AO_FMT_NATIVE
342 && ao->byte_format != MACHINE_AO_FMT) {
346 case 8: *(*pp)++ = "-b"; break;
347 case 16: *(*pp)++ = "-w"; break;
348 case 32: *(*pp)++ = "-l"; break;
349 case 64: *(*pp)++ = "-d"; break;
350 default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
354 switch(ao->byte_format) {
355 case AO_FMT_NATIVE: break;
356 case AO_FMT_BIG: *(*pp)++ = "-B"; break;
357 case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
359 *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
364 /* Make sure the sound device is open and has the right sample format. Return
365 * 0 on success and -1 on error. */
366 static int activate(void) {
367 /* If we don't know the format yet we cannot start. */
368 if(!playing->got_format) {
369 D((" - not got format for %s", playing->id));
372 switch(config->speaker_backend) {
373 case BACKEND_COMMAND:
374 case BACKEND_NETWORK:
375 /* If we pass audio on to some other agent then we enforce the configured
376 * sample format on the *inbound* audio data. */
377 if(!formats_equal(&playing->format, &config->sample_format)) {
378 char argbuf[1024], *q = argbuf;
379 const char *av[18], **pp = av;
383 soxargs(&pp, &q, &playing->format);
385 soxargs(&pp, &q, &config->sample_format);
389 for(pp = av; *pp; pp++)
390 D(("sox arg[%d] = %s", pp - av, *pp));
396 xdup2(playing->fd, 0);
397 xdup2(soxpipe[1], 1);
398 fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
402 execvp("sox", (char **)av);
405 D(("forking sox for format conversion (kid = %d)", soxkid));
408 playing->fd = soxpipe[0];
409 playing->format = config->sample_format;
413 pcm_format = config->sample_format;
414 bufsize = 3 * FRAMES;
415 bpf = bytes_per_frame(&config->sample_format);
416 D(("acquired audio device"));
422 /* If we need to change format then close the current device. */
423 if(pcm && !formats_equal(&playing->format, &pcm_format))
426 snd_pcm_hw_params_t *hwparams;
427 snd_pcm_sw_params_t *swparams;
428 snd_pcm_uframes_t pcm_bufsize;
430 int sample_format = 0;
434 if((err = snd_pcm_open(&pcm,
436 SND_PCM_STREAM_PLAYBACK,
437 SND_PCM_NONBLOCK))) {
438 error(0, "error from snd_pcm_open: %d", err);
441 snd_pcm_hw_params_alloca(&hwparams);
442 D(("set up hw params"));
443 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
444 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
445 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
446 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
447 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
448 switch(playing->format.bits) {
450 sample_format = SND_PCM_FORMAT_S8;
453 switch(playing->format.byte_format) {
454 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
455 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
456 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
457 error(0, "unrecognized byte format %d", playing->format.byte_format);
462 error(0, "unsupported sample size %d", playing->format.bits);
465 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
466 sample_format)) < 0) {
467 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
471 rate = playing->format.rate;
472 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
473 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
474 playing->format.rate, err);
477 if(rate != (unsigned)playing->format.rate)
478 info("want rate %d, got %u", playing->format.rate, rate);
479 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
480 playing->format.channels)) < 0) {
481 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
482 playing->format.channels, err);
485 bufsize = 3 * FRAMES;
486 pcm_bufsize = bufsize;
487 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
489 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
491 if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
492 info("asked for PCM buffer of %d frames, got %d",
493 3 * FRAMES, (int)pcm_bufsize);
494 last_pcm_bufsize = pcm_bufsize;
495 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
496 fatal(0, "error calling snd_pcm_hw_params: %d", err);
497 D(("set up sw params"));
498 snd_pcm_sw_params_alloca(&swparams);
499 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
500 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
501 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
502 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
504 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
505 fatal(0, "error calling snd_pcm_sw_params: %d", err);
506 pcm_format = playing->format;
507 bpf = bytes_per_frame(&pcm_format);
508 D(("acquired audio device"));
509 log_params(hwparams, swparams);
516 /* We assume the error is temporary and that we'll retry in a bit. */
528 /* Check to see whether the current track has finished playing */
529 static void maybe_finished(void) {
532 && (!playing->got_format
533 || playing->used < bytes_per_frame(&playing->format)))
537 static void fork_cmd(void) {
540 if(cmdfd != -1) close(cmdfd);
547 execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
548 fatal(errno, "error execing /bin/sh");
552 D(("forked cmd %d, fd = %d", cmdpid, cmdfd));
555 static void play(size_t frames) {
556 size_t avail_bytes, written_frames;
557 ssize_t written_bytes;
558 struct rtp_header header;
565 forceplay = 0; /* Must have called abandon() */
568 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
569 playing->eof ? " EOF" : "",
570 playing->format.rate,
571 playing->format.bits,
572 playing->format.channels));
573 /* If we haven't got enough bytes yet wait until we have. Exception: when
575 if(playing->used < frames * bpf && !playing->eof) {
579 /* We have got enough data so don't force play again */
581 /* Figure out how many frames there are available to write */
582 if(playing->start + playing->used > playing->size)
583 avail_bytes = playing->size - playing->start;
585 avail_bytes = playing->used;
587 switch(config->speaker_backend) {
590 snd_pcm_sframes_t pcm_written_frames;
594 avail_frames = avail_bytes / bpf;
595 if(avail_frames > frames)
596 avail_frames = frames;
599 pcm_written_frames = snd_pcm_writei(pcm,
600 playing->buffer + playing->start,
602 D(("actually play %zu frames, wrote %d",
603 avail_frames, (int)pcm_written_frames));
604 if(pcm_written_frames < 0) {
605 switch(pcm_written_frames) {
606 case -EPIPE: /* underrun */
607 error(0, "snd_pcm_writei reports underrun");
608 if((err = snd_pcm_prepare(pcm)) < 0)
609 fatal(0, "error calling snd_pcm_prepare: %d", err);
614 fatal(0, "error calling snd_pcm_writei: %d",
615 (int)pcm_written_frames);
618 written_frames = pcm_written_frames;
619 written_bytes = written_frames * bpf;
623 case BACKEND_COMMAND:
624 if(avail_bytes > frames * bpf)
625 avail_bytes = frames * bpf;
626 written_bytes = write(cmdfd, playing->buffer + playing->start,
628 D(("actually play %zu bytes, wrote %d",
629 avail_bytes, (int)written_bytes));
630 if(written_bytes < 0) {
633 error(0, "hmm, command died; trying another");
640 written_frames = written_bytes / bpf; /* good enough */
642 case BACKEND_NETWORK:
643 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
644 * AVT profile (RFC3551). */
645 if(rtp_time_real.tv_sec == 0)
646 xgettimeofday(&rtp_time_real, 0);
649 xgettimeofday(&now, 0);
650 /* There's been a gap. Fix up the RTP time accordingly. */
651 rtp_time += (((now.tv_sec + now.tv_usec /1000000.0)
652 - (rtp_time_real.tv_sec + rtp_time_real.tv_usec / 1000000.0))
653 * playing->format.rate * playing->format.channels);
655 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
656 header.seq = htons(rtp_seq++);
657 header.timestamp = htonl(rtp_time);
658 header.ssrc = rtp_id;
659 header.mpt = (idled ? 0x80 : 0x00) | 10;
660 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
661 * the sample rate (in a library somewhere so that configuration.c can rule
662 * out invalid rates).
665 if(avail_bytes > NETWORK_BYTES - sizeof header) {
666 avail_bytes = NETWORK_BYTES - sizeof header;
667 avail_bytes -= avail_bytes % bpf;
669 /* "The RTP clock rate used for generating the RTP timestamp is independent
670 * of the number of channels and the encoding; it equals the number of
671 * sampling periods per second. For N-channel encodings, each sampling
672 * period (say, 1/8000 of a second) generates N samples. (This terminology
673 * is standard, but somewhat confusing, as the total number of samples
674 * generated per second is then the sampling rate times the channel
677 vec[0].iov_base = (void *)&header;
678 vec[0].iov_len = sizeof header;
679 vec[1].iov_base = playing->buffer + playing->start;
680 vec[1].iov_len = avail_bytes;
683 char buffer[3 * sizeof header + 1];
685 const uint8_t *ptr = (void *)&header;
687 for(n = 0; n < sizeof header; ++n)
688 sprintf(&buffer[3 * n], "%02x ", *ptr++);
693 written_bytes = writev(bfd,
696 } while(written_bytes < 0 && errno == EINTR);
697 if(written_bytes < 0) {
698 error(errno, "error transmitting audio data");
700 if(audio_errors == 10)
701 fatal(0, "too many audio errors");
705 written_bytes = avail_bytes;
706 written_frames = written_bytes / bpf;
707 /* Advance RTP's notion of the time */
708 rtp_time += written_frames * playing->format.channels;
709 /* Advance the corresponding real time */
710 assert(NETWORK_BYTES <= 2000); /* else risk overflowing 32 bits */
711 rtp_time_real.tv_usec += written_frames * 1000000 / playing->format.rate;
712 if(rtp_time_real.tv_usec >= 1000000) {
713 ++rtp_time_real.tv_sec;
714 rtp_time_real.tv_usec -= 1000000;
720 /* written_bytes and written_frames had better both be set and correct by
722 playing->start += written_bytes;
723 playing->used -= written_bytes;
724 playing->played += written_frames;
725 /* If the pointer is at the end of the buffer (or the buffer is completely
726 * empty) wrap it back to the start. */
727 if(!playing->used || playing->start == playing->size)
729 frames -= written_frames;
732 /* Notify the server what we're up to. */
733 static void report(void) {
734 struct speaker_message sm;
736 if(playing && playing->buffer != (void *)&playing->format) {
737 memset(&sm, 0, sizeof sm);
738 sm.type = paused ? SM_PAUSED : SM_PLAYING;
739 strcpy(sm.id, playing->id);
740 sm.data = playing->played / playing->format.rate;
741 speaker_send(1, &sm, 0);
746 static void reap(int __attribute__((unused)) sig) {
751 cmdpid = waitpid(-1, &st, WNOHANG);
753 signal(SIGCHLD, reap);
756 static int addfd(int fd, int events) {
759 fds[fdno].events = events;
765 int main(int argc, char **argv) {
766 int n, fd, stdin_slot, alsa_slots, cmdfd_slot, bfd_slot, poke, timeout;
767 struct timeval now, delta;
769 struct speaker_message sm;
770 struct addrinfo *res, *sres;
771 static const struct addrinfo pref = {
781 static const struct addrinfo prefbind = {
791 static const int one = 1;
792 char *sockname, *ssockname;
794 int alsa_nslots = -1, err;
798 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
799 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
803 case 'c': configfile = optarg; break;
804 case 'd': debugging = 1; break;
805 case 'D': debugging = 0; break;
806 default: fatal(0, "invalid option");
809 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
810 /* If stderr is a TTY then log there, otherwise to syslog. */
812 openlog(progname, LOG_PID, LOG_DAEMON);
813 log_default = &log_syslog;
815 if(config_read()) fatal(0, "cannot read configuration");
817 signal(SIGPIPE, SIG_IGN);
819 signal(SIGCHLD, reap);
821 xnice(config->nice_speaker);
824 /* make sure we're not root, whatever the config says */
825 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
826 switch(config->speaker_backend) {
828 info("selected ALSA backend");
829 case BACKEND_COMMAND:
830 info("selected command backend");
833 case BACKEND_NETWORK:
834 res = get_address(&config->broadcast, &pref, &sockname);
836 if(config->broadcast_from.n) {
837 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
841 if((bfd = socket(res->ai_family,
843 res->ai_protocol)) < 0)
844 fatal(errno, "error creating broadcast socket");
845 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
846 fatal(errno, "error settting SO_BROADCAST on broadcast socket");
847 /* We might well want to set additional broadcast- or multicast-related
849 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
850 fatal(errno, "error binding broadcast socket to %s", ssockname);
851 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
852 fatal(errno, "error connecting broadcast socket to %s", sockname);
854 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
855 info("selected network backend, sending to %s", sockname);
856 if(config->sample_format.byte_format != AO_FMT_BIG) {
857 info("forcing big-endian sample format");
858 config->sample_format.byte_format = AO_FMT_BIG;
862 fatal(0, "unknown backend %d", config->speaker_backend);
864 while(getppid() != 1) {
866 /* Always ready for commands from the main server. */
867 stdin_slot = addfd(0, POLLIN);
868 /* Try to read sample data for the currently playing track if there is
870 if(playing && !playing->eof && playing->used < playing->size) {
871 playing->slot = addfd(playing->fd, POLLIN);
874 /* If forceplay is set then wait until it succeeds before waiting on the
879 /* By default we will wait up to a second before thinking about current
882 if(ready && !forceplay) {
883 switch(config->speaker_backend) {
884 case BACKEND_COMMAND:
885 /* We send sample data to the subprocess as fast as it can accept it.
886 * This isn't ideal as pause latency can be very high as a result. */
888 cmdfd_slot = addfd(cmdfd, POLLOUT);
890 case BACKEND_NETWORK:
891 /* We want to keep the notional playing point somewhere in the near
892 * future. If it's too near then clients that attempt even the
893 * slightest amount of read-ahead will never catch up, and those that
894 * don't will skip whenever there's a trivial network delay. If it's
895 * too far ahead then pause latency will be too high.
897 xgettimeofday(&now, 0);
898 delta = tvsub(rtp_time_real, now);
899 if(delta.tv_sec < RTP_AHEAD) {
900 D(("delta = %ld.%06ld", (long)delta.tv_sec, (long)delta.tv_usec));
901 bfd_slot = addfd(bfd, POLLOUT);
903 rtp_time_real = now; /* catch up */
908 /* We send sample data to ALSA as fast as it can accept it, relying on
909 * the fact that it has a relatively small buffer to minimize pause
916 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
918 || !(fds[alsa_slots].events & POLLOUT))
919 && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
920 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
921 if((err = snd_pcm_prepare(pcm)))
922 fatal(0, "error calling snd_pcm_prepare: %d", err);
925 } while(retry-- > 0);
932 assert(!"unknown backend");
935 /* If any other tracks don't have a full buffer, try to read sample data
937 for(t = tracks; t; t = t->next)
939 if(!t->eof && t->used < t->size) {
940 t->slot = addfd(t->fd, POLLIN | POLLHUP);
944 /* Wait for something interesting to happen */
945 n = poll(fds, fdno, timeout);
947 if(errno == EINTR) continue;
948 fatal(errno, "error calling poll");
950 /* Play some sound before doing anything else */
952 switch(config->speaker_backend) {
955 if(alsa_slots != -1) {
956 unsigned short alsa_revents;
958 if((err = snd_pcm_poll_descriptors_revents(pcm,
962 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
963 if(alsa_revents & (POLLOUT | POLLERR))
969 case BACKEND_COMMAND:
970 if(cmdfd_slot != -1) {
971 if(fds[cmdfd_slot].revents & (POLLOUT | POLLERR))
976 case BACKEND_NETWORK:
978 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
985 /* Some attempt to play must have failed */
986 if(playing && !paused)
989 forceplay = 0; /* just in case */
991 /* Perhaps we have a command to process */
992 if(fds[stdin_slot].revents & POLLIN) {
993 n = speaker_recv(0, &sm, &fd);
997 D(("SM_PREPARE %s %d", sm.id, fd));
998 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
999 t = findtrack(sm.id, 1);
1003 D(("SM_PLAY %s %d", sm.id, fd));
1004 if(playing) fatal(0, "got SM_PLAY but already playing something");
1005 t = findtrack(sm.id, 1);
1006 if(fd != -1) acquire(t, fd);
1026 D(("SM_CANCEL %s", sm.id));
1027 t = removetrack(sm.id);
1030 sm.type = SM_FINISHED;
1031 strcpy(sm.id, playing->id);
1032 speaker_send(1, &sm, 0);
1037 error(0, "SM_CANCEL for unknown track %s", sm.id);
1042 if(config_read()) error(0, "cannot read configuration");
1043 info("reloaded configuration");
1046 error(0, "unknown message type %d", sm.type);
1049 /* Read in any buffered data */
1050 for(t = tracks; t; t = t->next)
1051 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
1053 /* We might be able to play now */
1054 if(ready && forceplay && playing && !paused)
1056 /* Maybe we finished playing a track somewhere in the above */
1058 /* If we don't need the sound device for now then close it for the benefit
1059 * of anyone else who wants it. */
1060 if((!playing || paused) && ready)
1062 /* If we've not reported out state for a second do so now. */
1063 if(time(0) > last_report)
1066 info("stopped (parent terminated)");
1075 indent-tabs-mode:nil