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 * To implement gapless playback, the server is notified that a track has
45 * finished slightly early. @ref SM_PLAY is therefore allowed to arrive while
46 * the previous track is still playing provided an early @ref SM_FINISHED has
49 * @b Encodings. The encodings supported depend entirely on the uaudio backend
50 * chosen. See @ref uaudio.h, etc.
52 * Inbound data is expected to match @c config->sample_format. In normal use
53 * this is arranged by the @c disorder-normalize program (see @ref
54 * server/normalize.c).
56 * @b Garbage @b Collection. This program deliberately does not use the
57 * garbage collector even though it might be convenient to do so. This is for
58 * two reasons. Firstly some sound APIs use thread threads and we do not want
59 * to have to deal with potential interactions between threading and garbage
60 * collection. Secondly this process needs to be able to respond quickly and
61 * this is not compatible with the collector hanging the program even
64 * @b Units. This program thinks at various times in three different units.
65 * Bytes are obvious. A sample is a single sample on a single channel. A
66 * frame is several samples on different channels at the same point in time.
67 * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
79 #include <sys/select.h>
87 #include <sys/resource.h>
90 #include "configuration.h"
95 #include "speaker-protocol.h"
101 /** @brief Maximum number of FDs to poll for */
104 /** @brief Number of bytes before end of track to send SM_FINISHED
106 * Generally set to 1 second.
108 static size_t early_finish
;
110 /** @brief Track structure
112 * Known tracks are kept in a linked list. Usually there will be at most two
113 * of these but rearranging the queue can cause there to be more.
116 /** @brief Next track */
119 /** @brief Input file descriptor */
120 int fd
; /* input FD */
122 /** @brief Track ID */
125 /** @brief Start position of data in buffer */
128 /** @brief Number of bytes of data in buffer */
131 /** @brief Set @c fd is at EOF */
134 /** @brief Total number of samples played */
135 unsigned long long played
;
137 /** @brief Slot in @ref fds */
140 /** @brief Set when playable
142 * A track becomes playable whenever it fills its buffer or reaches EOF; it
143 * stops being playable when it entirely empties its buffer. Tracks start
144 * out life not playable.
148 /** @brief Set when finished
150 * This is set when we've notified the server that the track is finished.
151 * Once this has happened (typically very late in the track's lifetime) the
152 * track cannot be paused or cancelled.
156 /** @brief Input buffer
158 * 1Mbyte is enough for nearly 6s of 44100Hz 16-bit stereo
160 char buffer
[1048576];
163 /** @brief Lock protecting data structures
165 * This lock protects values shared between the main thread and the callback.
167 * It is held 'all' the time by the main thread, the exceptions being when
168 * called activate/deactivate callbacks and when calling (potentially) slow
169 * system calls (in particular poll(), where in fact the main thread will spend
170 * most of its time blocked).
172 * The callback holds it when it's running.
174 static pthread_mutex_t lock
= PTHREAD_MUTEX_INITIALIZER
;
176 /** @brief Linked list of all prepared tracks */
177 static struct track
*tracks
;
179 /** @brief Playing track, or NULL
181 * This means the track the speaker process intends to play. It does not
182 * reflect any other state (e.g. activation of uaudio backend).
184 static struct track
*playing
;
186 /** @brief Pending playing track, or NULL
188 * This means the track the server wants the speaker to play.
190 static struct track
*pending_playing
;
192 /** @brief Array of file descriptors for poll() */
193 static struct pollfd fds
[NFDS
];
195 /** @brief Next free slot in @ref fds */
198 /** @brief Listen socket */
201 /** @brief Timestamp of last potential report to server */
202 static time_t last_report
;
204 /** @brief Set when paused */
207 /** @brief Set when back end activated */
208 static int activated
;
210 /** @brief Signal pipe back into the poll() loop */
211 static int sigpipe
[2];
213 /** @brief Selected backend */
214 static const struct uaudio
*backend
;
216 static const struct option options
[] = {
217 { "help", no_argument
, 0, 'h' },
218 { "version", no_argument
, 0, 'V' },
219 { "config", required_argument
, 0, 'c' },
220 { "debug", no_argument
, 0, 'd' },
221 { "no-debug", no_argument
, 0, 'D' },
222 { "syslog", no_argument
, 0, 's' },
223 { "no-syslog", no_argument
, 0, 'S' },
227 /* Display usage message and terminate. */
228 static void help(void) {
230 " disorder-speaker [OPTIONS]\n"
232 " --help, -h Display usage message\n"
233 " --version, -V Display version number\n"
234 " --config PATH, -c PATH Set configuration file\n"
235 " --debug, -d Turn on debugging\n"
236 " --[no-]syslog Force logging\n"
238 "Speaker process for DisOrder. Not intended to be run\n"
244 /** @brief Find track @p id, maybe creating it if not found
245 * @param id Track ID to find
246 * @param create If nonzero, create track structure of @p id not found
247 * @return Pointer to track structure or NULL
249 static struct track
*findtrack(const char *id
, int create
) {
252 D(("findtrack %s %d", id
, create
));
253 for(t
= tracks
; t
&& strcmp(id
, t
->id
); t
= t
->next
)
256 t
= xmalloc(sizeof *t
);
265 /** @brief Remove track @p id (but do not destroy it)
266 * @param id Track ID to remove
267 * @return Track structure or NULL if not found
269 static struct track
*removetrack(const char *id
) {
270 struct track
*t
, **tt
;
272 D(("removetrack %s", id
));
273 for(tt
= &tracks
; (t
= *tt
) && strcmp(id
, t
->id
); tt
= &t
->next
)
280 /** @brief Destroy a track
281 * @param t Track structure
283 static void destroy(struct track
*t
) {
284 D(("destroy %s", t
->id
));
290 /** @brief Read data into a sample buffer
291 * @param t Pointer to track
292 * @return 0 on success, -1 on EOF
294 * This is effectively the read callback on @c t->fd. It is called from the
295 * main loop whenever the track's file descriptor is readable, assuming the
296 * buffer has not reached the maximum allowed occupancy.
298 static int speaker_fill(struct track
*t
) {
302 D(("fill %s: eof=%d used=%zu",
303 t
->id
, t
->eof
, t
->used
));
306 if(t
->used
< sizeof t
->buffer
) {
307 /* there is room left in the buffer */
308 where
= (t
->start
+ t
->used
) % sizeof t
->buffer
;
309 /* Get as much data as we can */
310 if(where
>= t
->start
)
311 left
= (sizeof t
->buffer
) - where
;
313 left
= t
->start
- where
;
314 pthread_mutex_unlock(&lock
);
316 n
= read(t
->fd
, t
->buffer
+ where
, left
);
317 } while(n
< 0 && errno
== EINTR
);
318 pthread_mutex_lock(&lock
);
321 fatal(errno
, "error reading sample stream");
324 D(("fill %s: eof detected", t
->id
));
326 /* A track always becomes playable at EOF; we're not going to see any
332 /* A track becomes playable when it (first) fills its buffer. For
333 * 44.1KHz 16-bit stereo this is ~6s of audio data. The latency will
334 * depend how long that takes to decode (hopefuly not very!) */
335 if(t
->used
== sizeof t
->buffer
)
343 /** @brief Return nonzero if we want to play some audio
345 * We want to play audio if there is a current track; and it is not paused; and
346 * it is playable according to the rules for @ref track::playable.
348 * We don't allow tracks to be paused if we've already told the server we've
349 * finished them; that would cause such tracks to survive much longer than the
350 * few samples they're supposed to, with report() remaining silent for the
353 static int playable(void) {
355 && (!paused
|| playing
->finished
)
356 && playing
->playable
;
359 /** @brief Notify the server what we're up to */
360 static void report(void) {
361 struct speaker_message sm
;
364 /* Had better not send a report for a track that the server thinks has
365 * finished, that would be confusing. */
366 if(playing
->finished
)
368 memset(&sm
, 0, sizeof sm
);
369 sm
.type
= paused ? SM_PAUSED
: SM_PLAYING
;
370 strcpy(sm
.id
, playing
->id
);
371 sm
.data
= playing
->played
/ (uaudio_rate
* uaudio_channels
);
372 speaker_send(1, &sm
);
377 /** @brief Add a file descriptor to the set to poll() for
378 * @param fd File descriptor
379 * @param events Events to wait for e.g. @c POLLIN
380 * @return Slot number
382 static int addfd(int fd
, int events
) {
385 fds
[fdno
].events
= events
;
391 /** @brief Callback to return some sampled data
392 * @param buffer Where to put sample data
393 * @param max_samples How many samples to return
394 * @param userdata User data
395 * @return Number of samples written
397 * See uaudio_callback().
399 static size_t speaker_callback(void *buffer
,
401 void attribute((unused
)) *userdata
) {
402 const size_t max_bytes
= max_samples
* uaudio_sample_size
;
403 size_t provided_samples
= 0;
405 pthread_mutex_lock(&lock
);
406 /* TODO perhaps we should immediately go silent if we've been asked to pause
407 * or cancel the playing track (maybe block in the cancel case and see what
410 if(playing
->used
> 0) {
412 /* Compute size of largest contiguous chunk. We get called as often as
413 * necessary so there's no need for cleverness here. */
414 if(playing
->start
+ playing
->used
> sizeof playing
->buffer
)
415 bytes
= sizeof playing
->buffer
- playing
->start
;
417 bytes
= playing
->used
;
418 /* Limit to what we were asked for */
419 if(bytes
> max_bytes
)
422 memcpy(buffer
, playing
->buffer
+ playing
->start
, bytes
);
423 playing
->start
+= bytes
;
424 playing
->used
-= bytes
;
425 /* Wrap around to start of buffer */
426 if(playing
->start
== sizeof playing
->buffer
)
428 /* See if we've reached the end of the track */
429 if(playing
->used
== 0 && playing
->eof
) {
430 int ignored
= write(sigpipe
[1], "", 1);
433 provided_samples
= bytes
/ uaudio_sample_size
;
434 playing
->played
+= provided_samples
;
437 /* If we couldn't provide anything at all, play dead air */
438 /* TODO maybe it would be better to block, in some cases? */
439 if(!provided_samples
) {
440 memset(buffer
, 0, max_bytes
);
441 provided_samples
= max_samples
;
443 info("%zu samples silence, playing->used=%zu", provided_samples
, playing
->used
);
445 info("%zu samples silence, playing=NULL", provided_samples
);
447 pthread_mutex_unlock(&lock
);
448 return provided_samples
;
451 /** @brief Main event loop */
452 static void mainloop(void) {
454 struct speaker_message sm
;
455 int n
, fd
, stdin_slot
, timeout
, listen_slot
, sigpipe_slot
;
457 /* Keep going while our parent process is alive */
458 pthread_mutex_lock(&lock
);
459 while(getppid() != 1) {
460 int force_report
= 0;
463 /* By default we will wait up to half a second before thinking about
466 /* Always ready for commands from the main server. */
467 stdin_slot
= addfd(0, POLLIN
);
468 /* Also always ready for inbound connections */
469 listen_slot
= addfd(listenfd
, POLLIN
);
470 /* Try to read sample data for the currently playing track if there is
475 && playing
->used
< (sizeof playing
->buffer
))
476 playing
->slot
= addfd(playing
->fd
, POLLIN
);
479 /* If any other tracks don't have a full buffer, try to read sample data
480 * from them. We do this last of all, so that if we run out of slots,
481 * nothing important can't be monitored. */
482 for(t
= tracks
; t
; t
= t
->next
)
486 && t
->used
< sizeof t
->buffer
) {
487 t
->slot
= addfd(t
->fd
, POLLIN
| POLLHUP
);
491 sigpipe_slot
= addfd(sigpipe
[0], POLLIN
);
492 /* Wait for something interesting to happen */
493 pthread_mutex_unlock(&lock
);
494 n
= poll(fds
, fdno
, timeout
);
495 pthread_mutex_lock(&lock
);
497 if(errno
== EINTR
) continue;
498 fatal(errno
, "error calling poll");
500 /* Perhaps a connection has arrived */
501 if(fds
[listen_slot
].revents
& POLLIN
) {
502 struct sockaddr_un addr
;
503 socklen_t addrlen
= sizeof addr
;
507 if((fd
= accept(listenfd
, (struct sockaddr
*)&addr
, &addrlen
)) >= 0) {
509 if(read(fd
, &l
, sizeof l
) < 4) {
510 error(errno
, "reading length from inbound connection");
512 } else if(l
>= sizeof id
) {
513 error(0, "id length too long");
515 } else if(read(fd
, id
, l
) < (ssize_t
)l
) {
516 error(errno
, "reading id from inbound connection");
520 D(("id %s fd %d", id
, fd
));
521 t
= findtrack(id
, 1/*create*/);
522 if (write(fd
, "", 1) < 0) /* write an ack */
523 error(errno
, "writing ack to inbound connection");
525 error(0, "%s: already got a connection", id
);
529 t
->fd
= fd
; /* yay */
533 error(errno
, "accept");
535 /* Perhaps we have a command to process */
536 if(fds
[stdin_slot
].revents
& POLLIN
) {
537 /* There might (in theory) be several commands queued up, but in general
538 * this won't be the case, so we don't bother looping around to pick them
540 n
= speaker_recv(0, &sm
);
542 /* As a rule we don't send success replies to most commands - we just
543 * force the regular status update to be sent immediately rather than
547 /* SM_PLAY is only allowed if the server reasonably believes that
548 * nothing is playing */
550 /* If finished isn't set then the server can't believe that this
551 * track has finished */
552 if(!playing
->finished
)
553 fatal(0, "got SM_PLAY but already playing something");
554 /* If pending_playing is set then the server must believe that that
557 fatal(0, "got SM_PLAY but have a pending playing track");
559 t
= findtrack(sm
.id
, 1);
560 D(("SM_PLAY %s fd %d", t
->id
, t
->fd
));
562 error(0, "cannot play track because no connection arrived");
563 /* TODO as things stand we often report this error message but then
564 * appear to proceed successfully. Understanding why requires a look
565 * at play.c: we call prepare() which makes the connection in a child
566 * process, and then sends the SM_PLAY in the parent process. The
567 * latter may well be faster. As it happens this is harmless; we'll
568 * just sit around sending silence until the decoder connects and
569 * starts sending some sample data. But is is annoying and ought to
572 /* If nothing is currently playing then we'll switch to the pending
573 * track below so there's no point distinguishing the situations
587 D(("SM_CANCEL %s", sm
.id
));
588 t
= removetrack(sm
.id
);
590 if(t
== playing
|| t
== pending_playing
) {
591 /* Scratching the track that the server believes is playing,
592 * which might either be the actual playing track or a pending
594 sm
.type
= SM_FINISHED
;
600 /* Could be scratching the playing track before it's quite got
601 * going, or could be just removing a track from the queue. We
602 * log more because there's been a bug here recently than because
603 * it's particularly interesting; the log message will be removed
604 * if no further problems show up. */
605 info("SM_CANCEL for nonplaying track %s", sm
.id
);
606 sm
.type
= SM_STILLBORN
;
608 strcpy(sm
.id
, t
->id
);
611 /* Probably scratching the playing track well before it's got
612 * going, but could indicate a bug, so we log this as an error. */
613 sm
.type
= SM_UNKNOWN
;
614 error(0, "SM_CANCEL for unknown track %s", sm
.id
);
616 speaker_send(1, &sm
);
621 if(config_read(1, NULL
))
622 error(0, "cannot read configuration");
623 info("reloaded configuration");
626 error(0, "unknown message type %d", sm
.type
);
629 /* Read in any buffered data */
630 for(t
= tracks
; t
; t
= t
->next
)
633 && (fds
[t
->slot
].revents
& (POLLIN
| POLLHUP
)))
635 /* Drain the signal pipe. We don't care about its contents, merely that it
636 * interrupted poll(). */
637 if(fds
[sigpipe_slot
].revents
& POLLIN
) {
639 int ignored
; (void)ignored
;
641 ignored
= read(sigpipe
[0], buffer
, sizeof buffer
);
643 /* Send SM_FINISHED when we're near the end of the track.
645 * This is how we implement gapless play; we hope that the SM_PLAY from the
646 * server arrives before the remaining bytes of the track play out.
650 && !playing
->finished
651 && playing
->used
<= early_finish
) {
652 memset(&sm
, 0, sizeof sm
);
653 sm
.type
= SM_FINISHED
;
654 strcpy(sm
.id
, playing
->id
);
655 speaker_send(1, &sm
);
656 playing
->finished
= 1;
658 /* When the track is actually finished, deconfigure it */
659 if(playing
&& playing
->eof
&& !playing
->used
) {
660 removetrack(playing
->id
);
664 /* Act on the pending SM_PLAY */
665 if(!playing
&& pending_playing
) {
666 playing
= pending_playing
;
670 /* Impose any state change required by the above */
674 pthread_mutex_unlock(&lock
);
676 pthread_mutex_lock(&lock
);
681 pthread_mutex_unlock(&lock
);
682 backend
->deactivate();
683 pthread_mutex_lock(&lock
);
686 /* If we've not reported our state for a second do so now. */
687 if(force_report
|| xtime(0) > last_report
)
692 int main(int argc
, char **argv
) {
693 int n
, logsyslog
= !isatty(2);
694 struct sockaddr_un addr
;
695 static const int one
= 1;
696 struct speaker_message sm
;
702 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
703 while((n
= getopt_long(argc
, argv
, "hVc:dDSs", options
, 0)) >= 0) {
706 case 'V': version("disorder-speaker");
707 case 'c': configfile
= optarg
; break;
708 case 'd': debugging
= 1; break;
709 case 'D': debugging
= 0; break;
710 case 'S': logsyslog
= 0; break;
711 case 's': logsyslog
= 1; break;
712 default: fatal(0, "invalid option");
715 if((d
= getenv("DISORDER_DEBUG_SPEAKER"))) debugging
= atoi(d
);
717 openlog(progname
, LOG_PID
, LOG_DAEMON
);
718 log_default
= &log_syslog
;
720 config_uaudio_apis
= uaudio_apis
;
721 if(config_read(1, NULL
)) fatal(0, "cannot read configuration");
723 signal(SIGPIPE
, SIG_IGN
);
725 xnice(config
->nice_speaker
);
728 /* make sure we're not root, whatever the config says */
729 if(getuid() == 0 || geteuid() == 0)
730 fatal(0, "do not run as root");
731 /* Make sure we can't have more than NFDS files open (it would bust our
733 if(getrlimit(RLIMIT_NOFILE
, rl
) < 0)
734 fatal(errno
, "getrlimit RLIMIT_NOFILE");
735 if(rl
->rlim_cur
> NFDS
) {
737 if(setrlimit(RLIMIT_NOFILE
, rl
) < 0)
738 fatal(errno
, "setrlimit to reduce RLIMIT_NOFILE to %lu",
739 (unsigned long)rl
->rlim_cur
);
740 info("set RLIM_NOFILE to %lu", (unsigned long)rl
->rlim_cur
);
742 info("RLIM_NOFILE is %lu", (unsigned long)rl
->rlim_cur
);
743 /* gcrypt initialization */
744 if(!gcry_check_version(NULL
))
745 disorder_fatal(0, "gcry_check_version failed");
746 gcry_control(GCRYCTL_INIT_SECMEM
, 0);
747 gcry_control (GCRYCTL_INITIALIZATION_FINISHED
, 0);
748 /* create a pipe between the backend callback and the poll() loop */
750 nonblock(sigpipe
[0]);
751 /* set up audio backend */
752 uaudio_set_format(config
->sample_format
.rate
,
753 config
->sample_format
.channels
,
754 config
->sample_format
.bits
,
755 config
->sample_format
.bits
!= 8);
756 early_finish
= uaudio_sample_size
* uaudio_channels
* uaudio_rate
;
757 /* TODO other parameters! */
758 backend
= uaudio_find(config
->api
);
759 /* backend-specific initialization */
760 if(backend
->configure
)
761 backend
->configure();
762 backend
->start(speaker_callback
, NULL
);
763 /* create the socket directory */
764 byte_xasprintf(&dir
, "%s/speaker", config
->home
);
765 unlink(dir
); /* might be a leftover socket */
766 if(mkdir(dir
, 0700) < 0 && errno
!= EEXIST
)
767 fatal(errno
, "error creating %s", dir
);
768 /* set up the listen socket */
769 listenfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
770 memset(&addr
, 0, sizeof addr
);
771 addr
.sun_family
= AF_UNIX
;
772 snprintf(addr
.sun_path
, sizeof addr
.sun_path
, "%s/speaker/socket",
774 if(unlink(addr
.sun_path
) < 0 && errno
!= ENOENT
)
775 error(errno
, "removing %s", addr
.sun_path
);
776 xsetsockopt(listenfd
, SOL_SOCKET
, SO_REUSEADDR
, &one
, sizeof one
);
777 if(bind(listenfd
, (const struct sockaddr
*)&addr
, sizeof addr
) < 0)
778 fatal(errno
, "error binding socket to %s", addr
.sun_path
);
779 xlisten(listenfd
, 128);
781 info("listening on %s", addr
.sun_path
);
782 memset(&sm
, 0, sizeof sm
);
784 speaker_send(1, &sm
);
786 info("stopped (parent terminated)");