chiark / gitweb /
Handle underrun when detected during poll() setup as well as from
[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 */
20
21/* This program deliberately does not use the garbage collector even though it
22 * might be convenient to do so. This is for two reasons. Firstly some libao
23 * drivers are implemented using threads and we do not want to have to deal
24 * with potential interactions between threading and garbage collection.
25 * Secondly this process needs to be able to respond quickly and this is not
26 * compatible with the collector hanging the program even relatively
27 * briefly. */
28
29#include <config.h>
30#include "types.h"
31
32#include <getopt.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <locale.h>
36#include <syslog.h>
37#include <unistd.h>
38#include <errno.h>
39#include <ao/ao.h>
40#include <string.h>
41#include <assert.h>
42#include <sys/select.h>
43#include <time.h>
460b9539 44
45#include "configuration.h"
46#include "syscalls.h"
47#include "log.h"
48#include "defs.h"
49#include "mem.h"
50#include "speaker.h"
51#include "user.h"
52
dea8f8aa
RK
53#if BUILD_SPEAKER
54#include <alsa/asoundlib.h>
55
460b9539 56#define BUFFER_SECONDS 5 /* How many seconds of input to
57 * buffer. */
58
59#define FRAMES 4096 /* Frame batch size */
60
61#define NFDS 256 /* Max FDs to poll for */
62
63/* Known tracks are kept in a linked list. We don't normally to have
64 * more than two - maybe three at the outside. */
65static struct track {
66 struct track *next; /* next track */
67 int fd; /* input FD */
68 char id[24]; /* ID */
69 size_t start, used; /* start + bytes used */
70 int eof; /* input is at EOF */
71 int got_format; /* got format yet? */
72 ao_sample_format format; /* sample format */
73 unsigned long long played; /* number of frames played */
74 char *buffer; /* sample buffer */
75 size_t size; /* sample buffer size */
76 int slot; /* poll array slot */
77} *tracks, *playing; /* all tracks + playing track */
78
79static time_t last_report; /* when we last reported */
80static int paused; /* pause status */
81static snd_pcm_t *pcm; /* current pcm handle */
82static ao_sample_format pcm_format; /* current format if aodev != 0 */
83static size_t bpf; /* bytes per frame */
84static struct pollfd fds[NFDS]; /* if we need more than that */
85static int fdno; /* fd number */
86static snd_pcm_uframes_t pcm_bufsize; /* buffer size */
87static int forceplay; /* frames to force play */
88
89static const struct option options[] = {
90 { "help", no_argument, 0, 'h' },
91 { "version", no_argument, 0, 'V' },
92 { "config", required_argument, 0, 'c' },
93 { "debug", no_argument, 0, 'd' },
94 { "no-debug", no_argument, 0, 'D' },
95 { 0, 0, 0, 0 }
96};
97
98/* Display usage message and terminate. */
99static void help(void) {
100 xprintf("Usage:\n"
101 " disorder-speaker [OPTIONS]\n"
102 "Options:\n"
103 " --help, -h Display usage message\n"
104 " --version, -V Display version number\n"
105 " --config PATH, -c PATH Set configuration file\n"
106 " --debug, -d Turn on debugging\n"
107 "\n"
108 "Speaker process for DisOrder. Not intended to be run\n"
109 "directly.\n");
110 xfclose(stdout);
111 exit(0);
112}
113
114/* Display version number and terminate. */
115static void version(void) {
116 xprintf("disorder-speaker version %s\n", disorder_version_string);
117 xfclose(stdout);
118 exit(0);
119}
120
121/* Return the number of bytes per frame in FORMAT. */
122static size_t bytes_per_frame(const ao_sample_format *format) {
123 return format->channels * format->bits / 8;
124}
125
126/* Find track ID, maybe creating it if not found. */
127static struct track *findtrack(const char *id, int create) {
128 struct track *t;
129
130 D(("findtrack %s %d", id, create));
131 for(t = tracks; t && strcmp(id, t->id); t = t->next)
132 ;
133 if(!t && create) {
134 t = xmalloc(sizeof *t);
135 t->next = tracks;
136 strcpy(t->id, id);
137 t->fd = -1;
138 tracks = t;
139 /* The initial input buffer will be the sample format. */
140 t->buffer = (void *)&t->format;
141 t->size = sizeof t->format;
142 }
143 return t;
144}
145
146/* Remove track ID (but do not destroy it). */
147static struct track *removetrack(const char *id) {
148 struct track *t, **tt;
149
150 D(("removetrack %s", id));
151 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
152 ;
153 if(t)
154 *tt = t->next;
155 return t;
156}
157
158/* Destroy a track. */
159static void destroy(struct track *t) {
160 D(("destroy %s", t->id));
161 if(t->fd != -1) xclose(t->fd);
162 if(t->buffer != (void *)&t->format) free(t->buffer);
163 free(t);
164}
165
166/* Notice a new FD. */
167static void acquire(struct track *t, int fd) {
168 D(("acquire %s %d", t->id, fd));
169 if(t->fd != -1)
170 xclose(t->fd);
171 t->fd = fd;
172 nonblock(fd);
173}
174
175/* Read data into a sample buffer. Return 0 on success, -1 on EOF. */
176static int fill(struct track *t) {
177 size_t where, left;
178 int n;
179
180 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
181 t->id, t->eof, t->used, t->size, t->got_format));
182 if(t->eof) return -1;
183 if(t->used < t->size) {
184 /* there is room left in the buffer */
185 where = (t->start + t->used) % t->size;
186 if(t->got_format) {
187 /* We are reading audio data, get as much as we can */
188 if(where >= t->start) left = t->size - where;
189 else left = t->start - where;
190 } else
191 /* We are still waiting for the format, only get that */
192 left = sizeof (ao_sample_format) - t->used;
193 do {
194 n = read(t->fd, t->buffer + where, left);
195 } while(n < 0 && errno == EINTR);
196 if(n < 0) {
197 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
198 return 0;
199 }
200 if(n == 0) {
201 D(("fill %s: eof detected", t->id));
202 t->eof = 1;
203 return -1;
204 }
205 t->used += n;
206 if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
207 assert(t->used == sizeof (ao_sample_format));
208 /* Check that our assumptions are met. */
209 if(t->format.bits & 7)
210 fatal(0, "bits per sample not a multiple of 8");
211 /* Make a new buffer for audio data. */
212 t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
213 t->buffer = xmalloc(t->size);
214 t->used = 0;
215 t->got_format = 1;
216 D(("got format for %s", t->id));
217 }
218 }
219 return 0;
220}
221
222/* Return true if A and B denote identical libao formats, else false. */
223static int formats_equal(const ao_sample_format *a,
224 const ao_sample_format *b) {
225 return (a->bits == b->bits
226 && a->rate == b->rate
227 && a->channels == b->channels
228 && a->byte_format == b->byte_format);
229}
230
231/* Close the sound device. */
232static void idle(void) {
233 int err;
234
235 D(("idle"));
236 if(pcm) {
237 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
238 fatal(0, "error calling snd_pcm_nonblock: %d", err);
239 D(("draining pcm"));
240 snd_pcm_drain(pcm);
241 D(("closing pcm"));
242 snd_pcm_close(pcm);
243 pcm = 0;
244 forceplay = 0;
245 D(("released audio device"));
246 }
247}
248
249/* Abandon the current track */
250static void abandon(void) {
251 struct speaker_message sm;
252
253 D(("abandon"));
254 memset(&sm, 0, sizeof sm);
255 sm.type = SM_FINISHED;
256 strcpy(sm.id, playing->id);
257 speaker_send(1, &sm, 0);
258 removetrack(playing->id);
259 destroy(playing);
260 playing = 0;
261 forceplay = 0;
262}
263
1c6e6a61 264static void log_params(snd_pcm_hw_params_t *hwparams,
265 snd_pcm_sw_params_t *swparams) {
266 snd_pcm_uframes_t f;
267 unsigned u;
268
269 if(hwparams) {
270 /* TODO */
271 }
272 if(swparams) {
273 snd_pcm_sw_params_get_silence_size(swparams, &f);
274 info("sw silence_size=%lu", (unsigned long)f);
275 snd_pcm_sw_params_get_silence_threshold(swparams, &f);
276 info("sw silence_threshold=%lu", (unsigned long)f);
277 snd_pcm_sw_params_get_sleep_min(swparams, &u);
278 info("sw sleep_min=%lu", (unsigned long)u);
279 snd_pcm_sw_params_get_start_threshold(swparams, &f);
280 info("sw start_threshold=%lu", (unsigned long)f);
281 snd_pcm_sw_params_get_stop_threshold(swparams, &f);
282 info("sw stop_threshold=%lu", (unsigned long)f);
283 snd_pcm_sw_params_get_xfer_align(swparams, &f);
284 info("sw xfer_align=%lu", (unsigned long)f);
285 }
286}
287
460b9539 288/* Make sure the sound device is open and has the right sample format. Return
289 * 0 on success and -1 on error. */
290static int activate(void) {
291 int err;
292 snd_pcm_hw_params_t *hwparams;
293 snd_pcm_sw_params_t *swparams;
294 int sample_format = 0;
295 unsigned rate;
296
297 /* If we don't know the format yet we cannot start. */
298 if(!playing->got_format) {
299 D((" - not got format for %s", playing->id));
300 return -1;
301 }
302 /* If we need to change format then close the current device. */
303 if(pcm && !formats_equal(&playing->format, &pcm_format))
304 idle();
305 if(!pcm) {
306 D(("snd_pcm_open"));
307 if((err = snd_pcm_open(&pcm,
308 config->device,
309 SND_PCM_STREAM_PLAYBACK,
310 SND_PCM_NONBLOCK))) {
311 error(0, "error from snd_pcm_open: %d", err);
312 goto error;
313 }
314 snd_pcm_hw_params_alloca(&hwparams);
315 D(("set up hw params"));
316 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
317 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
318 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
319 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
320 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
321 switch(playing->format.bits) {
322 case 8:
323 sample_format = SND_PCM_FORMAT_S8;
324 break;
325 case 16:
326 switch(playing->format.byte_format) {
327 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
328 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
329 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
330 error(0, "unrecognized byte format %d", playing->format.byte_format);
331 goto fatal;
332 }
333 break;
334 default:
335 error(0, "unsupported sample size %d", playing->format.bits);
336 goto fatal;
337 }
338 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
339 sample_format)) < 0) {
340 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
341 sample_format, err);
342 goto fatal;
343 }
344 rate = playing->format.rate;
345 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
346 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
347 playing->format.rate, err);
348 goto fatal;
349 }
350 if(rate != (unsigned)playing->format.rate)
351 info("want rate %d, got %u", playing->format.rate, rate);
352 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
353 playing->format.channels)) < 0) {
354 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
355 playing->format.channels, err);
356 goto fatal;
357 }
358 pcm_bufsize = 3 * FRAMES;
359 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
360 &pcm_bufsize)) < 0)
361 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
362 3 * FRAMES, err);
363 if(pcm_bufsize != 3 * FRAMES)
364 info("asked for PCM buffer of %d frames, got %d",
365 3 * FRAMES, (int)pcm_bufsize);
366 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
367 fatal(0, "error calling snd_pcm_hw_params: %d", err);
368 D(("set up sw params"));
369 snd_pcm_sw_params_alloca(&swparams);
370 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
371 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
372 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
373 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
374 FRAMES, err);
375 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
376 fatal(0, "error calling snd_pcm_sw_params: %d", err);
377 pcm_format = playing->format;
378 bpf = bytes_per_frame(&pcm_format);
379 D(("acquired audio device"));
1c6e6a61 380 log_params(hwparams, swparams);
460b9539 381 }
382 return 0;
383fatal:
384 abandon();
385error:
386 /* We assume the error is temporary and that we'll retry in a bit. */
387 if(pcm) {
388 snd_pcm_close(pcm);
389 pcm = 0;
390 }
391 return -1;
392}
393
394/* Check to see whether the current track has finished playing */
395static void maybe_finished(void) {
396 if(playing
397 && playing->eof
398 && (!playing->got_format
399 || playing->used < bytes_per_frame(&playing->format)))
400 abandon();
401}
402
403static void play(size_t frames) {
404 snd_pcm_sframes_t written_frames;
405 size_t avail_bytes, avail_frames, written_bytes;
406 int err;
407
408 if(activate()) {
409 if(playing)
410 forceplay = frames;
411 else
412 forceplay = 0; /* Must have called abandon() */
413 return;
414 }
415 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
416 playing->eof ? " EOF" : "",
417 playing->format.rate,
418 playing->format.bits,
419 playing->format.channels));
420 /* If we haven't got enough bytes yet wait until we have. Exception: when
421 * we are at eof. */
422 if(playing->used < frames * bpf && !playing->eof) {
423 forceplay = frames;
424 return;
425 }
426 /* We have got enough data so don't force play again */
427 forceplay = 0;
428 /* Figure out how many frames there are available to write */
429 if(playing->start + playing->used > playing->size)
430 avail_bytes = playing->size - playing->start;
431 else
432 avail_bytes = playing->used;
433 avail_frames = avail_bytes / bpf;
434 if(avail_frames > frames)
435 avail_frames = frames;
436 if(!avail_frames)
437 return;
438 written_frames = snd_pcm_writei(pcm,
439 playing->buffer + playing->start,
440 avail_frames);
441 D(("actually play %zu frames, wrote %d",
442 avail_frames, (int)written_frames));
443 if(written_frames < 0) {
444 switch(written_frames) {
445 case -EPIPE: /* underrun */
446 error(0, "snd_pcm_writei reports underrun");
447 if((err = snd_pcm_prepare(pcm)) < 0)
448 fatal(0, "error calling snd_pcm_prepare: %d", err);
449 return;
450 case -EAGAIN:
451 return;
452 default:
453 fatal(0, "error calling snd_pcm_writei: %d", (int)written_frames);
454 }
455 }
456 written_bytes = written_frames * bpf;
457 playing->start += written_bytes;
458 playing->used -= written_bytes;
459 playing->played += written_frames;
460 /* If the pointer is at the end of the buffer (or the buffer is completely
461 * empty) wrap it back to the start. */
462 if(!playing->used || playing->start == playing->size)
463 playing->start = 0;
464 frames -= written_frames;
465}
466
467/* Notify the server what we're up to. */
468static void report(void) {
469 struct speaker_message sm;
470
471 if(playing && playing->buffer != (void *)&playing->format) {
472 memset(&sm, 0, sizeof sm);
473 sm.type = paused ? SM_PAUSED : SM_PLAYING;
474 strcpy(sm.id, playing->id);
475 sm.data = playing->played / playing->format.rate;
476 speaker_send(1, &sm, 0);
477 }
478 time(&last_report);
479}
480
481static int addfd(int fd, int events) {
482 if(fdno < NFDS) {
483 fds[fdno].fd = fd;
484 fds[fdno].events = events;
485 return fdno++;
486 } else
487 return -1;
488}
489
490int main(int argc, char **argv) {
491 int n, fd, stdin_slot, alsa_slots, alsa_nslots = -1, err;
492 unsigned short alsa_revents;
493 struct track *t;
494 struct speaker_message sm;
495
496 set_progname(argv);
497 mem_init(0);
498 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
499 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
500 switch(n) {
501 case 'h': help();
502 case 'V': version();
503 case 'c': configfile = optarg; break;
504 case 'd': debugging = 1; break;
505 case 'D': debugging = 0; break;
506 default: fatal(0, "invalid option");
507 }
508 }
509 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
510 /* If stderr is a TTY then log there, otherwise to syslog. */
511 if(!isatty(2)) {
512 openlog(progname, LOG_PID, LOG_DAEMON);
513 log_default = &log_syslog;
514 }
515 if(config_read()) fatal(0, "cannot read configuration");
516 /* ignore SIGPIPE */
517 signal(SIGPIPE, SIG_IGN);
518 /* set nice value */
519 xnice(config->nice_speaker);
520 /* change user */
521 become_mortal();
522 /* make sure we're not root, whatever the config says */
523 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
524 info("started");
525 while(getppid() != 1) {
526 fdno = 0;
527 /* Always ready for commands from the main server. */
528 stdin_slot = addfd(0, POLLIN);
529 /* Try to read sample data for the currently playing track if there is
530 * buffer space. */
531 if(playing && !playing->eof && playing->used < playing->size) {
532 playing->slot = addfd(playing->fd, POLLIN);
533 } else if(playing)
534 playing->slot = -1;
535 /* If forceplay is set then wait until it succeeds before waiting on the
536 * sound device. */
537 if(pcm && !forceplay) {
1c6e6a61 538 int retry = 3;
539
460b9539 540 alsa_slots = fdno;
1c6e6a61 541 do {
542 retry = 0;
543 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
544 if((alsa_nslots <= 0
545 || !(fds[alsa_slots].events & POLLOUT))
546 && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
547 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
548 if((err = snd_pcm_prepare(pcm)))
549 fatal(0, "error calling snd_pcm_prepare: %d", err);
550 } else
551 break;
552 } while(retry-- > 0);
553 if(alsa_nslots >= 0)
554 fdno += alsa_nslots;
460b9539 555 } else
556 alsa_slots = -1;
557 /* If any other tracks don't have a full buffer, try to read sample data
558 * from them. */
559 for(t = tracks; t; t = t->next)
560 if(t != playing) {
561 if(!t->eof && t->used < t->size) {
562 t->slot = addfd(t->fd, POLLIN);
563 } else
564 t->slot = -1;
565 }
566 /* Wait up to a second before thinking about current state */
567 n = poll(fds, fdno, 1000);
568 if(n < 0) {
569 if(errno == EINTR) continue;
570 fatal(errno, "error calling poll");
571 }
572 /* Play some sound before doing anything else */
573 if(alsa_slots != -1) {
574 if((err = snd_pcm_poll_descriptors_revents(pcm,
575 &fds[alsa_slots],
576 alsa_nslots,
577 &alsa_revents)) < 0)
578 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
579 if(alsa_revents & POLLOUT)
580 play(3 * FRAMES);
581 } else {
582 /* Some attempt to play must have failed */
583 if(playing && !paused)
584 play(forceplay);
585 else
586 forceplay = 0; /* just in case */
587 }
588 /* Perhaps we have a command to process */
589 if(fds[stdin_slot].revents & POLLIN) {
590 n = speaker_recv(0, &sm, &fd);
591 if(n > 0)
592 switch(sm.type) {
593 case SM_PREPARE:
594 D(("SM_PREPARE %s %d", sm.id, fd));
595 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
596 t = findtrack(sm.id, 1);
597 acquire(t, fd);
598 break;
599 case SM_PLAY:
600 D(("SM_PLAY %s %d", sm.id, fd));
601 if(playing) fatal(0, "got SM_PLAY but already playing something");
602 t = findtrack(sm.id, 1);
603 if(fd != -1) acquire(t, fd);
604 playing = t;
605 play(pcm_bufsize);
606 report();
607 break;
608 case SM_PAUSE:
609 D(("SM_PAUSE"));
610 paused = 1;
611 report();
612 break;
613 case SM_RESUME:
614 D(("SM_RESUME"));
615 if(paused) {
616 paused = 0;
617 if(playing)
618 play(pcm_bufsize);
619 }
620 report();
621 break;
622 case SM_CANCEL:
623 D(("SM_CANCEL %s", sm.id));
624 t = removetrack(sm.id);
625 if(t) {
626 if(t == playing) {
627 sm.type = SM_FINISHED;
628 strcpy(sm.id, playing->id);
629 speaker_send(1, &sm, 0);
630 playing = 0;
631 }
632 destroy(t);
633 } else
634 error(0, "SM_CANCEL for unknown track %s", sm.id);
635 report();
636 break;
637 case SM_RELOAD:
638 D(("SM_RELOAD"));
639 if(config_read()) error(0, "cannot read configuration");
640 info("reloaded configuration");
641 break;
642 default:
643 error(0, "unknown message type %d", sm.type);
644 }
645 }
646 /* Read in any buffered data */
647 for(t = tracks; t; t = t->next)
648 if(t->slot != -1 && (fds[t->slot].revents & POLLIN))
649 fill(t);
650 /* We might be able to play now */
651 if(pcm && forceplay && playing && !paused)
652 play(forceplay);
653 /* Maybe we finished playing a track somewhere in the above */
654 maybe_finished();
655 /* If we don't need the sound device for now then close it for the benefit
656 * of anyone else who wants it. */
657 if((!playing || paused) && pcm)
658 idle();
659 /* If we've not reported out state for a second do so now. */
660 if(time(0) > last_report)
661 report();
662 }
663 info("stopped (parent terminated)");
664 exit(0);
665}
dea8f8aa
RK
666#else
667int main(int attribute((unused)) argc, char **argv) {
668 set_progname(argv);
669 mem_init(0);
670 fatal(0, "disorder-speaker not supported on this platform");
671}
672#endif
460b9539 673
674/*
675Local Variables:
676c-basic-offset:2
677comment-column:40
678fill-column:79
679indent-tabs-mode:nil
680End:
681*/