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