2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2006, 2007 Richard Kettlewell
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.
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.
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
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
42 #include <sys/select.h>
46 #include "configuration.h"
55 #include <alsa/asoundlib.h>
57 #define BUFFER_SECONDS 5 /* How many seconds of input to
60 #define FRAMES 4096 /* Frame batch size */
62 #define NFDS 256 /* Max FDs to poll for */
64 /* Known tracks are kept in a linked list. We don't normally to have
65 * more than two - maybe three at the outside. */
67 struct track
*next
; /* next track */
68 int fd
; /* input FD */
70 size_t start
, used
; /* start + bytes used */
71 int eof
; /* input is at EOF */
72 int got_format
; /* got format yet? */
73 ao_sample_format format
; /* sample format */
74 unsigned long long played
; /* number of frames played */
75 char *buffer
; /* sample buffer */
76 size_t size
; /* sample buffer size */
77 int slot
; /* poll array slot */
78 } *tracks
, *playing
; /* all tracks + playing track */
80 static time_t last_report
; /* when we last reported */
81 static int paused
; /* pause status */
82 static snd_pcm_t
*pcm
; /* current pcm handle */
83 static ao_sample_format pcm_format
; /* current format if aodev != 0 */
84 static size_t bpf
; /* bytes per frame */
85 static struct pollfd fds
[NFDS
]; /* if we need more than that */
86 static int fdno
; /* fd number */
87 static snd_pcm_uframes_t pcm_bufsize
; /* buffer size */
88 static snd_pcm_uframes_t last_pcm_bufsize
; /* last seen buffer size */
89 static int ready
; /* ready to send audio */
90 static int forceplay
; /* frames to force play */
91 static int kidfd
= -1; /* child process input */
93 static const struct option options
[] = {
94 { "help", no_argument
, 0, 'h' },
95 { "version", no_argument
, 0, 'V' },
96 { "config", required_argument
, 0, 'c' },
97 { "debug", no_argument
, 0, 'd' },
98 { "no-debug", no_argument
, 0, 'D' },
102 /* Display usage message and terminate. */
103 static void help(void) {
105 " disorder-speaker [OPTIONS]\n"
107 " --help, -h Display usage message\n"
108 " --version, -V Display version number\n"
109 " --config PATH, -c PATH Set configuration file\n"
110 " --debug, -d Turn on debugging\n"
112 "Speaker process for DisOrder. Not intended to be run\n"
118 /* Display version number and terminate. */
119 static void version(void) {
120 xprintf("disorder-speaker version %s\n", disorder_version_string
);
125 /* Return the number of bytes per frame in FORMAT. */
126 static size_t bytes_per_frame(const ao_sample_format
*format
) {
127 return format
->channels
* format
->bits
/ 8;
130 /* Find track ID, maybe creating it if not found. */
131 static struct track
*findtrack(const char *id
, int create
) {
134 D(("findtrack %s %d", id
, create
));
135 for(t
= tracks
; t
&& strcmp(id
, t
->id
); t
= t
->next
)
138 t
= xmalloc(sizeof *t
);
143 /* The initial input buffer will be the sample format. */
144 t
->buffer
= (void *)&t
->format
;
145 t
->size
= sizeof t
->format
;
150 /* Remove track ID (but do not destroy it). */
151 static struct track
*removetrack(const char *id
) {
152 struct track
*t
, **tt
;
154 D(("removetrack %s", id
));
155 for(tt
= &tracks
; (t
= *tt
) && strcmp(id
, t
->id
); tt
= &t
->next
)
162 /* Destroy a track. */
163 static void destroy(struct track
*t
) {
164 D(("destroy %s", t
->id
));
165 if(t
->fd
!= -1) xclose(t
->fd
);
166 if(t
->buffer
!= (void *)&t
->format
) free(t
->buffer
);
170 /* Notice a new FD. */
171 static void acquire(struct track
*t
, int fd
) {
172 D(("acquire %s %d", t
->id
, fd
));
179 /* Read data into a sample buffer. Return 0 on success, -1 on EOF. */
180 static int fill(struct track
*t
) {
184 D(("fill %s: eof=%d used=%zu size=%zu got_format=%d",
185 t
->id
, t
->eof
, t
->used
, t
->size
, t
->got_format
));
186 if(t
->eof
) return -1;
187 if(t
->used
< t
->size
) {
188 /* there is room left in the buffer */
189 where
= (t
->start
+ t
->used
) % t
->size
;
191 /* We are reading audio data, get as much as we can */
192 if(where
>= t
->start
) left
= t
->size
- where
;
193 else left
= t
->start
- where
;
195 /* We are still waiting for the format, only get that */
196 left
= sizeof (ao_sample_format
) - t
->used
;
198 n
= read(t
->fd
, t
->buffer
+ where
, left
);
199 } while(n
< 0 && errno
== EINTR
);
201 if(errno
!= EAGAIN
) fatal(errno
, "error reading sample stream");
205 D(("fill %s: eof detected", t
->id
));
210 if(!t
->got_format
&& t
->used
>= sizeof (ao_sample_format
)) {
211 assert(t
->used
== sizeof (ao_sample_format
));
212 /* Check that our assumptions are met. */
213 if(t
->format
.bits
& 7)
214 fatal(0, "bits per sample not a multiple of 8");
215 /* Make a new buffer for audio data. */
216 t
->size
= bytes_per_frame(&t
->format
) * t
->format
.rate
* BUFFER_SECONDS
;
217 t
->buffer
= xmalloc(t
->size
);
220 D(("got format for %s", t
->id
));
226 /* Return true if A and B denote identical libao formats, else false. */
227 static int formats_equal(const ao_sample_format
*a
,
228 const ao_sample_format
*b
) {
229 return (a
->bits
== b
->bits
230 && a
->rate
== b
->rate
231 && a
->channels
== b
->channels
232 && a
->byte_format
== b
->byte_format
);
235 /* Close the sound device. */
236 static void idle(void) {
241 if((err
= snd_pcm_nonblock(pcm
, 0)) < 0)
242 fatal(0, "error calling snd_pcm_nonblock: %d", err
);
249 D(("released audio device"));
254 /* Abandon the current track */
255 static void abandon(void) {
256 struct speaker_message sm
;
259 memset(&sm
, 0, sizeof sm
);
260 sm
.type
= SM_FINISHED
;
261 strcpy(sm
.id
, playing
->id
);
262 speaker_send(1, &sm
, 0);
263 removetrack(playing
->id
);
269 static void log_params(snd_pcm_hw_params_t
*hwparams
,
270 snd_pcm_sw_params_t
*swparams
) {
274 return; /* too verbose */
279 snd_pcm_sw_params_get_silence_size(swparams
, &f
);
280 info("sw silence_size=%lu", (unsigned long)f
);
281 snd_pcm_sw_params_get_silence_threshold(swparams
, &f
);
282 info("sw silence_threshold=%lu", (unsigned long)f
);
283 snd_pcm_sw_params_get_sleep_min(swparams
, &u
);
284 info("sw sleep_min=%lu", (unsigned long)u
);
285 snd_pcm_sw_params_get_start_threshold(swparams
, &f
);
286 info("sw start_threshold=%lu", (unsigned long)f
);
287 snd_pcm_sw_params_get_stop_threshold(swparams
, &f
);
288 info("sw stop_threshold=%lu", (unsigned long)f
);
289 snd_pcm_sw_params_get_xfer_align(swparams
, &f
);
290 info("sw xfer_align=%lu", (unsigned long)f
);
294 static void soxargs(const char ***pp
, char **qq
, ao_sample_format
*ao
)
300 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-r%d", ao
->rate
); *qq
+= n
+ 1;
301 switch(ao
->byte_format
) {
302 case AO_FMT_NATIVE
: break;
303 case AO_FMT_BIG
: *(*pp
)++ = "-B";
304 case AO_FMT_LITTLE
: *(*pp
)++ = "-L";
306 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-%d", ao
->bits
/8); *qq
+= n
+ 1;
307 *(*pp
)++ = *qq
; n
= sprintf(*qq
, "-c%d", ao
->channels
); *qq
+= n
+ 1;
310 /* Make sure the sound device is open and has the right sample format. Return
311 * 0 on success and -1 on error. */
312 static int activate(void) {
314 snd_pcm_hw_params_t
*hwparams
;
315 snd_pcm_sw_params_t
*swparams
;
316 int sample_format
= 0;
319 /* If we don't know the format yet we cannot start. */
320 if(!playing
->got_format
) {
321 D((" - not got format for %s", playing
->id
));
325 if(!formats_equal(&playing
->format
, &config
->sample_format
)) {
326 char argbuf
[1024], *q
= argbuf
;
327 const char *av
[18], **pp
= av
;
331 soxargs(&pp
, &q
, &playing
->format
);
333 soxargs(&pp
, &q
, &config
->sample_format
);
337 for(pp
= av
; *pp
; pp
++)
338 D(("sox arg[%d] = %s", pp
- av
, *pp
));
344 xdup2(playing
->fd
, 0);
345 xdup2(soxpipe
[1], 1);
346 fcntl(0, F_SETFL
, fcntl(0, F_GETFL
) & ~O_NONBLOCK
);
350 execvp("sox", (char **)av
);
353 D(("forking sox for format conversion (kid = %d)", soxkid
));
356 playing
->fd
= soxpipe
[0];
357 playing
->format
= config
->sample_format
;
361 pcm_format
= config
->sample_format
;
362 pcm_bufsize
= 3 * FRAMES
;
363 bpf
= bytes_per_frame(&config
->sample_format
);
364 D(("acquired audio device"));
369 /* If we need to change format then close the current device. */
370 if(pcm
&& !formats_equal(&playing
->format
, &pcm_format
))
374 if((err
= snd_pcm_open(&pcm
,
376 SND_PCM_STREAM_PLAYBACK
,
377 SND_PCM_NONBLOCK
))) {
378 error(0, "error from snd_pcm_open: %d", err
);
381 snd_pcm_hw_params_alloca(&hwparams
);
382 D(("set up hw params"));
383 if((err
= snd_pcm_hw_params_any(pcm
, hwparams
)) < 0)
384 fatal(0, "error from snd_pcm_hw_params_any: %d", err
);
385 if((err
= snd_pcm_hw_params_set_access(pcm
, hwparams
,
386 SND_PCM_ACCESS_RW_INTERLEAVED
)) < 0)
387 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err
);
388 switch(playing
->format
.bits
) {
390 sample_format
= SND_PCM_FORMAT_S8
;
393 switch(playing
->format
.byte_format
) {
394 case AO_FMT_NATIVE
: sample_format
= SND_PCM_FORMAT_S16
; break;
395 case AO_FMT_LITTLE
: sample_format
= SND_PCM_FORMAT_S16_LE
; break;
396 case AO_FMT_BIG
: sample_format
= SND_PCM_FORMAT_S16_BE
; break;
397 error(0, "unrecognized byte format %d", playing
->format
.byte_format
);
402 error(0, "unsupported sample size %d", playing
->format
.bits
);
405 if((err
= snd_pcm_hw_params_set_format(pcm
, hwparams
,
406 sample_format
)) < 0) {
407 error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
411 rate
= playing
->format
.rate
;
412 if((err
= snd_pcm_hw_params_set_rate_near(pcm
, hwparams
, &rate
, 0)) < 0) {
413 error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
414 playing
->format
.rate
, err
);
417 if(rate
!= (unsigned)playing
->format
.rate
)
418 info("want rate %d, got %u", playing
->format
.rate
, rate
);
419 if((err
= snd_pcm_hw_params_set_channels(pcm
, hwparams
,
420 playing
->format
.channels
)) < 0) {
421 error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
422 playing
->format
.channels
, err
);
425 pcm_bufsize
= 3 * FRAMES
;
426 if((err
= snd_pcm_hw_params_set_buffer_size_near(pcm
, hwparams
,
428 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
430 if(pcm_bufsize
!= 3 * FRAMES
&& pcm_bufsize
!= last_pcm_bufsize
)
431 info("asked for PCM buffer of %d frames, got %d",
432 3 * FRAMES
, (int)pcm_bufsize
);
433 last_pcm_bufsize
= pcm_bufsize
;
434 if((err
= snd_pcm_hw_params(pcm
, hwparams
)) < 0)
435 fatal(0, "error calling snd_pcm_hw_params: %d", err
);
436 D(("set up sw params"));
437 snd_pcm_sw_params_alloca(&swparams
);
438 if((err
= snd_pcm_sw_params_current(pcm
, swparams
)) < 0)
439 fatal(0, "error calling snd_pcm_sw_params_current: %d", err
);
440 if((err
= snd_pcm_sw_params_set_avail_min(pcm
, swparams
, FRAMES
)) < 0)
441 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
443 if((err
= snd_pcm_sw_params(pcm
, swparams
)) < 0)
444 fatal(0, "error calling snd_pcm_sw_params: %d", err
);
445 pcm_format
= playing
->format
;
446 bpf
= bytes_per_frame(&pcm_format
);
447 D(("acquired audio device"));
448 log_params(hwparams
, swparams
);
455 /* We assume the error is temporary and that we'll retry in a bit. */
463 /* Check to see whether the current track has finished playing */
464 static void maybe_finished(void) {
467 && (!playing
->got_format
468 || playing
->used
< bytes_per_frame(&playing
->format
)))
472 static void fork_kid(void) {
475 if(kidfd
!= -1) close(kidfd
);
482 execl("/bin/sh", "sh", "-c", config
->speaker_command
, (char *)0);
483 fatal(errno
, "error execing /bin/sh");
487 D(("forked kid %d, fd = %d", kid
, kidfd
));
490 static void play(size_t frames
) {
491 snd_pcm_sframes_t written_frames
;
492 size_t avail_bytes
, avail_frames
;
493 ssize_t written_bytes
;
500 forceplay
= 0; /* Must have called abandon() */
503 D(("play: play %zu/%zu%s %dHz %db %dc", frames
, playing
->used
/ bpf
,
504 playing
->eof ?
" EOF" : "",
505 playing
->format
.rate
,
506 playing
->format
.bits
,
507 playing
->format
.channels
));
508 /* If we haven't got enough bytes yet wait until we have. Exception: when
510 if(playing
->used
< frames
* bpf
&& !playing
->eof
) {
514 /* We have got enough data so don't force play again */
516 /* Figure out how many frames there are available to write */
517 if(playing
->start
+ playing
->used
> playing
->size
)
518 avail_bytes
= playing
->size
- playing
->start
;
520 avail_bytes
= playing
->used
;
523 avail_frames
= avail_bytes
/ bpf
;
524 if(avail_frames
> frames
)
525 avail_frames
= frames
;
528 written_frames
= snd_pcm_writei(pcm
,
529 playing
->buffer
+ playing
->start
,
531 D(("actually play %zu frames, wrote %d",
532 avail_frames
, (int)written_frames
));
533 if(written_frames
< 0) {
534 switch(written_frames
) {
535 case -EPIPE
: /* underrun */
536 error(0, "snd_pcm_writei reports underrun");
537 if((err
= snd_pcm_prepare(pcm
)) < 0)
538 fatal(0, "error calling snd_pcm_prepare: %d", err
);
543 fatal(0, "error calling snd_pcm_writei: %d", (int)written_frames
);
546 written_bytes
= written_frames
* bpf
;
548 if(avail_bytes
> frames
* bpf
)
549 avail_bytes
= frames
* bpf
;
550 written_bytes
= write(kidfd
, playing
->buffer
+ playing
->start
,
552 D(("actually play %zu bytes, wrote %d",
553 avail_bytes
, (int)written_bytes
));
554 if(written_bytes
< 0) {
557 error(0, "hmm, kid died; trying another");
564 written_frames
= written_bytes
/ bpf
; /* good enough */
566 playing
->start
+= written_bytes
;
567 playing
->used
-= written_bytes
;
568 playing
->played
+= written_frames
;
569 /* If the pointer is at the end of the buffer (or the buffer is completely
570 * empty) wrap it back to the start. */
571 if(!playing
->used
|| playing
->start
== playing
->size
)
573 frames
-= written_frames
;
576 /* Notify the server what we're up to. */
577 static void report(void) {
578 struct speaker_message sm
;
580 if(playing
&& playing
->buffer
!= (void *)&playing
->format
) {
581 memset(&sm
, 0, sizeof sm
);
582 sm
.type
= paused ? SM_PAUSED
: SM_PLAYING
;
583 strcpy(sm
.id
, playing
->id
);
584 sm
.data
= playing
->played
/ playing
->format
.rate
;
585 speaker_send(1, &sm
, 0);
590 static void reap(int __attribute__((unused
)) sig
) {
595 kid
= waitpid(-1, &st
, WNOHANG
);
597 signal(SIGCHLD
, reap
);
600 static int addfd(int fd
, int events
) {
603 fds
[fdno
].events
= events
;
609 int main(int argc
, char **argv
) {
610 int n
, fd
, stdin_slot
, alsa_slots
, alsa_nslots
= -1, kid_slot
, err
;
611 unsigned short alsa_revents
;
613 struct speaker_message sm
;
617 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
618 while((n
= getopt_long(argc
, argv
, "hVc:dD", options
, 0)) >= 0) {
622 case 'c': configfile
= optarg
; break;
623 case 'd': debugging
= 1; break;
624 case 'D': debugging
= 0; break;
625 default: fatal(0, "invalid option");
628 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging
= 1;
629 /* If stderr is a TTY then log there, otherwise to syslog. */
631 openlog(progname
, LOG_PID
, LOG_DAEMON
);
632 log_default
= &log_syslog
;
634 if(config_read()) fatal(0, "cannot read configuration");
636 signal(SIGPIPE
, SIG_IGN
);
638 signal(SIGCHLD
, reap
);
640 xnice(config
->nice_speaker
);
643 /* make sure we're not root, whatever the config says */
644 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
646 if(config
->speaker_command
) fork_kid();
647 while(getppid() != 1) {
649 /* Always ready for commands from the main server. */
650 stdin_slot
= addfd(0, POLLIN
);
651 /* Try to read sample data for the currently playing track if there is
653 if(playing
&& !playing
->eof
&& playing
->used
< playing
->size
) {
654 playing
->slot
= addfd(playing
->fd
, POLLIN
);
657 /* If forceplay is set then wait until it succeeds before waiting on the
661 if(pcm
&& !forceplay
) {
663 kid_slot
= addfd(kidfd
, POLLOUT
);
670 alsa_nslots
= snd_pcm_poll_descriptors(pcm
, &fds
[fdno
], NFDS
- fdno
);
672 || !(fds
[alsa_slots
].events
& POLLOUT
))
673 && snd_pcm_state(pcm
) == SND_PCM_STATE_XRUN
) {
674 error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
675 if((err
= snd_pcm_prepare(pcm
)))
676 fatal(0, "error calling snd_pcm_prepare: %d", err
);
679 } while(retry
-- > 0);
684 /* If any other tracks don't have a full buffer, try to read sample data
686 for(t
= tracks
; t
; t
= t
->next
)
688 if(!t
->eof
&& t
->used
< t
->size
) {
689 t
->slot
= addfd(t
->fd
, POLLIN
| POLLHUP
);
693 /* Wait up to a second before thinking about current state */
694 n
= poll(fds
, fdno
, 1000);
696 if(errno
== EINTR
) continue;
697 fatal(errno
, "error calling poll");
699 /* Play some sound before doing anything else */
700 if(alsa_slots
!= -1) {
701 if((err
= snd_pcm_poll_descriptors_revents(pcm
,
705 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err
);
706 if(alsa_revents
& (POLLOUT
| POLLERR
))
708 } else if(kid_slot
!= -1) {
709 if(fds
[kid_slot
].revents
& (POLLOUT
| POLLERR
))
712 /* Some attempt to play must have failed */
713 if(playing
&& !paused
)
716 forceplay
= 0; /* just in case */
718 /* Perhaps we have a command to process */
719 if(fds
[stdin_slot
].revents
& POLLIN
) {
720 n
= speaker_recv(0, &sm
, &fd
);
724 D(("SM_PREPARE %s %d", sm
.id
, fd
));
725 if(fd
== -1) fatal(0, "got SM_PREPARE but no file descriptor");
726 t
= findtrack(sm
.id
, 1);
730 D(("SM_PLAY %s %d", sm
.id
, fd
));
731 if(playing
) fatal(0, "got SM_PLAY but already playing something");
732 t
= findtrack(sm
.id
, 1);
733 if(fd
!= -1) acquire(t
, fd
);
753 D(("SM_CANCEL %s", sm
.id
));
754 t
= removetrack(sm
.id
);
757 sm
.type
= SM_FINISHED
;
758 strcpy(sm
.id
, playing
->id
);
759 speaker_send(1, &sm
, 0);
764 error(0, "SM_CANCEL for unknown track %s", sm
.id
);
769 if(config_read()) error(0, "cannot read configuration");
770 info("reloaded configuration");
773 error(0, "unknown message type %d", sm
.type
);
776 /* Read in any buffered data */
777 for(t
= tracks
; t
; t
= t
->next
)
778 if(t
->slot
!= -1 && (fds
[t
->slot
].revents
& (POLLIN
| POLLHUP
)))
780 /* We might be able to play now */
781 if(ready
&& forceplay
&& playing
&& !paused
)
783 /* Maybe we finished playing a track somewhere in the above */
785 /* If we don't need the sound device for now then close it for the benefit
786 * of anyone else who wants it. */
787 if((!playing
|| paused
) && ready
)
789 /* If we've not reported out state for a second do so now. */
790 if(time(0) > last_report
)
793 info("stopped (parent terminated)");
797 int main(int attribute((unused
)) argc
, char **argv
) {
800 fatal(0, "disorder-speaker not supported on this platform");