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