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