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