chiark / gitweb /
typo
[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
cf714d85 21 * @brief Speaker process
1674096e 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 *
795192f4 28 * @b Encodings. For the <a href="http://www.alsa-project.org/">ALSA</a> API,
29 * 8- and 16- bit stereo and mono are supported, with any sample rate (within
30 * the limits that ALSA can deal with.)
1674096e 31 *
6d2d327c
RK
32 * Inbound data is expected to match @c config->sample_format. In normal use
33 * this is arranged by the @c disorder-normalize program (see @ref
34 * server/normalize.c).
1674096e 35 *
795192f4 36 * @b Garbage @b Collection. This program deliberately does not use the
37 * garbage collector even though it might be convenient to do so. This is for
38 * two reasons. Firstly some sound APIs use thread threads and we do not want
39 * to have to deal with potential interactions between threading and garbage
40 * collection. Secondly this process needs to be able to respond quickly and
41 * this is not compatible with the collector hanging the program even
42 * relatively briefly.
43 *
44 * @b Units. This program thinks at various times in three different units.
45 * Bytes are obvious. A sample is a single sample on a single channel. A
46 * frame is several samples on different channels at the same point in time.
47 * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
48 * 2-byte samples.
1674096e 49 */
460b9539 50
51#include <config.h>
52#include "types.h"
53
54#include <getopt.h>
55#include <stdio.h>
56#include <stdlib.h>
57#include <locale.h>
58#include <syslog.h>
59#include <unistd.h>
60#include <errno.h>
61#include <ao/ao.h>
62#include <string.h>
63#include <assert.h>
64#include <sys/select.h>
9d5da576 65#include <sys/wait.h>
460b9539 66#include <time.h>
8023f60b 67#include <fcntl.h>
68#include <poll.h>
460b9539 69
70#include "configuration.h"
71#include "syscalls.h"
72#include "log.h"
73#include "defs.h"
74#include "mem.h"
ea410ba1 75#include "speaker-protocol.h"
460b9539 76#include "user.h"
cf714d85 77#include "speaker.h"
460b9539 78
cf714d85 79/** @brief Linked list of all prepared tracks */
80struct track *tracks;
e83d0967 81
cf714d85 82/** @brief Playing track, or NULL */
83struct track *playing;
460b9539 84
1c3f1e73 85/** @brief Number of bytes pre frame */
6d2d327c 86size_t bpf;
1c3f1e73 87
88/** @brief Array of file descriptors for poll() */
89struct pollfd fds[NFDS];
90
91/** @brief Next free slot in @ref fds */
92int fdno;
93
460b9539 94static time_t last_report; /* when we last reported */
95static int paused; /* pause status */
50ae38dd 96
5a7c42a8 97/** @brief The current device state */
98enum device_states device_state;
50ae38dd 99
55f35f2d 100/** @brief Set when idled
101 *
102 * This is set when the sound device is deliberately closed by idle().
55f35f2d 103 */
1c3f1e73 104int idled;
460b9539 105
29601377 106/** @brief Selected backend */
107static const struct speaker_backend *backend;
108
460b9539 109static const struct option options[] = {
110 { "help", no_argument, 0, 'h' },
111 { "version", no_argument, 0, 'V' },
112 { "config", required_argument, 0, 'c' },
113 { "debug", no_argument, 0, 'd' },
114 { "no-debug", no_argument, 0, 'D' },
115 { 0, 0, 0, 0 }
116};
117
118/* Display usage message and terminate. */
119static void help(void) {
120 xprintf("Usage:\n"
121 " disorder-speaker [OPTIONS]\n"
122 "Options:\n"
123 " --help, -h Display usage message\n"
124 " --version, -V Display version number\n"
125 " --config PATH, -c PATH Set configuration file\n"
126 " --debug, -d Turn on debugging\n"
127 "\n"
128 "Speaker process for DisOrder. Not intended to be run\n"
129 "directly.\n");
130 xfclose(stdout);
131 exit(0);
132}
133
134/* Display version number and terminate. */
135static void version(void) {
136 xprintf("disorder-speaker version %s\n", disorder_version_string);
137 xfclose(stdout);
138 exit(0);
139}
140
1674096e 141/** @brief Return the number of bytes per frame in @p format */
6d2d327c 142static size_t bytes_per_frame(const struct stream_header *format) {
460b9539 143 return format->channels * format->bits / 8;
144}
145
1674096e 146/** @brief Find track @p id, maybe creating it if not found */
460b9539 147static struct track *findtrack(const char *id, int create) {
148 struct track *t;
149
150 D(("findtrack %s %d", id, create));
151 for(t = tracks; t && strcmp(id, t->id); t = t->next)
152 ;
153 if(!t && create) {
154 t = xmalloc(sizeof *t);
155 t->next = tracks;
156 strcpy(t->id, id);
157 t->fd = -1;
158 tracks = t;
460b9539 159 }
160 return t;
161}
162
1674096e 163/** @brief Remove track @p id (but do not destroy it) */
460b9539 164static struct track *removetrack(const char *id) {
165 struct track *t, **tt;
166
167 D(("removetrack %s", id));
168 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
169 ;
170 if(t)
171 *tt = t->next;
172 return t;
173}
174
1674096e 175/** @brief Destroy a track */
460b9539 176static void destroy(struct track *t) {
177 D(("destroy %s", t->id));
178 if(t->fd != -1) xclose(t->fd);
460b9539 179 free(t);
180}
181
1674096e 182/** @brief Notice a new connection */
460b9539 183static void acquire(struct track *t, int fd) {
184 D(("acquire %s %d", t->id, fd));
185 if(t->fd != -1)
186 xclose(t->fd);
187 t->fd = fd;
188 nonblock(fd);
189}
190
1674096e 191/** @brief Read data into a sample buffer
192 * @param t Pointer to track
193 * @return 0 on success, -1 on EOF
194 *
55f35f2d 195 * This is effectively the read callback on @c t->fd. It is called from the
196 * main loop whenever the track's file descriptor is readable, assuming the
197 * buffer has not reached the maximum allowed occupancy.
1674096e 198 */
460b9539 199static int fill(struct track *t) {
200 size_t where, left;
201 int n;
202
6d2d327c
RK
203 D(("fill %s: eof=%d used=%zu",
204 t->id, t->eof, t->used));
460b9539 205 if(t->eof) return -1;
6d2d327c 206 if(t->used < sizeof t->buffer) {
460b9539 207 /* there is room left in the buffer */
6d2d327c
RK
208 where = (t->start + t->used) % sizeof t->buffer;
209 /* Get as much data as we can */
210 if(where >= t->start) left = (sizeof t->buffer) - where;
211 else left = t->start - where;
460b9539 212 do {
213 n = read(t->fd, t->buffer + where, left);
214 } while(n < 0 && errno == EINTR);
215 if(n < 0) {
216 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
217 return 0;
218 }
219 if(n == 0) {
220 D(("fill %s: eof detected", t->id));
221 t->eof = 1;
222 return -1;
223 }
224 t->used += n;
460b9539 225 }
226 return 0;
227}
228
55f35f2d 229/** @brief Close the sound device
230 *
231 * This is called to deactivate the output device when pausing, and also by the
232 * ALSA backend when changing encoding (in which case the sound device will be
233 * immediately reactivated).
234 */
460b9539 235static void idle(void) {
460b9539 236 D(("idle"));
5a7c42a8 237 if(backend->deactivate)
b5a99ad0 238 backend->deactivate();
5a7c42a8 239 else
240 device_state = device_closed;
e83d0967 241 idled = 1;
460b9539 242}
243
1674096e 244/** @brief Abandon the current track */
1c3f1e73 245void abandon(void) {
460b9539 246 struct speaker_message sm;
247
248 D(("abandon"));
249 memset(&sm, 0, sizeof sm);
250 sm.type = SM_FINISHED;
251 strcpy(sm.id, playing->id);
252 speaker_send(1, &sm, 0);
253 removetrack(playing->id);
254 destroy(playing);
255 playing = 0;
1c6e6a61 256}
257
1674096e 258/** @brief Enable sound output
259 *
260 * Makes sure the sound device is open and has the right sample format. Return
261 * 0 on success and -1 on error.
262 */
5a7c42a8 263static void activate(void) {
6d2d327c 264 if(backend->activate)
5a7c42a8 265 backend->activate();
6d2d327c 266 else
5a7c42a8 267 device_state = device_open;
460b9539 268}
269
55f35f2d 270/** @brief Check whether the current track has finished
271 *
272 * The current track is determined to have finished either if the input stream
273 * eded before the format could be determined (i.e. it is malformed) or the
274 * input is at end of file and there is less than a frame left unplayed. (So
275 * it copes with decoders that crash mid-frame.)
276 */
460b9539 277static void maybe_finished(void) {
278 if(playing
279 && playing->eof
6d2d327c 280 && playing->used < bytes_per_frame(&config->sample_format))
460b9539 281 abandon();
282}
283
5a7c42a8 284/** @brief Play up to @p frames frames of audio
285 *
286 * It is always safe to call this function.
287 * - If @ref playing is 0 then it will just return
288 * - If @ref paused is non-0 then it will just return
289 * - If @ref device_state != @ref device_open then it will call activate() and
290 * return if it it fails.
291 * - If there is not enough audio to play then it play what is available.
292 *
293 * If there are not enough frames to play then whatever is available is played
294 * instead. It is up to mainloop() to ensure that play() is not called when
295 * unreasonably only an small amounts of data is available to play.
296 */
460b9539 297static void play(size_t frames) {
3c68b773 298 size_t avail_frames, avail_bytes, written_frames;
9d5da576 299 ssize_t written_bytes;
460b9539 300
5a7c42a8 301 /* Make sure there's a track to play and it is not pasued */
302 if(!playing || paused)
460b9539 303 return;
6d2d327c
RK
304 /* Make sure the output device is open */
305 if(device_state != device_open) {
5a7c42a8 306 activate();
307 if(device_state != device_open)
308 return;
460b9539 309 }
6d2d327c 310 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
460b9539 311 playing->eof ? " EOF" : "",
6d2d327c
RK
312 config->sample_format.rate,
313 config->sample_format.bits,
314 config->sample_format.channels));
460b9539 315 /* Figure out how many frames there are available to write */
6d2d327c 316 if(playing->start + playing->used > sizeof playing->buffer)
7f9d5847 317 /* The ring buffer is currently wrapped, only play up to the wrap point */
6d2d327c 318 avail_bytes = (sizeof playing->buffer) - playing->start;
460b9539 319 else
7f9d5847 320 /* The ring buffer is not wrapped, can play the lot */
460b9539 321 avail_bytes = playing->used;
6d2d327c 322 avail_frames = avail_bytes / bpf;
7f9d5847 323 /* Only play up to the requested amount */
324 if(avail_frames > frames)
325 avail_frames = frames;
326 if(!avail_frames)
327 return;
3c68b773 328 /* Play it, Sam */
329 written_frames = backend->play(avail_frames);
6d2d327c 330 written_bytes = written_frames * bpf;
e83d0967
RK
331 /* written_bytes and written_frames had better both be set and correct by
332 * this point */
460b9539 333 playing->start += written_bytes;
334 playing->used -= written_bytes;
335 playing->played += written_frames;
336 /* If the pointer is at the end of the buffer (or the buffer is completely
337 * empty) wrap it back to the start. */
6d2d327c 338 if(!playing->used || playing->start == (sizeof playing->buffer))
460b9539 339 playing->start = 0;
340 frames -= written_frames;
5a7c42a8 341 return;
460b9539 342}
343
344/* Notify the server what we're up to. */
345static void report(void) {
346 struct speaker_message sm;
347
6d2d327c 348 if(playing) {
460b9539 349 memset(&sm, 0, sizeof sm);
350 sm.type = paused ? SM_PAUSED : SM_PLAYING;
351 strcpy(sm.id, playing->id);
6d2d327c 352 sm.data = playing->played / config->sample_format.rate;
460b9539 353 speaker_send(1, &sm, 0);
354 }
355 time(&last_report);
356}
357
9d5da576 358static void reap(int __attribute__((unused)) sig) {
e83d0967 359 pid_t cmdpid;
9d5da576 360 int st;
361
362 do
e83d0967
RK
363 cmdpid = waitpid(-1, &st, WNOHANG);
364 while(cmdpid > 0);
9d5da576 365 signal(SIGCHLD, reap);
366}
367
1c3f1e73 368int addfd(int fd, int events) {
460b9539 369 if(fdno < NFDS) {
370 fds[fdno].fd = fd;
371 fds[fdno].events = events;
372 return fdno++;
373 } else
374 return -1;
375}
376
572d74ba 377/** @brief Table of speaker backends */
1c3f1e73 378static const struct speaker_backend *backends[] = {
572d74ba 379#if API_ALSA
1c3f1e73 380 &alsa_backend,
572d74ba 381#endif
1c3f1e73 382 &command_backend,
383 &network_backend,
384 0
572d74ba 385};
386
5a7c42a8 387/** @brief Return nonzero if we want to play some audio
55f35f2d 388 *
5a7c42a8 389 * We want to play audio if there is a current track; and it is not paused; and
390 * there are at least @ref FRAMES frames of audio to play, or we are in sight
391 * of the end of the current track.
55f35f2d 392 */
5a7c42a8 393static int playable(void) {
394 return playing
395 && !paused
396 && (playing->used >= FRAMES || playing->eof);
397}
398
399/** @brief Main event loop */
55f35f2d 400static void mainloop(void) {
572d74ba 401 struct track *t;
402 struct speaker_message sm;
5a7c42a8 403 int n, fd, stdin_slot, timeout;
460b9539 404
460b9539 405 while(getppid() != 1) {
406 fdno = 0;
5a7c42a8 407 /* By default we will wait up to a second before thinking about current
408 * state. */
409 timeout = 1000;
460b9539 410 /* Always ready for commands from the main server. */
411 stdin_slot = addfd(0, POLLIN);
412 /* Try to read sample data for the currently playing track if there is
413 * buffer space. */
6d2d327c 414 if(playing && !playing->eof && playing->used < (sizeof playing->buffer))
460b9539 415 playing->slot = addfd(playing->fd, POLLIN);
5a7c42a8 416 else if(playing)
460b9539 417 playing->slot = -1;
5a7c42a8 418 if(playable()) {
419 /* We want to play some audio. If the device is closed then we attempt
420 * to open it. */
421 if(device_state == device_closed)
422 activate();
423 /* If the device is (now) open then we will wait up until it is ready for
424 * more. If something went wrong then we should have device_error
425 * instead, but the post-poll code will cope even if it's
426 * device_closed. */
427 if(device_state == device_open)
428 backend->beforepoll();
429 }
460b9539 430 /* If any other tracks don't have a full buffer, try to read sample data
5a7c42a8 431 * from them. We do this last of all, so that if we run out of slots,
432 * nothing important can't be monitored. */
460b9539 433 for(t = tracks; t; t = t->next)
434 if(t != playing) {
6d2d327c 435 if(!t->eof && t->used < sizeof t->buffer) {
9d5da576 436 t->slot = addfd(t->fd, POLLIN | POLLHUP);
460b9539 437 } else
438 t->slot = -1;
439 }
e83d0967
RK
440 /* Wait for something interesting to happen */
441 n = poll(fds, fdno, timeout);
460b9539 442 if(n < 0) {
443 if(errno == EINTR) continue;
444 fatal(errno, "error calling poll");
445 }
446 /* Play some sound before doing anything else */
5a7c42a8 447 if(playable()) {
448 /* We want to play some audio */
449 if(device_state == device_open) {
450 if(backend->ready())
451 play(3 * FRAMES);
452 } else {
453 /* We must be in _closed or _error, and it should be the latter, but we
454 * cope with either.
455 *
456 * We most likely timed out, so now is a good time to retry. play()
457 * knows to re-activate the device if necessary.
458 */
459 play(3 * FRAMES);
460 }
460b9539 461 }
462 /* Perhaps we have a command to process */
463 if(fds[stdin_slot].revents & POLLIN) {
5a7c42a8 464 /* There might (in theory) be several commands queued up, but in general
465 * this won't be the case, so we don't bother looping around to pick them
466 * all up. */
460b9539 467 n = speaker_recv(0, &sm, &fd);
468 if(n > 0)
469 switch(sm.type) {
470 case SM_PREPARE:
471 D(("SM_PREPARE %s %d", sm.id, fd));
472 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
473 t = findtrack(sm.id, 1);
474 acquire(t, fd);
475 break;
476 case SM_PLAY:
477 D(("SM_PLAY %s %d", sm.id, fd));
478 if(playing) fatal(0, "got SM_PLAY but already playing something");
479 t = findtrack(sm.id, 1);
480 if(fd != -1) acquire(t, fd);
481 playing = t;
5a7c42a8 482 /* We attempt to play straight away rather than going round the loop.
483 * play() is clever enough to perform any activation that is
484 * required. */
485 play(3 * FRAMES);
460b9539 486 report();
487 break;
488 case SM_PAUSE:
489 D(("SM_PAUSE"));
490 paused = 1;
491 report();
492 break;
493 case SM_RESUME:
494 D(("SM_RESUME"));
495 if(paused) {
496 paused = 0;
5a7c42a8 497 /* As for SM_PLAY we attempt to play straight away. */
460b9539 498 if(playing)
5a7c42a8 499 play(3 * FRAMES);
460b9539 500 }
501 report();
502 break;
503 case SM_CANCEL:
504 D(("SM_CANCEL %s", sm.id));
505 t = removetrack(sm.id);
506 if(t) {
507 if(t == playing) {
508 sm.type = SM_FINISHED;
509 strcpy(sm.id, playing->id);
510 speaker_send(1, &sm, 0);
511 playing = 0;
512 }
513 destroy(t);
514 } else
515 error(0, "SM_CANCEL for unknown track %s", sm.id);
516 report();
517 break;
518 case SM_RELOAD:
519 D(("SM_RELOAD"));
520 if(config_read()) error(0, "cannot read configuration");
521 info("reloaded configuration");
522 break;
523 default:
524 error(0, "unknown message type %d", sm.type);
525 }
526 }
527 /* Read in any buffered data */
528 for(t = tracks; t; t = t->next)
9d5da576 529 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
460b9539 530 fill(t);
460b9539 531 /* Maybe we finished playing a track somewhere in the above */
532 maybe_finished();
533 /* If we don't need the sound device for now then close it for the benefit
534 * of anyone else who wants it. */
5a7c42a8 535 if((!playing || paused) && device_state == device_open)
460b9539 536 idle();
537 /* If we've not reported out state for a second do so now. */
538 if(time(0) > last_report)
539 report();
540 }
55f35f2d 541}
542
543int main(int argc, char **argv) {
544 int n;
545
546 set_progname(argv);
547 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
548 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
549 switch(n) {
550 case 'h': help();
551 case 'V': version();
552 case 'c': configfile = optarg; break;
553 case 'd': debugging = 1; break;
554 case 'D': debugging = 0; break;
555 default: fatal(0, "invalid option");
556 }
557 }
558 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
559 /* If stderr is a TTY then log there, otherwise to syslog. */
560 if(!isatty(2)) {
561 openlog(progname, LOG_PID, LOG_DAEMON);
562 log_default = &log_syslog;
563 }
564 if(config_read()) fatal(0, "cannot read configuration");
6d2d327c 565 bpf = bytes_per_frame(&config->sample_format);
55f35f2d 566 /* ignore SIGPIPE */
567 signal(SIGPIPE, SIG_IGN);
568 /* reap kids */
569 signal(SIGCHLD, reap);
570 /* set nice value */
571 xnice(config->nice_speaker);
572 /* change user */
573 become_mortal();
574 /* make sure we're not root, whatever the config says */
575 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
576 /* identify the backend used to play */
1c3f1e73 577 for(n = 0; backends[n]; ++n)
578 if(backends[n]->backend == config->speaker_backend)
55f35f2d 579 break;
1c3f1e73 580 if(!backends[n])
55f35f2d 581 fatal(0, "unsupported backend %d", config->speaker_backend);
1c3f1e73 582 backend = backends[n];
55f35f2d 583 /* backend-specific initialization */
584 backend->init();
585 mainloop();
460b9539 586 info("stopped (parent terminated)");
587 exit(0);
588}
589
590/*
591Local Variables:
592c-basic-offset:2
593comment-column:40
594fill-column:79
595indent-tabs-mode:nil
596End:
597*/