chiark / gitweb /
speaker process is now more consistent about whether it's using ALSA
[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>
9d5da576 43#include <sys/wait.h>
460b9539 44#include <time.h>
8023f60b 45#include <fcntl.h>
46#include <poll.h>
460b9539 47
48#include "configuration.h"
49#include "syscalls.h"
50#include "log.h"
51#include "defs.h"
52#include "mem.h"
53#include "speaker.h"
54#include "user.h"
55
8023f60b 56#if API_ALSA
dea8f8aa 57#include <alsa/asoundlib.h>
8023f60b 58#endif
dea8f8aa 59
5330d674 60#ifdef WORDS_BIGENDIAN
61# define MACHINE_AO_FMT AO_FMT_BIG
62#else
63# define MACHINE_AO_FMT AO_FMT_LITTLE
64#endif
65
460b9539 66#define BUFFER_SECONDS 5 /* How many seconds of input to
67 * buffer. */
68
69#define FRAMES 4096 /* Frame batch size */
70
71#define NFDS 256 /* Max FDs to poll for */
72
73/* Known tracks are kept in a linked list. We don't normally to have
74 * more than two - maybe three at the outside. */
75static struct track {
76 struct track *next; /* next track */
77 int fd; /* input FD */
78 char id[24]; /* ID */
79 size_t start, used; /* start + bytes used */
80 int eof; /* input is at EOF */
81 int got_format; /* got format yet? */
82 ao_sample_format format; /* sample format */
83 unsigned long long played; /* number of frames played */
84 char *buffer; /* sample buffer */
85 size_t size; /* sample buffer size */
86 int slot; /* poll array slot */
87} *tracks, *playing; /* all tracks + playing track */
88
89static time_t last_report; /* when we last reported */
90static int paused; /* pause status */
460b9539 91static ao_sample_format pcm_format; /* current format if aodev != 0 */
92static size_t bpf; /* bytes per frame */
93static struct pollfd fds[NFDS]; /* if we need more than that */
94static int fdno; /* fd number */
8023f60b 95static size_t bufsize; /* buffer size */
96#if API_ALSA
97static snd_pcm_t *pcm; /* current pcm handle */
0c207c37 98static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
8023f60b 99#endif
9d5da576 100static int ready; /* ready to send audio */
460b9539 101static int forceplay; /* frames to force play */
9d5da576 102static int kidfd = -1; /* child process input */
460b9539 103
104static const struct option options[] = {
105 { "help", no_argument, 0, 'h' },
106 { "version", no_argument, 0, 'V' },
107 { "config", required_argument, 0, 'c' },
108 { "debug", no_argument, 0, 'd' },
109 { "no-debug", no_argument, 0, 'D' },
110 { 0, 0, 0, 0 }
111};
112
113/* Display usage message and terminate. */
114static void help(void) {
115 xprintf("Usage:\n"
116 " disorder-speaker [OPTIONS]\n"
117 "Options:\n"
118 " --help, -h Display usage message\n"
119 " --version, -V Display version number\n"
120 " --config PATH, -c PATH Set configuration file\n"
121 " --debug, -d Turn on debugging\n"
122 "\n"
123 "Speaker process for DisOrder. Not intended to be run\n"
124 "directly.\n");
125 xfclose(stdout);
126 exit(0);
127}
128
129/* Display version number and terminate. */
130static void version(void) {
131 xprintf("disorder-speaker version %s\n", disorder_version_string);
132 xfclose(stdout);
133 exit(0);
134}
135
136/* Return the number of bytes per frame in FORMAT. */
137static size_t bytes_per_frame(const ao_sample_format *format) {
138 return format->channels * format->bits / 8;
139}
140
141/* Find track ID, maybe creating it if not found. */
142static struct track *findtrack(const char *id, int create) {
143 struct track *t;
144
145 D(("findtrack %s %d", id, create));
146 for(t = tracks; t && strcmp(id, t->id); t = t->next)
147 ;
148 if(!t && create) {
149 t = xmalloc(sizeof *t);
150 t->next = tracks;
151 strcpy(t->id, id);
152 t->fd = -1;
153 tracks = t;
154 /* The initial input buffer will be the sample format. */
155 t->buffer = (void *)&t->format;
156 t->size = sizeof t->format;
157 }
158 return t;
159}
160
161/* Remove track ID (but do not destroy it). */
162static struct track *removetrack(const char *id) {
163 struct track *t, **tt;
164
165 D(("removetrack %s", id));
166 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
167 ;
168 if(t)
169 *tt = t->next;
170 return t;
171}
172
173/* Destroy a track. */
174static void destroy(struct track *t) {
175 D(("destroy %s", t->id));
176 if(t->fd != -1) xclose(t->fd);
177 if(t->buffer != (void *)&t->format) free(t->buffer);
178 free(t);
179}
180
181/* Notice a new FD. */
182static void acquire(struct track *t, int fd) {
183 D(("acquire %s %d", t->id, fd));
184 if(t->fd != -1)
185 xclose(t->fd);
186 t->fd = fd;
187 nonblock(fd);
188}
189
190/* Read data into a sample buffer. Return 0 on success, -1 on EOF. */
191static int fill(struct track *t) {
192 size_t where, left;
193 int n;
194
195 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
196 t->id, t->eof, t->used, t->size, t->got_format));
197 if(t->eof) return -1;
198 if(t->used < t->size) {
199 /* there is room left in the buffer */
200 where = (t->start + t->used) % t->size;
201 if(t->got_format) {
202 /* We are reading audio data, get as much as we can */
203 if(where >= t->start) left = t->size - where;
204 else left = t->start - where;
205 } else
206 /* We are still waiting for the format, only get that */
207 left = sizeof (ao_sample_format) - t->used;
208 do {
209 n = read(t->fd, t->buffer + where, left);
210 } while(n < 0 && errno == EINTR);
211 if(n < 0) {
212 if(errno != EAGAIN) fatal(errno, "error reading sample stream");
213 return 0;
214 }
215 if(n == 0) {
216 D(("fill %s: eof detected", t->id));
217 t->eof = 1;
218 return -1;
219 }
220 t->used += n;
221 if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
222 assert(t->used == sizeof (ao_sample_format));
223 /* Check that our assumptions are met. */
224 if(t->format.bits & 7)
225 fatal(0, "bits per sample not a multiple of 8");
226 /* Make a new buffer for audio data. */
227 t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
228 t->buffer = xmalloc(t->size);
229 t->used = 0;
230 t->got_format = 1;
231 D(("got format for %s", t->id));
232 }
233 }
234 return 0;
235}
236
237/* Return true if A and B denote identical libao formats, else false. */
238static int formats_equal(const ao_sample_format *a,
239 const ao_sample_format *b) {
240 return (a->bits == b->bits
241 && a->rate == b->rate
242 && a->channels == b->channels
243 && a->byte_format == b->byte_format);
244}
245
246/* Close the sound device. */
247static void idle(void) {
460b9539 248 D(("idle"));
8023f60b 249#if API_ALSA
460b9539 250 if(pcm) {
8023f60b 251 int err;
252
460b9539 253 if((err = snd_pcm_nonblock(pcm, 0)) < 0)
254 fatal(0, "error calling snd_pcm_nonblock: %d", err);
255 D(("draining pcm"));
256 snd_pcm_drain(pcm);
257 D(("closing pcm"));
258 snd_pcm_close(pcm);
259 pcm = 0;
260 forceplay = 0;
261 D(("released audio device"));
262 }
8023f60b 263#endif
9d5da576 264 ready = 0;
460b9539 265}
266
267/* Abandon the current track */
268static void abandon(void) {
269 struct speaker_message sm;
270
271 D(("abandon"));
272 memset(&sm, 0, sizeof sm);
273 sm.type = SM_FINISHED;
274 strcpy(sm.id, playing->id);
275 speaker_send(1, &sm, 0);
276 removetrack(playing->id);
277 destroy(playing);
278 playing = 0;
279 forceplay = 0;
280}
281
8023f60b 282#if API_ALSA
1c6e6a61 283static void log_params(snd_pcm_hw_params_t *hwparams,
284 snd_pcm_sw_params_t *swparams) {
285 snd_pcm_uframes_t f;
286 unsigned u;
287
0c207c37 288 return; /* too verbose */
1c6e6a61 289 if(hwparams) {
290 /* TODO */
291 }
292 if(swparams) {
293 snd_pcm_sw_params_get_silence_size(swparams, &f);
294 info("sw silence_size=%lu", (unsigned long)f);
295 snd_pcm_sw_params_get_silence_threshold(swparams, &f);
296 info("sw silence_threshold=%lu", (unsigned long)f);
297 snd_pcm_sw_params_get_sleep_min(swparams, &u);
298 info("sw sleep_min=%lu", (unsigned long)u);
299 snd_pcm_sw_params_get_start_threshold(swparams, &f);
300 info("sw start_threshold=%lu", (unsigned long)f);
301 snd_pcm_sw_params_get_stop_threshold(swparams, &f);
302 info("sw stop_threshold=%lu", (unsigned long)f);
303 snd_pcm_sw_params_get_xfer_align(swparams, &f);
304 info("sw xfer_align=%lu", (unsigned long)f);
305 }
306}
8023f60b 307#endif
1c6e6a61 308
5330d674 309static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
9d5da576 310 int n;
311
312 *(*pp)++ = "-t.raw";
313 *(*pp)++ = "-s";
314 *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
5330d674 315 *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
316 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
317 * deployed! */
318 switch(config->sox_generation) {
319 case 0:
320 if(ao->bits != 8
321 && ao->byte_format != AO_FMT_NATIVE
322 && ao->byte_format != MACHINE_AO_FMT) {
323 *(*pp)++ = "-x";
324 }
325 switch(ao->bits) {
326 case 8: *(*pp)++ = "-b"; break;
327 case 16: *(*pp)++ = "-w"; break;
328 case 32: *(*pp)++ = "-l"; break;
329 case 64: *(*pp)++ = "-d"; break;
330 default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
331 }
332 break;
333 case 1:
334 switch(ao->byte_format) {
9d5da576 335 case AO_FMT_NATIVE: break;
27801653 336 case AO_FMT_BIG: *(*pp)++ = "-B"; break;
337 case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
5330d674 338 }
339 *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
340 break;
9d5da576 341 }
9d5da576 342}
343
460b9539 344/* Make sure the sound device is open and has the right sample format. Return
345 * 0 on success and -1 on error. */
346static int activate(void) {
460b9539 347 /* If we don't know the format yet we cannot start. */
348 if(!playing->got_format) {
349 D((" - not got format for %s", playing->id));
350 return -1;
351 }
9d5da576 352 if(kidfd >= 0) {
353 if(!formats_equal(&playing->format, &config->sample_format)) {
354 char argbuf[1024], *q = argbuf;
355 const char *av[18], **pp = av;
356 int soxpipe[2];
357 pid_t soxkid;
358 *pp++ = "sox";
359 soxargs(&pp, &q, &playing->format);
360 *pp++ = "-";
361 soxargs(&pp, &q, &config->sample_format);
362 *pp++ = "-";
363 *pp++ = 0;
364 if(debugging) {
365 for(pp = av; *pp; pp++)
366 D(("sox arg[%d] = %s", pp - av, *pp));
367 D(("end args"));
368 }
369 xpipe(soxpipe);
370 soxkid = xfork();
371 if(soxkid == 0) {
372 xdup2(playing->fd, 0);
373 xdup2(soxpipe[1], 1);
374 fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
375 close(soxpipe[0]);
376 close(soxpipe[1]);
377 close(playing->fd);
378 execvp("sox", (char **)av);
379 _exit(1);
380 }
381 D(("forking sox for format conversion (kid = %d)", soxkid));
382 close(playing->fd);
383 close(soxpipe[1]);
384 playing->fd = soxpipe[0];
385 playing->format = config->sample_format;
386 ready = 0;
387 }
388 if(!ready) {
389 pcm_format = config->sample_format;
8023f60b 390 bufsize = 3 * FRAMES;
9d5da576 391 bpf = bytes_per_frame(&config->sample_format);
392 D(("acquired audio device"));
393 ready = 1;
394 }
395 return 0;
396 }
4dac3d2a 397 if(config->speaker_command)
398 return -1;
8023f60b 399#if API_ALSA
460b9539 400 /* If we need to change format then close the current device. */
401 if(pcm && !formats_equal(&playing->format, &pcm_format))
402 idle();
403 if(!pcm) {
8023f60b 404 snd_pcm_hw_params_t *hwparams;
405 snd_pcm_sw_params_t *swparams;
406 snd_pcm_uframes_t pcm_bufsize;
407 int err;
408 int sample_format = 0;
409 unsigned rate;
410
460b9539 411 D(("snd_pcm_open"));
412 if((err = snd_pcm_open(&pcm,
413 config->device,
414 SND_PCM_STREAM_PLAYBACK,
415 SND_PCM_NONBLOCK))) {
416 error(0, "error from snd_pcm_open: %d", err);
417 goto error;
418 }
419 snd_pcm_hw_params_alloca(&hwparams);
420 D(("set up hw params"));
421 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
422 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
423 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
424 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
425 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
426 switch(playing->format.bits) {
427 case 8:
428 sample_format = SND_PCM_FORMAT_S8;
429 break;
430 case 16:
431 switch(playing->format.byte_format) {
432 case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
433 case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
434 case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
435 error(0, "unrecognized byte format %d", playing->format.byte_format);
436 goto fatal;
437 }
438 break;
439 default:
440 error(0, "unsupported sample size %d", playing->format.bits);
441 goto fatal;
442 }
443 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
444 sample_format)) < 0) {
445 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
446 sample_format, err);
447 goto fatal;
448 }
449 rate = playing->format.rate;
450 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
451 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
452 playing->format.rate, err);
453 goto fatal;
454 }
455 if(rate != (unsigned)playing->format.rate)
456 info("want rate %d, got %u", playing->format.rate, rate);
457 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
458 playing->format.channels)) < 0) {
459 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
460 playing->format.channels, err);
461 goto fatal;
462 }
8023f60b 463 bufsize = 3 * FRAMES;
464 pcm_bufsize = bufsize;
460b9539 465 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
466 &pcm_bufsize)) < 0)
467 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
468 3 * FRAMES, err);
0c207c37 469 if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
460b9539 470 info("asked for PCM buffer of %d frames, got %d",
471 3 * FRAMES, (int)pcm_bufsize);
0c207c37 472 last_pcm_bufsize = pcm_bufsize;
460b9539 473 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
474 fatal(0, "error calling snd_pcm_hw_params: %d", err);
475 D(("set up sw params"));
476 snd_pcm_sw_params_alloca(&swparams);
477 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
478 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
479 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
480 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
481 FRAMES, err);
482 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
483 fatal(0, "error calling snd_pcm_sw_params: %d", err);
484 pcm_format = playing->format;
485 bpf = bytes_per_frame(&pcm_format);
486 D(("acquired audio device"));
1c6e6a61 487 log_params(hwparams, swparams);
9d5da576 488 ready = 1;
460b9539 489 }
490 return 0;
491fatal:
492 abandon();
493error:
494 /* We assume the error is temporary and that we'll retry in a bit. */
495 if(pcm) {
496 snd_pcm_close(pcm);
497 pcm = 0;
498 }
8023f60b 499#endif
460b9539 500 return -1;
501}
502
503/* Check to see whether the current track has finished playing */
504static void maybe_finished(void) {
505 if(playing
506 && playing->eof
507 && (!playing->got_format
508 || playing->used < bytes_per_frame(&playing->format)))
509 abandon();
510}
511
9d5da576 512static void fork_kid(void) {
513 pid_t kid;
514 int pfd[2];
515 if(kidfd != -1) close(kidfd);
516 xpipe(pfd);
517 kid = xfork();
518 if(!kid) {
519 xdup2(pfd[0], 0);
520 close(pfd[0]);
521 close(pfd[1]);
522 execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
523 fatal(errno, "error execing /bin/sh");
524 }
525 close(pfd[0]);
526 kidfd = pfd[1];
527 D(("forked kid %d, fd = %d", kid, kidfd));
528}
529
460b9539 530static void play(size_t frames) {
8023f60b 531 size_t avail_bytes, written_frames;
9d5da576 532 ssize_t written_bytes;
460b9539 533
534 if(activate()) {
535 if(playing)
536 forceplay = frames;
537 else
538 forceplay = 0; /* Must have called abandon() */
539 return;
540 }
541 D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf,
542 playing->eof ? " EOF" : "",
543 playing->format.rate,
544 playing->format.bits,
545 playing->format.channels));
546 /* If we haven't got enough bytes yet wait until we have. Exception: when
547 * we are at eof. */
548 if(playing->used < frames * bpf && !playing->eof) {
549 forceplay = frames;
550 return;
551 }
552 /* We have got enough data so don't force play again */
553 forceplay = 0;
554 /* Figure out how many frames there are available to write */
555 if(playing->start + playing->used > playing->size)
556 avail_bytes = playing->size - playing->start;
557 else
558 avail_bytes = playing->used;
9d5da576 559
4dac3d2a 560 if(!config->speaker_command) {
8023f60b 561#if API_ALSA
562 snd_pcm_sframes_t pcm_written_frames;
563 size_t avail_frames;
564 int err;
565
9d5da576 566 avail_frames = avail_bytes / bpf;
567 if(avail_frames > frames)
568 avail_frames = frames;
569 if(!avail_frames)
460b9539 570 return;
8023f60b 571 pcm_written_frames = snd_pcm_writei(pcm,
572 playing->buffer + playing->start,
573 avail_frames);
9d5da576 574 D(("actually play %zu frames, wrote %d",
8023f60b 575 avail_frames, (int)pcm_written_frames));
576 if(pcm_written_frames < 0) {
577 switch(pcm_written_frames) {
9d5da576 578 case -EPIPE: /* underrun */
579 error(0, "snd_pcm_writei reports underrun");
580 if((err = snd_pcm_prepare(pcm)) < 0)
581 fatal(0, "error calling snd_pcm_prepare: %d", err);
582 return;
583 case -EAGAIN:
584 return;
585 default:
8023f60b 586 fatal(0, "error calling snd_pcm_writei: %d",
587 (int)pcm_written_frames);
9d5da576 588 }
589 }
8023f60b 590 written_frames = pcm_written_frames;
9d5da576 591 written_bytes = written_frames * bpf;
8023f60b 592#else
593 assert(!"reached");
594#endif
9d5da576 595 } else {
596 if(avail_bytes > frames * bpf)
597 avail_bytes = frames * bpf;
598 written_bytes = write(kidfd, playing->buffer + playing->start,
599 avail_bytes);
600 D(("actually play %zu bytes, wrote %d",
601 avail_bytes, (int)written_bytes));
602 if(written_bytes < 0) {
603 switch(errno) {
604 case EPIPE:
605 error(0, "hmm, kid died; trying another");
606 fork_kid();
607 return;
608 case EAGAIN:
609 return;
610 }
460b9539 611 }
9d5da576 612 written_frames = written_bytes / bpf; /* good enough */
460b9539 613 }
460b9539 614 playing->start += written_bytes;
615 playing->used -= written_bytes;
616 playing->played += written_frames;
617 /* If the pointer is at the end of the buffer (or the buffer is completely
618 * empty) wrap it back to the start. */
619 if(!playing->used || playing->start == playing->size)
620 playing->start = 0;
621 frames -= written_frames;
622}
623
624/* Notify the server what we're up to. */
625static void report(void) {
626 struct speaker_message sm;
627
628 if(playing && playing->buffer != (void *)&playing->format) {
629 memset(&sm, 0, sizeof sm);
630 sm.type = paused ? SM_PAUSED : SM_PLAYING;
631 strcpy(sm.id, playing->id);
632 sm.data = playing->played / playing->format.rate;
633 speaker_send(1, &sm, 0);
634 }
635 time(&last_report);
636}
637
9d5da576 638static void reap(int __attribute__((unused)) sig) {
639 pid_t kid;
640 int st;
641
642 do
643 kid = waitpid(-1, &st, WNOHANG);
644 while(kid > 0);
645 signal(SIGCHLD, reap);
646}
647
460b9539 648static int addfd(int fd, int events) {
649 if(fdno < NFDS) {
650 fds[fdno].fd = fd;
651 fds[fdno].events = events;
652 return fdno++;
653 } else
654 return -1;
655}
656
657int main(int argc, char **argv) {
8023f60b 658 int n, fd, stdin_slot, alsa_slots, kid_slot;
460b9539 659 struct track *t;
660 struct speaker_message sm;
8023f60b 661#if API_ALSA
662 int alsa_nslots = -1, err;
663#endif
460b9539 664
665 set_progname(argv);
666 mem_init(0);
667 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
668 while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
669 switch(n) {
670 case 'h': help();
671 case 'V': version();
672 case 'c': configfile = optarg; break;
673 case 'd': debugging = 1; break;
674 case 'D': debugging = 0; break;
675 default: fatal(0, "invalid option");
676 }
677 }
678 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
679 /* If stderr is a TTY then log there, otherwise to syslog. */
680 if(!isatty(2)) {
681 openlog(progname, LOG_PID, LOG_DAEMON);
682 log_default = &log_syslog;
683 }
684 if(config_read()) fatal(0, "cannot read configuration");
685 /* ignore SIGPIPE */
686 signal(SIGPIPE, SIG_IGN);
9d5da576 687 /* reap kids */
688 signal(SIGCHLD, reap);
460b9539 689 /* set nice value */
690 xnice(config->nice_speaker);
691 /* change user */
692 become_mortal();
693 /* make sure we're not root, whatever the config says */
694 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
695 info("started");
8023f60b 696 if(config->speaker_command)
697 fork_kid();
698 else {
699#if API_ALSA
700 /* ok */
701#else
702 fatal(0, "invoked speaker but no speaker_command and no known sound API");
703 #endif
704 }
460b9539 705 while(getppid() != 1) {
706 fdno = 0;
707 /* Always ready for commands from the main server. */
708 stdin_slot = addfd(0, POLLIN);
709 /* Try to read sample data for the currently playing track if there is
710 * buffer space. */
711 if(playing && !playing->eof && playing->used < playing->size) {
712 playing->slot = addfd(playing->fd, POLLIN);
713 } else if(playing)
714 playing->slot = -1;
715 /* If forceplay is set then wait until it succeeds before waiting on the
716 * sound device. */
9d5da576 717 alsa_slots = -1;
718 kid_slot = -1;
8023f60b 719 if(ready && !forceplay) {
4dac3d2a 720 if(config->speaker_command) {
721 if(kidfd >= 0)
722 kid_slot = addfd(kidfd, POLLOUT);
723 } else {
8023f60b 724#if API_ALSA
9d5da576 725 int retry = 3;
726
727 alsa_slots = fdno;
728 do {
729 retry = 0;
730 alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
731 if((alsa_nslots <= 0
732 || !(fds[alsa_slots].events & POLLOUT))
733 && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
734 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
735 if((err = snd_pcm_prepare(pcm)))
736 fatal(0, "error calling snd_pcm_prepare: %d", err);
737 } else
738 break;
739 } while(retry-- > 0);
740 if(alsa_nslots >= 0)
741 fdno += alsa_nslots;
8023f60b 742#endif
9d5da576 743 }
744 }
460b9539 745 /* If any other tracks don't have a full buffer, try to read sample data
746 * from them. */
747 for(t = tracks; t; t = t->next)
748 if(t != playing) {
749 if(!t->eof && t->used < t->size) {
9d5da576 750 t->slot = addfd(t->fd, POLLIN | POLLHUP);
460b9539 751 } else
752 t->slot = -1;
753 }
754 /* Wait up to a second before thinking about current state */
755 n = poll(fds, fdno, 1000);
756 if(n < 0) {
757 if(errno == EINTR) continue;
758 fatal(errno, "error calling poll");
759 }
760 /* Play some sound before doing anything else */
761 if(alsa_slots != -1) {
8023f60b 762#if API_ALSA
763 unsigned short alsa_revents;
764
460b9539 765 if((err = snd_pcm_poll_descriptors_revents(pcm,
766 &fds[alsa_slots],
767 alsa_nslots,
768 &alsa_revents)) < 0)
769 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
9d5da576 770 if(alsa_revents & (POLLOUT | POLLERR))
771 play(3 * FRAMES);
8023f60b 772#endif
9d5da576 773 } else if(kid_slot != -1) {
774 if(fds[kid_slot].revents & (POLLOUT | POLLERR))
460b9539 775 play(3 * FRAMES);
776 } else {
777 /* Some attempt to play must have failed */
778 if(playing && !paused)
779 play(forceplay);
780 else
781 forceplay = 0; /* just in case */
782 }
783 /* Perhaps we have a command to process */
784 if(fds[stdin_slot].revents & POLLIN) {
785 n = speaker_recv(0, &sm, &fd);
786 if(n > 0)
787 switch(sm.type) {
788 case SM_PREPARE:
789 D(("SM_PREPARE %s %d", sm.id, fd));
790 if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
791 t = findtrack(sm.id, 1);
792 acquire(t, fd);
793 break;
794 case SM_PLAY:
795 D(("SM_PLAY %s %d", sm.id, fd));
796 if(playing) fatal(0, "got SM_PLAY but already playing something");
797 t = findtrack(sm.id, 1);
798 if(fd != -1) acquire(t, fd);
799 playing = t;
8023f60b 800 play(bufsize);
460b9539 801 report();
802 break;
803 case SM_PAUSE:
804 D(("SM_PAUSE"));
805 paused = 1;
806 report();
807 break;
808 case SM_RESUME:
809 D(("SM_RESUME"));
810 if(paused) {
811 paused = 0;
812 if(playing)
8023f60b 813 play(bufsize);
460b9539 814 }
815 report();
816 break;
817 case SM_CANCEL:
818 D(("SM_CANCEL %s", sm.id));
819 t = removetrack(sm.id);
820 if(t) {
821 if(t == playing) {
822 sm.type = SM_FINISHED;
823 strcpy(sm.id, playing->id);
824 speaker_send(1, &sm, 0);
825 playing = 0;
826 }
827 destroy(t);
828 } else
829 error(0, "SM_CANCEL for unknown track %s", sm.id);
830 report();
831 break;
832 case SM_RELOAD:
833 D(("SM_RELOAD"));
834 if(config_read()) error(0, "cannot read configuration");
835 info("reloaded configuration");
836 break;
837 default:
838 error(0, "unknown message type %d", sm.type);
839 }
840 }
841 /* Read in any buffered data */
842 for(t = tracks; t; t = t->next)
9d5da576 843 if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
460b9539 844 fill(t);
845 /* We might be able to play now */
9d5da576 846 if(ready && forceplay && playing && !paused)
460b9539 847 play(forceplay);
848 /* Maybe we finished playing a track somewhere in the above */
849 maybe_finished();
850 /* If we don't need the sound device for now then close it for the benefit
851 * of anyone else who wants it. */
9d5da576 852 if((!playing || paused) && ready)
460b9539 853 idle();
854 /* If we've not reported out state for a second do so now. */
855 if(time(0) > last_report)
856 report();
857 }
858 info("stopped (parent terminated)");
859 exit(0);
860}
861
862/*
863Local Variables:
864c-basic-offset:2
865comment-column:40
866fill-column:79
867indent-tabs-mode:nil
868End:
869*/