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