chiark / gitweb /
speaker: log empty buffers
[disorder] / server / speaker.c
... / ...
CommitLineData
1/*
2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2006, 2007 Richard Kettlewell
4 * Portions (C) 2007 Mark Wooding
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 * USA
20 */
21/** @file server/speaker.c
22 * @brief Speaker process
23 *
24 * This program is responsible for transmitting a single coherent audio stream
25 * to its destination (over the network, to some sound API, to some
26 * subprocess). It receives connections from decoders (or rather from the
27 * process that is about to become disorder-normalize) and plays them in the
28 * right order.
29 *
30 * @b Encodings. For the <a href="http://www.alsa-project.org/">ALSA</a> API,
31 * 8- and 16- bit stereo and mono are supported, with any sample rate (within
32 * the limits that ALSA can deal with.)
33 *
34 * Inbound data is expected to match @c config->sample_format. In normal use
35 * this is arranged by the @c disorder-normalize program (see @ref
36 * server/normalize.c).
37 *
38 * @b Garbage @b Collection. This program deliberately does not use the
39 * garbage collector even though it might be convenient to do so. This is for
40 * two reasons. Firstly some sound APIs use thread threads and we do not want
41 * to have to deal with potential interactions between threading and garbage
42 * collection. Secondly this process needs to be able to respond quickly and
43 * this is not compatible with the collector hanging the program even
44 * relatively briefly.
45 *
46 * @b Units. This program thinks at various times in three different units.
47 * Bytes are obvious. A sample is a single sample on a single channel. A
48 * frame is several samples on different channels at the same point in time.
49 * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
50 * 2-byte samples.
51 */
52
53#include <config.h>
54#include "types.h"
55
56#include <getopt.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <locale.h>
60#include <syslog.h>
61#include <unistd.h>
62#include <errno.h>
63#include <ao/ao.h>
64#include <string.h>
65#include <assert.h>
66#include <sys/select.h>
67#include <sys/wait.h>
68#include <time.h>
69#include <fcntl.h>
70#include <poll.h>
71#include <sys/un.h>
72
73#include "configuration.h"
74#include "syscalls.h"
75#include "log.h"
76#include "defs.h"
77#include "mem.h"
78#include "speaker-protocol.h"
79#include "user.h"
80#include "speaker.h"
81
82/** @brief Linked list of all prepared tracks */
83struct track *tracks;
84
85/** @brief Playing track, or NULL */
86struct track *playing;
87
88/** @brief Number of bytes pre frame */
89size_t bpf;
90
91/** @brief Array of file descriptors for poll() */
92struct pollfd fds[NFDS];
93
94/** @brief Next free slot in @ref fds */
95int fdno;
96
97/** @brief Listen socket */
98static int listenfd;
99
100static time_t last_report; /* when we last reported */
101static int paused; /* pause status */
102
103/** @brief The current device state */
104enum device_states device_state;
105
106/** @brief Set when idled
107 *
108 * This is set when the sound device is deliberately closed by idle().
109 */
110int idled;
111
112/** @brief Selected backend */
113static const struct speaker_backend *backend;
114
115static const struct option options[] = {
116 { "help", no_argument, 0, 'h' },
117 { "version", no_argument, 0, 'V' },
118 { "config", required_argument, 0, 'c' },
119 { "debug", no_argument, 0, 'd' },
120 { "no-debug", no_argument, 0, 'D' },
121 { "syslog", no_argument, 0, 's' },
122 { "no-syslog", no_argument, 0, 'S' },
123 { 0, 0, 0, 0 }
124};
125
126/* Display usage message and terminate. */
127static void help(void) {
128 xprintf("Usage:\n"
129 " disorder-speaker [OPTIONS]\n"
130 "Options:\n"
131 " --help, -h Display usage message\n"
132 " --version, -V Display version number\n"
133 " --config PATH, -c PATH Set configuration file\n"
134 " --debug, -d Turn on debugging\n"
135 " --[no-]syslog Force logging\n"
136 "\n"
137 "Speaker process for DisOrder. Not intended to be run\n"
138 "directly.\n");
139 xfclose(stdout);
140 exit(0);
141}
142
143/* Display version number and terminate. */
144static void version(void) {
145 xprintf("disorder-speaker version %s\n", disorder_version_string);
146 xfclose(stdout);
147 exit(0);
148}
149
150/** @brief Return the number of bytes per frame in @p format */
151static size_t bytes_per_frame(const struct stream_header *format) {
152 return format->channels * format->bits / 8;
153}
154
155/** @brief Find track @p id, maybe creating it if not found */
156static struct track *findtrack(const char *id, int create) {
157 struct track *t;
158
159 D(("findtrack %s %d", id, create));
160 for(t = tracks; t && strcmp(id, t->id); t = t->next)
161 ;
162 if(!t && create) {
163 t = xmalloc(sizeof *t);
164 t->next = tracks;
165 strcpy(t->id, id);
166 t->fd = -1;
167 tracks = t;
168 }
169 return t;
170}
171
172/** @brief Remove track @p id (but do not destroy it) */
173static struct track *removetrack(const char *id) {
174 struct track *t, **tt;
175
176 D(("removetrack %s", id));
177 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
178 ;
179 if(t)
180 *tt = t->next;
181 return t;
182}
183
184/** @brief Destroy a track */
185static void destroy(struct track *t) {
186 D(("destroy %s", t->id));
187 if(t->fd != -1) xclose(t->fd);
188 free(t);
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 speaker_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 t->playable = 1;
223 return -1;
224 }
225 t->used += n;
226 if(t->used == sizeof t->buffer)
227 t->playable = 1;
228 }
229 return 0;
230}
231
232/** @brief Close the sound device
233 *
234 * This is called to deactivate the output device when pausing, and also by the
235 * ALSA backend when changing encoding (in which case the sound device will be
236 * immediately reactivated).
237 */
238static void idle(void) {
239 D(("idle"));
240 if(backend->deactivate)
241 backend->deactivate();
242 else
243 device_state = device_closed;
244 idled = 1;
245}
246
247/** @brief Abandon the current track */
248void abandon(void) {
249 struct speaker_message sm;
250
251 D(("abandon"));
252 memset(&sm, 0, sizeof sm);
253 sm.type = SM_FINISHED;
254 strcpy(sm.id, playing->id);
255 speaker_send(1, &sm);
256 removetrack(playing->id);
257 destroy(playing);
258 playing = 0;
259}
260
261/** @brief Enable sound output
262 *
263 * Makes sure the sound device is open and has the right sample format. Return
264 * 0 on success and -1 on error.
265 */
266static void activate(void) {
267 if(backend->activate)
268 backend->activate();
269 else
270 device_state = device_open;
271}
272
273/** @brief Check whether the current track has finished
274 *
275 * The current track is determined to have finished either if the input stream
276 * eded before the format could be determined (i.e. it is malformed) or the
277 * input is at end of file and there is less than a frame left unplayed. (So
278 * it copes with decoders that crash mid-frame.)
279 */
280static void maybe_finished(void) {
281 if(playing
282 && playing->eof
283 && playing->used < bytes_per_frame(&config->sample_format))
284 abandon();
285}
286
287/** @brief Return nonzero if we want to play some audio
288 *
289 * We want to play audio if there is a current track; and it is not paused; and
290 * it is playable according to the rules for @ref track::playable.
291 */
292static int playable(void) {
293 return playing
294 && !paused
295 && playing->playable;
296}
297
298/** @brief Play up to @p frames frames of audio
299 *
300 * It is always safe to call this function.
301 * - If @ref playing is 0 then it will just return
302 * - If @ref paused is non-0 then it will just return
303 * - If @ref device_state != @ref device_open then it will call activate() and
304 * return if it it fails.
305 * - If there is not enough audio to play then it play what is available.
306 *
307 * If there are not enough frames to play then whatever is available is played
308 * instead. It is up to mainloop() to ensure that speaker_play() is not called
309 * when unreasonably only an small amounts of data is available to play.
310 */
311static void speaker_play(size_t frames) {
312 size_t avail_frames, avail_bytes, written_frames;
313 ssize_t written_bytes;
314
315 /* Make sure there's a track to play and it is not paused */
316 if(!playable())
317 return;
318 /* Make sure the output device is open */
319 if(device_state != device_open) {
320 activate();
321 if(device_state != device_open)
322 return;
323 }
324 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
325 playing->eof ? " EOF" : "",
326 config->sample_format.rate,
327 config->sample_format.bits,
328 config->sample_format.channels));
329 /* Figure out how many frames there are available to write */
330 if(playing->start + playing->used > sizeof playing->buffer)
331 /* The ring buffer is currently wrapped, only play up to the wrap point */
332 avail_bytes = (sizeof playing->buffer) - playing->start;
333 else
334 /* The ring buffer is not wrapped, can play the lot */
335 avail_bytes = playing->used;
336 avail_frames = avail_bytes / bpf;
337 /* Only play up to the requested amount */
338 if(avail_frames > frames)
339 avail_frames = frames;
340 if(!avail_frames)
341 return;
342 /* Play it, Sam */
343 written_frames = backend->play(avail_frames);
344 written_bytes = written_frames * bpf;
345 /* written_bytes and written_frames had better both be set and correct by
346 * this point */
347 playing->start += written_bytes;
348 playing->used -= written_bytes;
349 playing->played += written_frames;
350 /* If the pointer is at the end of the buffer (or the buffer is completely
351 * empty) wrap it back to the start. */
352 if(!playing->used || playing->start == (sizeof playing->buffer))
353 playing->start = 0;
354 /* If the buffer emptied out mark the track as unplayably */
355 if(!playing->used) {
356 error(0, "track buffer emptied");
357 playing->playable = 0;
358 }
359 frames -= written_frames;
360 return;
361}
362
363/* Notify the server what we're up to. */
364static void report(void) {
365 struct speaker_message sm;
366
367 if(playing) {
368 memset(&sm, 0, sizeof sm);
369 sm.type = paused ? SM_PAUSED : SM_PLAYING;
370 strcpy(sm.id, playing->id);
371 sm.data = playing->played / config->sample_format.rate;
372 speaker_send(1, &sm);
373 }
374 time(&last_report);
375}
376
377static void reap(int __attribute__((unused)) sig) {
378 pid_t cmdpid;
379 int st;
380
381 do
382 cmdpid = waitpid(-1, &st, WNOHANG);
383 while(cmdpid > 0);
384 signal(SIGCHLD, reap);
385}
386
387int addfd(int fd, int events) {
388 if(fdno < NFDS) {
389 fds[fdno].fd = fd;
390 fds[fdno].events = events;
391 return fdno++;
392 } else
393 return -1;
394}
395
396/** @brief Table of speaker backends */
397static const struct speaker_backend *backends[] = {
398#if HAVE_ALSA_ASOUNDLIB_H
399 &alsa_backend,
400#endif
401 &command_backend,
402 &network_backend,
403#if HAVE_COREAUDIO_AUDIOHARDWARE_H
404 &coreaudio_backend,
405#endif
406#if HAVE_SYS_SOUNDCARD_H
407 &oss_backend,
408#endif
409 0
410};
411
412/** @brief Main event loop */
413static void mainloop(void) {
414 struct track *t;
415 struct speaker_message sm;
416 int n, fd, stdin_slot, timeout, listen_slot;
417
418 while(getppid() != 1) {
419 fdno = 0;
420 /* By default we will wait up to a second before thinking about current
421 * state. */
422 timeout = 1000;
423 /* Always ready for commands from the main server. */
424 stdin_slot = addfd(0, POLLIN);
425 /* Also always ready for inbound connections */
426 listen_slot = addfd(listenfd, POLLIN);
427 /* Try to read sample data for the currently playing track if there is
428 * buffer space. */
429 if(playing
430 && playing->fd >= 0
431 && !playing->eof
432 && playing->used < (sizeof playing->buffer))
433 playing->slot = addfd(playing->fd, POLLIN);
434 else if(playing)
435 playing->slot = -1;
436 if(playable()) {
437 /* We want to play some audio. If the device is closed then we attempt
438 * to open it. */
439 if(device_state == device_closed)
440 activate();
441 /* If the device is (now) open then we will wait up until it is ready for
442 * more. If something went wrong then we should have device_error
443 * instead, but the post-poll code will cope even if it's
444 * device_closed. */
445 if(device_state == device_open)
446 backend->beforepoll(&timeout);
447 }
448 /* If any other tracks don't have a full buffer, try to read sample data
449 * from them. We do this last of all, so that if we run out of slots,
450 * nothing important can't be monitored. */
451 for(t = tracks; t; t = t->next)
452 if(t != playing) {
453 if(t->fd >= 0
454 && !t->eof
455 && t->used < sizeof t->buffer) {
456 t->slot = addfd(t->fd, POLLIN | POLLHUP);
457 } else
458 t->slot = -1;
459 }
460 /* Wait for something interesting to happen */
461 n = poll(fds, fdno, timeout);
462 if(n < 0) {
463 if(errno == EINTR) continue;
464 fatal(errno, "error calling poll");
465 }
466 /* Play some sound before doing anything else */
467 if(playable()) {
468 /* We want to play some audio */
469 if(device_state == device_open) {
470 if(backend->ready())
471 speaker_play(3 * FRAMES);
472 } else {
473 /* We must be in _closed or _error, and it should be the latter, but we
474 * cope with either.
475 *
476 * We most likely timed out, so now is a good time to retry.
477 * speaker_play() knows to re-activate the device if necessary.
478 */
479 speaker_play(3 * FRAMES);
480 }
481 }
482 /* Perhaps a connection has arrived */
483 if(fds[listen_slot].revents & POLLIN) {
484 struct sockaddr_un addr;
485 socklen_t addrlen = sizeof addr;
486 uint32_t l;
487 char id[24];
488
489 if((fd = accept(listenfd, (struct sockaddr *)&addr, &addrlen)) >= 0) {
490 blocking(fd);
491 if(read(fd, &l, sizeof l) < 4) {
492 error(errno, "reading length from inbound connection");
493 xclose(fd);
494 } else if(l >= sizeof id) {
495 error(0, "id length too long");
496 xclose(fd);
497 } else if(read(fd, id, l) < (ssize_t)l) {
498 error(errno, "reading id from inbound connection");
499 xclose(fd);
500 } else {
501 id[l] = 0;
502 D(("id %s fd %d", id, fd));
503 t = findtrack(id, 1/*create*/);
504 write(fd, "", 1); /* write an ack */
505 if(t->fd != -1) {
506 error(0, "%s: already got a connection", id);
507 xclose(fd);
508 } else {
509 nonblock(fd);
510 t->fd = fd; /* yay */
511 }
512 }
513 } else
514 error(errno, "accept");
515 }
516 /* Perhaps we have a command to process */
517 if(fds[stdin_slot].revents & POLLIN) {
518 /* There might (in theory) be several commands queued up, but in general
519 * this won't be the case, so we don't bother looping around to pick them
520 * all up. */
521 n = speaker_recv(0, &sm);
522 /* TODO */
523 if(n > 0)
524 switch(sm.type) {
525 case SM_PLAY:
526 if(playing) fatal(0, "got SM_PLAY but already playing something");
527 t = findtrack(sm.id, 1);
528 D(("SM_PLAY %s fd %d", t->id, t->fd));
529 if(t->fd == -1)
530 error(0, "cannot play track because no connection arrived");
531 playing = t;
532 /* We attempt to play straight away rather than going round the loop.
533 * speaker_play() is clever enough to perform any activation that is
534 * required. */
535 speaker_play(3 * FRAMES);
536 report();
537 break;
538 case SM_PAUSE:
539 D(("SM_PAUSE"));
540 paused = 1;
541 report();
542 break;
543 case SM_RESUME:
544 D(("SM_RESUME"));
545 if(paused) {
546 paused = 0;
547 /* As for SM_PLAY we attempt to play straight away. */
548 if(playing)
549 speaker_play(3 * FRAMES);
550 }
551 report();
552 break;
553 case SM_CANCEL:
554 D(("SM_CANCEL %s", sm.id));
555 t = removetrack(sm.id);
556 if(t) {
557 if(t == playing) {
558 sm.type = SM_FINISHED;
559 strcpy(sm.id, playing->id);
560 speaker_send(1, &sm);
561 playing = 0;
562 }
563 destroy(t);
564 } else
565 error(0, "SM_CANCEL for unknown track %s", sm.id);
566 report();
567 break;
568 case SM_RELOAD:
569 D(("SM_RELOAD"));
570 if(config_read(1)) error(0, "cannot read configuration");
571 info("reloaded configuration");
572 break;
573 default:
574 error(0, "unknown message type %d", sm.type);
575 }
576 }
577 /* Read in any buffered data */
578 for(t = tracks; t; t = t->next)
579 if(t->fd != -1
580 && t->slot != -1
581 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
582 speaker_fill(t);
583 /* Maybe we finished playing a track somewhere in the above */
584 maybe_finished();
585 /* If we don't need the sound device for now then close it for the benefit
586 * of anyone else who wants it. */
587 if((!playing || paused) && device_state == device_open)
588 idle();
589 /* If we've not reported out state for a second do so now. */
590 if(time(0) > last_report)
591 report();
592 }
593}
594
595int main(int argc, char **argv) {
596 int n, logsyslog = !isatty(2);
597 struct sockaddr_un addr;
598 static const int one = 1;
599 struct speaker_message sm;
600 const char *d;
601
602 set_progname(argv);
603 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
604 while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
605 switch(n) {
606 case 'h': help();
607 case 'V': version();
608 case 'c': configfile = optarg; break;
609 case 'd': debugging = 1; break;
610 case 'D': debugging = 0; break;
611 case 'S': logsyslog = 0; break;
612 case 's': logsyslog = 1; break;
613 default: fatal(0, "invalid option");
614 }
615 }
616 if((d = getenv("DISORDER_DEBUG_SPEAKER"))) debugging = atoi(d);
617 if(logsyslog) {
618 openlog(progname, LOG_PID, LOG_DAEMON);
619 log_default = &log_syslog;
620 }
621 if(config_read(1)) fatal(0, "cannot read configuration");
622 bpf = bytes_per_frame(&config->sample_format);
623 /* ignore SIGPIPE */
624 signal(SIGPIPE, SIG_IGN);
625 /* reap kids */
626 signal(SIGCHLD, reap);
627 /* set nice value */
628 xnice(config->nice_speaker);
629 /* change user */
630 become_mortal();
631 /* make sure we're not root, whatever the config says */
632 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
633 /* identify the backend used to play */
634 for(n = 0; backends[n]; ++n)
635 if(backends[n]->backend == config->speaker_backend)
636 break;
637 if(!backends[n])
638 fatal(0, "unsupported backend %d", config->speaker_backend);
639 backend = backends[n];
640 /* backend-specific initialization */
641 backend->init();
642 /* set up the listen socket */
643 listenfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
644 memset(&addr, 0, sizeof addr);
645 addr.sun_family = AF_UNIX;
646 snprintf(addr.sun_path, sizeof addr.sun_path, "%s/speaker",
647 config->home);
648 if(unlink(addr.sun_path) < 0 && errno != ENOENT)
649 error(errno, "removing %s", addr.sun_path);
650 xsetsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
651 if(bind(listenfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
652 fatal(errno, "error binding socket to %s", addr.sun_path);
653 xlisten(listenfd, 128);
654 nonblock(listenfd);
655 info("listening on %s", addr.sun_path);
656 memset(&sm, 0, sizeof sm);
657 sm.type = SM_READY;
658 speaker_send(1, &sm);
659 mainloop();
660 info("stopped (parent terminated)");
661 exit(0);
662}
663
664/*
665Local Variables:
666c-basic-offset:2
667comment-column:40
668fill-column:79
669indent-tabs-mode:nil
670End:
671*/