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