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