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