Commit | Line | Data |
---|---|---|
460b9539 | 1 | /* |
2 | * This file is part of DisOrder | |
de38ab9b | 3 | * Copyright (C) 2005-2010 Richard Kettlewell |
313acc77 | 4 | * Portions (C) 2007 Mark Wooding |
460b9539 | 5 | * |
e7eb3a27 | 6 | * This program is free software: you can redistribute it and/or modify |
460b9539 | 7 | * it under the terms of the GNU General Public License as published by |
e7eb3a27 | 8 | * the Free Software Foundation, either version 3 of the License, or |
460b9539 | 9 | * (at your option) any later version. |
e7eb3a27 RK |
10 | * |
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. | |
15 | * | |
460b9539 | 16 | * You should have received a copy of the GNU General Public License |
e7eb3a27 | 17 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
460b9539 | 18 | */ |
1674096e | 19 | /** @file server/speaker.c |
cf714d85 | 20 | * @brief Speaker process |
1674096e | 21 | * |
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 | |
42829e58 RK |
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 | |
26 | * right order. | |
1674096e | 27 | * |
b50cfb8a RK |
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 | |
32 | * the server. | |
33 | * | |
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. | |
37 | * | |
38 | * Audio is supplied from this buffer to the uaudio play callback. Playback is | |
e626b1f0 | 39 | * enabled when a track is to be played and disabled when its last bytes |
0cf685f6 | 40 | * have been returned by the callback; pause and resume is implemented the |
b50cfb8a RK |
41 | * obvious way. If the callback finds itself required to play when there is no |
42 | * playing track it returns dead air. | |
43 | * | |
888b8031 RK |
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 | |
47 | * been sent for it. | |
48 | * | |
b50cfb8a RK |
49 | * @b Encodings. The encodings supported depend entirely on the uaudio backend |
50 | * chosen. See @ref uaudio.h, etc. | |
1674096e | 51 | * |
6d2d327c RK |
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). | |
1674096e | 55 | * |
5b7a22c6 | 56 | * @b Garbage @b Collection. This program deliberately does not use the |
795192f4 | 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 | |
62 | * relatively briefly. | |
63 | * | |
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 | |
68 | * 2-byte samples. | |
1674096e | 69 | */ |
460b9539 | 70 | |
05b75f8d | 71 | #include "common.h" |
460b9539 | 72 | |
73 | #include <getopt.h> | |
460b9539 | 74 | #include <locale.h> |
75 | #include <syslog.h> | |
76 | #include <unistd.h> | |
77 | #include <errno.h> | |
460b9539 | 78 | #include <sys/select.h> |
9d5da576 | 79 | #include <sys/wait.h> |
460b9539 | 80 | #include <time.h> |
8023f60b | 81 | #include <fcntl.h> |
82 | #include <poll.h> | |
84aa9f93 | 83 | #include <sys/un.h> |
a5f3ca1e | 84 | #include <sys/stat.h> |
b50cfb8a | 85 | #include <pthread.h> |
adeb58a0 | 86 | #include <sys/resource.h> |
5bf7c546 | 87 | #include <gcrypt.h> |
460b9539 | 88 | |
89 | #include "configuration.h" | |
90 | #include "syscalls.h" | |
91 | #include "log.h" | |
92 | #include "defs.h" | |
93 | #include "mem.h" | |
ea410ba1 | 94 | #include "speaker-protocol.h" |
460b9539 | 95 | #include "user.h" |
85cb23d7 | 96 | #include "printf.h" |
3fbdc96d | 97 | #include "version.h" |
b50cfb8a | 98 | #include "uaudio.h" |
460b9539 | 99 | |
b50cfb8a RK |
100 | /** @brief Maximum number of FDs to poll for */ |
101 | #define NFDS 1024 | |
e83d0967 | 102 | |
888b8031 RK |
103 | /** @brief Number of bytes before end of track to send SM_FINISHED |
104 | * | |
105 | * Generally set to 1 second. | |
106 | */ | |
107 | static size_t early_finish; | |
108 | ||
b50cfb8a RK |
109 | /** @brief Track structure |
110 | * | |
111 | * Known tracks are kept in a linked list. Usually there will be at most two | |
112 | * of these but rearranging the queue can cause there to be more. | |
113 | */ | |
114 | struct track { | |
115 | /** @brief Next track */ | |
116 | struct track *next; | |
117 | ||
118 | /** @brief Input file descriptor */ | |
0cf685f6 | 119 | int fd; |
b50cfb8a RK |
120 | |
121 | /** @brief Track ID */ | |
122 | char id[24]; | |
123 | ||
124 | /** @brief Start position of data in buffer */ | |
125 | size_t start; | |
126 | ||
127 | /** @brief Number of bytes of data in buffer */ | |
128 | size_t used; | |
129 | ||
130 | /** @brief Set @c fd is at EOF */ | |
131 | int eof; | |
132 | ||
133 | /** @brief Total number of samples played */ | |
134 | unsigned long long played; | |
135 | ||
136 | /** @brief Slot in @ref fds */ | |
137 | int slot; | |
138 | ||
139 | /** @brief Set when playable | |
140 | * | |
141 | * A track becomes playable whenever it fills its buffer or reaches EOF; it | |
142 | * stops being playable when it entirely empties its buffer. Tracks start | |
143 | * out life not playable. | |
144 | */ | |
145 | int playable; | |
888b8031 RK |
146 | |
147 | /** @brief Set when finished | |
148 | * | |
149 | * This is set when we've notified the server that the track is finished. | |
150 | * Once this has happened (typically very late in the track's lifetime) the | |
151 | * track cannot be paused or cancelled. | |
152 | */ | |
153 | int finished; | |
b50cfb8a RK |
154 | |
155 | /** @brief Input buffer | |
156 | * | |
157 | * 1Mbyte is enough for nearly 6s of 44100Hz 16-bit stereo | |
158 | */ | |
159 | char buffer[1048576]; | |
160 | }; | |
460b9539 | 161 | |
b50cfb8a RK |
162 | /** @brief Lock protecting data structures |
163 | * | |
164 | * This lock protects values shared between the main thread and the callback. | |
89156c8c RK |
165 | * |
166 | * It is held 'all' the time by the main thread, the exceptions being when | |
167 | * called activate/deactivate callbacks and when calling (potentially) slow | |
168 | * system calls (in particular poll(), where in fact the main thread will spend | |
169 | * most of its time blocked). | |
170 | * | |
171 | * The callback holds it when it's running. | |
b50cfb8a RK |
172 | */ |
173 | static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; | |
174 | ||
0cf685f6 RK |
175 | /** @brief Linked list of all prepared tracks |
176 | * | |
177 | * This includes @ref playing and @ref pending_playing. | |
178 | */ | |
b50cfb8a RK |
179 | static struct track *tracks; |
180 | ||
181 | /** @brief Playing track, or NULL | |
182 | * | |
888b8031 RK |
183 | * This means the track the speaker process intends to play. It does not |
184 | * reflect any other state (e.g. activation of uaudio backend). | |
0cf685f6 RK |
185 | * |
186 | * This track remains on @ref track. | |
b50cfb8a RK |
187 | */ |
188 | static struct track *playing; | |
1c3f1e73 | 189 | |
888b8031 RK |
190 | /** @brief Pending playing track, or NULL |
191 | * | |
192 | * This means the track the server wants the speaker to play. | |
0cf685f6 RK |
193 | * |
194 | * This track remains on @p track. | |
888b8031 RK |
195 | */ |
196 | static struct track *pending_playing; | |
197 | ||
1c3f1e73 | 198 | /** @brief Array of file descriptors for poll() */ |
b50cfb8a | 199 | static struct pollfd fds[NFDS]; |
1c3f1e73 | 200 | |
0cf685f6 RK |
201 | /** @brief Next free slot in @ref fds |
202 | * | |
203 | * This is used when filling in the @ref fds array each iteration through the | |
204 | * event loop. | |
205 | */ | |
b50cfb8a | 206 | static int fdno; |
1c3f1e73 | 207 | |
84aa9f93 RK |
208 | /** @brief Listen socket */ |
209 | static int listenfd; | |
210 | ||
b50cfb8a RK |
211 | /** @brief Timestamp of last potential report to server */ |
212 | static time_t last_report; | |
50ae38dd | 213 | |
b50cfb8a RK |
214 | /** @brief Set when paused */ |
215 | static int paused; | |
50ae38dd | 216 | |
b50cfb8a RK |
217 | /** @brief Set when back end activated */ |
218 | static int activated; | |
219 | ||
220 | /** @brief Signal pipe back into the poll() loop */ | |
221 | static int sigpipe[2]; | |
460b9539 | 222 | |
29601377 | 223 | /** @brief Selected backend */ |
b50cfb8a | 224 | static const struct uaudio *backend; |
29601377 | 225 | |
460b9539 | 226 | static const struct option options[] = { |
227 | { "help", no_argument, 0, 'h' }, | |
228 | { "version", no_argument, 0, 'V' }, | |
229 | { "config", required_argument, 0, 'c' }, | |
230 | { "debug", no_argument, 0, 'd' }, | |
231 | { "no-debug", no_argument, 0, 'D' }, | |
0ca6d097 RK |
232 | { "syslog", no_argument, 0, 's' }, |
233 | { "no-syslog", no_argument, 0, 'S' }, | |
460b9539 | 234 | { 0, 0, 0, 0 } |
235 | }; | |
236 | ||
237 | /* Display usage message and terminate. */ | |
238 | static void help(void) { | |
239 | xprintf("Usage:\n" | |
240 | " disorder-speaker [OPTIONS]\n" | |
241 | "Options:\n" | |
242 | " --help, -h Display usage message\n" | |
243 | " --version, -V Display version number\n" | |
244 | " --config PATH, -c PATH Set configuration file\n" | |
245 | " --debug, -d Turn on debugging\n" | |
0ca6d097 | 246 | " --[no-]syslog Force logging\n" |
460b9539 | 247 | "\n" |
248 | "Speaker process for DisOrder. Not intended to be run\n" | |
249 | "directly.\n"); | |
250 | xfclose(stdout); | |
251 | exit(0); | |
252 | } | |
253 | ||
b50cfb8a RK |
254 | /** @brief Find track @p id, maybe creating it if not found |
255 | * @param id Track ID to find | |
0cf685f6 | 256 | * @param create If nonzero, create track structure of @p id if not found |
b50cfb8a RK |
257 | * @return Pointer to track structure or NULL |
258 | */ | |
460b9539 | 259 | static struct track *findtrack(const char *id, int create) { |
260 | struct track *t; | |
261 | ||
262 | D(("findtrack %s %d", id, create)); | |
263 | for(t = tracks; t && strcmp(id, t->id); t = t->next) | |
264 | ; | |
265 | if(!t && create) { | |
266 | t = xmalloc(sizeof *t); | |
267 | t->next = tracks; | |
268 | strcpy(t->id, id); | |
269 | t->fd = -1; | |
270 | tracks = t; | |
460b9539 | 271 | } |
272 | return t; | |
273 | } | |
274 | ||
b50cfb8a RK |
275 | /** @brief Remove track @p id (but do not destroy it) |
276 | * @param id Track ID to remove | |
277 | * @return Track structure or NULL if not found | |
278 | */ | |
460b9539 | 279 | static struct track *removetrack(const char *id) { |
280 | struct track *t, **tt; | |
281 | ||
282 | D(("removetrack %s", id)); | |
283 | for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next) | |
284 | ; | |
285 | if(t) | |
286 | *tt = t->next; | |
287 | return t; | |
288 | } | |
289 | ||
b50cfb8a RK |
290 | /** @brief Destroy a track |
291 | * @param t Track structure | |
292 | */ | |
460b9539 | 293 | static void destroy(struct track *t) { |
294 | D(("destroy %s", t->id)); | |
b50cfb8a RK |
295 | if(t->fd != -1) |
296 | xclose(t->fd); | |
460b9539 | 297 | free(t); |
298 | } | |
299 | ||
1674096e | 300 | /** @brief Read data into a sample buffer |
301 | * @param t Pointer to track | |
302 | * @return 0 on success, -1 on EOF | |
303 | * | |
55f35f2d | 304 | * This is effectively the read callback on @c t->fd. It is called from the |
305 | * main loop whenever the track's file descriptor is readable, assuming the | |
306 | * buffer has not reached the maximum allowed occupancy. | |
0cf685f6 RK |
307 | * |
308 | * Errors count as EOF. | |
1674096e | 309 | */ |
f5a03f58 | 310 | static int speaker_fill(struct track *t) { |
460b9539 | 311 | size_t where, left; |
b50cfb8a | 312 | int n, rc; |
460b9539 | 313 | |
6d2d327c RK |
314 | D(("fill %s: eof=%d used=%zu", |
315 | t->id, t->eof, t->used)); | |
b50cfb8a RK |
316 | if(t->eof) |
317 | return -1; | |
6d2d327c | 318 | if(t->used < sizeof t->buffer) { |
460b9539 | 319 | /* there is room left in the buffer */ |
6d2d327c RK |
320 | where = (t->start + t->used) % sizeof t->buffer; |
321 | /* Get as much data as we can */ | |
b50cfb8a RK |
322 | if(where >= t->start) |
323 | left = (sizeof t->buffer) - where; | |
324 | else | |
325 | left = t->start - where; | |
326 | pthread_mutex_unlock(&lock); | |
460b9539 | 327 | do { |
328 | n = read(t->fd, t->buffer + where, left); | |
329 | } while(n < 0 && errno == EINTR); | |
b50cfb8a | 330 | pthread_mutex_lock(&lock); |
de38ab9b RK |
331 | if(n < 0 && errno == EAGAIN) { |
332 | /* EAGAIN means more later */ | |
b50cfb8a | 333 | rc = 0; |
de38ab9b RK |
334 | } else if(n <= 0) { |
335 | /* n=0 means EOF. n<0 means some error occurred. We log the error but | |
336 | * otherwise treat it as identical to EOF. */ | |
337 | if(n < 0) | |
338 | disorder_error(errno, "error reading sample stream for %s", t->id); | |
339 | else | |
340 | D(("fill %s: eof detected", t->id)); | |
460b9539 | 341 | t->eof = 1; |
b50cfb8a RK |
342 | /* A track always becomes playable at EOF; we're not going to see any |
343 | * more data. */ | |
f5a03f58 | 344 | t->playable = 1; |
b50cfb8a RK |
345 | rc = -1; |
346 | } else { | |
347 | t->used += n; | |
348 | /* A track becomes playable when it (first) fills its buffer. For | |
349 | * 44.1KHz 16-bit stereo this is ~6s of audio data. The latency will | |
350 | * depend how long that takes to decode (hopefuly not very!) */ | |
351 | if(t->used == sizeof t->buffer) | |
352 | t->playable = 1; | |
353 | rc = 0; | |
460b9539 | 354 | } |
9efa107e RK |
355 | } else |
356 | rc = 0; | |
b50cfb8a | 357 | return rc; |
460b9539 | 358 | } |
359 | ||
dac25ef9 RK |
360 | /** @brief Return nonzero if we want to play some audio |
361 | * | |
362 | * We want to play audio if there is a current track; and it is not paused; and | |
363 | * it is playable according to the rules for @ref track::playable. | |
888b8031 RK |
364 | * |
365 | * We don't allow tracks to be paused if we've already told the server we've | |
366 | * finished them; that would cause such tracks to survive much longer than the | |
367 | * few samples they're supposed to, with report() remaining silent for the | |
0cf685f6 RK |
368 | * duration. The effect is that if you hit pause towards the end of a track, |
369 | * what should happen is that it finished but the next one is paused right at | |
370 | * its start. | |
dac25ef9 RK |
371 | */ |
372 | static int playable(void) { | |
373 | return playing | |
888b8031 | 374 | && (!paused || playing->finished) |
dac25ef9 RK |
375 | && playing->playable; |
376 | } | |
377 | ||
b50cfb8a | 378 | /** @brief Notify the server what we're up to */ |
460b9539 | 379 | static void report(void) { |
380 | struct speaker_message sm; | |
381 | ||
6d2d327c | 382 | if(playing) { |
888b8031 RK |
383 | /* Had better not send a report for a track that the server thinks has |
384 | * finished, that would be confusing. */ | |
385 | if(playing->finished) | |
386 | return; | |
460b9539 | 387 | memset(&sm, 0, sizeof sm); |
388 | sm.type = paused ? SM_PAUSED : SM_PLAYING; | |
389 | strcpy(sm.id, playing->id); | |
b50cfb8a | 390 | sm.data = playing->played / (uaudio_rate * uaudio_channels); |
84aa9f93 | 391 | speaker_send(1, &sm); |
4265e5d3 | 392 | xtime(&last_report); |
460b9539 | 393 | } |
460b9539 | 394 | } |
395 | ||
b50cfb8a RK |
396 | /** @brief Add a file descriptor to the set to poll() for |
397 | * @param fd File descriptor | |
398 | * @param events Events to wait for e.g. @c POLLIN | |
399 | * @return Slot number | |
400 | */ | |
401 | static int addfd(int fd, int events) { | |
460b9539 | 402 | if(fdno < NFDS) { |
403 | fds[fdno].fd = fd; | |
404 | fds[fdno].events = events; | |
405 | return fdno++; | |
406 | } else | |
407 | return -1; | |
408 | } | |
409 | ||
b50cfb8a RK |
410 | /** @brief Callback to return some sampled data |
411 | * @param buffer Where to put sample data | |
412 | * @param max_samples How many samples to return | |
413 | * @param userdata User data | |
414 | * @return Number of samples written | |
415 | * | |
416 | * See uaudio_callback(). | |
417 | */ | |
418 | static size_t speaker_callback(void *buffer, | |
419 | size_t max_samples, | |
420 | void attribute((unused)) *userdata) { | |
421 | const size_t max_bytes = max_samples * uaudio_sample_size; | |
422 | size_t provided_samples = 0; | |
423 | ||
424 | pthread_mutex_lock(&lock); | |
425 | /* TODO perhaps we should immediately go silent if we've been asked to pause | |
426 | * or cancel the playing track (maybe block in the cancel case and see what | |
427 | * else turns up?) */ | |
428 | if(playing) { | |
429 | if(playing->used > 0) { | |
430 | size_t bytes; | |
431 | /* Compute size of largest contiguous chunk. We get called as often as | |
432 | * necessary so there's no need for cleverness here. */ | |
433 | if(playing->start + playing->used > sizeof playing->buffer) | |
434 | bytes = sizeof playing->buffer - playing->start; | |
435 | else | |
436 | bytes = playing->used; | |
437 | /* Limit to what we were asked for */ | |
438 | if(bytes > max_bytes) | |
439 | bytes = max_bytes; | |
440 | /* Provide it */ | |
441 | memcpy(buffer, playing->buffer + playing->start, bytes); | |
442 | playing->start += bytes; | |
443 | playing->used -= bytes; | |
444 | /* Wrap around to start of buffer */ | |
445 | if(playing->start == sizeof playing->buffer) | |
446 | playing->start = 0; | |
0cf685f6 RK |
447 | /* See if we've reached the end of the track; if so make sure the event |
448 | * loop wakes up. */ | |
784744a8 RK |
449 | if(playing->used == 0 && playing->eof) { |
450 | int ignored = write(sigpipe[1], "", 1); | |
451 | (void) ignored; | |
452 | } | |
b50cfb8a RK |
453 | provided_samples = bytes / uaudio_sample_size; |
454 | playing->played += provided_samples; | |
455 | } | |
456 | } | |
457 | /* If we couldn't provide anything at all, play dead air */ | |
458 | /* TODO maybe it would be better to block, in some cases? */ | |
459 | if(!provided_samples) { | |
460 | memset(buffer, 0, max_bytes); | |
461 | provided_samples = max_samples; | |
89156c8c | 462 | if(playing) |
2e9ba080 RK |
463 | disorder_info("%zu samples silence, playing->used=%zu", |
464 | provided_samples, playing->used); | |
89156c8c | 465 | else |
2e9ba080 | 466 | disorder_info("%zu samples silence, playing=NULL", provided_samples); |
b50cfb8a RK |
467 | } |
468 | pthread_mutex_unlock(&lock); | |
469 | return provided_samples; | |
470 | } | |
572d74ba | 471 | |
5a7c42a8 | 472 | /** @brief Main event loop */ |
55f35f2d | 473 | static void mainloop(void) { |
572d74ba | 474 | struct track *t; |
475 | struct speaker_message sm; | |
b50cfb8a | 476 | int n, fd, stdin_slot, timeout, listen_slot, sigpipe_slot; |
460b9539 | 477 | |
89156c8c | 478 | pthread_mutex_lock(&lock); |
0cf685f6 | 479 | /* Keep going while our parent process is alive */ |
460b9539 | 480 | while(getppid() != 1) { |
b50cfb8a RK |
481 | int force_report = 0; |
482 | ||
460b9539 | 483 | fdno = 0; |
888b8031 RK |
484 | /* By default we will wait up to half a second before thinking about |
485 | * current state. */ | |
486 | timeout = 500; | |
460b9539 | 487 | /* Always ready for commands from the main server. */ |
488 | stdin_slot = addfd(0, POLLIN); | |
84aa9f93 RK |
489 | /* Also always ready for inbound connections */ |
490 | listen_slot = addfd(listenfd, POLLIN); | |
460b9539 | 491 | /* Try to read sample data for the currently playing track if there is |
492 | * buffer space. */ | |
84aa9f93 RK |
493 | if(playing |
494 | && playing->fd >= 0 | |
495 | && !playing->eof | |
496 | && playing->used < (sizeof playing->buffer)) | |
460b9539 | 497 | playing->slot = addfd(playing->fd, POLLIN); |
5a7c42a8 | 498 | else if(playing) |
460b9539 | 499 | playing->slot = -1; |
0cf685f6 RK |
500 | /* Allow the poll() to be interrupted at the end of a track */ |
501 | sigpipe_slot = addfd(sigpipe[0], POLLIN); | |
460b9539 | 502 | /* If any other tracks don't have a full buffer, try to read sample data |
5a7c42a8 | 503 | * from them. We do this last of all, so that if we run out of slots, |
504 | * nothing important can't be monitored. */ | |
460b9539 | 505 | for(t = tracks; t; t = t->next) |
506 | if(t != playing) { | |
84aa9f93 RK |
507 | if(t->fd >= 0 |
508 | && !t->eof | |
509 | && t->used < sizeof t->buffer) { | |
9d5da576 | 510 | t->slot = addfd(t->fd, POLLIN | POLLHUP); |
460b9539 | 511 | } else |
512 | t->slot = -1; | |
513 | } | |
e83d0967 | 514 | /* Wait for something interesting to happen */ |
89156c8c | 515 | pthread_mutex_unlock(&lock); |
e83d0967 | 516 | n = poll(fds, fdno, timeout); |
89156c8c | 517 | pthread_mutex_lock(&lock); |
460b9539 | 518 | if(n < 0) { |
519 | if(errno == EINTR) continue; | |
2e9ba080 | 520 | disorder_fatal(errno, "error calling poll"); |
460b9539 | 521 | } |
84aa9f93 RK |
522 | /* Perhaps a connection has arrived */ |
523 | if(fds[listen_slot].revents & POLLIN) { | |
524 | struct sockaddr_un addr; | |
525 | socklen_t addrlen = sizeof addr; | |
526 | uint32_t l; | |
527 | char id[24]; | |
528 | ||
dc450d30 | 529 | if((fd = accept(listenfd, (struct sockaddr *)&addr, &addrlen)) >= 0) { |
0cf685f6 RK |
530 | /* We do blocking reads for the header. In theory this means that the |
531 | * connecting process could wedge the speaker indefinitely. In | |
532 | * practice that would mean that the main server was broken anyway. | |
533 | * Still, this is ugly, and a rewrite would be nice. */ | |
937be4c0 | 534 | blocking(fd); |
84aa9f93 | 535 | if(read(fd, &l, sizeof l) < 4) { |
2e9ba080 | 536 | disorder_error(errno, "reading length from inbound connection"); |
84aa9f93 RK |
537 | xclose(fd); |
538 | } else if(l >= sizeof id) { | |
2e9ba080 | 539 | disorder_error(0, "id length too long"); |
84aa9f93 RK |
540 | xclose(fd); |
541 | } else if(read(fd, id, l) < (ssize_t)l) { | |
2e9ba080 | 542 | disorder_error(errno, "reading id from inbound connection"); |
84aa9f93 RK |
543 | xclose(fd); |
544 | } else { | |
545 | id[l] = 0; | |
546 | D(("id %s fd %d", id, fd)); | |
547 | t = findtrack(id, 1/*create*/); | |
918393ff | 548 | if (write(fd, "", 1) < 0) /* write an ack */ |
de38ab9b RK |
549 | disorder_error(errno, "writing ack to inbound connection for %s", |
550 | id); | |
84aa9f93 | 551 | if(t->fd != -1) { |
2e9ba080 | 552 | disorder_error(0, "%s: already got a connection", id); |
84aa9f93 RK |
553 | xclose(fd); |
554 | } else { | |
555 | nonblock(fd); | |
556 | t->fd = fd; /* yay */ | |
557 | } | |
2a1c84fb RK |
558 | /* Notify the server that the connection arrived */ |
559 | sm.type = SM_ARRIVED; | |
560 | strcpy(sm.id, id); | |
561 | speaker_send(1, &sm); | |
84aa9f93 RK |
562 | } |
563 | } else | |
2e9ba080 | 564 | disorder_error(errno, "accept"); |
84aa9f93 | 565 | } |
460b9539 | 566 | /* Perhaps we have a command to process */ |
567 | if(fds[stdin_slot].revents & POLLIN) { | |
5a7c42a8 | 568 | /* There might (in theory) be several commands queued up, but in general |
569 | * this won't be the case, so we don't bother looping around to pick them | |
570 | * all up. */ | |
84aa9f93 | 571 | n = speaker_recv(0, &sm); |
460b9539 | 572 | if(n > 0) |
888b8031 RK |
573 | /* As a rule we don't send success replies to most commands - we just |
574 | * force the regular status update to be sent immediately rather than | |
575 | * on schedule. */ | |
460b9539 | 576 | switch(sm.type) { |
460b9539 | 577 | case SM_PLAY: |
888b8031 RK |
578 | /* SM_PLAY is only allowed if the server reasonably believes that |
579 | * nothing is playing */ | |
580 | if(playing) { | |
581 | /* If finished isn't set then the server can't believe that this | |
582 | * track has finished */ | |
583 | if(!playing->finished) | |
2e9ba080 | 584 | disorder_fatal(0, "got SM_PLAY but already playing something"); |
888b8031 RK |
585 | /* If pending_playing is set then the server must believe that that |
586 | * is playing */ | |
587 | if(pending_playing) | |
2e9ba080 | 588 | disorder_fatal(0, "got SM_PLAY but have a pending playing track"); |
888b8031 | 589 | } |
460b9539 | 590 | t = findtrack(sm.id, 1); |
84aa9f93 RK |
591 | D(("SM_PLAY %s fd %d", t->id, t->fd)); |
592 | if(t->fd == -1) | |
2e9ba080 RK |
593 | disorder_error(0, |
594 | "cannot play track because no connection arrived"); | |
5bac5b78 RK |
595 | /* TODO as things stand we often report this error message but then |
596 | * appear to proceed successfully. Understanding why requires a look | |
597 | * at play.c: we call prepare() which makes the connection in a child | |
598 | * process, and then sends the SM_PLAY in the parent process. The | |
599 | * latter may well be faster. As it happens this is harmless; we'll | |
600 | * just sit around sending silence until the decoder connects and | |
601 | * starts sending some sample data. But is is annoying and ought to | |
602 | * be fixed. */ | |
888b8031 RK |
603 | pending_playing = t; |
604 | /* If nothing is currently playing then we'll switch to the pending | |
605 | * track below so there's no point distinguishing the situations | |
606 | * here. */ | |
460b9539 | 607 | break; |
608 | case SM_PAUSE: | |
609 | D(("SM_PAUSE")); | |
610 | paused = 1; | |
b50cfb8a | 611 | force_report = 1; |
460b9539 | 612 | break; |
613 | case SM_RESUME: | |
614 | D(("SM_RESUME")); | |
b50cfb8a RK |
615 | paused = 0; |
616 | force_report = 1; | |
460b9539 | 617 | break; |
618 | case SM_CANCEL: | |
819f5988 | 619 | D(("SM_CANCEL %s", sm.id)); |
460b9539 | 620 | t = removetrack(sm.id); |
621 | if(t) { | |
888b8031 RK |
622 | if(t == playing || t == pending_playing) { |
623 | /* Scratching the track that the server believes is playing, | |
624 | * which might either be the actual playing track or a pending | |
625 | * playing track */ | |
460b9539 | 626 | sm.type = SM_FINISHED; |
888b8031 RK |
627 | if(t == playing) |
628 | playing = 0; | |
629 | else | |
630 | pending_playing = 0; | |
819f5988 RK |
631 | } else { |
632 | /* Could be scratching the playing track before it's quite got | |
633 | * going, or could be just removing a track from the queue. We | |
634 | * log more because there's been a bug here recently than because | |
635 | * it's particularly interesting; the log message will be removed | |
636 | * if no further problems show up. */ | |
2e9ba080 | 637 | disorder_info("SM_CANCEL for nonplaying track %s", sm.id); |
819f5988 | 638 | sm.type = SM_STILLBORN; |
460b9539 | 639 | } |
819f5988 | 640 | strcpy(sm.id, t->id); |
460b9539 | 641 | destroy(t); |
2b2a5fed | 642 | } else { |
819f5988 RK |
643 | /* Probably scratching the playing track well before it's got |
644 | * going, but could indicate a bug, so we log this as an error. */ | |
2b2a5fed | 645 | sm.type = SM_UNKNOWN; |
2e9ba080 | 646 | disorder_error(0, "SM_CANCEL for unknown track %s", sm.id); |
2b2a5fed | 647 | } |
819f5988 | 648 | speaker_send(1, &sm); |
b50cfb8a | 649 | force_report = 1; |
460b9539 | 650 | break; |
651 | case SM_RELOAD: | |
652 | D(("SM_RELOAD")); | |
02ba7921 | 653 | if(config_read(1, NULL)) |
2e9ba080 RK |
654 | disorder_error(0, "cannot read configuration"); |
655 | disorder_info("reloaded configuration"); | |
460b9539 | 656 | break; |
657 | default: | |
2e9ba080 | 658 | disorder_error(0, "unknown message type %d", sm.type); |
460b9539 | 659 | } |
660 | } | |
661 | /* Read in any buffered data */ | |
662 | for(t = tracks; t; t = t->next) | |
84aa9f93 RK |
663 | if(t->fd != -1 |
664 | && t->slot != -1 | |
665 | && (fds[t->slot].revents & (POLLIN | POLLHUP))) | |
f5a03f58 | 666 | speaker_fill(t); |
b50cfb8a RK |
667 | /* Drain the signal pipe. We don't care about its contents, merely that it |
668 | * interrupted poll(). */ | |
669 | if(fds[sigpipe_slot].revents & POLLIN) { | |
670 | char buffer[64]; | |
784744a8 | 671 | int ignored; (void)ignored; |
b50cfb8a | 672 | |
784744a8 | 673 | ignored = read(sigpipe[0], buffer, sizeof buffer); |
b50cfb8a | 674 | } |
888b8031 RK |
675 | /* Send SM_FINISHED when we're near the end of the track. |
676 | * | |
677 | * This is how we implement gapless play; we hope that the SM_PLAY from the | |
678 | * server arrives before the remaining bytes of the track play out. | |
679 | */ | |
680 | if(playing | |
681 | && playing->eof | |
682 | && !playing->finished | |
683 | && playing->used <= early_finish) { | |
b50cfb8a RK |
684 | memset(&sm, 0, sizeof sm); |
685 | sm.type = SM_FINISHED; | |
686 | strcpy(sm.id, playing->id); | |
687 | speaker_send(1, &sm); | |
888b8031 RK |
688 | playing->finished = 1; |
689 | } | |
690 | /* When the track is actually finished, deconfigure it */ | |
691 | if(playing && playing->eof && !playing->used) { | |
0cf685f6 RK |
692 | if(!playing->finished) { |
693 | /* should never happen but we'd like to know if it does */ | |
694 | disorder_fatal(0, "track finish state inconsistent"); | |
695 | } | |
888b8031 | 696 | removetrack(playing->id); |
b50cfb8a RK |
697 | destroy(playing); |
698 | playing = 0; | |
888b8031 RK |
699 | } |
700 | /* Act on the pending SM_PLAY */ | |
9c55e9e4 | 701 | if(!playing && pending_playing) { |
888b8031 RK |
702 | playing = pending_playing; |
703 | pending_playing = 0; | |
888b8031 | 704 | force_report = 1; |
b50cfb8a RK |
705 | } |
706 | /* Impose any state change required by the above */ | |
707 | if(playable()) { | |
708 | if(!activated) { | |
709 | activated = 1; | |
89156c8c | 710 | pthread_mutex_unlock(&lock); |
b50cfb8a | 711 | backend->activate(); |
89156c8c | 712 | pthread_mutex_lock(&lock); |
b50cfb8a RK |
713 | } |
714 | } else { | |
715 | if(activated) { | |
716 | activated = 0; | |
89156c8c | 717 | pthread_mutex_unlock(&lock); |
b50cfb8a | 718 | backend->deactivate(); |
89156c8c | 719 | pthread_mutex_lock(&lock); |
b50cfb8a RK |
720 | } |
721 | } | |
722 | /* If we've not reported our state for a second do so now. */ | |
4265e5d3 | 723 | if(force_report || xtime(0) > last_report) |
460b9539 | 724 | report(); |
725 | } | |
55f35f2d | 726 | } |
727 | ||
728 | int main(int argc, char **argv) { | |
0ca6d097 | 729 | int n, logsyslog = !isatty(2); |
84aa9f93 RK |
730 | struct sockaddr_un addr; |
731 | static const int one = 1; | |
937be4c0 | 732 | struct speaker_message sm; |
38b8221f | 733 | const char *d; |
85cb23d7 | 734 | char *dir; |
b50cfb8a | 735 | struct rlimit rl[1]; |
55f35f2d | 736 | |
737 | set_progname(argv); | |
2e9ba080 | 738 | if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "error calling setlocale"); |
0ca6d097 | 739 | while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) { |
55f35f2d | 740 | switch(n) { |
741 | case 'h': help(); | |
3fbdc96d | 742 | case 'V': version("disorder-speaker"); |
55f35f2d | 743 | case 'c': configfile = optarg; break; |
744 | case 'd': debugging = 1; break; | |
745 | case 'D': debugging = 0; break; | |
0ca6d097 RK |
746 | case 'S': logsyslog = 0; break; |
747 | case 's': logsyslog = 1; break; | |
2e9ba080 | 748 | default: disorder_fatal(0, "invalid option"); |
55f35f2d | 749 | } |
750 | } | |
38b8221f | 751 | if((d = getenv("DISORDER_DEBUG_SPEAKER"))) debugging = atoi(d); |
0ca6d097 | 752 | if(logsyslog) { |
55f35f2d | 753 | openlog(progname, LOG_PID, LOG_DAEMON); |
754 | log_default = &log_syslog; | |
755 | } | |
b50cfb8a | 756 | config_uaudio_apis = uaudio_apis; |
2e9ba080 | 757 | if(config_read(1, NULL)) disorder_fatal(0, "cannot read configuration"); |
55f35f2d | 758 | /* ignore SIGPIPE */ |
759 | signal(SIGPIPE, SIG_IGN); | |
55f35f2d | 760 | /* set nice value */ |
761 | xnice(config->nice_speaker); | |
762 | /* change user */ | |
763 | become_mortal(); | |
764 | /* make sure we're not root, whatever the config says */ | |
b50cfb8a | 765 | if(getuid() == 0 || geteuid() == 0) |
2e9ba080 | 766 | disorder_fatal(0, "do not run as root"); |
b50cfb8a RK |
767 | /* Make sure we can't have more than NFDS files open (it would bust our |
768 | * poll() array) */ | |
769 | if(getrlimit(RLIMIT_NOFILE, rl) < 0) | |
2e9ba080 | 770 | disorder_fatal(errno, "getrlimit RLIMIT_NOFILE"); |
b50cfb8a RK |
771 | if(rl->rlim_cur > NFDS) { |
772 | rl->rlim_cur = NFDS; | |
773 | if(setrlimit(RLIMIT_NOFILE, rl) < 0) | |
2e9ba080 | 774 | disorder_fatal(errno, "setrlimit to reduce RLIMIT_NOFILE to %lu", |
b50cfb8a | 775 | (unsigned long)rl->rlim_cur); |
2e9ba080 | 776 | disorder_info("set RLIM_NOFILE to %lu", (unsigned long)rl->rlim_cur); |
b50cfb8a | 777 | } else |
2e9ba080 | 778 | disorder_info("RLIM_NOFILE is %lu", (unsigned long)rl->rlim_cur); |
5bf7c546 RK |
779 | /* gcrypt initialization */ |
780 | if(!gcry_check_version(NULL)) | |
781 | disorder_fatal(0, "gcry_check_version failed"); | |
782 | gcry_control(GCRYCTL_INIT_SECMEM, 0); | |
783 | gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); | |
b50cfb8a RK |
784 | /* create a pipe between the backend callback and the poll() loop */ |
785 | xpipe(sigpipe); | |
786 | nonblock(sigpipe[0]); | |
787 | /* set up audio backend */ | |
788 | uaudio_set_format(config->sample_format.rate, | |
789 | config->sample_format.channels, | |
790 | config->sample_format.bits, | |
791 | config->sample_format.bits != 8); | |
888b8031 | 792 | early_finish = uaudio_sample_size * uaudio_channels * uaudio_rate; |
b50cfb8a RK |
793 | /* TODO other parameters! */ |
794 | backend = uaudio_find(config->api); | |
55f35f2d | 795 | /* backend-specific initialization */ |
ba70caca RK |
796 | if(backend->configure) |
797 | backend->configure(); | |
b50cfb8a | 798 | backend->start(speaker_callback, NULL); |
85cb23d7 RK |
799 | /* create the socket directory */ |
800 | byte_xasprintf(&dir, "%s/speaker", config->home); | |
801 | unlink(dir); /* might be a leftover socket */ | |
a5f3ca1e | 802 | if(mkdir(dir, 0700) < 0 && errno != EEXIST) |
2e9ba080 | 803 | disorder_fatal(errno, "error creating %s", dir); |
84aa9f93 RK |
804 | /* set up the listen socket */ |
805 | listenfd = xsocket(PF_UNIX, SOCK_STREAM, 0); | |
806 | memset(&addr, 0, sizeof addr); | |
807 | addr.sun_family = AF_UNIX; | |
85cb23d7 | 808 | snprintf(addr.sun_path, sizeof addr.sun_path, "%s/speaker/socket", |
84aa9f93 RK |
809 | config->home); |
810 | if(unlink(addr.sun_path) < 0 && errno != ENOENT) | |
2e9ba080 | 811 | disorder_error(errno, "removing %s", addr.sun_path); |
84aa9f93 | 812 | xsetsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); |
dc450d30 | 813 | if(bind(listenfd, (const struct sockaddr *)&addr, sizeof addr) < 0) |
2e9ba080 | 814 | disorder_fatal(errno, "error binding socket to %s", addr.sun_path); |
84aa9f93 RK |
815 | xlisten(listenfd, 128); |
816 | nonblock(listenfd); | |
2e9ba080 | 817 | disorder_info("listening on %s", addr.sun_path); |
937be4c0 RK |
818 | memset(&sm, 0, sizeof sm); |
819 | sm.type = SM_READY; | |
820 | speaker_send(1, &sm); | |
55f35f2d | 821 | mainloop(); |
2e9ba080 | 822 | disorder_info("stopped (parent terminated)"); |
460b9539 | 823 | exit(0); |
824 | } | |
825 | ||
826 | /* | |
827 | Local Variables: | |
828 | c-basic-offset:2 | |
829 | comment-column:40 | |
830 | fill-column:79 | |
831 | indent-tabs-mode:nil | |
832 | End: | |
833 | */ |