chiark / gitweb /
plugins/tracklength-gstreamer.c: Rewrite to use `GstDiscoverer'.
[disorder] / server / speaker.c
CommitLineData
460b9539 1/*
2 * This file is part of DisOrder
e3953a41 3 * Copyright (C) 2005-2013 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 */
107static 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 */
114struct 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 */
173static 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
179static 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 */
188static 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 */
196static struct track *pending_playing;
197
1c3f1e73 198/** @brief Array of file descriptors for poll() */
b50cfb8a 199static 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 206static int fdno;
1c3f1e73 207
84aa9f93
RK
208/** @brief Listen socket */
209static int listenfd;
210
b50cfb8a
RK
211/** @brief Timestamp of last potential report to server */
212static time_t last_report;
50ae38dd 213
b50cfb8a
RK
214/** @brief Set when paused */
215static int paused;
50ae38dd 216
b50cfb8a
RK
217/** @brief Set when back end activated */
218static int activated;
219
220/** @brief Signal pipe back into the poll() loop */
221static int sigpipe[2];
460b9539 222
29601377 223/** @brief Selected backend */
b50cfb8a 224static const struct uaudio *backend;
29601377 225
460b9539 226static 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. */
238static 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 259static 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 279static 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 293static 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 310static 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 */
372static 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 379static 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;
e3953a41 389 strcpy(sm.u.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 */
401static 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 */
418static size_t speaker_callback(void *buffer,
419 size_t max_samples,
420 void attribute((unused)) *userdata) {
05577e6c 421 size_t max_bytes = max_samples * uaudio_sample_size;
b50cfb8a
RK
422 size_t provided_samples = 0;
423
05577e6c
MW
424 /* Be sure to keep the amount of data in a buffer a whole number of frames:
425 * otherwise the playing threads can become stuck. */
426 max_bytes -= max_bytes % (uaudio_sample_size * uaudio_channels);
427
b50cfb8a
RK
428 pthread_mutex_lock(&lock);
429 /* TODO perhaps we should immediately go silent if we've been asked to pause
430 * or cancel the playing track (maybe block in the cancel case and see what
431 * else turns up?) */
432 if(playing) {
433 if(playing->used > 0) {
434 size_t bytes;
435 /* Compute size of largest contiguous chunk. We get called as often as
436 * necessary so there's no need for cleverness here. */
437 if(playing->start + playing->used > sizeof playing->buffer)
438 bytes = sizeof playing->buffer - playing->start;
439 else
440 bytes = playing->used;
441 /* Limit to what we were asked for */
442 if(bytes > max_bytes)
443 bytes = max_bytes;
05577e6c
MW
444 /* And truncate to a whole number of frames. */
445 bytes -= bytes % (uaudio_sample_size * uaudio_channels);
b50cfb8a
RK
446 /* Provide it */
447 memcpy(buffer, playing->buffer + playing->start, bytes);
448 playing->start += bytes;
449 playing->used -= bytes;
450 /* Wrap around to start of buffer */
451 if(playing->start == sizeof playing->buffer)
452 playing->start = 0;
0cf685f6
RK
453 /* See if we've reached the end of the track; if so make sure the event
454 * loop wakes up. */
784744a8
RK
455 if(playing->used == 0 && playing->eof) {
456 int ignored = write(sigpipe[1], "", 1);
457 (void) ignored;
458 }
b50cfb8a
RK
459 provided_samples = bytes / uaudio_sample_size;
460 playing->played += provided_samples;
461 }
462 }
463 /* If we couldn't provide anything at all, play dead air */
464 /* TODO maybe it would be better to block, in some cases? */
465 if(!provided_samples) {
466 memset(buffer, 0, max_bytes);
467 provided_samples = max_samples;
89156c8c 468 if(playing)
2e9ba080
RK
469 disorder_info("%zu samples silence, playing->used=%zu",
470 provided_samples, playing->used);
89156c8c 471 else
2e9ba080 472 disorder_info("%zu samples silence, playing=NULL", provided_samples);
b50cfb8a
RK
473 }
474 pthread_mutex_unlock(&lock);
475 return provided_samples;
476}
572d74ba 477
5a7c42a8 478/** @brief Main event loop */
55f35f2d 479static void mainloop(void) {
572d74ba 480 struct track *t;
481 struct speaker_message sm;
b50cfb8a 482 int n, fd, stdin_slot, timeout, listen_slot, sigpipe_slot;
460b9539 483
89156c8c 484 pthread_mutex_lock(&lock);
0cf685f6 485 /* Keep going while our parent process is alive */
460b9539 486 while(getppid() != 1) {
b50cfb8a
RK
487 int force_report = 0;
488
460b9539 489 fdno = 0;
888b8031
RK
490 /* By default we will wait up to half a second before thinking about
491 * current state. */
492 timeout = 500;
460b9539 493 /* Always ready for commands from the main server. */
494 stdin_slot = addfd(0, POLLIN);
84aa9f93
RK
495 /* Also always ready for inbound connections */
496 listen_slot = addfd(listenfd, POLLIN);
460b9539 497 /* Try to read sample data for the currently playing track if there is
498 * buffer space. */
84aa9f93
RK
499 if(playing
500 && playing->fd >= 0
501 && !playing->eof
502 && playing->used < (sizeof playing->buffer))
460b9539 503 playing->slot = addfd(playing->fd, POLLIN);
5a7c42a8 504 else if(playing)
460b9539 505 playing->slot = -1;
0cf685f6
RK
506 /* Allow the poll() to be interrupted at the end of a track */
507 sigpipe_slot = addfd(sigpipe[0], POLLIN);
460b9539 508 /* If any other tracks don't have a full buffer, try to read sample data
5a7c42a8 509 * from them. We do this last of all, so that if we run out of slots,
510 * nothing important can't be monitored. */
460b9539 511 for(t = tracks; t; t = t->next)
512 if(t != playing) {
84aa9f93
RK
513 if(t->fd >= 0
514 && !t->eof
515 && t->used < sizeof t->buffer) {
9d5da576 516 t->slot = addfd(t->fd, POLLIN | POLLHUP);
460b9539 517 } else
518 t->slot = -1;
519 }
e83d0967 520 /* Wait for something interesting to happen */
89156c8c 521 pthread_mutex_unlock(&lock);
e83d0967 522 n = poll(fds, fdno, timeout);
89156c8c 523 pthread_mutex_lock(&lock);
460b9539 524 if(n < 0) {
525 if(errno == EINTR) continue;
2e9ba080 526 disorder_fatal(errno, "error calling poll");
460b9539 527 }
84aa9f93
RK
528 /* Perhaps a connection has arrived */
529 if(fds[listen_slot].revents & POLLIN) {
530 struct sockaddr_un addr;
531 socklen_t addrlen = sizeof addr;
532 uint32_t l;
533 char id[24];
534
dc450d30 535 if((fd = accept(listenfd, (struct sockaddr *)&addr, &addrlen)) >= 0) {
0cf685f6
RK
536 /* We do blocking reads for the header. In theory this means that the
537 * connecting process could wedge the speaker indefinitely. In
538 * practice that would mean that the main server was broken anyway.
539 * Still, this is ugly, and a rewrite would be nice. */
937be4c0 540 blocking(fd);
84aa9f93 541 if(read(fd, &l, sizeof l) < 4) {
2e9ba080 542 disorder_error(errno, "reading length from inbound connection");
84aa9f93
RK
543 xclose(fd);
544 } else if(l >= sizeof id) {
2e9ba080 545 disorder_error(0, "id length too long");
84aa9f93
RK
546 xclose(fd);
547 } else if(read(fd, id, l) < (ssize_t)l) {
2e9ba080 548 disorder_error(errno, "reading id from inbound connection");
84aa9f93
RK
549 xclose(fd);
550 } else {
551 id[l] = 0;
552 D(("id %s fd %d", id, fd));
553 t = findtrack(id, 1/*create*/);
918393ff 554 if (write(fd, "", 1) < 0) /* write an ack */
de38ab9b
RK
555 disorder_error(errno, "writing ack to inbound connection for %s",
556 id);
84aa9f93 557 if(t->fd != -1) {
2e9ba080 558 disorder_error(0, "%s: already got a connection", id);
84aa9f93
RK
559 xclose(fd);
560 } else {
561 nonblock(fd);
562 t->fd = fd; /* yay */
563 }
2a1c84fb
RK
564 /* Notify the server that the connection arrived */
565 sm.type = SM_ARRIVED;
e3953a41 566 strcpy(sm.u.id, id);
2a1c84fb 567 speaker_send(1, &sm);
84aa9f93
RK
568 }
569 } else
2e9ba080 570 disorder_error(errno, "accept");
84aa9f93 571 }
460b9539 572 /* Perhaps we have a command to process */
573 if(fds[stdin_slot].revents & POLLIN) {
5a7c42a8 574 /* There might (in theory) be several commands queued up, but in general
575 * this won't be the case, so we don't bother looping around to pick them
576 * all up. */
84aa9f93 577 n = speaker_recv(0, &sm);
460b9539 578 if(n > 0)
888b8031
RK
579 /* As a rule we don't send success replies to most commands - we just
580 * force the regular status update to be sent immediately rather than
581 * on schedule. */
460b9539 582 switch(sm.type) {
460b9539 583 case SM_PLAY:
888b8031
RK
584 /* SM_PLAY is only allowed if the server reasonably believes that
585 * nothing is playing */
586 if(playing) {
587 /* If finished isn't set then the server can't believe that this
588 * track has finished */
589 if(!playing->finished)
2e9ba080 590 disorder_fatal(0, "got SM_PLAY but already playing something");
888b8031
RK
591 /* If pending_playing is set then the server must believe that that
592 * is playing */
593 if(pending_playing)
2e9ba080 594 disorder_fatal(0, "got SM_PLAY but have a pending playing track");
888b8031 595 }
e3953a41 596 t = findtrack(sm.u.id, 1);
84aa9f93
RK
597 D(("SM_PLAY %s fd %d", t->id, t->fd));
598 if(t->fd == -1)
2e9ba080
RK
599 disorder_error(0,
600 "cannot play track because no connection arrived");
5bac5b78
RK
601 /* TODO as things stand we often report this error message but then
602 * appear to proceed successfully. Understanding why requires a look
603 * at play.c: we call prepare() which makes the connection in a child
604 * process, and then sends the SM_PLAY in the parent process. The
605 * latter may well be faster. As it happens this is harmless; we'll
606 * just sit around sending silence until the decoder connects and
607 * starts sending some sample data. But is is annoying and ought to
608 * be fixed. */
888b8031
RK
609 pending_playing = t;
610 /* If nothing is currently playing then we'll switch to the pending
611 * track below so there's no point distinguishing the situations
612 * here. */
460b9539 613 break;
614 case SM_PAUSE:
615 D(("SM_PAUSE"));
616 paused = 1;
b50cfb8a 617 force_report = 1;
460b9539 618 break;
619 case SM_RESUME:
620 D(("SM_RESUME"));
b50cfb8a
RK
621 paused = 0;
622 force_report = 1;
460b9539 623 break;
624 case SM_CANCEL:
e3953a41
RK
625 D(("SM_CANCEL %s", sm.u.id));
626 t = removetrack(sm.u.id);
460b9539 627 if(t) {
888b8031
RK
628 if(t == playing || t == pending_playing) {
629 /* Scratching the track that the server believes is playing,
630 * which might either be the actual playing track or a pending
631 * playing track */
460b9539 632 sm.type = SM_FINISHED;
888b8031
RK
633 if(t == playing)
634 playing = 0;
635 else
636 pending_playing = 0;
819f5988
RK
637 } else {
638 /* Could be scratching the playing track before it's quite got
639 * going, or could be just removing a track from the queue. We
640 * log more because there's been a bug here recently than because
641 * it's particularly interesting; the log message will be removed
642 * if no further problems show up. */
e3953a41 643 disorder_info("SM_CANCEL for nonplaying track %s", sm.u.id);
819f5988 644 sm.type = SM_STILLBORN;
460b9539 645 }
e3953a41 646 strcpy(sm.u.id, t->id);
460b9539 647 destroy(t);
2b2a5fed 648 } else {
819f5988
RK
649 /* Probably scratching the playing track well before it's got
650 * going, but could indicate a bug, so we log this as an error. */
2b2a5fed 651 sm.type = SM_UNKNOWN;
e3953a41 652 disorder_error(0, "SM_CANCEL for unknown track %s", sm.u.id);
2b2a5fed 653 }
819f5988 654 speaker_send(1, &sm);
b50cfb8a 655 force_report = 1;
460b9539 656 break;
657 case SM_RELOAD:
658 D(("SM_RELOAD"));
02ba7921 659 if(config_read(1, NULL))
2e9ba080
RK
660 disorder_error(0, "cannot read configuration");
661 disorder_info("reloaded configuration");
460b9539 662 break;
7f97fda7
RK
663 case SM_RTP_REQUEST:
664 /* TODO the error behavior here is really unhelpful */
665 if(rtp_add_recipient(&sm.u.address))
666 disorder_error(0, "unacceptable RTP destination");
667 break;
668 case SM_RTP_CANCEL:
669 if(rtp_remove_recipient(&sm.u.address))
670 disorder_error(0, "unacceptable RTP destination for removal");
671 break;
460b9539 672 default:
2e9ba080 673 disorder_error(0, "unknown message type %d", sm.type);
460b9539 674 }
675 }
676 /* Read in any buffered data */
677 for(t = tracks; t; t = t->next)
84aa9f93
RK
678 if(t->fd != -1
679 && t->slot != -1
680 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
f5a03f58 681 speaker_fill(t);
b50cfb8a
RK
682 /* Drain the signal pipe. We don't care about its contents, merely that it
683 * interrupted poll(). */
684 if(fds[sigpipe_slot].revents & POLLIN) {
685 char buffer[64];
784744a8 686 int ignored; (void)ignored;
b50cfb8a 687
784744a8 688 ignored = read(sigpipe[0], buffer, sizeof buffer);
b50cfb8a 689 }
888b8031
RK
690 /* Send SM_FINISHED when we're near the end of the track.
691 *
692 * This is how we implement gapless play; we hope that the SM_PLAY from the
693 * server arrives before the remaining bytes of the track play out.
694 */
695 if(playing
696 && playing->eof
697 && !playing->finished
698 && playing->used <= early_finish) {
b50cfb8a
RK
699 memset(&sm, 0, sizeof sm);
700 sm.type = SM_FINISHED;
e3953a41 701 strcpy(sm.u.id, playing->id);
b50cfb8a 702 speaker_send(1, &sm);
888b8031
RK
703 playing->finished = 1;
704 }
705 /* When the track is actually finished, deconfigure it */
706 if(playing && playing->eof && !playing->used) {
0cf685f6
RK
707 if(!playing->finished) {
708 /* should never happen but we'd like to know if it does */
709 disorder_fatal(0, "track finish state inconsistent");
710 }
888b8031 711 removetrack(playing->id);
b50cfb8a
RK
712 destroy(playing);
713 playing = 0;
888b8031
RK
714 }
715 /* Act on the pending SM_PLAY */
9c55e9e4 716 if(!playing && pending_playing) {
888b8031
RK
717 playing = pending_playing;
718 pending_playing = 0;
888b8031 719 force_report = 1;
b50cfb8a
RK
720 }
721 /* Impose any state change required by the above */
722 if(playable()) {
723 if(!activated) {
724 activated = 1;
89156c8c 725 pthread_mutex_unlock(&lock);
b50cfb8a 726 backend->activate();
89156c8c 727 pthread_mutex_lock(&lock);
b50cfb8a
RK
728 }
729 } else {
730 if(activated) {
731 activated = 0;
89156c8c 732 pthread_mutex_unlock(&lock);
b50cfb8a 733 backend->deactivate();
89156c8c 734 pthread_mutex_lock(&lock);
b50cfb8a
RK
735 }
736 }
737 /* If we've not reported our state for a second do so now. */
4265e5d3 738 if(force_report || xtime(0) > last_report)
460b9539 739 report();
740 }
55f35f2d 741}
742
743int main(int argc, char **argv) {
0ca6d097 744 int n, logsyslog = !isatty(2);
84aa9f93
RK
745 struct sockaddr_un addr;
746 static const int one = 1;
937be4c0 747 struct speaker_message sm;
38b8221f 748 const char *d;
85cb23d7 749 char *dir;
b50cfb8a 750 struct rlimit rl[1];
55f35f2d 751
752 set_progname(argv);
2e9ba080 753 if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "error calling setlocale");
0ca6d097 754 while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
55f35f2d 755 switch(n) {
756 case 'h': help();
3fbdc96d 757 case 'V': version("disorder-speaker");
55f35f2d 758 case 'c': configfile = optarg; break;
759 case 'd': debugging = 1; break;
760 case 'D': debugging = 0; break;
0ca6d097
RK
761 case 'S': logsyslog = 0; break;
762 case 's': logsyslog = 1; break;
2e9ba080 763 default: disorder_fatal(0, "invalid option");
55f35f2d 764 }
765 }
38b8221f 766 if((d = getenv("DISORDER_DEBUG_SPEAKER"))) debugging = atoi(d);
0ca6d097 767 if(logsyslog) {
55f35f2d 768 openlog(progname, LOG_PID, LOG_DAEMON);
769 log_default = &log_syslog;
770 }
b50cfb8a 771 config_uaudio_apis = uaudio_apis;
2e9ba080 772 if(config_read(1, NULL)) disorder_fatal(0, "cannot read configuration");
55f35f2d 773 /* ignore SIGPIPE */
774 signal(SIGPIPE, SIG_IGN);
55f35f2d 775 /* set nice value */
776 xnice(config->nice_speaker);
777 /* change user */
778 become_mortal();
779 /* make sure we're not root, whatever the config says */
b50cfb8a 780 if(getuid() == 0 || geteuid() == 0)
2e9ba080 781 disorder_fatal(0, "do not run as root");
b50cfb8a
RK
782 /* Make sure we can't have more than NFDS files open (it would bust our
783 * poll() array) */
784 if(getrlimit(RLIMIT_NOFILE, rl) < 0)
2e9ba080 785 disorder_fatal(errno, "getrlimit RLIMIT_NOFILE");
b50cfb8a
RK
786 if(rl->rlim_cur > NFDS) {
787 rl->rlim_cur = NFDS;
788 if(setrlimit(RLIMIT_NOFILE, rl) < 0)
2e9ba080 789 disorder_fatal(errno, "setrlimit to reduce RLIMIT_NOFILE to %lu",
b50cfb8a 790 (unsigned long)rl->rlim_cur);
2e9ba080 791 disorder_info("set RLIM_NOFILE to %lu", (unsigned long)rl->rlim_cur);
b50cfb8a 792 } else
2e9ba080 793 disorder_info("RLIM_NOFILE is %lu", (unsigned long)rl->rlim_cur);
5bf7c546
RK
794 /* gcrypt initialization */
795 if(!gcry_check_version(NULL))
796 disorder_fatal(0, "gcry_check_version failed");
797 gcry_control(GCRYCTL_INIT_SECMEM, 0);
798 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
b50cfb8a
RK
799 /* create a pipe between the backend callback and the poll() loop */
800 xpipe(sigpipe);
801 nonblock(sigpipe[0]);
802 /* set up audio backend */
803 uaudio_set_format(config->sample_format.rate,
804 config->sample_format.channels,
805 config->sample_format.bits,
806 config->sample_format.bits != 8);
888b8031 807 early_finish = uaudio_sample_size * uaudio_channels * uaudio_rate;
b50cfb8a
RK
808 /* TODO other parameters! */
809 backend = uaudio_find(config->api);
55f35f2d 810 /* backend-specific initialization */
ba70caca
RK
811 if(backend->configure)
812 backend->configure();
de0ef46e 813 uaudio_set("application", "disorder-speaker");
b50cfb8a 814 backend->start(speaker_callback, NULL);
de37b640
RK
815 /* create the private socket directory */
816 byte_xasprintf(&dir, "%s/private", config->home);
85cb23d7 817 unlink(dir); /* might be a leftover socket */
a5f3ca1e 818 if(mkdir(dir, 0700) < 0 && errno != EEXIST)
2e9ba080 819 disorder_fatal(errno, "error creating %s", dir);
84aa9f93
RK
820 /* set up the listen socket */
821 listenfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
822 memset(&addr, 0, sizeof addr);
823 addr.sun_family = AF_UNIX;
de37b640 824 snprintf(addr.sun_path, sizeof addr.sun_path, "%s/private/speaker",
84aa9f93
RK
825 config->home);
826 if(unlink(addr.sun_path) < 0 && errno != ENOENT)
2e9ba080 827 disorder_error(errno, "removing %s", addr.sun_path);
84aa9f93 828 xsetsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
dc450d30 829 if(bind(listenfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
2e9ba080 830 disorder_fatal(errno, "error binding socket to %s", addr.sun_path);
84aa9f93
RK
831 xlisten(listenfd, 128);
832 nonblock(listenfd);
7077d53f
RK
833 disorder_info("version "VERSION" process ID %lu",
834 (unsigned long)getpid());
2e9ba080 835 disorder_info("listening on %s", addr.sun_path);
937be4c0
RK
836 memset(&sm, 0, sizeof sm);
837 sm.type = SM_READY;
838 speaker_send(1, &sm);
55f35f2d 839 mainloop();
2e9ba080 840 disorder_info("stopped (parent terminated)");
460b9539 841 exit(0);
842}
843
844/*
845Local Variables:
846c-basic-offset:2
847comment-column:40
848fill-column:79
849indent-tabs-mode:nil
850End:
851*/