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
20 /** @file server/speaker.c
21 * @brief Speaker process
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.
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.)
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).
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
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
64 #include <sys/select.h>
71 #include "configuration.h"
76 #include "speaker-protocol.h"
80 /** @brief Linked list of all prepared tracks */
83 /** @brief Playing track, or NULL */
84 struct track
*playing
;
86 /** @brief Number of bytes pre frame */
89 /** @brief Array of file descriptors for poll() */
90 struct pollfd fds
[NFDS
];
92 /** @brief Next free slot in @ref fds */
95 /** @brief Listen socket */
98 static time_t last_report
; /* when we last reported */
99 static int paused
; /* pause status */
101 /** @brief The current device state */
102 enum device_states device_state
;
104 /** @brief Set when idled
106 * This is set when the sound device is deliberately closed by idle().
110 /** @brief Selected backend */
111 static const struct speaker_backend
*backend
;
113 static const struct option options
[] = {
114 { "help", no_argument
, 0, 'h' },
115 { "version", no_argument
, 0, 'V' },
116 { "config", required_argument
, 0, 'c' },
117 { "debug", no_argument
, 0, 'd' },
118 { "no-debug", no_argument
, 0, 'D' },
122 /* Display usage message and terminate. */
123 static void help(void) {
125 " disorder-speaker [OPTIONS]\n"
127 " --help, -h Display usage message\n"
128 " --version, -V Display version number\n"
129 " --config PATH, -c PATH Set configuration file\n"
130 " --debug, -d Turn on debugging\n"
132 "Speaker process for DisOrder. Not intended to be run\n"
138 /* Display version number and terminate. */
139 static void version(void) {
140 xprintf("disorder-speaker version %s\n", disorder_version_string
);
145 /** @brief Return the number of bytes per frame in @p format */
146 static size_t bytes_per_frame(const struct stream_header
*format
) {
147 return format
->channels
* format
->bits
/ 8;
150 /** @brief Find track @p id, maybe creating it if not found */
151 static struct track
*findtrack(const char *id
, int create
) {
154 D(("findtrack %s %d", id
, create
));
155 for(t
= tracks
; t
&& strcmp(id
, t
->id
); t
= t
->next
)
158 t
= xmalloc(sizeof *t
);
167 /** @brief Remove track @p id (but do not destroy it) */
168 static struct track
*removetrack(const char *id
) {
169 struct track
*t
, **tt
;
171 D(("removetrack %s", id
));
172 for(tt
= &tracks
; (t
= *tt
) && strcmp(id
, t
->id
); tt
= &t
->next
)
179 /** @brief Destroy a track */
180 static void destroy(struct track
*t
) {
181 D(("destroy %s", t
->id
));
182 if(t
->fd
!= -1) xclose(t
->fd
);
186 /** @brief Read data into a sample buffer
187 * @param t Pointer to track
188 * @return 0 on success, -1 on EOF
190 * This is effectively the read callback on @c t->fd. It is called from the
191 * main loop whenever the track's file descriptor is readable, assuming the
192 * buffer has not reached the maximum allowed occupancy.
194 static int fill(struct track
*t
) {
198 D(("fill %s: eof=%d used=%zu",
199 t
->id
, t
->eof
, t
->used
));
200 if(t
->eof
) return -1;
201 if(t
->used
< sizeof t
->buffer
) {
202 /* there is room left in the buffer */
203 where
= (t
->start
+ t
->used
) % sizeof t
->buffer
;
204 /* Get as much data as we can */
205 if(where
>= t
->start
) left
= (sizeof t
->buffer
) - where
;
206 else left
= t
->start
- where
;
208 n
= read(t
->fd
, t
->buffer
+ where
, left
);
209 } while(n
< 0 && errno
== EINTR
);
211 if(errno
!= EAGAIN
) fatal(errno
, "error reading sample stream");
215 D(("fill %s: eof detected", t
->id
));
224 /** @brief Close the sound device
226 * This is called to deactivate the output device when pausing, and also by the
227 * ALSA backend when changing encoding (in which case the sound device will be
228 * immediately reactivated).
230 static void idle(void) {
232 if(backend
->deactivate
)
233 backend
->deactivate();
235 device_state
= device_closed
;
239 /** @brief Abandon the current track */
241 struct speaker_message sm
;
244 memset(&sm
, 0, sizeof sm
);
245 sm
.type
= SM_FINISHED
;
246 strcpy(sm
.id
, playing
->id
);
247 speaker_send(1, &sm
);
248 removetrack(playing
->id
);
253 /** @brief Enable sound output
255 * Makes sure the sound device is open and has the right sample format. Return
256 * 0 on success and -1 on error.
258 static void activate(void) {
259 if(backend
->activate
)
262 device_state
= device_open
;
265 /** @brief Check whether the current track has finished
267 * The current track is determined to have finished either if the input stream
268 * eded before the format could be determined (i.e. it is malformed) or the
269 * input is at end of file and there is less than a frame left unplayed. (So
270 * it copes with decoders that crash mid-frame.)
272 static void maybe_finished(void) {
275 && playing
->used
< bytes_per_frame(&config
->sample_format
))
279 /** @brief Play up to @p frames frames of audio
281 * It is always safe to call this function.
282 * - If @ref playing is 0 then it will just return
283 * - If @ref paused is non-0 then it will just return
284 * - If @ref device_state != @ref device_open then it will call activate() and
285 * return if it it fails.
286 * - If there is not enough audio to play then it play what is available.
288 * If there are not enough frames to play then whatever is available is played
289 * instead. It is up to mainloop() to ensure that play() is not called when
290 * unreasonably only an small amounts of data is available to play.
292 static void play(size_t frames
) {
293 size_t avail_frames
, avail_bytes
, written_frames
;
294 ssize_t written_bytes
;
296 /* Make sure there's a track to play and it is not pasued */
297 if(!playing
|| paused
)
299 /* Make sure the output device is open */
300 if(device_state
!= device_open
) {
302 if(device_state
!= device_open
)
305 D(("play: play %zu/%zu%s %dHz %db %dc", frames
, playing
->used
/ bpf
,
306 playing
->eof ?
" EOF" : "",
307 config
->sample_format
.rate
,
308 config
->sample_format
.bits
,
309 config
->sample_format
.channels
));
310 /* Figure out how many frames there are available to write */
311 if(playing
->start
+ playing
->used
> sizeof playing
->buffer
)
312 /* The ring buffer is currently wrapped, only play up to the wrap point */
313 avail_bytes
= (sizeof playing
->buffer
) - playing
->start
;
315 /* The ring buffer is not wrapped, can play the lot */
316 avail_bytes
= playing
->used
;
317 avail_frames
= avail_bytes
/ bpf
;
318 /* Only play up to the requested amount */
319 if(avail_frames
> frames
)
320 avail_frames
= frames
;
324 written_frames
= backend
->play(avail_frames
);
325 written_bytes
= written_frames
* bpf
;
326 /* written_bytes and written_frames had better both be set and correct by
328 playing
->start
+= written_bytes
;
329 playing
->used
-= written_bytes
;
330 playing
->played
+= written_frames
;
331 /* If the pointer is at the end of the buffer (or the buffer is completely
332 * empty) wrap it back to the start. */
333 if(!playing
->used
|| playing
->start
== (sizeof playing
->buffer
))
335 frames
-= written_frames
;
339 /* Notify the server what we're up to. */
340 static void report(void) {
341 struct speaker_message sm
;
344 memset(&sm
, 0, sizeof sm
);
345 sm
.type
= paused ? SM_PAUSED
: SM_PLAYING
;
346 strcpy(sm
.id
, playing
->id
);
347 sm
.data
= playing
->played
/ config
->sample_format
.rate
;
348 speaker_send(1, &sm
);
353 static void reap(int __attribute__((unused
)) sig
) {
358 cmdpid
= waitpid(-1, &st
, WNOHANG
);
360 signal(SIGCHLD
, reap
);
363 int addfd(int fd
, int events
) {
366 fds
[fdno
].events
= events
;
372 /** @brief Table of speaker backends */
373 static const struct speaker_backend
*backends
[] = {
382 /** @brief Return nonzero if we want to play some audio
384 * We want to play audio if there is a current track; and it is not paused; and
385 * there are at least @ref FRAMES frames of audio to play, or we are in sight
386 * of the end of the current track.
388 static int playable(void) {
391 && (playing
->used
>= FRAMES
|| playing
->eof
);
394 /** @brief Main event loop */
395 static void mainloop(void) {
397 struct speaker_message sm
;
398 int n
, fd
, stdin_slot
, timeout
, listen_slot
;
400 while(getppid() != 1) {
402 /* By default we will wait up to a second before thinking about current
405 /* Always ready for commands from the main server. */
406 stdin_slot
= addfd(0, POLLIN
);
407 /* Also always ready for inbound connections */
408 listen_slot
= addfd(listenfd
, POLLIN
);
409 /* Try to read sample data for the currently playing track if there is
414 && playing
->used
< (sizeof playing
->buffer
))
415 playing
->slot
= addfd(playing
->fd
, POLLIN
);
419 /* We want to play some audio. If the device is closed then we attempt
421 if(device_state
== device_closed
)
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
427 if(device_state
== device_open
)
428 backend
->beforepoll();
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
)
437 && t
->used
< sizeof t
->buffer
) {
438 t
->slot
= addfd(t
->fd
, POLLIN
| POLLHUP
);
442 /* Wait for something interesting to happen */
443 n
= poll(fds
, fdno
, timeout
);
445 if(errno
== EINTR
) continue;
446 fatal(errno
, "error calling poll");
448 /* Play some sound before doing anything else */
450 /* We want to play some audio */
451 if(device_state
== device_open
) {
455 /* We must be in _closed or _error, and it should be the latter, but we
458 * We most likely timed out, so now is a good time to retry. play()
459 * knows to re-activate the device if necessary.
464 /* Perhaps a connection has arrived */
465 if(fds
[listen_slot
].revents
& POLLIN
) {
466 struct sockaddr_un addr
;
467 socklen_t addrlen
= sizeof addr
;
471 if((fd
= accept(listenfd
, &addr
, &addrlen
)) >= 0) {
472 if(read(fd
, &l
, sizeof l
) < 4) {
473 error(errno
, "reading length from inbound connection");
475 } else if(l
>= sizeof id
) {
476 error(0, "id length too long");
478 } else if(read(fd
, id
, l
) < (ssize_t
)l
) {
479 error(errno
, "reading id from inbound connection");
483 D(("id %s fd %d", id
, fd
));
484 t
= findtrack(id
, 1/*create*/);
485 write(fd
, "", 1); /* write an ack */
487 error(0, "got a connection for a track that already has one");
491 t
->fd
= fd
; /* yay */
495 error(errno
, "accept");
497 /* Perhaps we have a command to process */
498 if(fds
[stdin_slot
].revents
& POLLIN
) {
499 /* There might (in theory) be several commands queued up, but in general
500 * this won't be the case, so we don't bother looping around to pick them
502 n
= speaker_recv(0, &sm
);
507 if(playing
) fatal(0, "got SM_PLAY but already playing something");
508 t
= findtrack(sm
.id
, 1);
509 D(("SM_PLAY %s fd %d", t
->id
, t
->fd
));
511 error(0, "cannot play track because no connection arrived");
513 /* We attempt to play straight away rather than going round the loop.
514 * play() is clever enough to perform any activation that is
528 /* As for SM_PLAY we attempt to play straight away. */
535 D(("SM_CANCEL %s", sm
.id
));
536 t
= removetrack(sm
.id
);
539 sm
.type
= SM_FINISHED
;
540 strcpy(sm
.id
, playing
->id
);
541 speaker_send(1, &sm
);
546 error(0, "SM_CANCEL for unknown track %s", sm
.id
);
551 if(config_read(1)) error(0, "cannot read configuration");
552 info("reloaded configuration");
555 error(0, "unknown message type %d", sm
.type
);
558 /* Read in any buffered data */
559 for(t
= tracks
; t
; t
= t
->next
)
562 && (fds
[t
->slot
].revents
& (POLLIN
| POLLHUP
)))
564 /* Maybe we finished playing a track somewhere in the above */
566 /* If we don't need the sound device for now then close it for the benefit
567 * of anyone else who wants it. */
568 if((!playing
|| paused
) && device_state
== device_open
)
570 /* If we've not reported out state for a second do so now. */
571 if(time(0) > last_report
)
576 int main(int argc
, char **argv
) {
578 struct sockaddr_un addr
;
579 static const int one
= 1;
582 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
583 while((n
= getopt_long(argc
, argv
, "hVc:dD", options
, 0)) >= 0) {
587 case 'c': configfile
= optarg
; break;
588 case 'd': debugging
= 1; break;
589 case 'D': debugging
= 0; break;
590 default: fatal(0, "invalid option");
593 if(getenv("DISORDER_DEBUG_SPEAKER")) debugging
= 1;
594 /* If stderr is a TTY then log there, otherwise to syslog. */
596 openlog(progname
, LOG_PID
, LOG_DAEMON
);
597 log_default
= &log_syslog
;
599 if(config_read(1)) fatal(0, "cannot read configuration");
600 bpf
= bytes_per_frame(&config
->sample_format
);
602 signal(SIGPIPE
, SIG_IGN
);
604 signal(SIGCHLD
, reap
);
606 xnice(config
->nice_speaker
);
609 /* make sure we're not root, whatever the config says */
610 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
611 /* identify the backend used to play */
612 for(n
= 0; backends
[n
]; ++n
)
613 if(backends
[n
]->backend
== config
->speaker_backend
)
616 fatal(0, "unsupported backend %d", config
->speaker_backend
);
617 backend
= backends
[n
];
618 /* backend-specific initialization */
620 /* set up the listen socket */
621 listenfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
622 memset(&addr
, 0, sizeof addr
);
623 addr
.sun_family
= AF_UNIX
;
624 snprintf(addr
.sun_path
, sizeof addr
.sun_path
, "%s/speaker",
626 if(unlink(addr
.sun_path
) < 0 && errno
!= ENOENT
)
627 error(errno
, "removing %s", addr
.sun_path
);
628 xsetsockopt(listenfd
, SOL_SOCKET
, SO_REUSEADDR
, &one
, sizeof one
);
629 if(bind(listenfd
, &addr
, sizeof addr
) < 0)
630 fatal(errno
, "error binding socket to %s", addr
.sun_path
);
631 xlisten(listenfd
, 128);
633 info("listening on %s", addr
.sun_path
);
635 info("stopped (parent terminated)");