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 (ms) */
110 #define RTP_AHEAD_MS 1000
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 */
150 /** @brief RTP timestamp
152 * This counts the number of samples played (NB not the number of frames
155 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
156 * stereo, that only gives about half a day before wrapping, which is not
157 * particularly convenient for certain debugging purposes. Therefore the
158 * timestamp is maintained as a 64-bit integer, giving around six million years
159 * before wrapping, and truncated to 32 bits when transmitting.
161 static uint64_t rtp_time
;
163 /** @brief RTP base timestamp
165 * This is the real time correspoding to an @ref rtp_time of 0. It is used
166 * to recalculate the timestamp after idle periods.
168 static struct timeval rtp_time_0
;
170 static uint16_t rtp_seq
; /* frame sequence number */
171 static uint32_t rtp_id
; /* RTP SSRC */
172 static int idled
; /* set when idled */
173 static int audio_errors
; /* audio error counter */
175 static const struct option options
[] = {
176 { "help", no_argument
, 0, 'h' },
177 { "version", no_argument
, 0, 'V' },
178 { "config", required_argument
, 0, 'c' },
179 { "debug", no_argument
, 0, 'd' },
180 { "no-debug", no_argument
, 0, 'D' },
184 /* Display usage message and terminate. */
185 static void help(void) {
187 " disorder-speaker [OPTIONS]\n"
189 " --help, -h Display usage message\n"
190 " --version, -V Display version number\n"
191 " --config PATH, -c PATH Set configuration file\n"
192 " --debug, -d Turn on debugging\n"
194 "Speaker process for DisOrder. Not intended to be run\n"
200 /* Display version number and terminate. */
201 static void version(void) {
202 xprintf("disorder-speaker version %s\n", disorder_version_string
);
207 /** @brief Return the number of bytes per frame in @p format */
208 static size_t bytes_per_frame(const ao_sample_format
*format
) {
209 return format
->channels
* format
->bits
/ 8;
212 /** @brief Find track @p id, maybe creating it if not found */
213 static struct track
*findtrack(const char *id
, int create
) {
216 D(("findtrack %s %d", id
, create
));
217 for(t
= tracks
; t
&& strcmp(id
, t
->id
); t
= t
->next
)
220 t
= xmalloc(sizeof *t
);
225 /* The initial input buffer will be the sample format. */
226 t
->buffer
= (void *)&t
->format
;
227 t
->size
= sizeof t
->format
;
232 /** @brief Remove track @p id (but do not destroy it) */
233 static struct track
*removetrack(const char *id
) {
234 struct track
*t
, **tt
;
236 D(("removetrack %s", id
));
237 for(tt
= &tracks
; (t
= *tt
) && strcmp(id
, t
->id
); tt
= &t
->next
)
244 /** @brief Destroy a track */
245 static void destroy(struct track
*t
) {
246 D(("destroy %s", t
->id
));
247 if(t
->fd
!= -1) xclose(t
->fd
);
248 if(t
->buffer
!= (void *)&t
->format
) free(t
->buffer
);
252 /** @brief Notice a new connection */
253 static void acquire(struct track
*t
, int fd
) {
254 D(("acquire %s %d", t
->id
, fd
));
261 /** @brief Return true if A and B denote identical libao formats, else false */
262 static int formats_equal(const ao_sample_format
*a
,
263 const ao_sample_format
*b
) {
264 return (a
->bits
== b
->bits
265 && a
->rate
== b
->rate
266 && a
->channels
== b
->channels
267 && a
->byte_format
== b
->byte_format
);
270 /** @brief Compute arguments to sox */
271 static void soxargs(const char ***pp
, char **qq
, ao_sample_format
*ao
) {
276 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-r%d", ao
->rate
); *qq
+= n
+ 1;
277 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-c%d", ao
->channels
); *qq
+= n
+ 1;
278 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
280 switch(config
->sox_generation
) {
283 && ao
->byte_format
!= AO_FMT_NATIVE
284 && ao
->byte_format
!= MACHINE_AO_FMT
) {
288 case 8: *(*pp
)++ = "-b"; break;
289 case 16: *(*pp
)++ = "-w"; break;
290 case 32: *(*pp
)++ = "-l"; break;
291 case 64: *(*pp
)++ = "-d"; break;
292 default: fatal(0, "cannot handle sample size %d", (int)ao
->bits
);
296 switch(ao
->byte_format
) {
297 case AO_FMT_NATIVE
: break;
298 case AO_FMT_BIG
: *(*pp
)++ = "-B"; break;
299 case AO_FMT_LITTLE
: *(*pp
)++ = "-L"; break;
301 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-%d", ao
->bits
/8); *qq
+= n
+ 1;
306 /** @brief Enable format translation
308 * If necessary, replaces a tracks inbound file descriptor with one connected
309 * to a sox invocation, which performs the required translation.
311 static void enable_translation(struct track
*t
) {
312 switch(config
->speaker_backend
) {
313 case BACKEND_COMMAND
:
314 case BACKEND_NETWORK
:
315 /* These backends need a specific sample format */
321 if(!formats_equal(&t
->format
, &config
->sample_format
)) {
322 char argbuf
[1024], *q
= argbuf
;
323 const char *av
[18], **pp
= av
;
328 soxargs(&pp
, &q
, &t
->format
);
330 soxargs(&pp
, &q
, &config
->sample_format
);
334 for(pp
= av
; *pp
; pp
++)
335 D(("sox arg[%d] = %s", pp
- av
, *pp
));
341 signal(SIGPIPE
, SIG_DFL
);
343 xdup2(soxpipe
[1], 1);
344 fcntl(0, F_SETFL
, fcntl(0, F_GETFL
) & ~O_NONBLOCK
);
348 execvp("sox", (char **)av
);
351 D(("forking sox for format conversion (kid = %d)", soxkid
));
355 t
->format
= config
->sample_format
;
360 /** @brief Read data into a sample buffer
361 * @param t Pointer to track
362 * @return 0 on success, -1 on EOF
364 * This is effectively the read callback on @c t->fd.
366 static int fill(struct track
*t
) {
370 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
371 t
->id
, t
->eof
, t
->used
, t
->size
, t
->got_format
));
372 if(t
->eof
) return -1;
373 if(t
->used
< t
->size
) {
374 /* there is room left in the buffer */
375 where
= (t
->start
+ t
->used
) % t
->size
;
377 /* We are reading audio data, get as much as we can */
378 if(where
>= t
->start
) left
= t
->size
- where
;
379 else left
= t
->start
- where
;
381 /* We are still waiting for the format, only get that */
382 left
= sizeof (ao_sample_format
) - t
->used
;
384 n
= read(t
->fd
, t
->buffer
+ where
, left
);
385 } while(n
< 0 && errno
== EINTR
);
387 if(errno
!= EAGAIN
) fatal(errno
, "error reading sample stream");
391 D(("fill %s: eof detected", t
->id
));
396 if(!t
->got_format
&& t
->used
>= sizeof (ao_sample_format
)) {
397 assert(t
->used
== sizeof (ao_sample_format
));
398 /* Check that our assumptions are met. */
399 if(t
->format
.bits
& 7)
400 fatal(0, "bits per sample not a multiple of 8");
401 /* If the input format is unsuitable, arrange to translate it */
402 enable_translation(t
);
403 /* Make a new buffer for audio data. */
404 t
->size
= bytes_per_frame(&t
->format
) * t
->format
.rate
* BUFFER_SECONDS
;
405 t
->buffer
= xmalloc(t
->size
);
408 D(("got format for %s", t
->id
));
414 /** @brief Close the sound device */
415 static void idle(void) {
418 if(config
->speaker_backend
== BACKEND_ALSA
&& pcm
) {
421 if((err
= snd_pcm_nonblock(pcm
, 0)) < 0)
422 fatal(0, "error calling snd_pcm_nonblock: %d", err
);
429 D(("released audio device"));
436 /** @brief Abandon the current track */
437 static void abandon(void) {
438 struct speaker_message sm
;
441 memset(&sm
, 0, sizeof sm
);
442 sm
.type
= SM_FINISHED
;
443 strcpy(sm
.id
, playing
->id
);
444 speaker_send(1, &sm
, 0);
445 removetrack(playing
->id
);
452 /** @brief Log ALSA parameters */
453 static void log_params(snd_pcm_hw_params_t
*hwparams
,
454 snd_pcm_sw_params_t
*swparams
) {
458 return; /* too verbose */
463 snd_pcm_sw_params_get_silence_size(swparams
, &f
);
464 info("sw silence_size=%lu", (unsigned long)f
);
465 snd_pcm_sw_params_get_silence_threshold(swparams
, &f
);
466 info("sw silence_threshold=%lu", (unsigned long)f
);
467 snd_pcm_sw_params_get_sleep_min(swparams
, &u
);
468 info("sw sleep_min=%lu", (unsigned long)u
);
469 snd_pcm_sw_params_get_start_threshold(swparams
, &f
);
470 info("sw start_threshold=%lu", (unsigned long)f
);
471 snd_pcm_sw_params_get_stop_threshold(swparams
, &f
);
472 info("sw stop_threshold=%lu", (unsigned long)f
);
473 snd_pcm_sw_params_get_xfer_align(swparams
, &f
);
474 info("sw xfer_align=%lu", (unsigned long)f
);
479 /** @brief Enable sound output
481 * Makes sure the sound device is open and has the right sample format. Return
482 * 0 on success and -1 on error.
484 static int activate(void) {
485 /* If we don't know the format yet we cannot start. */
486 if(!playing
->got_format
) {
487 D((" - not got format for %s", playing
->id
));
490 switch(config
->speaker_backend
) {
491 case BACKEND_COMMAND
:
492 case BACKEND_NETWORK
:
494 pcm_format
= config
->sample_format
;
495 bufsize
= 3 * FRAMES
;
496 bpf
= bytes_per_frame(&config
->sample_format
);
497 D(("acquired audio device"));
503 /* If we need to change format then close the current device. */
504 if(pcm
&& !formats_equal(&playing
->format
, &pcm_format
))
507 snd_pcm_hw_params_t
*hwparams
;
508 snd_pcm_sw_params_t
*swparams
;
509 snd_pcm_uframes_t pcm_bufsize
;
511 int sample_format
= 0;
515 if((err
= snd_pcm_open(&pcm
,
517 SND_PCM_STREAM_PLAYBACK
,
518 SND_PCM_NONBLOCK
))) {
519 error(0, "error from snd_pcm_open: %d", err
);
522 snd_pcm_hw_params_alloca(&hwparams
);
523 D(("set up hw params"));
524 if((err
= snd_pcm_hw_params_any(pcm
, hwparams
)) < 0)
525 fatal(0, "error from snd_pcm_hw_params_any: %d", err
);
526 if((err
= snd_pcm_hw_params_set_access(pcm
, hwparams
,
527 SND_PCM_ACCESS_RW_INTERLEAVED
)) < 0)
528 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err
);
529 switch(playing
->format
.bits
) {
531 sample_format
= SND_PCM_FORMAT_S8
;
534 switch(playing
->format
.byte_format
) {
535 case AO_FMT_NATIVE
: sample_format
= SND_PCM_FORMAT_S16
; break;
536 case AO_FMT_LITTLE
: sample_format
= SND_PCM_FORMAT_S16_LE
; break;
537 case AO_FMT_BIG
: sample_format
= SND_PCM_FORMAT_S16_BE
; break;
538 error(0, "unrecognized byte format %d", playing
->format
.byte_format
);
543 error(0, "unsupported sample size %d", playing
->format
.bits
);
546 if((err
= snd_pcm_hw_params_set_format(pcm
, hwparams
,
547 sample_format
)) < 0) {
548 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
552 rate
= playing
->format
.rate
;
553 if((err
= snd_pcm_hw_params_set_rate_near(pcm
, hwparams
, &rate
, 0)) < 0) {
554 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
555 playing
->format
.rate
, err
);
558 if(rate
!= (unsigned)playing
->format
.rate
)
559 info("want rate %d, got %u", playing
->format
.rate
, rate
);
560 if((err
= snd_pcm_hw_params_set_channels(pcm
, hwparams
,
561 playing
->format
.channels
)) < 0) {
562 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
563 playing
->format
.channels
, err
);
566 bufsize
= 3 * FRAMES
;
567 pcm_bufsize
= bufsize
;
568 if((err
= snd_pcm_hw_params_set_buffer_size_near(pcm
, hwparams
,
570 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
572 if(pcm_bufsize
!= 3 * FRAMES
&& pcm_bufsize
!= last_pcm_bufsize
)
573 info("asked for PCM buffer of %d frames, got %d",
574 3 * FRAMES
, (int)pcm_bufsize
);
575 last_pcm_bufsize
= pcm_bufsize
;
576 if((err
= snd_pcm_hw_params(pcm
, hwparams
)) < 0)
577 fatal(0, "error calling snd_pcm_hw_params: %d", err
);
578 D(("set up sw params"));
579 snd_pcm_sw_params_alloca(&swparams
);
580 if((err
= snd_pcm_sw_params_current(pcm
, swparams
)) < 0)
581 fatal(0, "error calling snd_pcm_sw_params_current: %d", err
);
582 if((err
= snd_pcm_sw_params_set_avail_min(pcm
, swparams
, FRAMES
)) < 0)
583 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
585 if((err
= snd_pcm_sw_params(pcm
, swparams
)) < 0)
586 fatal(0, "error calling snd_pcm_sw_params: %d", err
);
587 pcm_format
= playing
->format
;
588 bpf
= bytes_per_frame(&pcm_format
);
589 D(("acquired audio device"));
590 log_params(hwparams
, swparams
);
597 /* We assume the error is temporary and that we'll retry in a bit. */
609 /* Check to see whether the current track has finished playing */
610 static void maybe_finished(void) {
613 && (!playing
->got_format
614 || playing
->used
< bytes_per_frame(&playing
->format
)))
618 static void fork_cmd(void) {
621 if(cmdfd
!= -1) close(cmdfd
);
625 signal(SIGPIPE
, SIG_DFL
);
629 execl("/bin/sh", "sh", "-c", config
->speaker_command
, (char *)0);
630 fatal(errno
, "error execing /bin/sh");
634 D(("forked cmd %d, fd = %d", cmdpid
, cmdfd
));
637 static void play(size_t frames
) {
638 size_t avail_bytes
, write_bytes
, written_frames
;
639 ssize_t written_bytes
;
640 struct rtp_header header
;
647 forceplay
= 0; /* Must have called abandon() */
650 D(("play: play %zu/%zu%s %dHz %db %dc", frames
, playing
->used
/ bpf
,
651 playing
->eof ?
" EOF" : "",
652 playing
->format
.rate
,
653 playing
->format
.bits
,
654 playing
->format
.channels
));
655 /* If we haven't got enough bytes yet wait until we have. Exception: when
657 if(playing
->used
< frames
* bpf
&& !playing
->eof
) {
661 /* We have got enough data so don't force play again */
663 /* Figure out how many frames there are available to write */
664 if(playing
->start
+ playing
->used
> playing
->size
)
665 avail_bytes
= playing
->size
- playing
->start
;
667 avail_bytes
= playing
->used
;
669 switch(config
->speaker_backend
) {
672 snd_pcm_sframes_t pcm_written_frames
;
676 avail_frames
= avail_bytes
/ bpf
;
677 if(avail_frames
> frames
)
678 avail_frames
= frames
;
681 pcm_written_frames
= snd_pcm_writei(pcm
,
682 playing
->buffer
+ playing
->start
,
684 D(("actually play %zu frames, wrote %d",
685 avail_frames
, (int)pcm_written_frames
));
686 if(pcm_written_frames
< 0) {
687 switch(pcm_written_frames
) {
688 case -EPIPE
: /* underrun */
689 error(0, "snd_pcm_writei reports underrun");
690 if((err
= snd_pcm_prepare(pcm
)) < 0)
691 fatal(0, "error calling snd_pcm_prepare: %d", err
);
696 fatal(0, "error calling snd_pcm_writei: %d",
697 (int)pcm_written_frames
);
700 written_frames
= pcm_written_frames
;
701 written_bytes
= written_frames
* bpf
;
705 case BACKEND_COMMAND
:
706 if(avail_bytes
> frames
* bpf
)
707 avail_bytes
= frames
* bpf
;
708 written_bytes
= write(cmdfd
, playing
->buffer
+ playing
->start
,
710 D(("actually play %zu bytes, wrote %d",
711 avail_bytes
, (int)written_bytes
));
712 if(written_bytes
< 0) {
715 error(0, "hmm, command died; trying another");
722 written_frames
= written_bytes
/ bpf
; /* good enough */
724 case BACKEND_NETWORK
:
725 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
726 * AVT profile (RFC3551). */
729 /* There's been a gap. Fix up the RTP time accordingly. */
732 uint64_t target_rtp_time
;
734 /* Find the current time */
735 xgettimeofday(&now
, 0);
736 /* Find the number of microseconds elapsed since rtp_time=0 */
737 delta
= tvsub_us(now
, rtp_time_0
);
738 assert(delta
<= UINT64_MAX
/ 88200);
739 target_rtp_time
= (delta
* playing
->format
.rate
740 * playing
->format
.channels
) / 1000000;
741 /* Overflows at ~6 years uptime with 44100Hz stereo */
742 if(target_rtp_time
> rtp_time
)
743 info("advancing rtp_time by %"PRIu64
" samples",
744 target_rtp_time
- rtp_time
);
745 else if(target_rtp_time
< rtp_time
)
746 info("reversing rtp_time by %"PRIu64
" samples",
747 rtp_time
- target_rtp_time
);
748 rtp_time
= target_rtp_time
;
750 header
.vpxcc
= 2 << 6; /* V=2, P=0, X=0, CC=0 */
751 header
.seq
= htons(rtp_seq
++);
752 header
.timestamp
= htonl((uint32_t)rtp_time
);
753 header
.ssrc
= rtp_id
;
754 header
.mpt
= (idled ?
0x80 : 0x00) | 10;
755 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
756 * the sample rate (in a library somewhere so that configuration.c can rule
757 * out invalid rates).
760 if(avail_bytes
> NETWORK_BYTES
- sizeof header
) {
761 avail_bytes
= NETWORK_BYTES
- sizeof header
;
762 /* Always send a whole number of frames */
763 avail_bytes
-= avail_bytes
% bpf
;
765 /* "The RTP clock rate used for generating the RTP timestamp is independent
766 * of the number of channels and the encoding; it equals the number of
767 * sampling periods per second. For N-channel encodings, each sampling
768 * period (say, 1/8000 of a second) generates N samples. (This terminology
769 * is standard, but somewhat confusing, as the total number of samples
770 * generated per second is then the sampling rate times the channel
773 write_bytes
= avail_bytes
;
775 vec
[0].iov_base
= (void *)&header
;
776 vec
[0].iov_len
= sizeof header
;
777 vec
[1].iov_base
= playing
->buffer
+ playing
->start
;
778 vec
[1].iov_len
= avail_bytes
;
780 written_bytes
= writev(bfd
,
783 } while(written_bytes
< 0 && errno
== EINTR
);
784 if(written_bytes
< 0) {
785 error(errno
, "error transmitting audio data");
787 if(audio_errors
== 10)
788 fatal(0, "too many audio errors");
793 written_bytes
= avail_bytes
;
794 written_frames
= written_bytes
/ bpf
;
795 /* Advance RTP's notion of the time */
796 rtp_time
+= written_frames
* playing
->format
.channels
;
801 /* written_bytes and written_frames had better both be set and correct by
803 playing
->start
+= written_bytes
;
804 playing
->used
-= written_bytes
;
805 playing
->played
+= written_frames
;
806 /* If the pointer is at the end of the buffer (or the buffer is completely
807 * empty) wrap it back to the start. */
808 if(!playing
->used
|| playing
->start
== playing
->size
)
810 frames
-= written_frames
;
813 /* Notify the server what we're up to. */
814 static void report(void) {
815 struct speaker_message sm
;
817 if(playing
&& playing
->buffer
!= (void *)&playing
->format
) {
818 memset(&sm
, 0, sizeof sm
);
819 sm
.type
= paused ? SM_PAUSED
: SM_PLAYING
;
820 strcpy(sm
.id
, playing
->id
);
821 sm
.data
= playing
->played
/ playing
->format
.rate
;
822 speaker_send(1, &sm
, 0);
827 static void reap(int __attribute__((unused
)) sig
) {
832 cmdpid
= waitpid(-1, &st
, WNOHANG
);
834 signal(SIGCHLD
, reap
);
837 static int addfd(int fd
, int events
) {
840 fds
[fdno
].events
= events
;
846 int main(int argc
, char **argv
) {
847 int n
, fd
, stdin_slot
, alsa_slots
, cmdfd_slot
, bfd_slot
, poke
, timeout
;
849 struct speaker_message sm
;
850 struct addrinfo
*res
, *sres
;
851 static const struct addrinfo pref
= {
861 static const struct addrinfo prefbind
= {
871 static const int one
= 1;
872 char *sockname
, *ssockname
;
874 int alsa_nslots
= -1, err
;
878 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
879 while((n
= getopt_long(argc
, argv
, "hVc:dD", options
, 0)) >= 0) {
883 case 'c': configfile
= optarg
; break;
884 case 'd': debugging
= 1; break;
885 case 'D': debugging
= 0; break;
886 default: fatal(0, "invalid option");
889 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging
= 1;
890 /* If stderr is a TTY then log there, otherwise to syslog. */
892 openlog(progname
, LOG_PID
, LOG_DAEMON
);
893 log_default
= &log_syslog
;
895 if(config_read()) fatal(0, "cannot read configuration");
897 signal(SIGPIPE
, SIG_IGN
);
899 signal(SIGCHLD
, reap
);
901 xnice(config
->nice_speaker
);
904 /* make sure we're not root, whatever the config says */
905 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
906 switch(config
->speaker_backend
) {
908 info("selected ALSA backend");
909 case BACKEND_COMMAND
:
910 info("selected command backend");
913 case BACKEND_NETWORK
:
914 res
= get_address(&config
->broadcast
, &pref
, &sockname
);
916 if(config
->broadcast_from
.n
) {
917 sres
= get_address(&config
->broadcast_from
, &prefbind
, &ssockname
);
921 if((bfd
= socket(res
->ai_family
,
923 res
->ai_protocol
)) < 0)
924 fatal(errno
, "error creating broadcast socket");
925 if(setsockopt(bfd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof one
) < 0)
926 fatal(errno
, "error settting SO_BROADCAST on broadcast socket");
927 /* We might well want to set additional broadcast- or multicast-related
929 if(sres
&& bind(bfd
, sres
->ai_addr
, sres
->ai_addrlen
) < 0)
930 fatal(errno
, "error binding broadcast socket to %s", ssockname
);
931 if(connect(bfd
, res
->ai_addr
, res
->ai_addrlen
) < 0)
932 fatal(errno
, "error connecting broadcast socket to %s", sockname
);
934 gcry_randomize(&rtp_id
, sizeof rtp_id
, GCRY_STRONG_RANDOM
);
935 info("selected network backend, sending to %s", sockname
);
936 if(config
->sample_format
.byte_format
!= AO_FMT_BIG
) {
937 info("forcing big-endian sample format");
938 config
->sample_format
.byte_format
= AO_FMT_BIG
;
942 fatal(0, "unknown backend %d", config
->speaker_backend
);
944 while(getppid() != 1) {
946 /* Always ready for commands from the main server. */
947 stdin_slot
= addfd(0, POLLIN
);
948 /* Try to read sample data for the currently playing track if there is
950 if(playing
&& !playing
->eof
&& playing
->used
< playing
->size
) {
951 playing
->slot
= addfd(playing
->fd
, POLLIN
);
954 /* If forceplay is set then wait until it succeeds before waiting on the
959 /* By default we will wait up to a second before thinking about current
962 if(ready
&& !forceplay
) {
963 switch(config
->speaker_backend
) {
964 case BACKEND_COMMAND
:
965 /* We send sample data to the subprocess as fast as it can accept it.
966 * This isn't ideal as pause latency can be very high as a result. */
968 cmdfd_slot
= addfd(cmdfd
, POLLOUT
);
970 case BACKEND_NETWORK
: {
973 uint64_t target_rtp_time
;
974 const int64_t samples_ahead
= ((uint64_t)RTP_AHEAD_MS
975 * config
->sample_format
.rate
976 * config
->sample_format
.channels
978 static unsigned logit
;
980 /* If we're starting then initialize the base time */
982 xgettimeofday(&rtp_time_0
, 0);
983 /* We send audio data whenever we get RTP_AHEAD seconds or more
985 xgettimeofday(&now
, 0);
986 target_us
= tvsub_us(now
, rtp_time_0
);
987 assert(target_us
<= UINT64_MAX
/ 88200);
988 target_rtp_time
= (target_us
* config
->sample_format
.rate
989 * config
->sample_format
.channels
)
993 /* TODO remove logging guff */
994 if(!(logit
++ & 1023))
995 info("rtp_time %llu target %llu difference %lld [%lld]",
996 rtp_time
, target_rtp_time
,
997 rtp_time
- target_rtp_time
,
1000 if((int64_t)(rtp_time
- target_rtp_time
) < samples_ahead
)
1001 bfd_slot
= addfd(bfd
, POLLOUT
);
1005 case BACKEND_ALSA
: {
1006 /* We send sample data to ALSA as fast as it can accept it, relying on
1007 * the fact that it has a relatively small buffer to minimize pause
1014 alsa_nslots
= snd_pcm_poll_descriptors(pcm
, &fds
[fdno
], NFDS
- fdno
);
1015 if((alsa_nslots
<= 0
1016 || !(fds
[alsa_slots
].events
& POLLOUT
))
1017 && snd_pcm_state(pcm
) == SND_PCM_STATE_XRUN
) {
1018 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
1019 if((err
= snd_pcm_prepare(pcm
)))
1020 fatal(0, "error calling snd_pcm_prepare: %d", err
);
1023 } while(retry
-- > 0);
1024 if(alsa_nslots
>= 0)
1025 fdno
+= alsa_nslots
;
1030 assert(!"unknown backend");
1033 /* If any other tracks don't have a full buffer, try to read sample data
1035 for(t
= tracks
; t
; t
= t
->next
)
1037 if(!t
->eof
&& t
->used
< t
->size
) {
1038 t
->slot
= addfd(t
->fd
, POLLIN
| POLLHUP
);
1042 /* Wait for something interesting to happen */
1043 n
= poll(fds
, fdno
, timeout
);
1045 if(errno
== EINTR
) continue;
1046 fatal(errno
, "error calling poll");
1048 /* Play some sound before doing anything else */
1050 switch(config
->speaker_backend
) {
1053 if(alsa_slots
!= -1) {
1054 unsigned short alsa_revents
;
1056 if((err
= snd_pcm_poll_descriptors_revents(pcm
,
1059 &alsa_revents
)) < 0)
1060 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err
);
1061 if(alsa_revents
& (POLLOUT
| POLLERR
))
1067 case BACKEND_COMMAND
:
1068 if(cmdfd_slot
!= -1) {
1069 if(fds
[cmdfd_slot
].revents
& (POLLOUT
| POLLERR
))
1074 case BACKEND_NETWORK
:
1075 if(bfd_slot
!= -1) {
1076 if(fds
[bfd_slot
].revents
& (POLLOUT
| POLLERR
))
1083 /* Some attempt to play must have failed */
1084 if(playing
&& !paused
)
1087 forceplay
= 0; /* just in case */
1089 /* Perhaps we have a command to process */
1090 if(fds
[stdin_slot
].revents
& POLLIN
) {
1091 n
= speaker_recv(0, &sm
, &fd
);
1095 D(("SM_PREPARE %s %d", sm
.id
, fd
));
1096 if(fd
== -1) fatal(0, "got SM_PREPARE but no file descriptor");
1097 t
= findtrack(sm
.id
, 1);
1101 D(("SM_PLAY %s %d", sm
.id
, fd
));
1102 if(playing
) fatal(0, "got SM_PLAY but already playing something");
1103 t
= findtrack(sm
.id
, 1);
1104 if(fd
!= -1) acquire(t
, fd
);
1124 D(("SM_CANCEL %s", sm
.id
));
1125 t
= removetrack(sm
.id
);
1128 sm
.type
= SM_FINISHED
;
1129 strcpy(sm
.id
, playing
->id
);
1130 speaker_send(1, &sm
, 0);
1135 error(0, "SM_CANCEL for unknown track %s", sm
.id
);
1140 if(config_read()) error(0, "cannot read configuration");
1141 info("reloaded configuration");
1144 error(0, "unknown message type %d", sm
.type
);
1147 /* Read in any buffered data */
1148 for(t
= tracks
; t
; t
= t
->next
)
1149 if(t
->slot
!= -1 && (fds
[t
->slot
].revents
& (POLLIN
| POLLHUP
)))
1151 /* We might be able to play now */
1152 if(ready
&& forceplay
&& playing
&& !paused
)
1154 /* Maybe we finished playing a track somewhere in the above */
1156 /* If we don't need the sound device for now then close it for the benefit
1157 * of anyone else who wants it. */
1158 if((!playing
|| paused
) && ready
)
1160 /* If we've not reported out state for a second do so now. */
1161 if(time(0) > last_report
)
1164 info("stopped (parent terminated)");
1173 indent-tabs-mode:nil