2 * This file is part of DisOrder
3 * Copyright (C) 2005-2009 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 Model. mainloop() implements a select loop awaiting commands from the
29 * main server, new connections to the speaker socket, and audio data on those
30 * connections. Each connection starts with a queue ID (with a 32-bit
31 * native-endian length word), allowing it to be referred to in commands from
34 * Data read on connections is buffered, up to a limit (currently 1Mbyte per
35 * track). No attempt is made here to limit the number of tracks, it is
36 * assumed that the main server won't start outrageously many decoders.
38 * Audio is supplied from this buffer to the uaudio play callback. Playback is
39 * enabled when a track is to be played and disabled when the its last bytes
40 * have been return by the callback; pause and resume is implemneted the
41 * obvious way. If the callback finds itself required to play when there is no
42 * playing track it returns dead air.
44 * @b Encodings. The encodings supported depend entirely on the uaudio backend
45 * chosen. See @ref uaudio.h, etc.
47 * Inbound data is expected to match @c config->sample_format. In normal use
48 * this is arranged by the @c disorder-normalize program (see @ref
49 * server/normalize.c).
51 * @b Garbage @b Collection. This program deliberately does not use the
52 * garbage collector even though it might be convenient to do so. This is for
53 * two reasons. Firstly some sound APIs use thread threads and we do not want
54 * to have to deal with potential interactions between threading and garbage
55 * collection. Secondly this process needs to be able to respond quickly and
56 * this is not compatible with the collector hanging the program even
59 * @b Units. This program thinks at various times in three different units.
60 * Bytes are obvious. A sample is a single sample on a single channel. A
61 * frame is several samples on different channels at the same point in time.
62 * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
74 #include <sys/select.h>
82 #include <sys/resource.h>
84 #include "configuration.h"
89 #include "speaker-protocol.h"
95 /** @brief Maximum number of FDs to poll for */
98 /** @brief Track structure
100 * Known tracks are kept in a linked list. Usually there will be at most two
101 * of these but rearranging the queue can cause there to be more.
104 /** @brief Next track */
107 /** @brief Input file descriptor */
108 int fd
; /* input FD */
110 /** @brief Track ID */
113 /** @brief Start position of data in buffer */
116 /** @brief Number of bytes of data in buffer */
119 /** @brief Set @c fd is at EOF */
122 /** @brief Total number of samples played */
123 unsigned long long played
;
125 /** @brief Slot in @ref fds */
128 /** @brief Set when playable
130 * A track becomes playable whenever it fills its buffer or reaches EOF; it
131 * stops being playable when it entirely empties its buffer. Tracks start
132 * out life not playable.
136 /** @brief Input buffer
138 * 1Mbyte is enough for nearly 6s of 44100Hz 16-bit stereo
140 char buffer
[1048576];
143 /** @brief Lock protecting data structures
145 * This lock protects values shared between the main thread and the callback.
146 * It is needed e.g. if changing @ref playing or if modifying buffer pointers.
147 * It is not needed to add a new track, to read values only modified in the
150 static pthread_mutex_t lock
= PTHREAD_MUTEX_INITIALIZER
;
152 /** @brief Linked list of all prepared tracks */
153 static struct track
*tracks
;
155 /** @brief Playing track, or NULL
157 * This means the DESIRED playing track. It does not reflect any other state
158 * (e.g. activation of uaudio backend).
160 static struct track
*playing
;
162 /** @brief Array of file descriptors for poll() */
163 static struct pollfd fds
[NFDS
];
165 /** @brief Next free slot in @ref fds */
168 /** @brief Listen socket */
171 /** @brief Timestamp of last potential report to server */
172 static time_t last_report
;
174 /** @brief Set when paused */
177 /** @brief Set when back end activated */
178 static int activated
;
180 /** @brief Signal pipe back into the poll() loop */
181 static int sigpipe
[2];
183 /** @brief Selected backend */
184 static const struct uaudio
*backend
;
186 static const struct option options
[] = {
187 { "help", no_argument
, 0, 'h' },
188 { "version", no_argument
, 0, 'V' },
189 { "config", required_argument
, 0, 'c' },
190 { "debug", no_argument
, 0, 'd' },
191 { "no-debug", no_argument
, 0, 'D' },
192 { "syslog", no_argument
, 0, 's' },
193 { "no-syslog", no_argument
, 0, 'S' },
197 /* Display usage message and terminate. */
198 static void help(void) {
200 " disorder-speaker [OPTIONS]\n"
202 " --help, -h Display usage message\n"
203 " --version, -V Display version number\n"
204 " --config PATH, -c PATH Set configuration file\n"
205 " --debug, -d Turn on debugging\n"
206 " --[no-]syslog Force logging\n"
208 "Speaker process for DisOrder. Not intended to be run\n"
214 /** @brief Find track @p id, maybe creating it if not found
215 * @param id Track ID to find
216 * @param create If nonzero, create track structure of @p id not found
217 * @return Pointer to track structure or NULL
219 static struct track
*findtrack(const char *id
, int create
) {
222 D(("findtrack %s %d", id
, create
));
223 for(t
= tracks
; t
&& strcmp(id
, t
->id
); t
= t
->next
)
226 t
= xmalloc(sizeof *t
);
235 /** @brief Remove track @p id (but do not destroy it)
236 * @param id Track ID to remove
237 * @return Track structure or NULL if not found
239 static struct track
*removetrack(const char *id
) {
240 struct track
*t
, **tt
;
242 D(("removetrack %s", id
));
243 for(tt
= &tracks
; (t
= *tt
) && strcmp(id
, t
->id
); tt
= &t
->next
)
250 /** @brief Destroy a track
251 * @param t Track structure
253 static void destroy(struct track
*t
) {
254 D(("destroy %s", t
->id
));
260 /** @brief Read data into a sample buffer
261 * @param t Pointer to track
262 * @return 0 on success, -1 on EOF
264 * This is effectively the read callback on @c t->fd. It is called from the
265 * main loop whenever the track's file descriptor is readable, assuming the
266 * buffer has not reached the maximum allowed occupancy.
268 static int speaker_fill(struct track
*t
) {
272 D(("fill %s: eof=%d used=%zu",
273 t
->id
, t
->eof
, t
->used
));
276 pthread_mutex_lock(&lock
);
277 if(t
->used
< sizeof t
->buffer
) {
278 /* there is room left in the buffer */
279 where
= (t
->start
+ t
->used
) % sizeof t
->buffer
;
280 /* Get as much data as we can */
281 if(where
>= t
->start
)
282 left
= (sizeof t
->buffer
) - where
;
284 left
= t
->start
- where
;
285 pthread_mutex_unlock(&lock
);
287 n
= read(t
->fd
, t
->buffer
+ where
, left
);
288 } while(n
< 0 && errno
== EINTR
);
289 pthread_mutex_lock(&lock
);
292 fatal(errno
, "error reading sample stream");
295 D(("fill %s: eof detected", t
->id
));
297 /* A track always becomes playable at EOF; we're not going to see any
303 /* A track becomes playable when it (first) fills its buffer. For
304 * 44.1KHz 16-bit stereo this is ~6s of audio data. The latency will
305 * depend how long that takes to decode (hopefuly not very!) */
306 if(t
->used
== sizeof t
->buffer
)
311 pthread_mutex_unlock(&lock
);
315 /** @brief Return nonzero if we want to play some audio
317 * We want to play audio if there is a current track; and it is not paused; and
318 * it is playable according to the rules for @ref track::playable.
320 static int playable(void) {
323 && playing
->playable
;
326 /** @brief Notify the server what we're up to */
327 static void report(void) {
328 struct speaker_message sm
;
331 memset(&sm
, 0, sizeof sm
);
332 sm
.type
= paused ? SM_PAUSED
: SM_PLAYING
;
333 strcpy(sm
.id
, playing
->id
);
334 pthread_mutex_lock(&lock
);
335 sm
.data
= playing
->played
/ (uaudio_rate
* uaudio_channels
);
336 pthread_mutex_unlock(&lock
);
337 speaker_send(1, &sm
);
342 /** @brief Add a file descriptor to the set to poll() for
343 * @param fd File descriptor
344 * @param events Events to wait for e.g. @c POLLIN
345 * @return Slot number
347 static int addfd(int fd
, int events
) {
350 fds
[fdno
].events
= events
;
356 /** @brief Callback to return some sampled data
357 * @param buffer Where to put sample data
358 * @param max_samples How many samples to return
359 * @param userdata User data
360 * @return Number of samples written
362 * See uaudio_callback().
364 static size_t speaker_callback(void *buffer
,
366 void attribute((unused
)) *userdata
) {
367 const size_t max_bytes
= max_samples
* uaudio_sample_size
;
368 size_t provided_samples
= 0;
370 pthread_mutex_lock(&lock
);
371 /* TODO perhaps we should immediately go silent if we've been asked to pause
372 * or cancel the playing track (maybe block in the cancel case and see what
375 if(playing
->used
> 0) {
377 /* Compute size of largest contiguous chunk. We get called as often as
378 * necessary so there's no need for cleverness here. */
379 if(playing
->start
+ playing
->used
> sizeof playing
->buffer
)
380 bytes
= sizeof playing
->buffer
- playing
->start
;
382 bytes
= playing
->used
;
383 /* Limit to what we were asked for */
384 if(bytes
> max_bytes
)
387 memcpy(buffer
, playing
->buffer
+ playing
->start
, bytes
);
388 playing
->start
+= bytes
;
389 playing
->used
-= bytes
;
390 /* Wrap around to start of buffer */
391 if(playing
->start
== sizeof playing
->buffer
)
393 /* See if we've reached the end of the track */
394 if(playing
->used
== 0 && playing
->eof
)
395 write(sigpipe
[1], "", 1);
396 provided_samples
= bytes
/ uaudio_sample_size
;
397 playing
->played
+= provided_samples
;
400 /* If we couldn't provide anything at all, play dead air */
401 /* TODO maybe it would be better to block, in some cases? */
402 if(!provided_samples
) {
403 memset(buffer
, 0, max_bytes
);
404 provided_samples
= max_samples
;
406 pthread_mutex_unlock(&lock
);
407 return provided_samples
;
410 /** @brief Main event loop */
411 static void mainloop(void) {
413 struct speaker_message sm
;
414 int n
, fd
, stdin_slot
, timeout
, listen_slot
, sigpipe_slot
;
416 /* Keep going while our parent process is alive */
417 while(getppid() != 1) {
418 int force_report
= 0;
421 /* By default we will wait up to a second before thinking about current
424 /* Always ready for commands from the main server. */
425 stdin_slot
= addfd(0, POLLIN
);
426 /* Also always ready for inbound connections */
427 listen_slot
= addfd(listenfd
, POLLIN
);
428 /* Try to read sample data for the currently playing track if there is
433 && playing
->used
< (sizeof playing
->buffer
))
434 playing
->slot
= addfd(playing
->fd
, POLLIN
);
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 sigpipe_slot
= addfd(sigpipe
[1], POLLIN
);
450 /* Wait for something interesting to happen */
451 n
= poll(fds
, fdno
, timeout
);
453 if(errno
== EINTR
) continue;
454 fatal(errno
, "error calling poll");
456 /* Perhaps a connection has arrived */
457 if(fds
[listen_slot
].revents
& POLLIN
) {
458 struct sockaddr_un addr
;
459 socklen_t addrlen
= sizeof addr
;
463 if((fd
= accept(listenfd
, (struct sockaddr
*)&addr
, &addrlen
)) >= 0) {
465 if(read(fd
, &l
, sizeof l
) < 4) {
466 error(errno
, "reading length from inbound connection");
468 } else if(l
>= sizeof id
) {
469 error(0, "id length too long");
471 } else if(read(fd
, id
, l
) < (ssize_t
)l
) {
472 error(errno
, "reading id from inbound connection");
476 D(("id %s fd %d", id
, fd
));
477 t
= findtrack(id
, 1/*create*/);
478 if (write(fd
, "", 1) < 0) /* write an ack */
479 error(errno
, "writing ack to inbound connection");
481 error(0, "%s: already got a connection", id
);
485 t
->fd
= fd
; /* yay */
489 error(errno
, "accept");
491 /* Perhaps we have a command to process */
492 if(fds
[stdin_slot
].revents
& POLLIN
) {
493 /* There might (in theory) be several commands queued up, but in general
494 * this won't be the case, so we don't bother looping around to pick them
496 n
= speaker_recv(0, &sm
);
502 fatal(0, "got SM_PLAY but already playing something");
503 t
= findtrack(sm
.id
, 1);
504 D(("SM_PLAY %s fd %d", t
->id
, t
->fd
));
506 error(0, "cannot play track because no connection arrived");
521 D(("SM_CANCEL %s", sm
.id
));
522 t
= removetrack(sm
.id
);
524 pthread_mutex_lock(&lock
);
526 /* scratching the playing track */
527 sm
.type
= SM_FINISHED
;
530 /* Could be scratching the playing track before it's quite got
531 * going, or could be just removing a track from the queue. We
532 * log more because there's been a bug here recently than because
533 * it's particularly interesting; the log message will be removed
534 * if no further problems show up. */
535 info("SM_CANCEL for nonplaying track %s", sm
.id
);
536 sm
.type
= SM_STILLBORN
;
538 strcpy(sm
.id
, t
->id
);
540 pthread_mutex_unlock(&lock
);
542 /* Probably scratching the playing track well before it's got
543 * going, but could indicate a bug, so we log this as an error. */
544 sm
.type
= SM_UNKNOWN
;
545 error(0, "SM_CANCEL for unknown track %s", sm
.id
);
547 speaker_send(1, &sm
);
553 error(0, "cannot read configuration");
554 info("reloaded configuration");
557 error(0, "unknown message type %d", sm
.type
);
560 /* Read in any buffered data */
561 for(t
= tracks
; t
; t
= t
->next
)
564 && (fds
[t
->slot
].revents
& (POLLIN
| POLLHUP
)))
566 /* Drain the signal pipe. We don't care about its contents, merely that it
567 * interrupted poll(). */
568 if(fds
[sigpipe_slot
].revents
& POLLIN
) {
571 read(sigpipe
[0], buffer
, sizeof buffer
);
573 if(playing
&& playing
->used
== 0 && playing
->eof
) {
574 /* The playing track is done. Tell the server, and destroy it. */
575 memset(&sm
, 0, sizeof sm
);
576 sm
.type
= SM_FINISHED
;
577 strcpy(sm
.id
, playing
->id
);
578 speaker_send(1, &sm
);
579 removetrack(playing
->id
);
580 pthread_mutex_lock(&lock
);
583 pthread_mutex_unlock(&lock
);
584 /* The server will presumalby send as an SM_PLAY by return */
586 /* Impose any state change required by the above */
595 backend
->deactivate();
598 /* If we've not reported our state for a second do so now. */
599 if(force_report
|| time(0) > last_report
)
604 int main(int argc
, char **argv
) {
605 int n
, logsyslog
= !isatty(2);
606 struct sockaddr_un addr
;
607 static const int one
= 1;
608 struct speaker_message sm
;
614 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
615 while((n
= getopt_long(argc
, argv
, "hVc:dDSs", options
, 0)) >= 0) {
618 case 'V': version("disorder-speaker");
619 case 'c': configfile
= optarg
; break;
620 case 'd': debugging
= 1; break;
621 case 'D': debugging
= 0; break;
622 case 'S': logsyslog
= 0; break;
623 case 's': logsyslog
= 1; break;
624 default: fatal(0, "invalid option");
627 if((d
= getenv("DISORDER_DEBUG_SPEAKER"))) debugging
= atoi(d
);
629 openlog(progname
, LOG_PID
, LOG_DAEMON
);
630 log_default
= &log_syslog
;
632 config_uaudio_apis
= uaudio_apis
;
633 if(config_read(1)) fatal(0, "cannot read configuration");
635 signal(SIGPIPE
, SIG_IGN
);
637 xnice(config
->nice_speaker
);
640 /* make sure we're not root, whatever the config says */
641 if(getuid() == 0 || geteuid() == 0)
642 fatal(0, "do not run as root");
643 /* Make sure we can't have more than NFDS files open (it would bust our
645 if(getrlimit(RLIMIT_NOFILE
, rl
) < 0)
646 fatal(errno
, "getrlimit RLIMIT_NOFILE");
647 if(rl
->rlim_cur
> NFDS
) {
649 if(setrlimit(RLIMIT_NOFILE
, rl
) < 0)
650 fatal(errno
, "setrlimit to reduce RLIMIT_NOFILE to %lu",
651 (unsigned long)rl
->rlim_cur
);
652 info("set RLIM_NOFILE to %lu", (unsigned long)rl
->rlim_cur
);
654 info("RLIM_NOFILE is %lu", (unsigned long)rl
->rlim_cur
);
655 /* create a pipe between the backend callback and the poll() loop */
657 nonblock(sigpipe
[0]);
658 /* set up audio backend */
659 uaudio_set_format(config
->sample_format
.rate
,
660 config
->sample_format
.channels
,
661 config
->sample_format
.bits
,
662 config
->sample_format
.bits
!= 8);
663 /* TODO other parameters! */
664 backend
= uaudio_find(config
->api
);
665 /* backend-specific initialization */
666 backend
->start(speaker_callback
, NULL
);
667 /* create the socket directory */
668 byte_xasprintf(&dir
, "%s/speaker", config
->home
);
669 unlink(dir
); /* might be a leftover socket */
670 if(mkdir(dir
, 0700) < 0 && errno
!= EEXIST
)
671 fatal(errno
, "error creating %s", dir
);
672 /* set up the listen socket */
673 listenfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
674 memset(&addr
, 0, sizeof addr
);
675 addr
.sun_family
= AF_UNIX
;
676 snprintf(addr
.sun_path
, sizeof addr
.sun_path
, "%s/speaker/socket",
678 if(unlink(addr
.sun_path
) < 0 && errno
!= ENOENT
)
679 error(errno
, "removing %s", addr
.sun_path
);
680 xsetsockopt(listenfd
, SOL_SOCKET
, SO_REUSEADDR
, &one
, sizeof one
);
681 if(bind(listenfd
, (const struct sockaddr
*)&addr
, sizeof addr
) < 0)
682 fatal(errno
, "error binding socket to %s", addr
.sun_path
);
683 xlisten(listenfd
, 128);
685 info("listening on %s", addr
.sun_path
);
686 memset(&sm
, 0, sizeof sm
);
688 speaker_send(1, &sm
);
690 info("stopped (parent terminated)");