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