chiark / gitweb /
Merge volume and build fixes
[disorder] / server / speaker.c
CommitLineData
460b9539 1/*
2 * This file is part of DisOrder
b50cfb8a 3 * Copyright (C) 2005-2009 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
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.
43 *
44 * @b Encodings. The encodings supported depend entirely on the uaudio backend
45 * chosen. See @ref uaudio.h, etc.
1674096e 46 *
6d2d327c
RK
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).
1674096e 50 *
5b7a22c6 51 * @b Garbage @b Collection. This program deliberately does not use the
795192f4 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
57 * relatively briefly.
58 *
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
63 * 2-byte samples.
1674096e 64 */
460b9539 65
05b75f8d 66#include "common.h"
460b9539 67
68#include <getopt.h>
460b9539 69#include <locale.h>
70#include <syslog.h>
71#include <unistd.h>
72#include <errno.h>
73#include <ao/ao.h>
460b9539 74#include <sys/select.h>
9d5da576 75#include <sys/wait.h>
460b9539 76#include <time.h>
8023f60b 77#include <fcntl.h>
78#include <poll.h>
84aa9f93 79#include <sys/un.h>
a5f3ca1e 80#include <sys/stat.h>
b50cfb8a 81#include <pthread.h>
adeb58a0 82#include <sys/resource.h>
5bf7c546 83#include <gcrypt.h>
460b9539 84
85#include "configuration.h"
86#include "syscalls.h"
87#include "log.h"
88#include "defs.h"
89#include "mem.h"
ea410ba1 90#include "speaker-protocol.h"
460b9539 91#include "user.h"
85cb23d7 92#include "printf.h"
3fbdc96d 93#include "version.h"
b50cfb8a 94#include "uaudio.h"
460b9539 95
b50cfb8a
RK
96/** @brief Maximum number of FDs to poll for */
97#define NFDS 1024
e83d0967 98
b50cfb8a
RK
99/** @brief Track structure
100 *
101 * Known tracks are kept in a linked list. Usually there will be at most two
102 * of these but rearranging the queue can cause there to be more.
103 */
104struct track {
105 /** @brief Next track */
106 struct track *next;
107
108 /** @brief Input file descriptor */
109 int fd; /* input FD */
110
111 /** @brief Track ID */
112 char id[24];
113
114 /** @brief Start position of data in buffer */
115 size_t start;
116
117 /** @brief Number of bytes of data in buffer */
118 size_t used;
119
120 /** @brief Set @c fd is at EOF */
121 int eof;
122
123 /** @brief Total number of samples played */
124 unsigned long long played;
125
126 /** @brief Slot in @ref fds */
127 int slot;
128
129 /** @brief Set when playable
130 *
131 * A track becomes playable whenever it fills its buffer or reaches EOF; it
132 * stops being playable when it entirely empties its buffer. Tracks start
133 * out life not playable.
134 */
135 int playable;
136
137 /** @brief Input buffer
138 *
139 * 1Mbyte is enough for nearly 6s of 44100Hz 16-bit stereo
140 */
141 char buffer[1048576];
142};
460b9539 143
b50cfb8a
RK
144/** @brief Lock protecting data structures
145 *
146 * This lock protects values shared between the main thread and the callback.
147 * It is needed e.g. if changing @ref playing or if modifying buffer pointers.
148 * It is not needed to add a new track, to read values only modified in the
149 * same thread, etc.
150 */
151static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
152
153/** @brief Linked list of all prepared tracks */
154static struct track *tracks;
155
156/** @brief Playing track, or NULL
157 *
158 * This means the DESIRED playing track. It does not reflect any other state
159 * (e.g. activation of uaudio backend).
160 */
161static struct track *playing;
1c3f1e73 162
163/** @brief Array of file descriptors for poll() */
b50cfb8a 164static struct pollfd fds[NFDS];
1c3f1e73 165
166/** @brief Next free slot in @ref fds */
b50cfb8a 167static int fdno;
1c3f1e73 168
84aa9f93
RK
169/** @brief Listen socket */
170static int listenfd;
171
b50cfb8a
RK
172/** @brief Timestamp of last potential report to server */
173static time_t last_report;
50ae38dd 174
b50cfb8a
RK
175/** @brief Set when paused */
176static int paused;
50ae38dd 177
b50cfb8a
RK
178/** @brief Set when back end activated */
179static int activated;
180
181/** @brief Signal pipe back into the poll() loop */
182static int sigpipe[2];
460b9539 183
29601377 184/** @brief Selected backend */
b50cfb8a 185static const struct uaudio *backend;
29601377 186
460b9539 187static const struct option options[] = {
188 { "help", no_argument, 0, 'h' },
189 { "version", no_argument, 0, 'V' },
190 { "config", required_argument, 0, 'c' },
191 { "debug", no_argument, 0, 'd' },
192 { "no-debug", no_argument, 0, 'D' },
0ca6d097
RK
193 { "syslog", no_argument, 0, 's' },
194 { "no-syslog", no_argument, 0, 'S' },
460b9539 195 { 0, 0, 0, 0 }
196};
197
198/* Display usage message and terminate. */
199static void help(void) {
200 xprintf("Usage:\n"
201 " disorder-speaker [OPTIONS]\n"
202 "Options:\n"
203 " --help, -h Display usage message\n"
204 " --version, -V Display version number\n"
205 " --config PATH, -c PATH Set configuration file\n"
206 " --debug, -d Turn on debugging\n"
0ca6d097 207 " --[no-]syslog Force logging\n"
460b9539 208 "\n"
209 "Speaker process for DisOrder. Not intended to be run\n"
210 "directly.\n");
211 xfclose(stdout);
212 exit(0);
213}
214
b50cfb8a
RK
215/** @brief Find track @p id, maybe creating it if not found
216 * @param id Track ID to find
217 * @param create If nonzero, create track structure of @p id not found
218 * @return Pointer to track structure or NULL
219 */
460b9539 220static struct track *findtrack(const char *id, int create) {
221 struct track *t;
222
223 D(("findtrack %s %d", id, create));
224 for(t = tracks; t && strcmp(id, t->id); t = t->next)
225 ;
226 if(!t && create) {
227 t = xmalloc(sizeof *t);
228 t->next = tracks;
229 strcpy(t->id, id);
230 t->fd = -1;
231 tracks = t;
460b9539 232 }
233 return t;
234}
235
b50cfb8a
RK
236/** @brief Remove track @p id (but do not destroy it)
237 * @param id Track ID to remove
238 * @return Track structure or NULL if not found
239 */
460b9539 240static struct track *removetrack(const char *id) {
241 struct track *t, **tt;
242
243 D(("removetrack %s", id));
244 for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
245 ;
246 if(t)
247 *tt = t->next;
248 return t;
249}
250
b50cfb8a
RK
251/** @brief Destroy a track
252 * @param t Track structure
253 */
460b9539 254static void destroy(struct track *t) {
255 D(("destroy %s", t->id));
b50cfb8a
RK
256 if(t->fd != -1)
257 xclose(t->fd);
460b9539 258 free(t);
259}
260
1674096e 261/** @brief Read data into a sample buffer
262 * @param t Pointer to track
263 * @return 0 on success, -1 on EOF
264 *
55f35f2d 265 * This is effectively the read callback on @c t->fd. It is called from the
266 * main loop whenever the track's file descriptor is readable, assuming the
267 * buffer has not reached the maximum allowed occupancy.
1674096e 268 */
f5a03f58 269static int speaker_fill(struct track *t) {
460b9539 270 size_t where, left;
b50cfb8a 271 int n, rc;
460b9539 272
6d2d327c
RK
273 D(("fill %s: eof=%d used=%zu",
274 t->id, t->eof, t->used));
b50cfb8a
RK
275 if(t->eof)
276 return -1;
277 pthread_mutex_lock(&lock);
6d2d327c 278 if(t->used < sizeof t->buffer) {
460b9539 279 /* there is room left in the buffer */
6d2d327c
RK
280 where = (t->start + t->used) % sizeof t->buffer;
281 /* Get as much data as we can */
b50cfb8a
RK
282 if(where >= t->start)
283 left = (sizeof t->buffer) - where;
284 else
285 left = t->start - where;
286 pthread_mutex_unlock(&lock);
460b9539 287 do {
288 n = read(t->fd, t->buffer + where, left);
289 } while(n < 0 && errno == EINTR);
b50cfb8a 290 pthread_mutex_lock(&lock);
460b9539 291 if(n < 0) {
b50cfb8a
RK
292 if(errno != EAGAIN)
293 fatal(errno, "error reading sample stream");
294 rc = 0;
295 } else if(n == 0) {
460b9539 296 D(("fill %s: eof detected", t->id));
297 t->eof = 1;
b50cfb8a
RK
298 /* A track always becomes playable at EOF; we're not going to see any
299 * more data. */
f5a03f58 300 t->playable = 1;
b50cfb8a
RK
301 rc = -1;
302 } else {
303 t->used += n;
304 /* A track becomes playable when it (first) fills its buffer. For
305 * 44.1KHz 16-bit stereo this is ~6s of audio data. The latency will
306 * depend how long that takes to decode (hopefuly not very!) */
307 if(t->used == sizeof t->buffer)
308 t->playable = 1;
309 rc = 0;
460b9539 310 }
460b9539 311 }
b50cfb8a
RK
312 pthread_mutex_unlock(&lock);
313 return rc;
460b9539 314}
315
dac25ef9
RK
316/** @brief Return nonzero if we want to play some audio
317 *
318 * We want to play audio if there is a current track; and it is not paused; and
319 * it is playable according to the rules for @ref track::playable.
320 */
321static int playable(void) {
322 return playing
323 && !paused
324 && playing->playable;
325}
326
b50cfb8a 327/** @brief Notify the server what we're up to */
460b9539 328static void report(void) {
329 struct speaker_message sm;
330
6d2d327c 331 if(playing) {
460b9539 332 memset(&sm, 0, sizeof sm);
333 sm.type = paused ? SM_PAUSED : SM_PLAYING;
334 strcpy(sm.id, playing->id);
b50cfb8a
RK
335 pthread_mutex_lock(&lock);
336 sm.data = playing->played / (uaudio_rate * uaudio_channels);
337 pthread_mutex_unlock(&lock);
84aa9f93 338 speaker_send(1, &sm);
460b9539 339 }
340 time(&last_report);
341}
342
b50cfb8a
RK
343/** @brief Add a file descriptor to the set to poll() for
344 * @param fd File descriptor
345 * @param events Events to wait for e.g. @c POLLIN
346 * @return Slot number
347 */
348static int addfd(int fd, int events) {
460b9539 349 if(fdno < NFDS) {
350 fds[fdno].fd = fd;
351 fds[fdno].events = events;
352 return fdno++;
353 } else
354 return -1;
355}
356
b50cfb8a
RK
357/** @brief Callback to return some sampled data
358 * @param buffer Where to put sample data
359 * @param max_samples How many samples to return
360 * @param userdata User data
361 * @return Number of samples written
362 *
363 * See uaudio_callback().
364 */
365static size_t speaker_callback(void *buffer,
366 size_t max_samples,
367 void attribute((unused)) *userdata) {
368 const size_t max_bytes = max_samples * uaudio_sample_size;
369 size_t provided_samples = 0;
370
371 pthread_mutex_lock(&lock);
372 /* TODO perhaps we should immediately go silent if we've been asked to pause
373 * or cancel the playing track (maybe block in the cancel case and see what
374 * else turns up?) */
375 if(playing) {
376 if(playing->used > 0) {
377 size_t bytes;
378 /* Compute size of largest contiguous chunk. We get called as often as
379 * necessary so there's no need for cleverness here. */
380 if(playing->start + playing->used > sizeof playing->buffer)
381 bytes = sizeof playing->buffer - playing->start;
382 else
383 bytes = playing->used;
384 /* Limit to what we were asked for */
385 if(bytes > max_bytes)
386 bytes = max_bytes;
387 /* Provide it */
388 memcpy(buffer, playing->buffer + playing->start, bytes);
389 playing->start += bytes;
390 playing->used -= bytes;
391 /* Wrap around to start of buffer */
392 if(playing->start == sizeof playing->buffer)
393 playing->start = 0;
394 /* See if we've reached the end of the track */
395 if(playing->used == 0 && playing->eof)
396 write(sigpipe[1], "", 1);
397 provided_samples = bytes / uaudio_sample_size;
398 playing->played += provided_samples;
399 }
400 }
401 /* If we couldn't provide anything at all, play dead air */
402 /* TODO maybe it would be better to block, in some cases? */
403 if(!provided_samples) {
404 memset(buffer, 0, max_bytes);
405 provided_samples = max_samples;
406 }
407 pthread_mutex_unlock(&lock);
408 return provided_samples;
409}
572d74ba 410
5a7c42a8 411/** @brief Main event loop */
55f35f2d 412static void mainloop(void) {
572d74ba 413 struct track *t;
414 struct speaker_message sm;
b50cfb8a 415 int n, fd, stdin_slot, timeout, listen_slot, sigpipe_slot;
460b9539 416
b50cfb8a 417 /* Keep going while our parent process is alive */
460b9539 418 while(getppid() != 1) {
b50cfb8a
RK
419 int force_report = 0;
420
460b9539 421 fdno = 0;
5a7c42a8 422 /* By default we will wait up to a second before thinking about current
423 * state. */
424 timeout = 1000;
460b9539 425 /* Always ready for commands from the main server. */
426 stdin_slot = addfd(0, POLLIN);
84aa9f93
RK
427 /* Also always ready for inbound connections */
428 listen_slot = addfd(listenfd, POLLIN);
460b9539 429 /* Try to read sample data for the currently playing track if there is
430 * buffer space. */
84aa9f93
RK
431 if(playing
432 && playing->fd >= 0
433 && !playing->eof
434 && playing->used < (sizeof playing->buffer))
460b9539 435 playing->slot = addfd(playing->fd, POLLIN);
5a7c42a8 436 else if(playing)
460b9539 437 playing->slot = -1;
460b9539 438 /* If any other tracks don't have a full buffer, try to read sample data
5a7c42a8 439 * from them. We do this last of all, so that if we run out of slots,
440 * nothing important can't be monitored. */
460b9539 441 for(t = tracks; t; t = t->next)
442 if(t != playing) {
84aa9f93
RK
443 if(t->fd >= 0
444 && !t->eof
445 && t->used < sizeof t->buffer) {
9d5da576 446 t->slot = addfd(t->fd, POLLIN | POLLHUP);
460b9539 447 } else
448 t->slot = -1;
449 }
b50cfb8a 450 sigpipe_slot = addfd(sigpipe[1], POLLIN);
e83d0967
RK
451 /* Wait for something interesting to happen */
452 n = poll(fds, fdno, timeout);
460b9539 453 if(n < 0) {
454 if(errno == EINTR) continue;
455 fatal(errno, "error calling poll");
456 }
84aa9f93
RK
457 /* Perhaps a connection has arrived */
458 if(fds[listen_slot].revents & POLLIN) {
459 struct sockaddr_un addr;
460 socklen_t addrlen = sizeof addr;
461 uint32_t l;
462 char id[24];
463
dc450d30 464 if((fd = accept(listenfd, (struct sockaddr *)&addr, &addrlen)) >= 0) {
937be4c0 465 blocking(fd);
84aa9f93
RK
466 if(read(fd, &l, sizeof l) < 4) {
467 error(errno, "reading length from inbound connection");
468 xclose(fd);
469 } else if(l >= sizeof id) {
470 error(0, "id length too long");
471 xclose(fd);
472 } else if(read(fd, id, l) < (ssize_t)l) {
473 error(errno, "reading id from inbound connection");
474 xclose(fd);
475 } else {
476 id[l] = 0;
477 D(("id %s fd %d", id, fd));
478 t = findtrack(id, 1/*create*/);
918393ff
RK
479 if (write(fd, "", 1) < 0) /* write an ack */
480 error(errno, "writing ack to inbound connection");
84aa9f93 481 if(t->fd != -1) {
66bb2e02 482 error(0, "%s: already got a connection", id);
84aa9f93
RK
483 xclose(fd);
484 } else {
485 nonblock(fd);
486 t->fd = fd; /* yay */
487 }
488 }
489 } else
490 error(errno, "accept");
491 }
460b9539 492 /* Perhaps we have a command to process */
493 if(fds[stdin_slot].revents & POLLIN) {
5a7c42a8 494 /* There might (in theory) be several commands queued up, but in general
495 * this won't be the case, so we don't bother looping around to pick them
496 * all up. */
84aa9f93
RK
497 n = speaker_recv(0, &sm);
498 /* TODO */
460b9539 499 if(n > 0)
500 switch(sm.type) {
460b9539 501 case SM_PLAY:
b50cfb8a
RK
502 if(playing)
503 fatal(0, "got SM_PLAY but already playing something");
460b9539 504 t = findtrack(sm.id, 1);
84aa9f93
RK
505 D(("SM_PLAY %s fd %d", t->id, t->fd));
506 if(t->fd == -1)
507 error(0, "cannot play track because no connection arrived");
460b9539 508 playing = t;
b50cfb8a 509 force_report = 1;
460b9539 510 break;
511 case SM_PAUSE:
512 D(("SM_PAUSE"));
513 paused = 1;
b50cfb8a 514 force_report = 1;
460b9539 515 break;
516 case SM_RESUME:
517 D(("SM_RESUME"));
b50cfb8a
RK
518 paused = 0;
519 force_report = 1;
460b9539 520 break;
521 case SM_CANCEL:
819f5988 522 D(("SM_CANCEL %s", sm.id));
460b9539 523 t = removetrack(sm.id);
524 if(t) {
b50cfb8a 525 pthread_mutex_lock(&lock);
460b9539 526 if(t == playing) {
819f5988 527 /* scratching the playing track */
460b9539 528 sm.type = SM_FINISHED;
460b9539 529 playing = 0;
819f5988
RK
530 } else {
531 /* Could be scratching the playing track before it's quite got
532 * going, or could be just removing a track from the queue. We
533 * log more because there's been a bug here recently than because
534 * it's particularly interesting; the log message will be removed
535 * if no further problems show up. */
536 info("SM_CANCEL for nonplaying track %s", sm.id);
537 sm.type = SM_STILLBORN;
460b9539 538 }
819f5988 539 strcpy(sm.id, t->id);
460b9539 540 destroy(t);
b50cfb8a 541 pthread_mutex_unlock(&lock);
2b2a5fed 542 } else {
819f5988
RK
543 /* Probably scratching the playing track well before it's got
544 * going, but could indicate a bug, so we log this as an error. */
2b2a5fed 545 sm.type = SM_UNKNOWN;
460b9539 546 error(0, "SM_CANCEL for unknown track %s", sm.id);
2b2a5fed 547 }
819f5988 548 speaker_send(1, &sm);
b50cfb8a 549 force_report = 1;
460b9539 550 break;
551 case SM_RELOAD:
552 D(("SM_RELOAD"));
b50cfb8a
RK
553 if(config_read(1))
554 error(0, "cannot read configuration");
460b9539 555 info("reloaded configuration");
556 break;
557 default:
558 error(0, "unknown message type %d", sm.type);
559 }
560 }
561 /* Read in any buffered data */
562 for(t = tracks; t; t = t->next)
84aa9f93
RK
563 if(t->fd != -1
564 && t->slot != -1
565 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
f5a03f58 566 speaker_fill(t);
b50cfb8a
RK
567 /* Drain the signal pipe. We don't care about its contents, merely that it
568 * interrupted poll(). */
569 if(fds[sigpipe_slot].revents & POLLIN) {
570 char buffer[64];
571
572 read(sigpipe[0], buffer, sizeof buffer);
573 }
574 if(playing && playing->used == 0 && playing->eof) {
575 /* The playing track is done. Tell the server, and destroy it. */
576 memset(&sm, 0, sizeof sm);
577 sm.type = SM_FINISHED;
578 strcpy(sm.id, playing->id);
579 speaker_send(1, &sm);
580 removetrack(playing->id);
581 pthread_mutex_lock(&lock);
582 destroy(playing);
583 playing = 0;
584 pthread_mutex_unlock(&lock);
585 /* The server will presumalby send as an SM_PLAY by return */
586 }
587 /* Impose any state change required by the above */
588 if(playable()) {
589 if(!activated) {
590 activated = 1;
591 backend->activate();
592 }
593 } else {
594 if(activated) {
595 activated = 0;
596 backend->deactivate();
597 }
598 }
599 /* If we've not reported our state for a second do so now. */
600 if(force_report || time(0) > last_report)
460b9539 601 report();
602 }
55f35f2d 603}
604
605int main(int argc, char **argv) {
0ca6d097 606 int n, logsyslog = !isatty(2);
84aa9f93
RK
607 struct sockaddr_un addr;
608 static const int one = 1;
937be4c0 609 struct speaker_message sm;
38b8221f 610 const char *d;
85cb23d7 611 char *dir;
b50cfb8a 612 struct rlimit rl[1];
55f35f2d 613
614 set_progname(argv);
615 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
0ca6d097 616 while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
55f35f2d 617 switch(n) {
618 case 'h': help();
3fbdc96d 619 case 'V': version("disorder-speaker");
55f35f2d 620 case 'c': configfile = optarg; break;
621 case 'd': debugging = 1; break;
622 case 'D': debugging = 0; break;
0ca6d097
RK
623 case 'S': logsyslog = 0; break;
624 case 's': logsyslog = 1; break;
55f35f2d 625 default: fatal(0, "invalid option");
626 }
627 }
38b8221f 628 if((d = getenv("DISORDER_DEBUG_SPEAKER"))) debugging = atoi(d);
0ca6d097 629 if(logsyslog) {
55f35f2d 630 openlog(progname, LOG_PID, LOG_DAEMON);
631 log_default = &log_syslog;
632 }
b50cfb8a 633 config_uaudio_apis = uaudio_apis;
c00fce3a 634 if(config_read(1)) fatal(0, "cannot read configuration");
55f35f2d 635 /* ignore SIGPIPE */
636 signal(SIGPIPE, SIG_IGN);
55f35f2d 637 /* set nice value */
638 xnice(config->nice_speaker);
639 /* change user */
640 become_mortal();
641 /* make sure we're not root, whatever the config says */
b50cfb8a
RK
642 if(getuid() == 0 || geteuid() == 0)
643 fatal(0, "do not run as root");
644 /* Make sure we can't have more than NFDS files open (it would bust our
645 * poll() array) */
646 if(getrlimit(RLIMIT_NOFILE, rl) < 0)
647 fatal(errno, "getrlimit RLIMIT_NOFILE");
648 if(rl->rlim_cur > NFDS) {
649 rl->rlim_cur = NFDS;
650 if(setrlimit(RLIMIT_NOFILE, rl) < 0)
651 fatal(errno, "setrlimit to reduce RLIMIT_NOFILE to %lu",
652 (unsigned long)rl->rlim_cur);
653 info("set RLIM_NOFILE to %lu", (unsigned long)rl->rlim_cur);
654 } else
655 info("RLIM_NOFILE is %lu", (unsigned long)rl->rlim_cur);
5bf7c546
RK
656 /* gcrypt initialization */
657 if(!gcry_check_version(NULL))
658 disorder_fatal(0, "gcry_check_version failed");
659 gcry_control(GCRYCTL_INIT_SECMEM, 0);
660 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
b50cfb8a
RK
661 /* create a pipe between the backend callback and the poll() loop */
662 xpipe(sigpipe);
663 nonblock(sigpipe[0]);
664 /* set up audio backend */
665 uaudio_set_format(config->sample_format.rate,
666 config->sample_format.channels,
667 config->sample_format.bits,
668 config->sample_format.bits != 8);
669 /* TODO other parameters! */
670 backend = uaudio_find(config->api);
55f35f2d 671 /* backend-specific initialization */
ba70caca
RK
672 if(backend->configure)
673 backend->configure();
b50cfb8a 674 backend->start(speaker_callback, NULL);
85cb23d7
RK
675 /* create the socket directory */
676 byte_xasprintf(&dir, "%s/speaker", config->home);
677 unlink(dir); /* might be a leftover socket */
a5f3ca1e 678 if(mkdir(dir, 0700) < 0 && errno != EEXIST)
85cb23d7 679 fatal(errno, "error creating %s", dir);
84aa9f93
RK
680 /* set up the listen socket */
681 listenfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
682 memset(&addr, 0, sizeof addr);
683 addr.sun_family = AF_UNIX;
85cb23d7 684 snprintf(addr.sun_path, sizeof addr.sun_path, "%s/speaker/socket",
84aa9f93
RK
685 config->home);
686 if(unlink(addr.sun_path) < 0 && errno != ENOENT)
687 error(errno, "removing %s", addr.sun_path);
688 xsetsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
dc450d30 689 if(bind(listenfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
84aa9f93
RK
690 fatal(errno, "error binding socket to %s", addr.sun_path);
691 xlisten(listenfd, 128);
692 nonblock(listenfd);
693 info("listening on %s", addr.sun_path);
937be4c0
RK
694 memset(&sm, 0, sizeof sm);
695 sm.type = SM_READY;
696 speaker_send(1, &sm);
55f35f2d 697 mainloop();
460b9539 698 info("stopped (parent terminated)");
699 exit(0);
700}
701
702/*
703Local Variables:
704c-basic-offset:2
705comment-column:40
706fill-column:79
707indent-tabs-mode:nil
708End:
709*/