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 process
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 * @b Encodings. For the <a href="http://www.alsa-project.org/">ALSA</a> API,
29 * 8- and 16- bit stereo and mono are supported, with any sample rate (within
30 * the limits that 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 * @b Garbage @b Collection. This program deliberately does not use the
43 * garbage collector even though it might be convenient to do so. This is for
44 * two reasons. Firstly some sound APIs use thread threads and we do not want
45 * to have to deal with potential interactions between threading and garbage
46 * collection. Secondly this process needs to be able to respond quickly and
47 * this is not compatible with the collector hanging the program even
50 * @b Units. This program thinks at various times in three different units.
51 * Bytes are obvious. A sample is a single sample on a single channel. A
52 * frame is several samples on different channels at the same point in time.
53 * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
70 #include <sys/select.h>
75 #include <sys/socket.h>
80 #include "configuration.h"
85 #include "speaker-protocol.h"
93 #include <alsa/asoundlib.h>
96 /** @brief Linked list of all prepared tracks */
99 /** @brief Playing track, or NULL */
100 struct track
*playing
;
102 static time_t last_report
; /* when we last reported */
103 static int paused
; /* pause status */
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 */
108 /** @brief The current PCM handle */
109 static snd_pcm_t
*pcm
;
110 static snd_pcm_uframes_t last_pcm_bufsize
; /* last seen buffer size */
113 /** @brief The current device state */
114 enum device_states device_state
;
116 /** @brief The current device sample format
118 * Only meaningful if @ref device_state = @ref device_open or perhaps @ref
119 * device_error. For @ref FIXED_FORMAT backends, this should always match @c
120 * config->sample_format.
122 ao_sample_format device_format
;
124 /** @brief Pipe to subprocess
126 * This is the file descriptor to write to for @ref BACKEND_COMMAND.
128 static int cmdfd
= -1;
130 /** @brief Network socket
132 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
136 /** @brief RTP timestamp
138 * This counts the number of samples played (NB not the number of frames
141 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
142 * stereo, that only gives about half a day before wrapping, which is not
143 * particularly convenient for certain debugging purposes. Therefore the
144 * timestamp is maintained as a 64-bit integer, giving around six million years
145 * before wrapping, and truncated to 32 bits when transmitting.
147 static uint64_t rtp_time
;
149 /** @brief RTP base timestamp
151 * This is the real time correspoding to an @ref rtp_time of 0. It is used
152 * to recalculate the timestamp after idle periods.
154 static struct timeval rtp_time_0
;
156 /** @brief RTP packet sequence number */
157 static uint16_t rtp_seq
;
159 /** @brief RTP SSRC */
160 static uint32_t rtp_id
;
162 /** @brief Set when idled
164 * This is set when the sound device is deliberately closed by idle().
166 static int idled
; /* set when idled */
168 /** @brief Error counter */
169 static int audio_errors
;
171 /** @brief Selected backend */
172 static const struct speaker_backend
*backend
;
174 static const struct option options
[] = {
175 { "help", no_argument
, 0, 'h' },
176 { "version", no_argument
, 0, 'V' },
177 { "config", required_argument
, 0, 'c' },
178 { "debug", no_argument
, 0, 'd' },
179 { "no-debug", no_argument
, 0, 'D' },
183 /* Display usage message and terminate. */
184 static void help(void) {
186 " disorder-speaker [OPTIONS]\n"
188 " --help, -h Display usage message\n"
189 " --version, -V Display version number\n"
190 " --config PATH, -c PATH Set configuration file\n"
191 " --debug, -d Turn on debugging\n"
193 "Speaker process for DisOrder. Not intended to be run\n"
199 /* Display version number and terminate. */
200 static void version(void) {
201 xprintf("disorder-speaker version %s\n", disorder_version_string
);
206 /** @brief Return the number of bytes per frame in @p format */
207 static size_t bytes_per_frame(const ao_sample_format
*format
) {
208 return format
->channels
* format
->bits
/ 8;
211 /** @brief Find track @p id, maybe creating it if not found */
212 static struct track
*findtrack(const char *id
, int create
) {
215 D(("findtrack %s %d", id
, create
));
216 for(t
= tracks
; t
&& strcmp(id
, t
->id
); t
= t
->next
)
219 t
= xmalloc(sizeof *t
);
224 /* The initial input buffer will be the sample format. */
225 t
->buffer
= (void *)&t
->format
;
226 t
->size
= sizeof t
->format
;
231 /** @brief Remove track @p id (but do not destroy it) */
232 static struct track
*removetrack(const char *id
) {
233 struct track
*t
, **tt
;
235 D(("removetrack %s", id
));
236 for(tt
= &tracks
; (t
= *tt
) && strcmp(id
, t
->id
); tt
= &t
->next
)
243 /** @brief Destroy a track */
244 static void destroy(struct track
*t
) {
245 D(("destroy %s", t
->id
));
246 if(t
->fd
!= -1) xclose(t
->fd
);
247 if(t
->buffer
!= (void *)&t
->format
) free(t
->buffer
);
251 /** @brief Notice a new connection */
252 static void acquire(struct track
*t
, int fd
) {
253 D(("acquire %s %d", t
->id
, fd
));
260 /** @brief Return true if A and B denote identical libao formats, else false */
261 static int formats_equal(const ao_sample_format
*a
,
262 const ao_sample_format
*b
) {
263 return (a
->bits
== b
->bits
264 && a
->rate
== b
->rate
265 && a
->channels
== b
->channels
266 && a
->byte_format
== b
->byte_format
);
269 /** @brief Compute arguments to sox */
270 static void soxargs(const char ***pp
, char **qq
, ao_sample_format
*ao
) {
275 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-r%d", ao
->rate
); *qq
+= n
+ 1;
276 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-c%d", ao
->channels
); *qq
+= n
+ 1;
277 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
279 switch(config
->sox_generation
) {
282 && ao
->byte_format
!= AO_FMT_NATIVE
283 && ao
->byte_format
!= MACHINE_AO_FMT
) {
287 case 8: *(*pp
)++ = "-b"; break;
288 case 16: *(*pp
)++ = "-w"; break;
289 case 32: *(*pp
)++ = "-l"; break;
290 case 64: *(*pp
)++ = "-d"; break;
291 default: fatal(0, "cannot handle sample size %d", (int)ao
->bits
);
295 switch(ao
->byte_format
) {
296 case AO_FMT_NATIVE
: break;
297 case AO_FMT_BIG
: *(*pp
)++ = "-B"; break;
298 case AO_FMT_LITTLE
: *(*pp
)++ = "-L"; break;
300 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-%d", ao
->bits
/8); *qq
+= n
+ 1;
305 /** @brief Enable format translation
307 * If necessary, replaces a tracks inbound file descriptor with one connected
308 * to a sox invocation, which performs the required translation.
310 static void enable_translation(struct track
*t
) {
311 if((backend
->flags
& FIXED_FORMAT
)
312 && !formats_equal(&t
->format
, &config
->sample_format
)) {
313 char argbuf
[1024], *q
= argbuf
;
314 const char *av
[18], **pp
= av
;
319 soxargs(&pp
, &q
, &t
->format
);
321 soxargs(&pp
, &q
, &config
->sample_format
);
325 for(pp
= av
; *pp
; pp
++)
326 D(("sox arg[%d] = %s", pp
- av
, *pp
));
332 signal(SIGPIPE
, SIG_DFL
);
334 xdup2(soxpipe
[1], 1);
335 fcntl(0, F_SETFL
, fcntl(0, F_GETFL
) & ~O_NONBLOCK
);
339 execvp("sox", (char **)av
);
342 D(("forking sox for format conversion (kid = %d)", soxkid
));
346 t
->format
= config
->sample_format
;
350 /** @brief Read data into a sample buffer
351 * @param t Pointer to track
352 * @return 0 on success, -1 on EOF
354 * This is effectively the read callback on @c t->fd. It is called from the
355 * main loop whenever the track's file descriptor is readable, assuming the
356 * buffer has not reached the maximum allowed occupancy.
358 static int fill(struct track
*t
) {
362 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
363 t
->id
, t
->eof
, t
->used
, t
->size
, t
->got_format
));
364 if(t
->eof
) return -1;
365 if(t
->used
< t
->size
) {
366 /* there is room left in the buffer */
367 where
= (t
->start
+ t
->used
) % t
->size
;
369 /* We are reading audio data, get as much as we can */
370 if(where
>= t
->start
) left
= t
->size
- where
;
371 else left
= t
->start
- where
;
373 /* We are still waiting for the format, only get that */
374 left
= sizeof (ao_sample_format
) - t
->used
;
376 n
= read(t
->fd
, t
->buffer
+ where
, left
);
377 } while(n
< 0 && errno
== EINTR
);
379 if(errno
!= EAGAIN
) fatal(errno
, "error reading sample stream");
383 D(("fill %s: eof detected", t
->id
));
388 if(!t
->got_format
&& t
->used
>= sizeof (ao_sample_format
)) {
389 assert(t
->used
== sizeof (ao_sample_format
));
390 /* Check that our assumptions are met. */
391 if(t
->format
.bits
& 7)
392 fatal(0, "bits per sample not a multiple of 8");
393 /* If the input format is unsuitable, arrange to translate it */
394 enable_translation(t
);
395 /* Make a new buffer for audio data. */
396 t
->size
= bytes_per_frame(&t
->format
) * t
->format
.rate
* BUFFER_SECONDS
;
397 t
->buffer
= xmalloc(t
->size
);
400 D(("got format for %s", t
->id
));
406 /** @brief Close the sound device
408 * This is called to deactivate the output device when pausing, and also by the
409 * ALSA backend when changing encoding (in which case the sound device will be
410 * immediately reactivated).
412 static void idle(void) {
414 if(backend
->deactivate
)
415 backend
->deactivate();
417 device_state
= device_closed
;
421 /** @brief Abandon the current track */
422 static void abandon(void) {
423 struct speaker_message sm
;
426 memset(&sm
, 0, sizeof sm
);
427 sm
.type
= SM_FINISHED
;
428 strcpy(sm
.id
, playing
->id
);
429 speaker_send(1, &sm
, 0);
430 removetrack(playing
->id
);
435 /** @brief Enable sound output
437 * Makes sure the sound device is open and has the right sample format. Return
438 * 0 on success and -1 on error.
440 static void activate(void) {
441 /* If we don't know the format yet we cannot start. */
442 if(!playing
->got_format
) {
443 D((" - not got format for %s", playing
->id
));
446 if(backend
->flags
& FIXED_FORMAT
)
447 device_format
= config
->sample_format
;
448 if(backend
->activate
) {
451 assert(backend
->flags
& FIXED_FORMAT
);
452 /* ...otherwise device_format not set */
453 device_state
= device_open
;
455 if(device_state
== device_open
)
456 bpf
= bytes_per_frame(&device_format
);
459 /** @brief Check whether the current track has finished
461 * The current track is determined to have finished either if the input stream
462 * eded before the format could be determined (i.e. it is malformed) or the
463 * input is at end of file and there is less than a frame left unplayed. (So
464 * it copes with decoders that crash mid-frame.)
466 static void maybe_finished(void) {
469 && (!playing
->got_format
470 || playing
->used
< bytes_per_frame(&playing
->format
)))
474 /** @brief Play up to @p frames frames of audio
476 * It is always safe to call this function.
477 * - If @ref playing is 0 then it will just return
478 * - If @ref paused is non-0 then it will just return
479 * - If @ref device_state != @ref device_open then it will call activate() and
480 * return if it it fails.
481 * - If there is not enough audio to play then it play what is available.
483 * If there are not enough frames to play then whatever is available is played
484 * instead. It is up to mainloop() to ensure that play() is not called when
485 * unreasonably only an small amounts of data is available to play.
487 static void play(size_t frames
) {
488 size_t avail_frames
, avail_bytes
, written_frames
;
489 ssize_t written_bytes
;
491 /* Make sure there's a track to play and it is not pasued */
492 if(!playing
|| paused
)
494 /* Make sure the output device is open and has the right sample format */
495 if(device_state
!= device_open
496 || !formats_equal(&device_format
, &playing
->format
)) {
498 if(device_state
!= device_open
)
501 D(("play: play %zu/%zu%s %dHz %db %dc", frames
, playing
->used
/ bpf
,
502 playing
->eof ?
" EOF" : "",
503 playing
->format
.rate
,
504 playing
->format
.bits
,
505 playing
->format
.channels
));
506 /* Figure out how many frames there are available to write */
507 if(playing
->start
+ playing
->used
> playing
->size
)
508 /* The ring buffer is currently wrapped, only play up to the wrap point */
509 avail_bytes
= playing
->size
- playing
->start
;
511 /* The ring buffer is not wrapped, can play the lot */
512 avail_bytes
= playing
->used
;
513 avail_frames
= avail_bytes
/ bpf
;
514 /* Only play up to the requested amount */
515 if(avail_frames
> frames
)
516 avail_frames
= frames
;
520 written_frames
= backend
->play(avail_frames
);
521 written_bytes
= written_frames
* bpf
;
522 /* written_bytes and written_frames had better both be set and correct by
524 playing
->start
+= written_bytes
;
525 playing
->used
-= written_bytes
;
526 playing
->played
+= written_frames
;
527 /* If the pointer is at the end of the buffer (or the buffer is completely
528 * empty) wrap it back to the start. */
529 if(!playing
->used
|| playing
->start
== playing
->size
)
531 frames
-= written_frames
;
535 /* Notify the server what we're up to. */
536 static void report(void) {
537 struct speaker_message sm
;
539 if(playing
&& playing
->buffer
!= (void *)&playing
->format
) {
540 memset(&sm
, 0, sizeof sm
);
541 sm
.type
= paused ? SM_PAUSED
: SM_PLAYING
;
542 strcpy(sm
.id
, playing
->id
);
543 sm
.data
= playing
->played
/ playing
->format
.rate
;
544 speaker_send(1, &sm
, 0);
549 static void reap(int __attribute__((unused
)) sig
) {
554 cmdpid
= waitpid(-1, &st
, WNOHANG
);
556 signal(SIGCHLD
, reap
);
559 static int addfd(int fd
, int events
) {
562 fds
[fdno
].events
= events
;
569 /** @brief ALSA backend initialization */
570 static void alsa_init(void) {
571 info("selected ALSA backend");
574 /** @brief Log ALSA parameters */
575 static void log_params(snd_pcm_hw_params_t
*hwparams
,
576 snd_pcm_sw_params_t
*swparams
) {
580 return; /* too verbose */
585 snd_pcm_sw_params_get_silence_size(swparams
, &f
);
586 info("sw silence_size=%lu", (unsigned long)f
);
587 snd_pcm_sw_params_get_silence_threshold(swparams
, &f
);
588 info("sw silence_threshold=%lu", (unsigned long)f
);
589 snd_pcm_sw_params_get_sleep_min(swparams
, &u
);
590 info("sw sleep_min=%lu", (unsigned long)u
);
591 snd_pcm_sw_params_get_start_threshold(swparams
, &f
);
592 info("sw start_threshold=%lu", (unsigned long)f
);
593 snd_pcm_sw_params_get_stop_threshold(swparams
, &f
);
594 info("sw stop_threshold=%lu", (unsigned long)f
);
595 snd_pcm_sw_params_get_xfer_align(swparams
, &f
);
596 info("sw xfer_align=%lu", (unsigned long)f
);
600 /** @brief ALSA deactivation */
601 static void alsa_deactivate(void) {
605 if((err
= snd_pcm_nonblock(pcm
, 0)) < 0)
606 fatal(0, "error calling snd_pcm_nonblock: %d", err
);
612 device_state
= device_closed
;
613 D(("released audio device"));
617 /** @brief ALSA backend activation */
618 static void alsa_activate(void) {
619 /* If we need to change format then close the current device. */
620 if(pcm
&& !formats_equal(&playing
->format
, &device_format
))
622 /* Now if the sound device is open it must have the right format */
624 snd_pcm_hw_params_t
*hwparams
;
625 snd_pcm_sw_params_t
*swparams
;
626 snd_pcm_uframes_t pcm_bufsize
;
628 int sample_format
= 0;
632 if((err
= snd_pcm_open(&pcm
,
634 SND_PCM_STREAM_PLAYBACK
,
635 SND_PCM_NONBLOCK
))) {
636 error(0, "error from snd_pcm_open: %d", err
);
639 snd_pcm_hw_params_alloca(&hwparams
);
640 D(("set up hw params"));
641 if((err
= snd_pcm_hw_params_any(pcm
, hwparams
)) < 0)
642 fatal(0, "error from snd_pcm_hw_params_any: %d", err
);
643 if((err
= snd_pcm_hw_params_set_access(pcm
, hwparams
,
644 SND_PCM_ACCESS_RW_INTERLEAVED
)) < 0)
645 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err
);
646 switch(playing
->format
.bits
) {
648 sample_format
= SND_PCM_FORMAT_S8
;
651 switch(playing
->format
.byte_format
) {
652 case AO_FMT_NATIVE
: sample_format
= SND_PCM_FORMAT_S16
; break;
653 case AO_FMT_LITTLE
: sample_format
= SND_PCM_FORMAT_S16_LE
; break;
654 case AO_FMT_BIG
: sample_format
= SND_PCM_FORMAT_S16_BE
; break;
655 error(0, "unrecognized byte format %d", playing
->format
.byte_format
);
660 error(0, "unsupported sample size %d", playing
->format
.bits
);
663 if((err
= snd_pcm_hw_params_set_format(pcm
, hwparams
,
664 sample_format
)) < 0) {
665 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
669 rate
= playing
->format
.rate
;
670 if((err
= snd_pcm_hw_params_set_rate_near(pcm
, hwparams
, &rate
, 0)) < 0) {
671 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
672 playing
->format
.rate
, err
);
675 if(rate
!= (unsigned)playing
->format
.rate
)
676 info("want rate %d, got %u", playing
->format
.rate
, rate
);
677 if((err
= snd_pcm_hw_params_set_channels(pcm
, hwparams
,
678 playing
->format
.channels
)) < 0) {
679 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
680 playing
->format
.channels
, err
);
683 pcm_bufsize
= 3 * FRAMES
;
684 if((err
= snd_pcm_hw_params_set_buffer_size_near(pcm
, hwparams
,
686 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
688 if(pcm_bufsize
!= 3 * FRAMES
&& pcm_bufsize
!= last_pcm_bufsize
)
689 info("asked for PCM buffer of %d frames, got %d",
690 3 * FRAMES
, (int)pcm_bufsize
);
691 last_pcm_bufsize
= pcm_bufsize
;
692 if((err
= snd_pcm_hw_params(pcm
, hwparams
)) < 0)
693 fatal(0, "error calling snd_pcm_hw_params: %d", err
);
694 D(("set up sw params"));
695 snd_pcm_sw_params_alloca(&swparams
);
696 if((err
= snd_pcm_sw_params_current(pcm
, swparams
)) < 0)
697 fatal(0, "error calling snd_pcm_sw_params_current: %d", err
);
698 if((err
= snd_pcm_sw_params_set_avail_min(pcm
, swparams
, FRAMES
)) < 0)
699 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
701 if((err
= snd_pcm_sw_params(pcm
, swparams
)) < 0)
702 fatal(0, "error calling snd_pcm_sw_params: %d", err
);
703 device_format
= playing
->format
;
704 D(("acquired audio device"));
705 log_params(hwparams
, swparams
);
706 device_state
= device_open
;
712 /* We assume the error is temporary and that we'll retry in a bit. */
716 device_state
= device_error
;
721 /** @brief Play via ALSA */
722 static size_t alsa_play(size_t frames
) {
723 snd_pcm_sframes_t pcm_written_frames
;
726 pcm_written_frames
= snd_pcm_writei(pcm
,
727 playing
->buffer
+ playing
->start
,
729 D(("actually play %zu frames, wrote %d",
730 frames
, (int)pcm_written_frames
));
731 if(pcm_written_frames
< 0) {
732 switch(pcm_written_frames
) {
733 case -EPIPE
: /* underrun */
734 error(0, "snd_pcm_writei reports underrun");
735 if((err
= snd_pcm_prepare(pcm
)) < 0)
736 fatal(0, "error calling snd_pcm_prepare: %d", err
);
741 fatal(0, "error calling snd_pcm_writei: %d",
742 (int)pcm_written_frames
);
745 return pcm_written_frames
;
748 static int alsa_slots
, alsa_nslots
= -1;
750 /** @brief Fill in poll fd array for ALSA */
751 static void alsa_beforepoll(void) {
752 /* We send sample data to ALSA as fast as it can accept it, relying on
753 * the fact that it has a relatively small buffer to minimize pause
760 alsa_nslots
= snd_pcm_poll_descriptors(pcm
, &fds
[fdno
], NFDS
- fdno
);
762 || !(fds
[alsa_slots
].events
& POLLOUT
))
763 && snd_pcm_state(pcm
) == SND_PCM_STATE_XRUN
) {
764 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
765 if((err
= snd_pcm_prepare(pcm
)))
766 fatal(0, "error calling snd_pcm_prepare: %d", err
);
769 } while(retry
-- > 0);
774 /** @brief Process poll() results for ALSA */
775 static int alsa_ready(void) {
778 unsigned short alsa_revents
;
780 if((err
= snd_pcm_poll_descriptors_revents(pcm
,
784 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err
);
785 if(alsa_revents
& (POLLOUT
| POLLERR
))
792 /** @brief Start the subprocess for @ref BACKEND_COMMAND */
793 static void fork_cmd(void) {
796 if(cmdfd
!= -1) close(cmdfd
);
800 signal(SIGPIPE
, SIG_DFL
);
804 execl("/bin/sh", "sh", "-c", config
->speaker_command
, (char *)0);
805 fatal(errno
, "error execing /bin/sh");
809 D(("forked cmd %d, fd = %d", cmdpid
, cmdfd
));
812 /** @brief Command backend initialization */
813 static void command_init(void) {
814 info("selected command backend");
818 /** @brief Play to a subprocess */
819 static size_t command_play(size_t frames
) {
820 size_t bytes
= frames
* bpf
;
823 written_bytes
= write(cmdfd
, playing
->buffer
+ playing
->start
, bytes
);
824 D(("actually play %zu bytes, wrote %d",
825 bytes
, written_bytes
));
826 if(written_bytes
< 0) {
829 error(0, "hmm, command died; trying another");
835 fatal(errno
, "error writing to subprocess");
838 return written_bytes
/ bpf
;
841 static int cmdfd_slot
;
843 /** @brief Update poll array for writing to subprocess */
844 static void command_beforepoll(void) {
845 /* We send sample data to the subprocess as fast as it can accept it.
846 * This isn't ideal as pause latency can be very high as a result. */
848 cmdfd_slot
= addfd(cmdfd
, POLLOUT
);
851 /** @brief Process poll() results for subprocess play */
852 static int command_ready(void) {
853 if(fds
[cmdfd_slot
].revents
& (POLLOUT
| POLLERR
))
859 /** @brief Network backend initialization */
860 static void network_init(void) {
861 struct addrinfo
*res
, *sres
;
862 static const struct addrinfo pref
= {
872 static const struct addrinfo prefbind
= {
882 static const int one
= 1;
883 int sndbuf
, target_sndbuf
= 131072;
885 char *sockname
, *ssockname
;
887 res
= get_address(&config
->broadcast
, &pref
, &sockname
);
889 if(config
->broadcast_from
.n
) {
890 sres
= get_address(&config
->broadcast_from
, &prefbind
, &ssockname
);
894 if((bfd
= socket(res
->ai_family
,
896 res
->ai_protocol
)) < 0)
897 fatal(errno
, "error creating broadcast socket");
898 if(setsockopt(bfd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof one
) < 0)
899 fatal(errno
, "error setting SO_BROADCAST on broadcast socket");
901 if(getsockopt(bfd
, SOL_SOCKET
, SO_SNDBUF
,
903 fatal(errno
, "error getting SO_SNDBUF");
904 if(target_sndbuf
> sndbuf
) {
905 if(setsockopt(bfd
, SOL_SOCKET
, SO_SNDBUF
,
906 &target_sndbuf
, sizeof target_sndbuf
) < 0)
907 error(errno
, "error setting SO_SNDBUF to %d", target_sndbuf
);
909 info("changed socket send buffer size from %d to %d",
910 sndbuf
, target_sndbuf
);
912 info("default socket send buffer is %d",
914 /* We might well want to set additional broadcast- or multicast-related
916 if(sres
&& bind(bfd
, sres
->ai_addr
, sres
->ai_addrlen
) < 0)
917 fatal(errno
, "error binding broadcast socket to %s", ssockname
);
918 if(connect(bfd
, res
->ai_addr
, res
->ai_addrlen
) < 0)
919 fatal(errno
, "error connecting broadcast socket to %s", sockname
);
921 gcry_randomize(&rtp_id
, sizeof rtp_id
, GCRY_STRONG_RANDOM
);
922 info("selected network backend, sending to %s", sockname
);
923 if(config
->sample_format
.byte_format
!= AO_FMT_BIG
) {
924 info("forcing big-endian sample format");
925 config
->sample_format
.byte_format
= AO_FMT_BIG
;
929 /** @brief Play over the network */
930 static size_t network_play(size_t frames
) {
931 struct rtp_header header
;
933 size_t bytes
= frames
* bpf
, written_frames
;
935 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
936 * AVT profile (RFC3551). */
939 /* There may have been a gap. Fix up the RTP time accordingly. */
942 uint64_t target_rtp_time
;
944 /* Find the current time */
945 xgettimeofday(&now
, 0);
946 /* Find the number of microseconds elapsed since rtp_time=0 */
947 delta
= tvsub_us(now
, rtp_time_0
);
948 assert(delta
<= UINT64_MAX
/ 88200);
949 target_rtp_time
= (delta
* playing
->format
.rate
950 * playing
->format
.channels
) / 1000000;
951 /* Overflows at ~6 years uptime with 44100Hz stereo */
953 /* rtp_time is the number of samples we've played. NB that we play
954 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
955 * the value we deduce from time comparison.
957 * Suppose we have 1s track started at t=0, and another track begins to
958 * play at t=2s. Suppose RTP_AHEAD_MS=1000 and 44100Hz stereo. In that
959 * case we'll send 1s of audio as fast as we can, giving rtp_time=88200.
960 * rtp_time stops at this point.
962 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
963 * set rtp_time=176400 and the player can correctly conclude that it
964 * should leave 1s between the tracks.
966 * Suppose instead that the second track arrives at t=0.5s, and that
967 * we've managed to transmit the whole of the first track already. We'll
968 * have target_rtp_time=44100.
970 * The desired behaviour is to play the second track back to back with
971 * first. In this case therefore we do not modify rtp_time.
973 * Is it ever right to reduce rtp_time? No; for that would imply
974 * transmitting packets with overlapping timestamp ranges, which does not
977 target_rtp_time
&= ~(uint64_t)1; /* stereo! */
978 if(target_rtp_time
> rtp_time
) {
979 /* More time has elapsed than we've transmitted samples. That implies
980 * we've been 'sending' silence. */
981 info("advancing rtp_time by %"PRIu64
" samples",
982 target_rtp_time
- rtp_time
);
983 rtp_time
= target_rtp_time
;
984 } else if(target_rtp_time
< rtp_time
) {
985 const int64_t samples_ahead
= ((uint64_t)RTP_AHEAD_MS
986 * config
->sample_format
.rate
987 * config
->sample_format
.channels
990 if(target_rtp_time
+ samples_ahead
< rtp_time
) {
991 info("reversing rtp_time by %"PRIu64
" samples",
992 rtp_time
- target_rtp_time
);
996 header
.vpxcc
= 2 << 6; /* V=2, P=0, X=0, CC=0 */
997 header
.seq
= htons(rtp_seq
++);
998 header
.timestamp
= htonl((uint32_t)rtp_time
);
999 header
.ssrc
= rtp_id
;
1000 header
.mpt
= (idled ?
0x80 : 0x00) | 10;
1001 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
1002 * the sample rate (in a library somewhere so that configuration.c can rule
1003 * out invalid rates).
1006 if(bytes
> NETWORK_BYTES
- sizeof header
) {
1007 bytes
= NETWORK_BYTES
- sizeof header
;
1008 /* Always send a whole number of frames */
1009 bytes
-= bytes
% bpf
;
1011 /* "The RTP clock rate used for generating the RTP timestamp is independent
1012 * of the number of channels and the encoding; it equals the number of
1013 * sampling periods per second. For N-channel encodings, each sampling
1014 * period (say, 1/8000 of a second) generates N samples. (This terminology
1015 * is standard, but somewhat confusing, as the total number of samples
1016 * generated per second is then the sampling rate times the channel
1019 vec
[0].iov_base
= (void *)&header
;
1020 vec
[0].iov_len
= sizeof header
;
1021 vec
[1].iov_base
= playing
->buffer
+ playing
->start
;
1022 vec
[1].iov_len
= bytes
;
1024 written_bytes
= writev(bfd
, vec
, 2);
1025 } while(written_bytes
< 0 && errno
== EINTR
);
1026 if(written_bytes
< 0) {
1027 error(errno
, "error transmitting audio data");
1029 if(audio_errors
== 10)
1030 fatal(0, "too many audio errors");
1034 written_bytes
-= sizeof (struct rtp_header
);
1035 written_frames
= written_bytes
/ bpf
;
1036 /* Advance RTP's notion of the time */
1037 rtp_time
+= written_frames
* playing
->format
.channels
;
1038 return written_frames
;
1041 static int bfd_slot
;
1043 /** @brief Set up poll array for network play */
1044 static void network_beforepoll(void) {
1047 uint64_t target_rtp_time
;
1048 const int64_t samples_ahead
= ((uint64_t)RTP_AHEAD_MS
1049 * config
->sample_format
.rate
1050 * config
->sample_format
.channels
1053 /* If we're starting then initialize the base time */
1055 xgettimeofday(&rtp_time_0
, 0);
1056 /* We send audio data whenever we get RTP_AHEAD seconds or more
1058 xgettimeofday(&now
, 0);
1059 target_us
= tvsub_us(now
, rtp_time_0
);
1060 assert(target_us
<= UINT64_MAX
/ 88200);
1061 target_rtp_time
= (target_us
* config
->sample_format
.rate
1062 * config
->sample_format
.channels
)
1064 if((int64_t)(rtp_time
- target_rtp_time
) < samples_ahead
)
1065 bfd_slot
= addfd(bfd
, POLLOUT
);
1068 /** @brief Process poll() results for network play */
1069 static int network_ready(void) {
1070 if(fds
[bfd_slot
].revents
& (POLLOUT
| POLLERR
))
1076 /** @brief Table of speaker backends */
1077 static const struct speaker_backend backends
[] = {
1110 { -1, 0, 0, 0, 0, 0, 0, 0 } /* end of list */
1113 /** @brief Return nonzero if we want to play some audio
1115 * We want to play audio if there is a current track; and it is not paused; and
1116 * there are at least @ref FRAMES frames of audio to play, or we are in sight
1117 * of the end of the current track.
1119 static int playable(void) {
1122 && (playing
->used
>= FRAMES
|| playing
->eof
);
1125 /** @brief Main event loop */
1126 static void mainloop(void) {
1128 struct speaker_message sm
;
1129 int n
, fd
, stdin_slot
, timeout
;
1131 while(getppid() != 1) {
1133 /* By default we will wait up to a second before thinking about current
1136 /* Always ready for commands from the main server. */
1137 stdin_slot
= addfd(0, POLLIN
);
1138 /* Try to read sample data for the currently playing track if there is
1140 if(playing
&& !playing
->eof
&& playing
->used
< playing
->size
)
1141 playing
->slot
= addfd(playing
->fd
, POLLIN
);
1145 /* We want to play some audio. If the device is closed then we attempt
1147 if(device_state
== device_closed
)
1149 /* If the device is (now) open then we will wait up until it is ready for
1150 * more. If something went wrong then we should have device_error
1151 * instead, but the post-poll code will cope even if it's
1153 if(device_state
== device_open
)
1154 backend
->beforepoll();
1156 /* If any other tracks don't have a full buffer, try to read sample data
1157 * from them. We do this last of all, so that if we run out of slots,
1158 * nothing important can't be monitored. */
1159 for(t
= tracks
; t
; t
= t
->next
)
1161 if(!t
->eof
&& t
->used
< t
->size
) {
1162 t
->slot
= addfd(t
->fd
, POLLIN
| POLLHUP
);
1166 /* Wait for something interesting to happen */
1167 n
= poll(fds
, fdno
, timeout
);
1169 if(errno
== EINTR
) continue;
1170 fatal(errno
, "error calling poll");
1172 /* Play some sound before doing anything else */
1174 /* We want to play some audio */
1175 if(device_state
== device_open
) {
1176 if(backend
->ready())
1179 /* We must be in _closed or _error, and it should be the latter, but we
1182 * We most likely timed out, so now is a good time to retry. play()
1183 * knows to re-activate the device if necessary.
1188 /* Perhaps we have a command to process */
1189 if(fds
[stdin_slot
].revents
& POLLIN
) {
1190 /* There might (in theory) be several commands queued up, but in general
1191 * this won't be the case, so we don't bother looping around to pick them
1193 n
= speaker_recv(0, &sm
, &fd
);
1197 D(("SM_PREPARE %s %d", sm
.id
, fd
));
1198 if(fd
== -1) fatal(0, "got SM_PREPARE but no file descriptor");
1199 t
= findtrack(sm
.id
, 1);
1203 D(("SM_PLAY %s %d", sm
.id
, fd
));
1204 if(playing
) fatal(0, "got SM_PLAY but already playing something");
1205 t
= findtrack(sm
.id
, 1);
1206 if(fd
!= -1) acquire(t
, fd
);
1208 /* We attempt to play straight away rather than going round the loop.
1209 * play() is clever enough to perform any activation that is
1223 /* As for SM_PLAY we attempt to play straight away. */
1230 D(("SM_CANCEL %s", sm
.id
));
1231 t
= removetrack(sm
.id
);
1234 sm
.type
= SM_FINISHED
;
1235 strcpy(sm
.id
, playing
->id
);
1236 speaker_send(1, &sm
, 0);
1241 error(0, "SM_CANCEL for unknown track %s", sm
.id
);
1246 if(config_read()) error(0, "cannot read configuration");
1247 info("reloaded configuration");
1250 error(0, "unknown message type %d", sm
.type
);
1253 /* Read in any buffered data */
1254 for(t
= tracks
; t
; t
= t
->next
)
1255 if(t
->slot
!= -1 && (fds
[t
->slot
].revents
& (POLLIN
| POLLHUP
)))
1257 /* Maybe we finished playing a track somewhere in the above */
1259 /* If we don't need the sound device for now then close it for the benefit
1260 * of anyone else who wants it. */
1261 if((!playing
|| paused
) && device_state
== device_open
)
1263 /* If we've not reported out state for a second do so now. */
1264 if(time(0) > last_report
)
1269 int main(int argc
, char **argv
) {
1273 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
1274 while((n
= getopt_long(argc
, argv
, "hVc:dD", options
, 0)) >= 0) {
1277 case 'V': version();
1278 case 'c': configfile
= optarg
; break;
1279 case 'd': debugging
= 1; break;
1280 case 'D': debugging
= 0; break;
1281 default: fatal(0, "invalid option");
1284 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging
= 1;
1285 /* If stderr is a TTY then log there, otherwise to syslog. */
1287 openlog(progname
, LOG_PID
, LOG_DAEMON
);
1288 log_default
= &log_syslog
;
1290 if(config_read()) fatal(0, "cannot read configuration");
1291 /* ignore SIGPIPE */
1292 signal(SIGPIPE
, SIG_IGN
);
1294 signal(SIGCHLD
, reap
);
1295 /* set nice value */
1296 xnice(config
->nice_speaker
);
1299 /* make sure we're not root, whatever the config says */
1300 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
1301 /* identify the backend used to play */
1302 for(n
= 0; backends
[n
].backend
!= -1; ++n
)
1303 if(backends
[n
].backend
== config
->speaker_backend
)
1305 if(backends
[n
].backend
== -1)
1306 fatal(0, "unsupported backend %d", config
->speaker_backend
);
1307 backend
= &backends
[n
];
1308 /* backend-specific initialization */
1311 info("stopped (parent terminated)");
1320 indent-tabs-mode:nil