2 * This file is part of DisOrder
3 * Copyright (C) 2005-2008 Richard Kettlewell
4 * Portions (C) 2007 Mark Wooding
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 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 /** @file server/speaker.c
20 * @brief Speaker process
22 * This program is responsible for transmitting a single coherent audio stream
23 * to its destination (over the network, to some sound API, to some
24 * subprocess). It receives connections from decoders (or rather from the
25 * process that is about to become disorder-normalize) and plays them in the
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 7 * @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
59 #include <sys/select.h>
67 #include "configuration.h"
72 #include "speaker-protocol.h"
78 /** @brief Linked list of all prepared tracks */
81 /** @brief Playing track, or NULL */
82 struct track
*playing
;
84 /** @brief Number of bytes pre frame */
87 /** @brief Array of file descriptors for poll() */
88 struct pollfd fds
[NFDS
];
90 /** @brief Next free slot in @ref fds */
93 /** @brief Listen socket */
96 static time_t last_report
; /* when we last reported */
97 static int paused
; /* pause status */
99 /** @brief The current device state */
100 enum device_states device_state
;
102 /** @brief Set when idled
104 * This is set when the sound device is deliberately closed by idle().
108 /** @brief Selected backend */
109 static const struct speaker_backend
*backend
;
111 static const struct option options
[] = {
112 { "help", no_argument
, 0, 'h' },
113 { "version", no_argument
, 0, 'V' },
114 { "config", required_argument
, 0, 'c' },
115 { "debug", no_argument
, 0, 'd' },
116 { "no-debug", no_argument
, 0, 'D' },
117 { "syslog", no_argument
, 0, 's' },
118 { "no-syslog", no_argument
, 0, 'S' },
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"
131 " --[no-]syslog Force logging\n"
133 "Speaker process for DisOrder. Not intended to be run\n"
139 /** @brief Return the number of bytes per frame in @p format */
140 static size_t bytes_per_frame(const struct stream_header
*format
) {
141 return format
->channels
* format
->bits
/ 8;
144 /** @brief Find track @p id, maybe creating it if not found */
145 static struct track
*findtrack(const char *id
, int create
) {
148 D(("findtrack %s %d", id
, create
));
149 for(t
= tracks
; t
&& strcmp(id
, t
->id
); t
= t
->next
)
152 t
= xmalloc(sizeof *t
);
161 /** @brief Remove track @p id (but do not destroy it) */
162 static struct track
*removetrack(const char *id
) {
163 struct track
*t
, **tt
;
165 D(("removetrack %s", id
));
166 for(tt
= &tracks
; (t
= *tt
) && strcmp(id
, t
->id
); tt
= &t
->next
)
173 /** @brief Destroy a track */
174 static void destroy(struct track
*t
) {
175 D(("destroy %s", t
->id
));
176 if(t
->fd
!= -1) xclose(t
->fd
);
180 /** @brief Read data into a sample buffer
181 * @param t Pointer to track
182 * @return 0 on success, -1 on EOF
184 * This is effectively the read callback on @c t->fd. It is called from the
185 * main loop whenever the track's file descriptor is readable, assuming the
186 * buffer has not reached the maximum allowed occupancy.
188 static int speaker_fill(struct track
*t
) {
192 D(("fill %s: eof=%d used=%zu",
193 t
->id
, t
->eof
, t
->used
));
194 if(t
->eof
) return -1;
195 if(t
->used
< sizeof t
->buffer
) {
196 /* there is room left in the buffer */
197 where
= (t
->start
+ t
->used
) % sizeof t
->buffer
;
198 /* Get as much data as we can */
199 if(where
>= t
->start
) left
= (sizeof t
->buffer
) - where
;
200 else left
= t
->start
- where
;
202 n
= read(t
->fd
, t
->buffer
+ where
, left
);
203 } while(n
< 0 && errno
== EINTR
);
205 if(errno
!= EAGAIN
) fatal(errno
, "error reading sample stream");
209 D(("fill %s: eof detected", t
->id
));
215 if(t
->used
== sizeof t
->buffer
)
221 /** @brief Close the sound device
223 * This is called to deactivate the output device when pausing, and also by the
224 * ALSA backend when changing encoding (in which case the sound device will be
225 * immediately reactivated).
227 static void idle(void) {
229 if(backend
->deactivate
)
230 backend
->deactivate();
232 device_state
= device_closed
;
236 /** @brief Abandon the current track */
238 struct speaker_message sm
;
241 memset(&sm
, 0, sizeof sm
);
242 sm
.type
= SM_FINISHED
;
243 strcpy(sm
.id
, playing
->id
);
244 speaker_send(1, &sm
);
245 removetrack(playing
->id
);
250 /** @brief Enable sound output
252 * Makes sure the sound device is open and has the right sample format. Return
253 * 0 on success and -1 on error.
255 static void activate(void) {
256 if(backend
->activate
)
259 device_state
= device_open
;
262 /** @brief Check whether the current track has finished
264 * The current track is determined to have finished either if the input stream
265 * eded before the format could be determined (i.e. it is malformed) or the
266 * input is at end of file and there is less than a frame left unplayed. (So
267 * it copes with decoders that crash mid-frame.)
269 static void maybe_finished(void) {
272 && playing
->used
< bytes_per_frame(&config
->sample_format
))
276 /** @brief Return nonzero if we want to play some audio
278 * We want to play audio if there is a current track; and it is not paused; and
279 * it is playable according to the rules for @ref track::playable.
281 static int playable(void) {
284 && playing
->playable
;
287 /** @brief Play up to @p frames frames of audio
289 * It is always safe to call this function.
290 * - If @ref playing is 0 then it will just return
291 * - If @ref paused is non-0 then it will just return
292 * - If @ref device_state != @ref device_open then it will call activate() and
293 * return if it it fails.
294 * - If there is not enough audio to play then it play what is available.
296 * If there are not enough frames to play then whatever is available is played
297 * instead. It is up to mainloop() to ensure that speaker_play() is not called
298 * when unreasonably only an small amounts of data is available to play.
300 static void speaker_play(size_t frames
) {
301 size_t avail_frames
, avail_bytes
, written_frames
;
302 ssize_t written_bytes
;
304 /* Make sure there's a track to play and it is not paused */
307 /* Make sure the output device is open */
308 if(device_state
!= device_open
) {
310 if(device_state
!= device_open
)
313 D(("play: play %zu/%zu%s %dHz %db %dc", frames
, playing
->used
/ bpf
,
314 playing
->eof ?
" EOF" : "",
315 config
->sample_format
.rate
,
316 config
->sample_format
.bits
,
317 config
->sample_format
.channels
));
318 /* Figure out how many frames there are available to write */
319 if(playing
->start
+ playing
->used
> sizeof playing
->buffer
)
320 /* The ring buffer is currently wrapped, only play up to the wrap point */
321 avail_bytes
= (sizeof playing
->buffer
) - playing
->start
;
323 /* The ring buffer is not wrapped, can play the lot */
324 avail_bytes
= playing
->used
;
325 avail_frames
= avail_bytes
/ bpf
;
326 /* Only play up to the requested amount */
327 if(avail_frames
> frames
)
328 avail_frames
= frames
;
332 written_frames
= backend
->play(avail_frames
);
333 written_bytes
= written_frames
* bpf
;
334 /* written_bytes and written_frames had better both be set and correct by
336 playing
->start
+= written_bytes
;
337 playing
->used
-= written_bytes
;
338 playing
->played
+= written_frames
;
339 /* If the pointer is at the end of the buffer (or the buffer is completely
340 * empty) wrap it back to the start. */
341 if(!playing
->used
|| playing
->start
== (sizeof playing
->buffer
))
343 /* If the buffer emptied out mark the track as unplayably */
344 if(!playing
->used
&& !playing
->eof
) {
345 error(0, "track buffer emptied");
346 playing
->playable
= 0;
348 frames
-= written_frames
;
352 /* Notify the server what we're up to. */
353 static void report(void) {
354 struct speaker_message sm
;
357 memset(&sm
, 0, sizeof sm
);
358 sm
.type
= paused ? SM_PAUSED
: SM_PLAYING
;
359 strcpy(sm
.id
, playing
->id
);
360 sm
.data
= playing
->played
/ config
->sample_format
.rate
;
361 speaker_send(1, &sm
);
366 static void reap(int __attribute__((unused
)) sig
) {
371 cmdpid
= waitpid(-1, &st
, WNOHANG
);
373 signal(SIGCHLD
, reap
);
376 int addfd(int fd
, int events
) {
379 fds
[fdno
].events
= events
;
385 /** @brief Table of speaker backends */
386 static const struct speaker_backend
*backends
[] = {
387 #if HAVE_ALSA_ASOUNDLIB_H
392 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
395 #if HAVE_SYS_SOUNDCARD_H
401 /** @brief Main event loop */
402 static void mainloop(void) {
404 struct speaker_message sm
;
405 int n
, fd
, stdin_slot
, timeout
, listen_slot
;
407 while(getppid() != 1) {
409 /* By default we will wait up to a second before thinking about current
412 /* Always ready for commands from the main server. */
413 stdin_slot
= addfd(0, POLLIN
);
414 /* Also always ready for inbound connections */
415 listen_slot
= addfd(listenfd
, POLLIN
);
416 /* Try to read sample data for the currently playing track if there is
421 && playing
->used
< (sizeof playing
->buffer
))
422 playing
->slot
= addfd(playing
->fd
, POLLIN
);
426 /* We want to play some audio. If the device is closed then we attempt
428 if(device_state
== device_closed
)
430 /* If the device is (now) open then we will wait up until it is ready for
431 * more. If something went wrong then we should have device_error
432 * instead, but the post-poll code will cope even if it's
434 if(device_state
== device_open
)
435 backend
->beforepoll(&timeout
);
437 /* If any other tracks don't have a full buffer, try to read sample data
438 * from them. We do this last of all, so that if we run out of slots,
439 * nothing important can't be monitored. */
440 for(t
= tracks
; t
; t
= t
->next
)
444 && t
->used
< sizeof t
->buffer
) {
445 t
->slot
= addfd(t
->fd
, POLLIN
| POLLHUP
);
449 /* Wait for something interesting to happen */
450 n
= poll(fds
, fdno
, timeout
);
452 if(errno
== EINTR
) continue;
453 fatal(errno
, "error calling poll");
455 /* Play some sound before doing anything else */
457 /* We want to play some audio */
458 if(device_state
== device_open
) {
460 speaker_play(3 * FRAMES
);
462 /* We must be in _closed or _error, and it should be the latter, but we
465 * We most likely timed out, so now is a good time to retry.
466 * speaker_play() knows to re-activate the device if necessary.
468 speaker_play(3 * FRAMES
);
471 /* Perhaps a connection has arrived */
472 if(fds
[listen_slot
].revents
& POLLIN
) {
473 struct sockaddr_un addr
;
474 socklen_t addrlen
= sizeof addr
;
478 if((fd
= accept(listenfd
, (struct sockaddr
*)&addr
, &addrlen
)) >= 0) {
480 if(read(fd
, &l
, sizeof l
) < 4) {
481 error(errno
, "reading length from inbound connection");
483 } else if(l
>= sizeof id
) {
484 error(0, "id length too long");
486 } else if(read(fd
, id
, l
) < (ssize_t
)l
) {
487 error(errno
, "reading id from inbound connection");
491 D(("id %s fd %d", id
, fd
));
492 t
= findtrack(id
, 1/*create*/);
493 write(fd
, "", 1); /* write an ack */
495 error(0, "%s: already got a connection", id
);
499 t
->fd
= fd
; /* yay */
503 error(errno
, "accept");
505 /* Perhaps we have a command to process */
506 if(fds
[stdin_slot
].revents
& POLLIN
) {
507 /* There might (in theory) be several commands queued up, but in general
508 * this won't be the case, so we don't bother looping around to pick them
510 n
= speaker_recv(0, &sm
);
515 if(playing
) fatal(0, "got SM_PLAY but already playing something");
516 t
= findtrack(sm
.id
, 1);
517 D(("SM_PLAY %s fd %d", t
->id
, t
->fd
));
519 error(0, "cannot play track because no connection arrived");
521 /* We attempt to play straight away rather than going round the loop.
522 * speaker_play() is clever enough to perform any activation that is
524 speaker_play(3 * FRAMES
);
536 /* As for SM_PLAY we attempt to play straight away. */
538 speaker_play(3 * FRAMES
);
543 D(("SM_CANCEL %s", sm
.id
));
544 t
= removetrack(sm
.id
);
547 /* scratching the playing track */
548 sm
.type
= SM_FINISHED
;
551 /* Could be scratching the playing track before it's quite got
552 * going, or could be just removing a track from the queue. We
553 * log more because there's been a bug here recently than because
554 * it's particularly interesting; the log message will be removed
555 * if no further problems show up. */
556 info("SM_CANCEL for nonplaying track %s", sm
.id
);
557 sm
.type
= SM_STILLBORN
;
559 strcpy(sm
.id
, t
->id
);
562 /* Probably scratching the playing track well before it's got
563 * going, but could indicate a bug, so we log this as an error. */
564 sm
.type
= SM_UNKNOWN
;
565 error(0, "SM_CANCEL for unknown track %s", sm
.id
);
567 speaker_send(1, &sm
);
572 if(config_read(1)) error(0, "cannot read configuration");
573 info("reloaded configuration");
576 error(0, "unknown message type %d", sm
.type
);
579 /* Read in any buffered data */
580 for(t
= tracks
; t
; t
= t
->next
)
583 && (fds
[t
->slot
].revents
& (POLLIN
| POLLHUP
)))
585 /* Maybe we finished playing a track somewhere in the above */
587 /* If we don't need the sound device for now then close it for the benefit
588 * of anyone else who wants it. */
589 if((!playing
|| paused
) && device_state
== device_open
)
591 /* If we've not reported out state for a second do so now. */
592 if(time(0) > last_report
)
597 int main(int argc
, char **argv
) {
598 int n
, logsyslog
= !isatty(2);
599 struct sockaddr_un addr
;
600 static const int one
= 1;
601 struct speaker_message sm
;
606 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
607 while((n
= getopt_long(argc
, argv
, "hVc:dDSs", options
, 0)) >= 0) {
610 case 'V': version("disorder-speaker");
611 case 'c': configfile
= optarg
; break;
612 case 'd': debugging
= 1; break;
613 case 'D': debugging
= 0; break;
614 case 'S': logsyslog
= 0; break;
615 case 's': logsyslog
= 1; break;
616 default: fatal(0, "invalid option");
619 if((d
= getenv("DISORDER_DEBUG_SPEAKER"))) debugging
= atoi(d
);
621 openlog(progname
, LOG_PID
, LOG_DAEMON
);
622 log_default
= &log_syslog
;
624 if(config_read(1)) fatal(0, "cannot read configuration");
625 bpf
= bytes_per_frame(&config
->sample_format
);
627 signal(SIGPIPE
, SIG_IGN
);
629 signal(SIGCHLD
, reap
);
631 xnice(config
->nice_speaker
);
634 /* make sure we're not root, whatever the config says */
635 if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
636 /* identify the backend used to play */
637 for(n
= 0; backends
[n
]; ++n
)
638 if(backends
[n
]->backend
== config
->api
)
641 fatal(0, "unsupported api %d", config
->api
);
642 backend
= backends
[n
];
643 /* backend-specific initialization */
645 /* create the socket directory */
646 byte_xasprintf(&dir
, "%s/speaker", config
->home
);
647 unlink(dir
); /* might be a leftover socket */
648 if(mkdir(dir
, 0700) < 0 && errno
!= EEXIST
)
649 fatal(errno
, "error creating %s", dir
);
650 /* set up the listen socket */
651 listenfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
652 memset(&addr
, 0, sizeof addr
);
653 addr
.sun_family
= AF_UNIX
;
654 snprintf(addr
.sun_path
, sizeof addr
.sun_path
, "%s/speaker/socket",
656 if(unlink(addr
.sun_path
) < 0 && errno
!= ENOENT
)
657 error(errno
, "removing %s", addr
.sun_path
);
658 xsetsockopt(listenfd
, SOL_SOCKET
, SO_REUSEADDR
, &one
, sizeof one
);
659 if(bind(listenfd
, (const struct sockaddr
*)&addr
, sizeof addr
) < 0)
660 fatal(errno
, "error binding socket to %s", addr
.sun_path
);
661 xlisten(listenfd
, 128);
663 info("listening on %s", addr
.sun_path
);
664 memset(&sm
, 0, sizeof sm
);
666 speaker_send(1, &sm
);
668 info("stopped (parent terminated)");