chiark / gitweb /
speaker protocol redesign to cope with libao re-opening
[disorder] / server / speaker.c
... / ...
CommitLineData
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 process
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 * @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.)
31 *
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).
35 *
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.
49 */
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>
65#include <sys/wait.h>
66#include <time.h>
67#include <fcntl.h>
68#include <poll.h>
69
70#include "configuration.h"
71#include "syscalls.h"
72#include "log.h"
73#include "defs.h"
74#include "mem.h"
75#include "speaker-protocol.h"
76#include "user.h"
77#include "speaker.h"
78
79/** @brief Linked list of all prepared tracks */
80struct track *tracks;
81
82/** @brief Playing track, or NULL */
83struct track *playing;
84
85/** @brief Number of bytes pre frame */
86size_t bpf;
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
94static time_t last_report; /* when we last reported */
95static int paused; /* pause status */
96
97/** @brief The current device state */
98enum device_states device_state;
99
100/** @brief Set when idled
101 *
102 * This is set when the sound device is deliberately closed by idle().
103 */
104int idled;
105
106/** @brief Selected backend */
107static const struct speaker_backend *backend;
108
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
141/** @brief Return the number of bytes per frame in @p format */
142static size_t bytes_per_frame(const struct stream_header *format) {
143 return format->channels * format->bits / 8;
144}
145
146/** @brief Find track @p id, maybe creating it if not found */
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;
159 }
160 return t;
161}
162
163/** @brief Remove track @p id (but do not destroy it) */
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
175/** @brief Destroy a track */
176static void destroy(struct track *t) {
177 D(("destroy %s", t->id));
178 if(t->fd != -1) xclose(t->fd);
179 free(t);
180}
181
182/** @brief Notice a new connection */
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
191/** @brief Read data into a sample buffer
192 * @param t Pointer to track
193 * @return 0 on success, -1 on EOF
194 *
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.
198 */
199static int fill(struct track *t) {
200 size_t where, left;
201 int n;
202
203 D(("fill %s: eof=%d used=%zu",
204 t->id, t->eof, t->used));
205 if(t->eof) return -1;
206 if(t->used < sizeof t->buffer) {
207 /* there is room left in the buffer */
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;
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;
225 }
226 return 0;
227}
228
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 */
235static void idle(void) {
236 D(("idle"));
237 if(backend->deactivate)
238 backend->deactivate();
239 else
240 device_state = device_closed;
241 idled = 1;
242}
243
244/** @brief Abandon the current track */
245void abandon(void) {
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;
256}
257
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 */
263static void activate(void) {
264 if(backend->activate)
265 backend->activate();
266 else
267 device_state = device_open;
268}
269
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 */
277static void maybe_finished(void) {
278 if(playing
279 && playing->eof
280 && playing->used < bytes_per_frame(&config->sample_format))
281 abandon();
282}
283
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 */
297static void play(size_t frames) {
298 size_t avail_frames, avail_bytes, written_frames;
299 ssize_t written_bytes;
300
301 /* Make sure there's a track to play and it is not pasued */
302 if(!playing || paused)
303 return;
304 /* Make sure the output device is open */
305 if(device_state != device_open) {
306 activate();
307 if(device_state != device_open)
308 return;
309 }
310 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
311 playing->eof ? " EOF" : "",
312 config->sample_format.rate,
313 config->sample_format.bits,
314 config->sample_format.channels));
315 /* Figure out how many frames there are available to write */
316 if(playing->start + playing->used > sizeof playing->buffer)
317 /* The ring buffer is currently wrapped, only play up to the wrap point */
318 avail_bytes = (sizeof playing->buffer) - playing->start;
319 else
320 /* The ring buffer is not wrapped, can play the lot */
321 avail_bytes = playing->used;
322 avail_frames = avail_bytes / bpf;
323 /* Only play up to the requested amount */
324 if(avail_frames > frames)
325 avail_frames = frames;
326 if(!avail_frames)
327 return;
328 /* Play it, Sam */
329 written_frames = backend->play(avail_frames);
330 written_bytes = written_frames * bpf;
331 /* written_bytes and written_frames had better both be set and correct by
332 * this point */
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. */
338 if(!playing->used || playing->start == (sizeof playing->buffer))
339 playing->start = 0;
340 frames -= written_frames;
341 return;
342}
343
344/* Notify the server what we're up to. */
345static void report(void) {
346 struct speaker_message sm;
347
348 if(playing) {
349 memset(&sm, 0, sizeof sm);
350 sm.type = paused ? SM_PAUSED : SM_PLAYING;
351 strcpy(sm.id, playing->id);
352 sm.data = playing->played / config->sample_format.rate;
353 speaker_send(1, &sm, 0);
354 }
355 time(&last_report);
356}
357
358static void reap(int __attribute__((unused)) sig) {
359 pid_t cmdpid;
360 int st;
361
362 do
363 cmdpid = waitpid(-1, &st, WNOHANG);
364 while(cmdpid > 0);
365 signal(SIGCHLD, reap);
366}
367
368int addfd(int fd, int events) {
369 if(fdno < NFDS) {
370 fds[fdno].fd = fd;
371 fds[fdno].events = events;
372 return fdno++;
373 } else
374 return -1;
375}
376
377/** @brief Table of speaker backends */
378static const struct speaker_backend *backends[] = {
379#if API_ALSA
380 &alsa_backend,
381#endif
382 &command_backend,
383 &network_backend,
384 0
385};
386
387/** @brief Return nonzero if we want to play some audio
388 *
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.
392 */
393static int playable(void) {
394 return playing
395 && !paused
396 && (playing->used >= FRAMES || playing->eof);
397}
398
399/** @brief Main event loop */
400static void mainloop(void) {
401 struct track *t;
402 struct speaker_message sm;
403 int n, fd, stdin_slot, timeout;
404
405 while(getppid() != 1) {
406 fdno = 0;
407 /* By default we will wait up to a second before thinking about current
408 * state. */
409 timeout = 1000;
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. */
414 if(playing && !playing->eof && playing->used < (sizeof playing->buffer))
415 playing->slot = addfd(playing->fd, POLLIN);
416 else if(playing)
417 playing->slot = -1;
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 }
430 /* If any other tracks don't have a full buffer, try to read sample data
431 * from them. We do this last of all, so that if we run out of slots,
432 * nothing important can't be monitored. */
433 for(t = tracks; t; t = t->next)
434 if(t != playing) {
435 if(!t->eof && t->used < sizeof t->buffer) {
436 t->slot = addfd(t->fd, POLLIN | POLLHUP);
437 } else
438 t->slot = -1;
439 }
440 /* Wait for something interesting to happen */
441 n = poll(fds, fdno, timeout);
442 if(n < 0) {
443 if(errno == EINTR) continue;
444 fatal(errno, "error calling poll");
445 }
446 /* Play some sound before doing anything else */
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 }
461 }
462 /* Perhaps we have a command to process */
463 if(fds[stdin_slot].revents & POLLIN) {
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. */
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;
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);
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;
497 /* As for SM_PLAY we attempt to play straight away. */
498 if(playing)
499 play(3 * FRAMES);
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)
529 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
530 fill(t);
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. */
535 if((!playing || paused) && device_state == device_open)
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 }
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");
565 bpf = bytes_per_frame(&config->sample_format);
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 */
577 for(n = 0; backends[n]; ++n)
578 if(backends[n]->backend == config->speaker_backend)
579 break;
580 if(!backends[n])
581 fatal(0, "unsupported backend %d", config->speaker_backend);
582 backend = backends[n];
583 /* backend-specific initialization */
584 backend->init();
585 mainloop();
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*/