chiark / gitweb /
move speaker declarations to speaker.h
[disorder] / server / speaker.c
... / ...
CommitLineData
1/*
2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2006, 2007 Richard Kettlewell
4 *
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.
9 *
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.
14 *
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
18 * USA
19 */
20/** @file server/speaker.c
21 * @brief Speaker process
22 *
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.
27 *
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.)
31 *
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.
36 *
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.
41 *
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
48 * relatively briefly.
49 *
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
54 * 2-byte samples.
55 */
56
57#include <config.h>
58#include "types.h"
59
60#include <getopt.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <locale.h>
64#include <syslog.h>
65#include <unistd.h>
66#include <errno.h>
67#include <ao/ao.h>
68#include <string.h>
69#include <assert.h>
70#include <sys/select.h>
71#include <sys/wait.h>
72#include <time.h>
73#include <fcntl.h>
74#include <poll.h>
75#include <sys/socket.h>
76#include <netdb.h>
77#include <gcrypt.h>
78#include <sys/uio.h>
79
80#include "configuration.h"
81#include "syscalls.h"
82#include "log.h"
83#include "defs.h"
84#include "mem.h"
85#include "speaker-protocol.h"
86#include "user.h"
87#include "addr.h"
88#include "timeval.h"
89#include "rtp.h"
90#include "speaker.h"
91
92#if API_ALSA
93#include <alsa/asoundlib.h>
94#endif
95
96/** @brief Linked list of all prepared tracks */
97struct track *tracks;
98
99/** @brief Playing track, or NULL */
100struct track *playing;
101
102static time_t last_report; /* when we last reported */
103static int paused; /* pause status */
104static size_t bpf; /* bytes per frame */
105static struct pollfd fds[NFDS]; /* if we need more than that */
106static int fdno; /* fd number */
107static size_t bufsize; /* buffer size */
108#if API_ALSA
109/** @brief The current PCM handle */
110static snd_pcm_t *pcm;
111static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
112static ao_sample_format pcm_format; /* current format if aodev != 0 */
113#endif
114
115/** @brief Ready to send audio
116 *
117 * This is set when the destination is ready to receive audio. Generally
118 * this implies that the sound device is open. In the ALSA backend it
119 * does @b not necessarily imply that is has the right sample format.
120 */
121static int ready;
122
123/** @brief Frames to force-play
124 *
125 * If this is nonzero, and playing is enabled, then the main loop will attempt
126 * to play this many frames without checking whether the output device is
127 * ready.
128 */
129static int forceplay;
130
131/** @brief Pipe to subprocess
132 *
133 * This is the file descriptor to write to for @ref BACKEND_COMMAND.
134 */
135static int cmdfd = -1;
136
137/** @brief Network socket
138 *
139 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
140 */
141static int bfd = -1;
142
143/** @brief RTP timestamp
144 *
145 * This counts the number of samples played (NB not the number of frames
146 * played).
147 *
148 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
149 * stereo, that only gives about half a day before wrapping, which is not
150 * particularly convenient for certain debugging purposes. Therefore the
151 * timestamp is maintained as a 64-bit integer, giving around six million years
152 * before wrapping, and truncated to 32 bits when transmitting.
153 */
154static uint64_t rtp_time;
155
156/** @brief RTP base timestamp
157 *
158 * This is the real time correspoding to an @ref rtp_time of 0. It is used
159 * to recalculate the timestamp after idle periods.
160 */
161static struct timeval rtp_time_0;
162
163/** @brief RTP packet sequence number */
164static uint16_t rtp_seq;
165
166/** @brief RTP SSRC */
167static uint32_t rtp_id;
168
169/** @brief Set when idled
170 *
171 * This is set when the sound device is deliberately closed by idle().
172 * @ref ready is set to 0 at the same time.
173 */
174static int idled; /* set when idled */
175
176/** @brief Error counter */
177static int audio_errors;
178
179/** @brief Selected backend */
180static const struct speaker_backend *backend;
181
182static const struct option options[] = {
183 { "help", no_argument, 0, 'h' },
184 { "version", no_argument, 0, 'V' },
185 { "config", required_argument, 0, 'c' },
186 { "debug", no_argument, 0, 'd' },
187 { "no-debug", no_argument, 0, 'D' },
188 { 0, 0, 0, 0 }
189};
190
191/* Display usage message and terminate. */
192static void help(void) {
193 xprintf("Usage:\n"
194 " disorder-speaker [OPTIONS]\n"
195 "Options:\n"
196 " --help, -h Display usage message\n"
197 " --version, -V Display version number\n"
198 " --config PATH, -c PATH Set configuration file\n"
199 " --debug, -d Turn on debugging\n"
200 "\n"
201 "Speaker process for DisOrder. Not intended to be run\n"
202 "directly.\n");
203 xfclose(stdout);
204 exit(0);
205}
206
207/* Display version number and terminate. */
208static void version(void) {
209 xprintf("disorder-speaker version %s\n", disorder_version_string);
210 xfclose(stdout);
211 exit(0);
212}
213
214/** @brief Return the number of bytes per frame in @p format */
215static size_t bytes_per_frame(const ao_sample_format *format) {
216 return format->channels * format->bits / 8;
217}
218
219/** @brief Find track @p id, maybe creating it if not found */
220static struct track *findtrack(const char *id, int create) {
221 struct track *t;
222
223 D(("findtrack %s %d", id, create));
224 for(t = tracks; t && strcmp(id, t->id); t = t->next)
225 ;
226 if(!t && create) {
227 t = xmalloc(sizeof *t);
228 t->next = tracks;
229 strcpy(t->id, id);
230 t->fd = -1;
231 tracks = t;
232 /* The initial input buffer will be the sample format. */
233 t->buffer = (void *)&t->format;
234 t->size = sizeof t->format;
235 }
236 return t;
237}
238
239/** @brief Remove track @p id (but do not destroy it) */
240static struct track *removetrack(const char *id) {
241 struct track *t, **tt;
242
243 D(("removetrack %s", id));
244 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
245 ;
246 if(t)
247 *tt = t->next;
248 return t;
249}
250
251/** @brief Destroy a track */
252static void destroy(struct track *t) {
253 D(("destroy %s", t->id));
254 if(t->fd != -1) xclose(t->fd);
255 if(t->buffer != (void *)&t->format) free(t->buffer);
256 free(t);
257}
258
259/** @brief Notice a new connection */
260static void acquire(struct track *t, int fd) {
261 D(("acquire %s %d", t->id, fd));
262 if(t->fd != -1)
263 xclose(t->fd);
264 t->fd = fd;
265 nonblock(fd);
266}
267
268/** @brief Return true if A and B denote identical libao formats, else false */
269static int formats_equal(const ao_sample_format *a,
270 const ao_sample_format *b) {
271 return (a->bits == b->bits
272 && a->rate == b->rate
273 && a->channels == b->channels
274 && a->byte_format == b->byte_format);
275}
276
277/** @brief Compute arguments to sox */
278static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
279 int n;
280
281 *(*pp)++ = "-t.raw";
282 *(*pp)++ = "-s";
283 *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
284 *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
285 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
286 * deployed! */
287 switch(config->sox_generation) {
288 case 0:
289 if(ao->bits != 8
290 && ao->byte_format != AO_FMT_NATIVE
291 && ao->byte_format != MACHINE_AO_FMT) {
292 *(*pp)++ = "-x";
293 }
294 switch(ao->bits) {
295 case 8: *(*pp)++ = "-b"; break;
296 case 16: *(*pp)++ = "-w"; break;
297 case 32: *(*pp)++ = "-l"; break;
298 case 64: *(*pp)++ = "-d"; break;
299 default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
300 }
301 break;
302 case 1:
303 switch(ao->byte_format) {
304 case AO_FMT_NATIVE: break;
305 case AO_FMT_BIG: *(*pp)++ = "-B"; break;
306 case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
307 }
308 *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
309 break;
310 }
311}
312
313/** @brief Enable format translation
314 *
315 * If necessary, replaces a tracks inbound file descriptor with one connected
316 * to a sox invocation, which performs the required translation.
317 */
318static void enable_translation(struct track *t) {
319 if((backend->flags & FIXED_FORMAT)
320 && !formats_equal(&t->format, &config->sample_format)) {
321 char argbuf[1024], *q = argbuf;
322 const char *av[18], **pp = av;
323 int soxpipe[2];
324 pid_t soxkid;
325
326 *pp++ = "sox";
327 soxargs(&pp, &q, &t->format);
328 *pp++ = "-";
329 soxargs(&pp, &q, &config->sample_format);
330 *pp++ = "-";
331 *pp++ = 0;
332 if(debugging) {
333 for(pp = av; *pp; pp++)
334 D(("sox arg[%d] = %s", pp - av, *pp));
335 D(("end args"));
336 }
337 xpipe(soxpipe);
338 soxkid = xfork();
339 if(soxkid == 0) {
340 signal(SIGPIPE, SIG_DFL);
341 xdup2(t->fd, 0);
342 xdup2(soxpipe[1], 1);
343 fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
344 close(soxpipe[0]);
345 close(soxpipe[1]);
346 close(t->fd);
347 execvp("sox", (char **)av);
348 _exit(1);
349 }
350 D(("forking sox for format conversion (kid = %d)", soxkid));
351 close(t->fd);
352 close(soxpipe[1]);
353 t->fd = soxpipe[0];
354 t->format = config->sample_format;
355 }
356}
357
358/** @brief Read data into a sample buffer
359 * @param t Pointer to track
360 * @return 0 on success, -1 on EOF
361 *
362 * This is effectively the read callback on @c t->fd. It is called from the
363 * main loop whenever the track's file descriptor is readable, assuming the
364 * buffer has not reached the maximum allowed occupancy.
365 */
366static int fill(struct track *t) {
367 size_t where, left;
368 int n;
369
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;
376 if(t->got_format) {
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;
380 } else
381 /* We are still waiting for the format, only get that */
382 left = sizeof (ao_sample_format) - t->used;
383 do {
384 n = read(t->fd, t->buffer + where, left);
385 } while(n < 0 && errno == EINTR);
386 if(n < 0) {
387 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
388 return 0;
389 }
390 if(n == 0) {
391 D(("fill %s: eof detected", t->id));
392 t->eof = 1;
393 return -1;
394 }
395 t->used += n;
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);
406 t->used = 0;
407 t->got_format = 1;
408 D(("got format for %s", t->id));
409 }
410 }
411 return 0;
412}
413
414/** @brief Close the sound device
415 *
416 * This is called to deactivate the output device when pausing, and also by the
417 * ALSA backend when changing encoding (in which case the sound device will be
418 * immediately reactivated).
419 */
420static void idle(void) {
421 D(("idle"));
422 if(backend->deactivate)
423 backend->deactivate();
424 idled = 1;
425 ready = 0;
426}
427
428/** @brief Abandon the current track */
429static void abandon(void) {
430 struct speaker_message sm;
431
432 D(("abandon"));
433 memset(&sm, 0, sizeof sm);
434 sm.type = SM_FINISHED;
435 strcpy(sm.id, playing->id);
436 speaker_send(1, &sm, 0);
437 removetrack(playing->id);
438 destroy(playing);
439 playing = 0;
440 forceplay = 0;
441}
442
443#if API_ALSA
444/** @brief Log ALSA parameters */
445static void log_params(snd_pcm_hw_params_t *hwparams,
446 snd_pcm_sw_params_t *swparams) {
447 snd_pcm_uframes_t f;
448 unsigned u;
449
450 return; /* too verbose */
451 if(hwparams) {
452 /* TODO */
453 }
454 if(swparams) {
455 snd_pcm_sw_params_get_silence_size(swparams, &f);
456 info("sw silence_size=%lu", (unsigned long)f);
457 snd_pcm_sw_params_get_silence_threshold(swparams, &f);
458 info("sw silence_threshold=%lu", (unsigned long)f);
459 snd_pcm_sw_params_get_sleep_min(swparams, &u);
460 info("sw sleep_min=%lu", (unsigned long)u);
461 snd_pcm_sw_params_get_start_threshold(swparams, &f);
462 info("sw start_threshold=%lu", (unsigned long)f);
463 snd_pcm_sw_params_get_stop_threshold(swparams, &f);
464 info("sw stop_threshold=%lu", (unsigned long)f);
465 snd_pcm_sw_params_get_xfer_align(swparams, &f);
466 info("sw xfer_align=%lu", (unsigned long)f);
467 }
468}
469#endif
470
471/** @brief Enable sound output
472 *
473 * Makes sure the sound device is open and has the right sample format. Return
474 * 0 on success and -1 on error.
475 */
476static int activate(void) {
477 /* If we don't know the format yet we cannot start. */
478 if(!playing->got_format) {
479 D((" - not got format for %s", playing->id));
480 return -1;
481 }
482 return backend->activate();
483}
484
485/** @brief Check whether the current track has finished
486 *
487 * The current track is determined to have finished either if the input stream
488 * eded before the format could be determined (i.e. it is malformed) or the
489 * input is at end of file and there is less than a frame left unplayed. (So
490 * it copes with decoders that crash mid-frame.)
491 */
492static void maybe_finished(void) {
493 if(playing
494 && playing->eof
495 && (!playing->got_format
496 || playing->used < bytes_per_frame(&playing->format)))
497 abandon();
498}
499
500/** @brief Start the subprocess for @ref BACKEND_COMMAND */
501static void fork_cmd(void) {
502 pid_t cmdpid;
503 int pfd[2];
504 if(cmdfd != -1) close(cmdfd);
505 xpipe(pfd);
506 cmdpid = xfork();
507 if(!cmdpid) {
508 signal(SIGPIPE, SIG_DFL);
509 xdup2(pfd[0], 0);
510 close(pfd[0]);
511 close(pfd[1]);
512 execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
513 fatal(errno, "error execing /bin/sh");
514 }
515 close(pfd[0]);
516 cmdfd = pfd[1];
517 D(("forked cmd %d, fd = %d", cmdpid, cmdfd));
518}
519
520/** @brief Play up to @p frames frames of audio */
521static void play(size_t frames) {
522 size_t avail_frames, avail_bytes, written_frames;
523 ssize_t written_bytes;
524
525 /* Make sure the output device is activated */
526 if(activate()) {
527 if(playing)
528 forceplay = frames;
529 else
530 forceplay = 0; /* Must have called abandon() */
531 return;
532 }
533 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
534 playing->eof ? " EOF" : "",
535 playing->format.rate,
536 playing->format.bits,
537 playing->format.channels));
538 /* If we haven't got enough bytes yet wait until we have. Exception: when
539 * we are at eof. */
540 if(playing->used < frames * bpf && !playing->eof) {
541 forceplay = frames;
542 return;
543 }
544 /* We have got enough data so don't force play again */
545 forceplay = 0;
546 /* Figure out how many frames there are available to write */
547 if(playing->start + playing->used > playing->size)
548 /* The ring buffer is currently wrapped, only play up to the wrap point */
549 avail_bytes = playing->size - playing->start;
550 else
551 /* The ring buffer is not wrapped, can play the lot */
552 avail_bytes = playing->used;
553 avail_frames = avail_bytes / bpf;
554 /* Only play up to the requested amount */
555 if(avail_frames > frames)
556 avail_frames = frames;
557 if(!avail_frames)
558 return;
559 /* Play it, Sam */
560 written_frames = backend->play(avail_frames);
561 written_bytes = written_frames * bpf;
562 /* written_bytes and written_frames had better both be set and correct by
563 * this point */
564 playing->start += written_bytes;
565 playing->used -= written_bytes;
566 playing->played += written_frames;
567 /* If the pointer is at the end of the buffer (or the buffer is completely
568 * empty) wrap it back to the start. */
569 if(!playing->used || playing->start == playing->size)
570 playing->start = 0;
571 frames -= written_frames;
572}
573
574/* Notify the server what we're up to. */
575static void report(void) {
576 struct speaker_message sm;
577
578 if(playing && playing->buffer != (void *)&playing->format) {
579 memset(&sm, 0, sizeof sm);
580 sm.type = paused ? SM_PAUSED : SM_PLAYING;
581 strcpy(sm.id, playing->id);
582 sm.data = playing->played / playing->format.rate;
583 speaker_send(1, &sm, 0);
584 }
585 time(&last_report);
586}
587
588static void reap(int __attribute__((unused)) sig) {
589 pid_t cmdpid;
590 int st;
591
592 do
593 cmdpid = waitpid(-1, &st, WNOHANG);
594 while(cmdpid > 0);
595 signal(SIGCHLD, reap);
596}
597
598static int addfd(int fd, int events) {
599 if(fdno < NFDS) {
600 fds[fdno].fd = fd;
601 fds[fdno].events = events;
602 return fdno++;
603 } else
604 return -1;
605}
606
607#if API_ALSA
608/** @brief ALSA backend initialization */
609static void alsa_init(void) {
610 info("selected ALSA backend");
611}
612
613/** @brief ALSA backend activation */
614static int alsa_activate(void) {
615 /* If we need to change format then close the current device. */
616 if(pcm && !formats_equal(&playing->format, &pcm_format))
617 idle();
618 if(!pcm) {
619 snd_pcm_hw_params_t *hwparams;
620 snd_pcm_sw_params_t *swparams;
621 snd_pcm_uframes_t pcm_bufsize;
622 int err;
623 int sample_format = 0;
624 unsigned rate;
625
626 D(("snd_pcm_open"));
627 if((err = snd_pcm_open(&pcm,
628 config->device,
629 SND_PCM_STREAM_PLAYBACK,
630 SND_PCM_NONBLOCK))) {
631 error(0, "error from snd_pcm_open: %d", err);
632 goto error;
633 }
634 snd_pcm_hw_params_alloca(&hwparams);
635 D(("set up hw params"));
636 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
637 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
638 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
639 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
640 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
641 switch(playing->format.bits) {
642 case 8:
643 sample_format = SND_PCM_FORMAT_S8;
644 break;
645 case 16:
646 switch(playing->format.byte_format) {
647 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
648 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
649 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
650 error(0, "unrecognized byte format %d", playing->format.byte_format);
651 goto fatal;
652 }
653 break;
654 default:
655 error(0, "unsupported sample size %d", playing->format.bits);
656 goto fatal;
657 }
658 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
659 sample_format)) < 0) {
660 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
661 sample_format, err);
662 goto fatal;
663 }
664 rate = playing->format.rate;
665 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
666 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
667 playing->format.rate, err);
668 goto fatal;
669 }
670 if(rate != (unsigned)playing->format.rate)
671 info("want rate %d, got %u", playing->format.rate, rate);
672 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
673 playing->format.channels)) < 0) {
674 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
675 playing->format.channels, err);
676 goto fatal;
677 }
678 bufsize = 3 * FRAMES;
679 pcm_bufsize = bufsize;
680 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
681 &pcm_bufsize)) < 0)
682 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
683 3 * FRAMES, err);
684 if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
685 info("asked for PCM buffer of %d frames, got %d",
686 3 * FRAMES, (int)pcm_bufsize);
687 last_pcm_bufsize = pcm_bufsize;
688 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
689 fatal(0, "error calling snd_pcm_hw_params: %d", err);
690 D(("set up sw params"));
691 snd_pcm_sw_params_alloca(&swparams);
692 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
693 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
694 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
695 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
696 FRAMES, err);
697 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
698 fatal(0, "error calling snd_pcm_sw_params: %d", err);
699 pcm_format = playing->format;
700 bpf = bytes_per_frame(&pcm_format);
701 D(("acquired audio device"));
702 log_params(hwparams, swparams);
703 ready = 1;
704 }
705 return 0;
706fatal:
707 abandon();
708error:
709 /* We assume the error is temporary and that we'll retry in a bit. */
710 if(pcm) {
711 snd_pcm_close(pcm);
712 pcm = 0;
713 }
714 return -1;
715}
716
717/** @brief Play via ALSA */
718static size_t alsa_play(size_t frames) {
719 snd_pcm_sframes_t pcm_written_frames;
720 int err;
721
722 pcm_written_frames = snd_pcm_writei(pcm,
723 playing->buffer + playing->start,
724 frames);
725 D(("actually play %zu frames, wrote %d",
726 frames, (int)pcm_written_frames));
727 if(pcm_written_frames < 0) {
728 switch(pcm_written_frames) {
729 case -EPIPE: /* underrun */
730 error(0, "snd_pcm_writei reports underrun");
731 if((err = snd_pcm_prepare(pcm)) < 0)
732 fatal(0, "error calling snd_pcm_prepare: %d", err);
733 return 0;
734 case -EAGAIN:
735 return 0;
736 default:
737 fatal(0, "error calling snd_pcm_writei: %d",
738 (int)pcm_written_frames);
739 }
740 } else
741 return pcm_written_frames;
742}
743
744static int alsa_slots, alsa_nslots = -1;
745
746/** @brief Fill in poll fd array for ALSA */
747static void alsa_beforepoll(void) {
748 /* We send sample data to ALSA as fast as it can accept it, relying on
749 * the fact that it has a relatively small buffer to minimize pause
750 * latency. */
751 int retry = 3, err;
752
753 alsa_slots = fdno;
754 do {
755 retry = 0;
756 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
757 if((alsa_nslots <= 0
758 || !(fds[alsa_slots].events & POLLOUT))
759 && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
760 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
761 if((err = snd_pcm_prepare(pcm)))
762 fatal(0, "error calling snd_pcm_prepare: %d", err);
763 } else
764 break;
765 } while(retry-- > 0);
766 if(alsa_nslots >= 0)
767 fdno += alsa_nslots;
768}
769
770/** @brief Process poll() results for ALSA */
771static int alsa_afterpoll(void) {
772 int err;
773
774 if(alsa_slots != -1) {
775 unsigned short alsa_revents;
776
777 if((err = snd_pcm_poll_descriptors_revents(pcm,
778 &fds[alsa_slots],
779 alsa_nslots,
780 &alsa_revents)) < 0)
781 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
782 if(alsa_revents & (POLLOUT | POLLERR))
783 play(3 * FRAMES);
784 return 0;
785 } else
786 return 1;
787}
788
789/** @brief ALSA deactivation */
790static void alsa_deactivate(void) {
791 if(pcm) {
792 int err;
793
794 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
795 fatal(0, "error calling snd_pcm_nonblock: %d", err);
796 D(("draining pcm"));
797 snd_pcm_drain(pcm);
798 D(("closing pcm"));
799 snd_pcm_close(pcm);
800 pcm = 0;
801 forceplay = 0;
802 D(("released audio device"));
803 }
804}
805#endif
806
807/** @brief Command backend initialization */
808static void command_init(void) {
809 info("selected command backend");
810 fork_cmd();
811}
812
813/** @brief Play to a subprocess */
814static size_t command_play(size_t frames) {
815 size_t bytes = frames * bpf;
816 int written_bytes;
817
818 written_bytes = write(cmdfd, playing->buffer + playing->start, bytes);
819 D(("actually play %zu bytes, wrote %d",
820 bytes, written_bytes));
821 if(written_bytes < 0) {
822 switch(errno) {
823 case EPIPE:
824 error(0, "hmm, command died; trying another");
825 fork_cmd();
826 return 0;
827 case EAGAIN:
828 return 0;
829 default:
830 fatal(errno, "error writing to subprocess");
831 }
832 } else
833 return written_bytes / bpf;
834}
835
836static int cmdfd_slot;
837
838/** @brief Update poll array for writing to subprocess */
839static void command_beforepoll(void) {
840 /* We send sample data to the subprocess as fast as it can accept it.
841 * This isn't ideal as pause latency can be very high as a result. */
842 if(cmdfd >= 0)
843 cmdfd_slot = addfd(cmdfd, POLLOUT);
844}
845
846/** @brief Process poll() results for subprocess play */
847static int command_afterpoll(void) {
848 if(cmdfd_slot != -1) {
849 if(fds[cmdfd_slot].revents & (POLLOUT | POLLERR))
850 play(3 * FRAMES);
851 return 0;
852 } else
853 return -1;
854}
855
856/** @brief Command/network backend activation */
857static int generic_activate(void) {
858 if(!ready) {
859 bufsize = 3 * FRAMES;
860 bpf = bytes_per_frame(&config->sample_format);
861 D(("acquired audio device"));
862 ready = 1;
863 }
864 return 0;
865}
866
867/** @brief Network backend initialization */
868static void network_init(void) {
869 struct addrinfo *res, *sres;
870 static const struct addrinfo pref = {
871 0,
872 PF_INET,
873 SOCK_DGRAM,
874 IPPROTO_UDP,
875 0,
876 0,
877 0,
878 0
879 };
880 static const struct addrinfo prefbind = {
881 AI_PASSIVE,
882 PF_INET,
883 SOCK_DGRAM,
884 IPPROTO_UDP,
885 0,
886 0,
887 0,
888 0
889 };
890 static const int one = 1;
891 int sndbuf, target_sndbuf = 131072;
892 socklen_t len;
893 char *sockname, *ssockname;
894
895 res = get_address(&config->broadcast, &pref, &sockname);
896 if(!res) exit(-1);
897 if(config->broadcast_from.n) {
898 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
899 if(!sres) exit(-1);
900 } else
901 sres = 0;
902 if((bfd = socket(res->ai_family,
903 res->ai_socktype,
904 res->ai_protocol)) < 0)
905 fatal(errno, "error creating broadcast socket");
906 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
907 fatal(errno, "error setting SO_BROADCAST on broadcast socket");
908 len = sizeof sndbuf;
909 if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
910 &sndbuf, &len) < 0)
911 fatal(errno, "error getting SO_SNDBUF");
912 if(target_sndbuf > sndbuf) {
913 if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
914 &target_sndbuf, sizeof target_sndbuf) < 0)
915 error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
916 else
917 info("changed socket send buffer size from %d to %d",
918 sndbuf, target_sndbuf);
919 } else
920 info("default socket send buffer is %d",
921 sndbuf);
922 /* We might well want to set additional broadcast- or multicast-related
923 * options here */
924 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
925 fatal(errno, "error binding broadcast socket to %s", ssockname);
926 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
927 fatal(errno, "error connecting broadcast socket to %s", sockname);
928 /* Select an SSRC */
929 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
930 info("selected network backend, sending to %s", sockname);
931 if(config->sample_format.byte_format != AO_FMT_BIG) {
932 info("forcing big-endian sample format");
933 config->sample_format.byte_format = AO_FMT_BIG;
934 }
935}
936
937/** @brief Play over the network */
938static size_t network_play(size_t frames) {
939 struct rtp_header header;
940 struct iovec vec[2];
941 size_t bytes = frames * bpf, written_frames;
942 int written_bytes;
943 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
944 * AVT profile (RFC3551). */
945
946 if(idled) {
947 /* There may have been a gap. Fix up the RTP time accordingly. */
948 struct timeval now;
949 uint64_t delta;
950 uint64_t target_rtp_time;
951
952 /* Find the current time */
953 xgettimeofday(&now, 0);
954 /* Find the number of microseconds elapsed since rtp_time=0 */
955 delta = tvsub_us(now, rtp_time_0);
956 assert(delta <= UINT64_MAX / 88200);
957 target_rtp_time = (delta * playing->format.rate
958 * playing->format.channels) / 1000000;
959 /* Overflows at ~6 years uptime with 44100Hz stereo */
960
961 /* rtp_time is the number of samples we've played. NB that we play
962 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
963 * the value we deduce from time comparison.
964 *
965 * Suppose we have 1s track started at t=0, and another track begins to
966 * play at t=2s. Suppose RTP_AHEAD_MS=1000 and 44100Hz stereo. In that
967 * case we'll send 1s of audio as fast as we can, giving rtp_time=88200.
968 * rtp_time stops at this point.
969 *
970 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
971 * set rtp_time=176400 and the player can correctly conclude that it
972 * should leave 1s between the tracks.
973 *
974 * Suppose instead that the second track arrives at t=0.5s, and that
975 * we've managed to transmit the whole of the first track already. We'll
976 * have target_rtp_time=44100.
977 *
978 * The desired behaviour is to play the second track back to back with
979 * first. In this case therefore we do not modify rtp_time.
980 *
981 * Is it ever right to reduce rtp_time? No; for that would imply
982 * transmitting packets with overlapping timestamp ranges, which does not
983 * make sense.
984 */
985 if(target_rtp_time > rtp_time) {
986 /* More time has elapsed than we've transmitted samples. That implies
987 * we've been 'sending' silence. */
988 info("advancing rtp_time by %"PRIu64" samples",
989 target_rtp_time - rtp_time);
990 rtp_time = target_rtp_time;
991 } else if(target_rtp_time < rtp_time) {
992 const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
993 * config->sample_format.rate
994 * config->sample_format.channels
995 / 1000);
996
997 if(target_rtp_time + samples_ahead < rtp_time) {
998 info("reversing rtp_time by %"PRIu64" samples",
999 rtp_time - target_rtp_time);
1000 }
1001 }
1002 }
1003 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
1004 header.seq = htons(rtp_seq++);
1005 header.timestamp = htonl((uint32_t)rtp_time);
1006 header.ssrc = rtp_id;
1007 header.mpt = (idled ? 0x80 : 0x00) | 10;
1008 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
1009 * the sample rate (in a library somewhere so that configuration.c can rule
1010 * out invalid rates).
1011 */
1012 idled = 0;
1013 if(bytes > NETWORK_BYTES - sizeof header) {
1014 bytes = NETWORK_BYTES - sizeof header;
1015 /* Always send a whole number of frames */
1016 bytes -= bytes % bpf;
1017 }
1018 /* "The RTP clock rate used for generating the RTP timestamp is independent
1019 * of the number of channels and the encoding; it equals the number of
1020 * sampling periods per second. For N-channel encodings, each sampling
1021 * period (say, 1/8000 of a second) generates N samples. (This terminology
1022 * is standard, but somewhat confusing, as the total number of samples
1023 * generated per second is then the sampling rate times the channel
1024 * count.)"
1025 */
1026 vec[0].iov_base = (void *)&header;
1027 vec[0].iov_len = sizeof header;
1028 vec[1].iov_base = playing->buffer + playing->start;
1029 vec[1].iov_len = bytes;
1030 do {
1031 written_bytes = writev(bfd, vec, 2);
1032 } while(written_bytes < 0 && errno == EINTR);
1033 if(written_bytes < 0) {
1034 error(errno, "error transmitting audio data");
1035 ++audio_errors;
1036 if(audio_errors == 10)
1037 fatal(0, "too many audio errors");
1038 return 0;
1039 } else
1040 audio_errors /= 2;
1041 written_bytes -= sizeof (struct rtp_header);
1042 written_frames = written_bytes / bpf;
1043 /* Advance RTP's notion of the time */
1044 rtp_time += written_frames * playing->format.channels;
1045 return written_frames;
1046}
1047
1048static int bfd_slot;
1049
1050/** @brief Set up poll array for network play */
1051static void network_beforepoll(void) {
1052 struct timeval now;
1053 uint64_t target_us;
1054 uint64_t target_rtp_time;
1055 const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
1056 * config->sample_format.rate
1057 * config->sample_format.channels
1058 / 1000);
1059
1060 /* If we're starting then initialize the base time */
1061 if(!rtp_time)
1062 xgettimeofday(&rtp_time_0, 0);
1063 /* We send audio data whenever we get RTP_AHEAD seconds or more
1064 * behind */
1065 xgettimeofday(&now, 0);
1066 target_us = tvsub_us(now, rtp_time_0);
1067 assert(target_us <= UINT64_MAX / 88200);
1068 target_rtp_time = (target_us * config->sample_format.rate
1069 * config->sample_format.channels)
1070 / 1000000;
1071 if((int64_t)(rtp_time - target_rtp_time) < samples_ahead)
1072 bfd_slot = addfd(bfd, POLLOUT);
1073}
1074
1075/** @brief Process poll() results for network play */
1076static int network_afterpoll(void) {
1077 if(bfd_slot != -1) {
1078 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
1079 play(3 * FRAMES);
1080 return 0;
1081 } else
1082 return 1;
1083}
1084
1085/** @brief Table of speaker backends */
1086static const struct speaker_backend backends[] = {
1087#if API_ALSA
1088 {
1089 BACKEND_ALSA,
1090 0,
1091 alsa_init,
1092 alsa_activate,
1093 alsa_play,
1094 alsa_deactivate,
1095 alsa_beforepoll,
1096 alsa_afterpoll
1097 },
1098#endif
1099 {
1100 BACKEND_COMMAND,
1101 FIXED_FORMAT,
1102 command_init,
1103 generic_activate,
1104 command_play,
1105 0, /* deactivate */
1106 command_beforepoll,
1107 command_afterpoll
1108 },
1109 {
1110 BACKEND_NETWORK,
1111 FIXED_FORMAT,
1112 network_init,
1113 generic_activate,
1114 network_play,
1115 0, /* deactivate */
1116 network_beforepoll,
1117 network_afterpoll
1118 },
1119 { -1, 0, 0, 0, 0, 0, 0, 0 } /* end of list */
1120};
1121
1122/** @brief Main event loop
1123 *
1124 * This has grown in a rather bizarre and ad-hoc way is very sensitive to
1125 * changes...
1126 *
1127 * Firstly the loop is terminated when the parent process exits. Therefore the
1128 * speaker process has the same lifetime as the main server. This and the
1129 * reading of data from decoders is comprehensible enough.
1130 *
1131 * The playing of audio is more complicated however.
1132 *
1133 * On the first run through when a track is ready to be played, @ref ready and
1134 * @ref forceplay will both be zero. Therefore @c beforepoll is not called.
1135 *
1136 * @c afterpoll on the other hand @b is called and will return nonzero. The
1137 * result is that we call @c play(0). This will call activate(), setting
1138 * @ref ready nonzero, but otherwise has no immediate effect.
1139 *
1140 * We then deal with stdin and the decoders.
1141 *
1142 * We then reach the second place we might play some audio. @ref forceplay is
1143 * 0 so nothing happens here again.
1144 *
1145 * On the next iteration through however @ref ready is nonzero, and @ref
1146 * forceplay is 0, so we call @c beforepoll. After the @c poll() we call @c
1147 * afterpoll and actually get some audio played.
1148 *
1149 * This is surely @b far more complicated than it needs to be!
1150 *
1151 * If at any call to play(), activate() fails, or if there aren't enough bytes
1152 * in the buffer to satisfy the request, then @ref forceplay is set non-0. On
1153 * the next pass through the event loop @c beforepoll is not called. This
1154 * means that (if none of the other FDs trigger) the @c poll() call will block
1155 * for up to a second. @c afterpoll will return nonzero, since @c beforepoll
1156 * wasn't called, and consequently play() is called with @ref forceplay as its
1157 * argument.
1158 *
1159 * The effect is to attempt to restart playing audio - including the activate()
1160 * step, which may have failed at the previous attempt - at least once a second
1161 * after an error has disabled it. The delay prevents busy-waiting on whatever
1162 * condition has rendered the audio device uncooperative.
1163 */
1164static void mainloop(void) {
1165 struct track *t;
1166 struct speaker_message sm;
1167 int n, fd, stdin_slot, poke, timeout;
1168
1169 while(getppid() != 1) {
1170 fdno = 0;
1171 /* Always ready for commands from the main server. */
1172 stdin_slot = addfd(0, POLLIN);
1173 /* Try to read sample data for the currently playing track if there is
1174 * buffer space. */
1175 if(playing && !playing->eof && playing->used < playing->size) {
1176 playing->slot = addfd(playing->fd, POLLIN);
1177 } else if(playing)
1178 playing->slot = -1;
1179 /* If forceplay is set then wait until it succeeds before waiting on the
1180 * sound device. */
1181#if API_ALSA
1182 alsa_slots = -1;
1183#endif
1184 cmdfd_slot = -1;
1185 bfd_slot = -1;
1186 /* By default we will wait up to a second before thinking about current
1187 * state. */
1188 timeout = 1000;
1189 /* We'll break the poll as soon as the underlying sound device is ready for
1190 * more data */
1191 if(ready && !forceplay)
1192 backend->beforepoll();
1193 /* If any other tracks don't have a full buffer, try to read sample data
1194 * from them. */
1195 for(t = tracks; t; t = t->next)
1196 if(t != playing) {
1197 if(!t->eof && t->used < t->size) {
1198 t->slot = addfd(t->fd, POLLIN | POLLHUP);
1199 } else
1200 t->slot = -1;
1201 }
1202 /* Wait for something interesting to happen */
1203 n = poll(fds, fdno, timeout);
1204 if(n < 0) {
1205 if(errno == EINTR) continue;
1206 fatal(errno, "error calling poll");
1207 }
1208 /* Play some sound before doing anything else */
1209 poke = backend->afterpoll();
1210 if(poke) {
1211 /* Some attempt to play must have failed */
1212 if(playing && !paused)
1213 play(forceplay);
1214 else
1215 forceplay = 0; /* just in case */
1216 }
1217 /* Perhaps we have a command to process */
1218 if(fds[stdin_slot].revents & POLLIN) {
1219 n = speaker_recv(0, &sm, &fd);
1220 if(n > 0)
1221 switch(sm.type) {
1222 case SM_PREPARE:
1223 D(("SM_PREPARE %s %d", sm.id, fd));
1224 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
1225 t = findtrack(sm.id, 1);
1226 acquire(t, fd);
1227 break;
1228 case SM_PLAY:
1229 D(("SM_PLAY %s %d", sm.id, fd));
1230 if(playing) fatal(0, "got SM_PLAY but already playing something");
1231 t = findtrack(sm.id, 1);
1232 if(fd != -1) acquire(t, fd);
1233 playing = t;
1234 play(bufsize);
1235 report();
1236 break;
1237 case SM_PAUSE:
1238 D(("SM_PAUSE"));
1239 paused = 1;
1240 report();
1241 break;
1242 case SM_RESUME:
1243 D(("SM_RESUME"));
1244 if(paused) {
1245 paused = 0;
1246 if(playing)
1247 play(bufsize);
1248 }
1249 report();
1250 break;
1251 case SM_CANCEL:
1252 D(("SM_CANCEL %s", sm.id));
1253 t = removetrack(sm.id);
1254 if(t) {
1255 if(t == playing) {
1256 sm.type = SM_FINISHED;
1257 strcpy(sm.id, playing->id);
1258 speaker_send(1, &sm, 0);
1259 playing = 0;
1260 }
1261 destroy(t);
1262 } else
1263 error(0, "SM_CANCEL for unknown track %s", sm.id);
1264 report();
1265 break;
1266 case SM_RELOAD:
1267 D(("SM_RELOAD"));
1268 if(config_read()) error(0, "cannot read configuration");
1269 info("reloaded configuration");
1270 break;
1271 default:
1272 error(0, "unknown message type %d", sm.type);
1273 }
1274 }
1275 /* Read in any buffered data */
1276 for(t = tracks; t; t = t->next)
1277 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
1278 fill(t);
1279 /* We might be able to play now */
1280 if(ready && forceplay && playing && !paused)
1281 play(forceplay);
1282 /* Maybe we finished playing a track somewhere in the above */
1283 maybe_finished();
1284 /* If we don't need the sound device for now then close it for the benefit
1285 * of anyone else who wants it. */
1286 if((!playing || paused) && ready)
1287 idle();
1288 /* If we've not reported out state for a second do so now. */
1289 if(time(0) > last_report)
1290 report();
1291 }
1292}
1293
1294int main(int argc, char **argv) {
1295 int n;
1296
1297 set_progname(argv);
1298 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
1299 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
1300 switch(n) {
1301 case 'h': help();
1302 case 'V': version();
1303 case 'c': configfile = optarg; break;
1304 case 'd': debugging = 1; break;
1305 case 'D': debugging = 0; break;
1306 default: fatal(0, "invalid option");
1307 }
1308 }
1309 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
1310 /* If stderr is a TTY then log there, otherwise to syslog. */
1311 if(!isatty(2)) {
1312 openlog(progname, LOG_PID, LOG_DAEMON);
1313 log_default = &log_syslog;
1314 }
1315 if(config_read()) fatal(0, "cannot read configuration");
1316 /* ignore SIGPIPE */
1317 signal(SIGPIPE, SIG_IGN);
1318 /* reap kids */
1319 signal(SIGCHLD, reap);
1320 /* set nice value */
1321 xnice(config->nice_speaker);
1322 /* change user */
1323 become_mortal();
1324 /* make sure we're not root, whatever the config says */
1325 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
1326 /* identify the backend used to play */
1327 for(n = 0; backends[n].backend != -1; ++n)
1328 if(backends[n].backend == config->speaker_backend)
1329 break;
1330 if(backends[n].backend == -1)
1331 fatal(0, "unsupported backend %d", config->speaker_backend);
1332 backend = &backends[n];
1333 /* backend-specific initialization */
1334 backend->init();
1335 mainloop();
1336 info("stopped (parent terminated)");
1337 exit(0);
1338}
1339
1340/*
1341Local Variables:
1342c-basic-offset:2
1343comment-column:40
1344fill-column:79
1345indent-tabs-mode:nil
1346End:
1347*/