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