chiark / gitweb /
Install disorderd under launchd in Mac OS X.
[disorder] / server / speaker.c
CommitLineData
460b9539 1/*
2 * This file is part of DisOrder
dea8f8aa 3 * Copyright (C) 2005, 2006, 2007 Richard Kettlewell
460b9539 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
21/* This program deliberately does not use the garbage collector even though it
22 * might be convenient to do so. This is for two reasons. Firstly some libao
23 * drivers are implemented using threads and we do not want to have to deal
24 * with potential interactions between threading and garbage collection.
25 * Secondly this process needs to be able to respond quickly and this is not
26 * compatible with the collector hanging the program even relatively
27 * briefly. */
28
29#include <config.h>
30#include "types.h"
31
32#include <getopt.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <locale.h>
36#include <syslog.h>
37#include <unistd.h>
38#include <errno.h>
39#include <ao/ao.h>
40#include <string.h>
41#include <assert.h>
42#include <sys/select.h>
9d5da576 43#include <sys/wait.h>
460b9539 44#include <time.h>
8023f60b 45#include <fcntl.h>
46#include <poll.h>
e83d0967
RK
47#include <sys/socket.h>
48#include <netdb.h>
49#include <gcrypt.h>
50#include <sys/uio.h>
460b9539 51
52#include "configuration.h"
53#include "syscalls.h"
54#include "log.h"
55#include "defs.h"
56#include "mem.h"
57#include "speaker.h"
58#include "user.h"
e83d0967
RK
59#include "addr.h"
60#include "timeval.h"
61#include "rtp.h"
460b9539 62
8023f60b 63#if API_ALSA
dea8f8aa 64#include <alsa/asoundlib.h>
8023f60b 65#endif
dea8f8aa 66
5330d674 67#ifdef WORDS_BIGENDIAN
68# define MACHINE_AO_FMT AO_FMT_BIG
69#else
70# define MACHINE_AO_FMT AO_FMT_LITTLE
71#endif
72
460b9539 73#define BUFFER_SECONDS 5 /* How many seconds of input to
74 * buffer. */
75
76#define FRAMES 4096 /* Frame batch size */
77
e83d0967
RK
78#define NETWORK_BYTES 1024 /* Bytes to send per network packet */
79/* (don't make this too big or arithmetic will start to overflow) */
80
81#define RTP_AHEAD 2 /* Max RTP playahead (seconds) */
82
460b9539 83#define NFDS 256 /* Max FDs to poll for */
84
85/* Known tracks are kept in a linked list. We don't normally to have
86 * more than two - maybe three at the outside. */
87static struct track {
88 struct track *next; /* next track */
89 int fd; /* input FD */
90 char id[24]; /* ID */
91 size_t start, used; /* start + bytes used */
92 int eof; /* input is at EOF */
93 int got_format; /* got format yet? */
94 ao_sample_format format; /* sample format */
95 unsigned long long played; /* number of frames played */
96 char *buffer; /* sample buffer */
97 size_t size; /* sample buffer size */
98 int slot; /* poll array slot */
99} *tracks, *playing; /* all tracks + playing track */
100
101static time_t last_report; /* when we last reported */
102static int paused; /* pause status */
460b9539 103static ao_sample_format pcm_format; /* current format if aodev != 0 */
104static size_t bpf; /* bytes per frame */
105static struct pollfd fds[NFDS]; /* if we need more than that */
106static int fdno; /* fd number */
8023f60b 107static size_t bufsize; /* buffer size */
108#if API_ALSA
109static snd_pcm_t *pcm; /* current pcm handle */
0c207c37 110static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
8023f60b 111#endif
9d5da576 112static int ready; /* ready to send audio */
460b9539 113static int forceplay; /* frames to force play */
e83d0967
RK
114static int cmdfd = -1; /* child process input */
115static int bfd = -1; /* broadcast FD */
116static uint32_t rtp_time; /* RTP timestamp */
117static struct timeval rtp_time_real; /* corresponding real time */
118static uint16_t rtp_seq; /* frame sequence number */
119static uint32_t rtp_id; /* RTP SSRC */
120static int idled; /* set when idled */
121static int audio_errors; /* audio error counter */
460b9539 122
123static const struct option options[] = {
124 { "help", no_argument, 0, 'h' },
125 { "version", no_argument, 0, 'V' },
126 { "config", required_argument, 0, 'c' },
127 { "debug", no_argument, 0, 'd' },
128 { "no-debug", no_argument, 0, 'D' },
129 { 0, 0, 0, 0 }
130};
131
132/* Display usage message and terminate. */
133static void help(void) {
134 xprintf("Usage:\n"
135 " disorder-speaker [OPTIONS]\n"
136 "Options:\n"
137 " --help, -h Display usage message\n"
138 " --version, -V Display version number\n"
139 " --config PATH, -c PATH Set configuration file\n"
140 " --debug, -d Turn on debugging\n"
141 "\n"
142 "Speaker process for DisOrder. Not intended to be run\n"
143 "directly.\n");
144 xfclose(stdout);
145 exit(0);
146}
147
148/* Display version number and terminate. */
149static void version(void) {
150 xprintf("disorder-speaker version %s\n", disorder_version_string);
151 xfclose(stdout);
152 exit(0);
153}
154
155/* Return the number of bytes per frame in FORMAT. */
156static size_t bytes_per_frame(const ao_sample_format *format) {
157 return format->channels * format->bits / 8;
158}
159
160/* Find track ID, maybe creating it if not found. */
161static struct track *findtrack(const char *id, int create) {
162 struct track *t;
163
164 D(("findtrack %s %d", id, create));
165 for(t = tracks; t && strcmp(id, t->id); t = t->next)
166 ;
167 if(!t && create) {
168 t = xmalloc(sizeof *t);
169 t->next = tracks;
170 strcpy(t->id, id);
171 t->fd = -1;
172 tracks = t;
173 /* The initial input buffer will be the sample format. */
174 t->buffer = (void *)&t->format;
175 t->size = sizeof t->format;
176 }
177 return t;
178}
179
180/* Remove track ID (but do not destroy it). */
181static struct track *removetrack(const char *id) {
182 struct track *t, **tt;
183
184 D(("removetrack %s", id));
185 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
186 ;
187 if(t)
188 *tt = t->next;
189 return t;
190}
191
192/* Destroy a track. */
193static void destroy(struct track *t) {
194 D(("destroy %s", t->id));
195 if(t->fd != -1) xclose(t->fd);
196 if(t->buffer != (void *)&t->format) free(t->buffer);
197 free(t);
198}
199
200/* Notice a new FD. */
201static void acquire(struct track *t, int fd) {
202 D(("acquire %s %d", t->id, fd));
203 if(t->fd != -1)
204 xclose(t->fd);
205 t->fd = fd;
206 nonblock(fd);
207}
208
209/* Read data into a sample buffer. Return 0 on success, -1 on EOF. */
210static int fill(struct track *t) {
211 size_t where, left;
212 int n;
213
214 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
215 t->id, t->eof, t->used, t->size, t->got_format));
216 if(t->eof) return -1;
217 if(t->used < t->size) {
218 /* there is room left in the buffer */
219 where = (t->start + t->used) % t->size;
220 if(t->got_format) {
221 /* We are reading audio data, get as much as we can */
222 if(where >= t->start) left = t->size - where;
223 else left = t->start - where;
224 } else
225 /* We are still waiting for the format, only get that */
226 left = sizeof (ao_sample_format) - t->used;
227 do {
228 n = read(t->fd, t->buffer + where, left);
229 } while(n < 0 && errno == EINTR);
230 if(n < 0) {
231 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
232 return 0;
233 }
234 if(n == 0) {
235 D(("fill %s: eof detected", t->id));
236 t->eof = 1;
237 return -1;
238 }
239 t->used += n;
240 if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
241 assert(t->used == sizeof (ao_sample_format));
242 /* Check that our assumptions are met. */
243 if(t->format.bits & 7)
244 fatal(0, "bits per sample not a multiple of 8");
245 /* Make a new buffer for audio data. */
246 t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
247 t->buffer = xmalloc(t->size);
248 t->used = 0;
249 t->got_format = 1;
250 D(("got format for %s", t->id));
251 }
252 }
253 return 0;
254}
255
256/* Return true if A and B denote identical libao formats, else false. */
257static int formats_equal(const ao_sample_format *a,
258 const ao_sample_format *b) {
259 return (a->bits == b->bits
260 && a->rate == b->rate
261 && a->channels == b->channels
262 && a->byte_format == b->byte_format);
263}
264
265/* Close the sound device. */
266static void idle(void) {
460b9539 267 D(("idle"));
8023f60b 268#if API_ALSA
e83d0967 269 if(config->speaker_backend == BACKEND_ALSA && pcm) {
8023f60b 270 int err;
271
460b9539 272 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
273 fatal(0, "error calling snd_pcm_nonblock: %d", err);
274 D(("draining pcm"));
275 snd_pcm_drain(pcm);
276 D(("closing pcm"));
277 snd_pcm_close(pcm);
278 pcm = 0;
279 forceplay = 0;
280 D(("released audio device"));
281 }
8023f60b 282#endif
e83d0967 283 idled = 1;
9d5da576 284 ready = 0;
460b9539 285}
286
287/* Abandon the current track */
288static void abandon(void) {
289 struct speaker_message sm;
290
291 D(("abandon"));
292 memset(&sm, 0, sizeof sm);
293 sm.type = SM_FINISHED;
294 strcpy(sm.id, playing->id);
295 speaker_send(1, &sm, 0);
296 removetrack(playing->id);
297 destroy(playing);
298 playing = 0;
299 forceplay = 0;
300}
301
8023f60b 302#if API_ALSA
1c6e6a61 303static void log_params(snd_pcm_hw_params_t *hwparams,
304 snd_pcm_sw_params_t *swparams) {
305 snd_pcm_uframes_t f;
306 unsigned u;
307
0c207c37 308 return; /* too verbose */
1c6e6a61 309 if(hwparams) {
310 /* TODO */
311 }
312 if(swparams) {
313 snd_pcm_sw_params_get_silence_size(swparams, &f);
314 info("sw silence_size=%lu", (unsigned long)f);
315 snd_pcm_sw_params_get_silence_threshold(swparams, &f);
316 info("sw silence_threshold=%lu", (unsigned long)f);
317 snd_pcm_sw_params_get_sleep_min(swparams, &u);
318 info("sw sleep_min=%lu", (unsigned long)u);
319 snd_pcm_sw_params_get_start_threshold(swparams, &f);
320 info("sw start_threshold=%lu", (unsigned long)f);
321 snd_pcm_sw_params_get_stop_threshold(swparams, &f);
322 info("sw stop_threshold=%lu", (unsigned long)f);
323 snd_pcm_sw_params_get_xfer_align(swparams, &f);
324 info("sw xfer_align=%lu", (unsigned long)f);
325 }
326}
8023f60b 327#endif
1c6e6a61 328
5330d674 329static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
9d5da576 330 int n;
331
332 *(*pp)++ = "-t.raw";
333 *(*pp)++ = "-s";
334 *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
5330d674 335 *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
336 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
337 * deployed! */
338 switch(config->sox_generation) {
339 case 0:
340 if(ao->bits != 8
341 && ao->byte_format != AO_FMT_NATIVE
342 && ao->byte_format != MACHINE_AO_FMT) {
343 *(*pp)++ = "-x";
344 }
345 switch(ao->bits) {
346 case 8: *(*pp)++ = "-b"; break;
347 case 16: *(*pp)++ = "-w"; break;
348 case 32: *(*pp)++ = "-l"; break;
349 case 64: *(*pp)++ = "-d"; break;
350 default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
351 }
352 break;
353 case 1:
354 switch(ao->byte_format) {
9d5da576 355 case AO_FMT_NATIVE: break;
27801653 356 case AO_FMT_BIG: *(*pp)++ = "-B"; break;
357 case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
5330d674 358 }
359 *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
360 break;
9d5da576 361 }
9d5da576 362}
363
460b9539 364/* Make sure the sound device is open and has the right sample format. Return
365 * 0 on success and -1 on error. */
366static int activate(void) {
460b9539 367 /* If we don't know the format yet we cannot start. */
368 if(!playing->got_format) {
369 D((" - not got format for %s", playing->id));
370 return -1;
371 }
e83d0967
RK
372 switch(config->speaker_backend) {
373 case BACKEND_COMMAND:
374 case BACKEND_NETWORK:
375 /* If we pass audio on to some other agent then we enforce the configured
376 * sample format on the *inbound* audio data. */
9d5da576 377 if(!formats_equal(&playing->format, &config->sample_format)) {
378 char argbuf[1024], *q = argbuf;
379 const char *av[18], **pp = av;
380 int soxpipe[2];
381 pid_t soxkid;
382 *pp++ = "sox";
383 soxargs(&pp, &q, &playing->format);
384 *pp++ = "-";
385 soxargs(&pp, &q, &config->sample_format);
386 *pp++ = "-";
387 *pp++ = 0;
388 if(debugging) {
389 for(pp = av; *pp; pp++)
390 D(("sox arg[%d] = %s", pp - av, *pp));
391 D(("end args"));
392 }
393 xpipe(soxpipe);
394 soxkid = xfork();
395 if(soxkid == 0) {
396 xdup2(playing->fd, 0);
397 xdup2(soxpipe[1], 1);
398 fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
399 close(soxpipe[0]);
400 close(soxpipe[1]);
401 close(playing->fd);
402 execvp("sox", (char **)av);
403 _exit(1);
404 }
405 D(("forking sox for format conversion (kid = %d)", soxkid));
406 close(playing->fd);
407 close(soxpipe[1]);
408 playing->fd = soxpipe[0];
409 playing->format = config->sample_format;
410 ready = 0;
411 }
412 if(!ready) {
413 pcm_format = config->sample_format;
8023f60b 414 bufsize = 3 * FRAMES;
9d5da576 415 bpf = bytes_per_frame(&config->sample_format);
416 D(("acquired audio device"));
417 ready = 1;
418 }
419 return 0;
e83d0967 420 case BACKEND_ALSA:
8023f60b 421#if API_ALSA
e83d0967
RK
422 /* If we need to change format then close the current device. */
423 if(pcm && !formats_equal(&playing->format, &pcm_format))
424 idle();
425 if(!pcm) {
426 snd_pcm_hw_params_t *hwparams;
427 snd_pcm_sw_params_t *swparams;
428 snd_pcm_uframes_t pcm_bufsize;
429 int err;
430 int sample_format = 0;
431 unsigned rate;
432
433 D(("snd_pcm_open"));
434 if((err = snd_pcm_open(&pcm,
435 config->device,
436 SND_PCM_STREAM_PLAYBACK,
437 SND_PCM_NONBLOCK))) {
438 error(0, "error from snd_pcm_open: %d", err);
439 goto error;
440 }
441 snd_pcm_hw_params_alloca(&hwparams);
442 D(("set up hw params"));
443 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
444 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
445 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
446 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
447 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
448 switch(playing->format.bits) {
449 case 8:
450 sample_format = SND_PCM_FORMAT_S8;
451 break;
452 case 16:
453 switch(playing->format.byte_format) {
454 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
455 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
456 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
457 error(0, "unrecognized byte format %d", playing->format.byte_format);
458 goto fatal;
459 }
460 break;
461 default:
462 error(0, "unsupported sample size %d", playing->format.bits);
460b9539 463 goto fatal;
464 }
e83d0967
RK
465 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
466 sample_format)) < 0) {
467 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
468 sample_format, err);
469 goto fatal;
470 }
471 rate = playing->format.rate;
472 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
473 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
474 playing->format.rate, err);
475 goto fatal;
476 }
477 if(rate != (unsigned)playing->format.rate)
478 info("want rate %d, got %u", playing->format.rate, rate);
479 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
480 playing->format.channels)) < 0) {
481 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
482 playing->format.channels, err);
483 goto fatal;
484 }
485 bufsize = 3 * FRAMES;
486 pcm_bufsize = bufsize;
487 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
488 &pcm_bufsize)) < 0)
489 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
490 3 * FRAMES, err);
491 if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
492 info("asked for PCM buffer of %d frames, got %d",
493 3 * FRAMES, (int)pcm_bufsize);
494 last_pcm_bufsize = pcm_bufsize;
495 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
496 fatal(0, "error calling snd_pcm_hw_params: %d", err);
497 D(("set up sw params"));
498 snd_pcm_sw_params_alloca(&swparams);
499 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
500 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
501 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
502 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
503 FRAMES, err);
504 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
505 fatal(0, "error calling snd_pcm_sw_params: %d", err);
506 pcm_format = playing->format;
507 bpf = bytes_per_frame(&pcm_format);
508 D(("acquired audio device"));
509 log_params(hwparams, swparams);
510 ready = 1;
460b9539 511 }
e83d0967
RK
512 return 0;
513 fatal:
514 abandon();
515 error:
516 /* We assume the error is temporary and that we'll retry in a bit. */
517 if(pcm) {
518 snd_pcm_close(pcm);
519 pcm = 0;
460b9539 520 }
e83d0967 521 return -1;
8023f60b 522#endif
e83d0967
RK
523 default:
524 assert(!"reached");
525 }
460b9539 526}
527
528/* Check to see whether the current track has finished playing */
529static void maybe_finished(void) {
530 if(playing
531 && playing->eof
532 && (!playing->got_format
533 || playing->used < bytes_per_frame(&playing->format)))
534 abandon();
535}
536
e83d0967
RK
537static void fork_cmd(void) {
538 pid_t cmdpid;
9d5da576 539 int pfd[2];
e83d0967 540 if(cmdfd != -1) close(cmdfd);
9d5da576 541 xpipe(pfd);
e83d0967
RK
542 cmdpid = xfork();
543 if(!cmdpid) {
9d5da576 544 xdup2(pfd[0], 0);
545 close(pfd[0]);
546 close(pfd[1]);
547 execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
548 fatal(errno, "error execing /bin/sh");
549 }
550 close(pfd[0]);
e83d0967
RK
551 cmdfd = pfd[1];
552 D(("forked cmd %d, fd = %d", cmdpid, cmdfd));
9d5da576 553}
554
460b9539 555static void play(size_t frames) {
8023f60b 556 size_t avail_bytes, written_frames;
9d5da576 557 ssize_t written_bytes;
e83d0967
RK
558 struct rtp header;
559 struct iovec vec[2];
460b9539 560
561 if(activate()) {
562 if(playing)
563 forceplay = frames;
564 else
565 forceplay = 0; /* Must have called abandon() */
566 return;
567 }
568 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
569 playing->eof ? " EOF" : "",
570 playing->format.rate,
571 playing->format.bits,
572 playing->format.channels));
573 /* If we haven't got enough bytes yet wait until we have. Exception: when
574 * we are at eof. */
575 if(playing->used < frames * bpf && !playing->eof) {
576 forceplay = frames;
577 return;
578 }
579 /* We have got enough data so don't force play again */
580 forceplay = 0;
581 /* Figure out how many frames there are available to write */
582 if(playing->start + playing->used > playing->size)
583 avail_bytes = playing->size - playing->start;
584 else
585 avail_bytes = playing->used;
9d5da576 586
e83d0967 587 switch(config->speaker_backend) {
8023f60b 588#if API_ALSA
e83d0967 589 case BACKEND_ALSA:
8023f60b 590 snd_pcm_sframes_t pcm_written_frames;
591 size_t avail_frames;
592 int err;
593
9d5da576 594 avail_frames = avail_bytes / bpf;
595 if(avail_frames > frames)
596 avail_frames = frames;
597 if(!avail_frames)
460b9539 598 return;
8023f60b 599 pcm_written_frames = snd_pcm_writei(pcm,
600 playing->buffer + playing->start,
601 avail_frames);
9d5da576 602 D(("actually play %zu frames, wrote %d",
8023f60b 603 avail_frames, (int)pcm_written_frames));
604 if(pcm_written_frames < 0) {
605 switch(pcm_written_frames) {
9d5da576 606 case -EPIPE: /* underrun */
607 error(0, "snd_pcm_writei reports underrun");
608 if((err = snd_pcm_prepare(pcm)) < 0)
609 fatal(0, "error calling snd_pcm_prepare: %d", err);
610 return;
611 case -EAGAIN:
612 return;
613 default:
8023f60b 614 fatal(0, "error calling snd_pcm_writei: %d",
615 (int)pcm_written_frames);
9d5da576 616 }
617 }
8023f60b 618 written_frames = pcm_written_frames;
9d5da576 619 written_bytes = written_frames * bpf;
e83d0967 620 break;
8023f60b 621#endif
e83d0967 622 case BACKEND_COMMAND:
9d5da576 623 if(avail_bytes > frames * bpf)
624 avail_bytes = frames * bpf;
e83d0967 625 written_bytes = write(cmdfd, playing->buffer + playing->start,
9d5da576 626 avail_bytes);
627 D(("actually play %zu bytes, wrote %d",
628 avail_bytes, (int)written_bytes));
629 if(written_bytes < 0) {
630 switch(errno) {
631 case EPIPE:
e83d0967
RK
632 error(0, "hmm, command died; trying another");
633 fork_cmd();
9d5da576 634 return;
635 case EAGAIN:
636 return;
637 }
460b9539 638 }
9d5da576 639 written_frames = written_bytes / bpf; /* good enough */
e83d0967
RK
640 break;
641 case BACKEND_NETWORK:
642 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
643 * AVT profile (RFC3551). */
644 if(rtp_time_real.tv_sec == 0)
645 xgettimeofday(&rtp_time_real, 0);
646 if(idled) {
647 struct timeval now;
648 xgettimeofday(&now, 0);
649 /* There's been a gap. Fix up the RTP time accordingly. */
650 rtp_time += (((now.tv_sec + now.tv_usec /1000000.0)
651 - (rtp_time_real.tv_sec + rtp_time_real.tv_usec / 1000000.0))
652 * playing->format.rate * playing->format.channels);
653 }
654 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
655 header.seq = htons(rtp_seq++);
656 header.timestamp = htonl(rtp_time);
657 header.ssrc = rtp_id;
658 header.mpt = (idled ? 0x80 : 0x00) | 10;
659 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
660 * the sample rate (in a library somewhere so that configuration.c can rule
661 * out invalid rates).
662 */
663 idled = 0;
664 if(avail_bytes > NETWORK_BYTES - sizeof header) {
665 avail_bytes = NETWORK_BYTES - sizeof header;
666 avail_bytes -= avail_bytes % bpf;
667 }
668 /* "The RTP clock rate used for generating the RTP timestamp is independent
669 * of the number of channels and the encoding; it equals the number of
670 * sampling periods per second. For N-channel encodings, each sampling
671 * period (say, 1/8000 of a second) generates N samples. (This terminology
672 * is standard, but somewhat confusing, as the total number of samples
673 * generated per second is then the sampling rate times the channel
674 * count.)"
675 */
676 vec[0].iov_base = (void *)&header;
677 vec[0].iov_len = sizeof header;
678 vec[1].iov_base = playing->buffer + playing->start;
679 vec[1].iov_len = avail_bytes;
680#if 0
681 {
682 char buffer[3 * sizeof header + 1];
683 size_t n;
684 const uint8_t *ptr = (void *)&header;
685
686 for(n = 0; n < sizeof header; ++n)
687 sprintf(&buffer[3 * n], "%02x ", *ptr++);
688 info(buffer);
689 }
690#endif
691 do {
692 written_bytes = writev(bfd,
693 vec,
694 2);
695 } while(written_bytes < 0 && errno == EINTR);
696 if(written_bytes < 0) {
697 error(errno, "error transmitting audio data");
698 ++audio_errors;
699 if(audio_errors == 10)
700 fatal(0, "too many audio errors");
701 return;
702 }
703 audio_errors /= 2;
704 written_bytes = avail_bytes;
705 written_frames = written_bytes / bpf;
706 /* Advance RTP's notion of the time */
707 rtp_time += written_frames * playing->format.channels;
708 /* Advance the corresponding real time */
709 assert(NETWORK_BYTES <= 2000); /* else risk overflowing 32 bits */
710 rtp_time_real.tv_usec += written_frames * 1000000 / playing->format.rate;
711 if(rtp_time_real.tv_usec >= 1000000) {
712 ++rtp_time_real.tv_sec;
713 rtp_time_real.tv_usec -= 1000000;
714 }
715 break;
716 default:
717 assert(!"reached");
460b9539 718 }
e83d0967
RK
719 /* written_bytes and written_frames had better both be set and correct by
720 * this point */
460b9539 721 playing->start += written_bytes;
722 playing->used -= written_bytes;
723 playing->played += written_frames;
724 /* If the pointer is at the end of the buffer (or the buffer is completely
725 * empty) wrap it back to the start. */
726 if(!playing->used || playing->start == playing->size)
727 playing->start = 0;
728 frames -= written_frames;
729}
730
731/* Notify the server what we're up to. */
732static void report(void) {
733 struct speaker_message sm;
734
735 if(playing && playing->buffer != (void *)&playing->format) {
736 memset(&sm, 0, sizeof sm);
737 sm.type = paused ? SM_PAUSED : SM_PLAYING;
738 strcpy(sm.id, playing->id);
739 sm.data = playing->played / playing->format.rate;
740 speaker_send(1, &sm, 0);
741 }
742 time(&last_report);
743}
744
9d5da576 745static void reap(int __attribute__((unused)) sig) {
e83d0967 746 pid_t cmdpid;
9d5da576 747 int st;
748
749 do
e83d0967
RK
750 cmdpid = waitpid(-1, &st, WNOHANG);
751 while(cmdpid > 0);
9d5da576 752 signal(SIGCHLD, reap);
753}
754
460b9539 755static int addfd(int fd, int events) {
756 if(fdno < NFDS) {
757 fds[fdno].fd = fd;
758 fds[fdno].events = events;
759 return fdno++;
760 } else
761 return -1;
762}
763
764int main(int argc, char **argv) {
e83d0967
RK
765 int n, fd, stdin_slot, alsa_slots, cmdfd_slot, bfd_slot, poke, timeout;
766 struct timeval now, delta;
460b9539 767 struct track *t;
768 struct speaker_message sm;
e83d0967
RK
769 struct addrinfo *res, *sres;
770 static const struct addrinfo pref = {
771 0,
772 PF_INET,
773 SOCK_DGRAM,
774 IPPROTO_UDP,
775 0,
776 0,
777 0,
778 0
779 };
780 static const struct addrinfo prefbind = {
781 AI_PASSIVE,
782 PF_INET,
783 SOCK_DGRAM,
784 IPPROTO_UDP,
785 0,
786 0,
787 0,
788 0
789 };
790 static const int one = 1;
791 char *sockname, *ssockname;
8023f60b 792#if API_ALSA
793 int alsa_nslots = -1, err;
794#endif
460b9539 795
796 set_progname(argv);
460b9539 797 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
798 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
799 switch(n) {
800 case 'h': help();
801 case 'V': version();
802 case 'c': configfile = optarg; break;
803 case 'd': debugging = 1; break;
804 case 'D': debugging = 0; break;
805 default: fatal(0, "invalid option");
806 }
807 }
808 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
809 /* If stderr is a TTY then log there, otherwise to syslog. */
810 if(!isatty(2)) {
811 openlog(progname, LOG_PID, LOG_DAEMON);
812 log_default = &log_syslog;
813 }
814 if(config_read()) fatal(0, "cannot read configuration");
815 /* ignore SIGPIPE */
816 signal(SIGPIPE, SIG_IGN);
9d5da576 817 /* reap kids */
818 signal(SIGCHLD, reap);
460b9539 819 /* set nice value */
820 xnice(config->nice_speaker);
821 /* change user */
822 become_mortal();
823 /* make sure we're not root, whatever the config says */
824 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
e83d0967
RK
825 switch(config->speaker_backend) {
826 case BACKEND_ALSA:
827 info("selected ALSA backend");
828 case BACKEND_COMMAND:
829 info("selected command backend");
830 fork_cmd();
831 break;
832 case BACKEND_NETWORK:
833 res = get_address(&config->broadcast, &pref, &sockname);
834 if(!res) return -1;
835 if(config->broadcast_from.n) {
836 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
837 if(!sres) return -1;
838 } else
839 sres = 0;
840 if((bfd = socket(res->ai_family,
841 res->ai_socktype,
842 res->ai_protocol)) < 0)
843 fatal(errno, "error creating broadcast socket");
844 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
845 fatal(errno, "error settting SO_BROADCAST on broadcast socket");
846 /* We might well want to set additional broadcast- or multicast-related
847 * options here */
848 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
849 fatal(errno, "error binding broadcast socket to %s", ssockname);
850 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
851 fatal(errno, "error connecting broadcast socket to %s", sockname);
852 /* Select an SSRC */
853 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
854 info("selected network backend, sending to %s", sockname);
855 if(config->sample_format.byte_format != AO_FMT_BIG) {
856 info("forcing big-endian sample format");
857 config->sample_format.byte_format = AO_FMT_BIG;
858 }
859 break;
860 default:
861 fatal(0, "unknown backend %d", config->speaker_backend);
8023f60b 862 }
460b9539 863 while(getppid() != 1) {
864 fdno = 0;
865 /* Always ready for commands from the main server. */
866 stdin_slot = addfd(0, POLLIN);
867 /* Try to read sample data for the currently playing track if there is
868 * buffer space. */
869 if(playing && !playing->eof && playing->used < playing->size) {
870 playing->slot = addfd(playing->fd, POLLIN);
871 } else if(playing)
872 playing->slot = -1;
873 /* If forceplay is set then wait until it succeeds before waiting on the
874 * sound device. */
9d5da576 875 alsa_slots = -1;
e83d0967
RK
876 cmdfd_slot = -1;
877 bfd_slot = -1;
878 /* By default we will wait up to a second before thinking about current
879 * state. */
880 timeout = 1000;
8023f60b 881 if(ready && !forceplay) {
e83d0967
RK
882 switch(config->speaker_backend) {
883 case BACKEND_COMMAND:
884 /* We send sample data to the subprocess as fast as it can accept it.
885 * This isn't ideal as pause latency can be very high as a result. */
886 if(cmdfd >= 0)
887 cmdfd_slot = addfd(cmdfd, POLLOUT);
888 break;
889 case BACKEND_NETWORK:
890 /* We want to keep the notional playing point somewhere in the near
891 * future. If it's too near then clients that attempt even the
892 * slightest amount of read-ahead will never catch up, and those that
893 * don't will skip whenever there's a trivial network delay. If it's
894 * too far ahead then pause latency will be too high.
895 */
896 xgettimeofday(&now, 0);
897 delta = tvsub(rtp_time_real, now);
898 if(delta.tv_sec < RTP_AHEAD) {
899 D(("delta = %ld.%06ld", (long)delta.tv_sec, (long)delta.tv_usec));
900 bfd_slot = addfd(bfd, POLLOUT);
901 if(delta.tv_sec < 0)
902 rtp_time_real = now; /* catch up */
903 }
904 break;
8023f60b 905#if API_ALSA
e83d0967
RK
906 case BACKEND_ALSA:
907 /* We send sample data to ALSA as fast as it can accept it, relying on
908 * the fact that it has a relatively small buffer to minimize pause
909 * latency. */
9d5da576 910 int retry = 3;
911
912 alsa_slots = fdno;
913 do {
914 retry = 0;
915 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
916 if((alsa_nslots <= 0
917 || !(fds[alsa_slots].events & POLLOUT))
918 && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
919 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
920 if((err = snd_pcm_prepare(pcm)))
921 fatal(0, "error calling snd_pcm_prepare: %d", err);
922 } else
923 break;
924 } while(retry-- > 0);
925 if(alsa_nslots >= 0)
926 fdno += alsa_nslots;
e83d0967 927 break;
8023f60b 928#endif
e83d0967
RK
929 default:
930 assert(!"unknown backend");
9d5da576 931 }
932 }
460b9539 933 /* If any other tracks don't have a full buffer, try to read sample data
934 * from them. */
935 for(t = tracks; t; t = t->next)
936 if(t != playing) {
937 if(!t->eof && t->used < t->size) {
9d5da576 938 t->slot = addfd(t->fd, POLLIN | POLLHUP);
460b9539 939 } else
940 t->slot = -1;
941 }
e83d0967
RK
942 /* Wait for something interesting to happen */
943 n = poll(fds, fdno, timeout);
460b9539 944 if(n < 0) {
945 if(errno == EINTR) continue;
946 fatal(errno, "error calling poll");
947 }
948 /* Play some sound before doing anything else */
e83d0967
RK
949 poke = 0;
950 switch(config->speaker_backend) {
8023f60b 951#if API_ALSA
e83d0967
RK
952 case BACKEND_ALSA:
953 if(alsa_slots != -1) {
954 unsigned short alsa_revents;
955
956 if((err = snd_pcm_poll_descriptors_revents(pcm,
957 &fds[alsa_slots],
958 alsa_nslots,
959 &alsa_revents)) < 0)
960 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
961 if(alsa_revents & (POLLOUT | POLLERR))
962 play(3 * FRAMES);
963 } else
964 poke = 1;
965 break;
8023f60b 966#endif
e83d0967
RK
967 case BACKEND_COMMAND:
968 if(cmdfd_slot != -1) {
969 if(fds[cmdfd_slot].revents & (POLLOUT | POLLERR))
970 play(3 * FRAMES);
971 } else
972 poke = 1;
973 break;
974 case BACKEND_NETWORK:
975 if(bfd_slot != -1) {
976 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
977 play(3 * FRAMES);
978 } else
979 poke = 1;
980 break;
981 }
982 if(poke) {
460b9539 983 /* Some attempt to play must have failed */
984 if(playing && !paused)
985 play(forceplay);
986 else
987 forceplay = 0; /* just in case */
988 }
989 /* Perhaps we have a command to process */
990 if(fds[stdin_slot].revents & POLLIN) {
991 n = speaker_recv(0, &sm, &fd);
992 if(n > 0)
993 switch(sm.type) {
994 case SM_PREPARE:
995 D(("SM_PREPARE %s %d", sm.id, fd));
996 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
997 t = findtrack(sm.id, 1);
998 acquire(t, fd);
999 break;
1000 case SM_PLAY:
1001 D(("SM_PLAY %s %d", sm.id, fd));
1002 if(playing) fatal(0, "got SM_PLAY but already playing something");
1003 t = findtrack(sm.id, 1);
1004 if(fd != -1) acquire(t, fd);
1005 playing = t;
8023f60b 1006 play(bufsize);
460b9539 1007 report();
1008 break;
1009 case SM_PAUSE:
1010 D(("SM_PAUSE"));
1011 paused = 1;
1012 report();
1013 break;
1014 case SM_RESUME:
1015 D(("SM_RESUME"));
1016 if(paused) {
1017 paused = 0;
1018 if(playing)
8023f60b 1019 play(bufsize);
460b9539 1020 }
1021 report();
1022 break;
1023 case SM_CANCEL:
1024 D(("SM_CANCEL %s", sm.id));
1025 t = removetrack(sm.id);
1026 if(t) {
1027 if(t == playing) {
1028 sm.type = SM_FINISHED;
1029 strcpy(sm.id, playing->id);
1030 speaker_send(1, &sm, 0);
1031 playing = 0;
1032 }
1033 destroy(t);
1034 } else
1035 error(0, "SM_CANCEL for unknown track %s", sm.id);
1036 report();
1037 break;
1038 case SM_RELOAD:
1039 D(("SM_RELOAD"));
1040 if(config_read()) error(0, "cannot read configuration");
1041 info("reloaded configuration");
1042 break;
1043 default:
1044 error(0, "unknown message type %d", sm.type);
1045 }
1046 }
1047 /* Read in any buffered data */
1048 for(t = tracks; t; t = t->next)
9d5da576 1049 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
460b9539 1050 fill(t);
1051 /* We might be able to play now */
9d5da576 1052 if(ready && forceplay && playing && !paused)
460b9539 1053 play(forceplay);
1054 /* Maybe we finished playing a track somewhere in the above */
1055 maybe_finished();
1056 /* If we don't need the sound device for now then close it for the benefit
1057 * of anyone else who wants it. */
9d5da576 1058 if((!playing || paused) && ready)
460b9539 1059 idle();
1060 /* If we've not reported out state for a second do so now. */
1061 if(time(0) > last_report)
1062 report();
1063 }
1064 info("stopped (parent terminated)");
1065 exit(0);
1066}
1067
1068/*
1069Local Variables:
1070c-basic-offset:2
1071comment-column:40
1072fill-column:79
1073indent-tabs-mode:nil
1074End:
1075*/