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