chiark / gitweb /
Build fixes for FreeBSD
[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  * @b Encodings.  The encodings supported depend entirely on the uaudio backend
45  * chosen.  See @ref uaudio.h, etc.
46  *
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).
50  *
51  * @b Garbage @b Collection.  This program deliberately does not use the
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.
64  */
65
66 #include "common.h"
67
68 #include <getopt.h>
69 #include <locale.h>
70 #include <syslog.h>
71 #include <unistd.h>
72 #include <errno.h>
73 #include <ao/ao.h>
74 #include <sys/select.h>
75 #include <sys/wait.h>
76 #include <time.h>
77 #include <fcntl.h>
78 #include <poll.h>
79 #include <sys/un.h>
80 #include <sys/stat.h>
81 #include <pthread.h>
82 #include <sys/resource.h>
83
84 #include "configuration.h"
85 #include "syscalls.h"
86 #include "log.h"
87 #include "defs.h"
88 #include "mem.h"
89 #include "speaker-protocol.h"
90 #include "user.h"
91 #include "printf.h"
92 #include "version.h"
93 #include "uaudio.h"
94
95 /** @brief Maximum number of FDs to poll for */
96 #define NFDS 1024
97
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  */
103 struct 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 };
142
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  */
150 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
151
152 /** @brief Linked list of all prepared tracks */
153 static 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  */
160 static struct track *playing;
161
162 /** @brief Array of file descriptors for poll() */
163 static struct pollfd fds[NFDS];
164
165 /** @brief Next free slot in @ref fds */
166 static int fdno;
167
168 /** @brief Listen socket */
169 static int listenfd;
170
171 /** @brief Timestamp of last potential report to server */
172 static time_t last_report;
173
174 /** @brief Set when paused */
175 static int paused;
176
177 /** @brief Set when back end activated */
178 static int activated;
179
180 /** @brief Signal pipe back into the poll() loop */
181 static int sigpipe[2];
182
183 /** @brief Selected backend */
184 static const struct uaudio *backend;
185
186 static 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' },
192   { "syslog", no_argument, 0, 's' },
193   { "no-syslog", no_argument, 0, 'S' },
194   { 0, 0, 0, 0 }
195 };
196
197 /* Display usage message and terminate. */
198 static 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"
206           "  --[no-]syslog           Force logging\n"
207           "\n"
208           "Speaker process for DisOrder.  Not intended to be run\n"
209           "directly.\n");
210   xfclose(stdout);
211   exit(0);
212 }
213
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  */
219 static 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;
231   }
232   return t;
233 }
234
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  */
239 static 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
250 /** @brief Destroy a track
251  * @param t Track structure
252  */
253 static void destroy(struct track *t) {
254   D(("destroy %s", t->id));
255   if(t->fd != -1)
256     xclose(t->fd);
257   free(t);
258 }
259
260 /** @brief Read data into a sample buffer
261  * @param t Pointer to track
262  * @return 0 on success, -1 on EOF
263  *
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.
267  */
268 static int speaker_fill(struct track *t) {
269   size_t where, left;
270   int n, rc;
271
272   D(("fill %s: eof=%d used=%zu",
273      t->id, t->eof, t->used));
274   if(t->eof)
275     return -1;
276   pthread_mutex_lock(&lock);
277   if(t->used < sizeof t->buffer) {
278     /* there is room left in the buffer */
279     where = (t->start + t->used) % sizeof t->buffer;
280     /* Get as much data as we can */
281     if(where >= t->start)
282       left = (sizeof t->buffer) - where;
283     else
284       left = t->start - where;
285     pthread_mutex_unlock(&lock);
286     do {
287       n = read(t->fd, t->buffer + where, left);
288     } while(n < 0 && errno == EINTR);
289     pthread_mutex_lock(&lock);
290     if(n < 0) {
291       if(errno != EAGAIN)
292         fatal(errno, "error reading sample stream");
293       rc = 0;
294     } else if(n == 0) {
295       D(("fill %s: eof detected", t->id));
296       t->eof = 1;
297       /* A track always becomes playable at EOF; we're not going to see any
298        * more data. */
299       t->playable = 1;
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;
309     }
310   }
311   pthread_mutex_unlock(&lock);
312   return rc;
313 }
314
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  */
320 static int playable(void) {
321   return playing
322          && !paused
323          && playing->playable;
324 }
325
326 /** @brief Notify the server what we're up to */
327 static void report(void) {
328   struct speaker_message sm;
329
330   if(playing) {
331     memset(&sm, 0, sizeof sm);
332     sm.type = paused ? SM_PAUSED : SM_PLAYING;
333     strcpy(sm.id, playing->id);
334     pthread_mutex_lock(&lock);
335     sm.data = playing->played / (uaudio_rate * uaudio_channels);
336     pthread_mutex_unlock(&lock);
337     speaker_send(1, &sm);
338   }
339   time(&last_report);
340 }
341
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  */
347 static int addfd(int fd, int events) {
348   if(fdno < NFDS) {
349     fds[fdno].fd = fd;
350     fds[fdno].events = events;
351     return fdno++;
352   } else
353     return -1;
354 }
355
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  */
364 static 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 }
409
410 /** @brief Main event loop */
411 static void mainloop(void) {
412   struct track *t;
413   struct speaker_message sm;
414   int n, fd, stdin_slot, timeout, listen_slot, sigpipe_slot;
415
416   /* Keep going while our parent process is alive */
417   while(getppid() != 1) {
418     int force_report = 0;
419
420     fdno = 0;
421     /* By default we will wait up to a second before thinking about current
422      * state. */
423     timeout = 1000;
424     /* Always ready for commands from the main server. */
425     stdin_slot = addfd(0, POLLIN);
426     /* Also always ready for inbound connections */
427     listen_slot = addfd(listenfd, POLLIN);
428     /* Try to read sample data for the currently playing track if there is
429      * buffer space. */
430     if(playing
431        && playing->fd >= 0
432        && !playing->eof
433        && playing->used < (sizeof playing->buffer))
434       playing->slot = addfd(playing->fd, POLLIN);
435     else if(playing)
436       playing->slot = -1;
437     /* If any other tracks don't have a full buffer, try to read sample data
438      * from them.  We do this last of all, so that if we run out of slots,
439      * nothing important can't be monitored. */
440     for(t = tracks; t; t = t->next)
441       if(t != playing) {
442         if(t->fd >= 0
443            && !t->eof
444            && t->used < sizeof t->buffer) {
445           t->slot = addfd(t->fd,  POLLIN | POLLHUP);
446         } else
447           t->slot = -1;
448       }
449     sigpipe_slot = addfd(sigpipe[1], POLLIN);
450     /* Wait for something interesting to happen */
451     n = poll(fds, fdno, timeout);
452     if(n < 0) {
453       if(errno == EINTR) continue;
454       fatal(errno, "error calling poll");
455     }
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
463       if((fd = accept(listenfd, (struct sockaddr *)&addr, &addrlen)) >= 0) {
464         blocking(fd);
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*/);
478           if (write(fd, "", 1) < 0)             /* write an ack */
479                         error(errno, "writing ack to inbound connection");
480           if(t->fd != -1) {
481             error(0, "%s: already got a connection", id);
482             xclose(fd);
483           } else {
484             nonblock(fd);
485             t->fd = fd;               /* yay */
486           }
487         }
488       } else
489         error(errno, "accept");
490     }
491     /* Perhaps we have a command to process */
492     if(fds[stdin_slot].revents & POLLIN) {
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. */ 
496       n = speaker_recv(0, &sm);
497       /* TODO */
498       if(n > 0)
499         switch(sm.type) {
500         case SM_PLAY:
501           if(playing)
502             fatal(0, "got SM_PLAY but already playing something");
503           t = findtrack(sm.id, 1);
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");
507           playing = t;
508           force_report = 1;
509           break;
510         case SM_PAUSE:
511           D(("SM_PAUSE"));
512           paused = 1;
513           force_report = 1;
514           break;
515         case SM_RESUME:
516           D(("SM_RESUME"));
517           paused = 0;
518           force_report = 1;
519           break;
520         case SM_CANCEL:
521           D(("SM_CANCEL %s", sm.id));
522           t = removetrack(sm.id);
523           if(t) {
524             pthread_mutex_lock(&lock);
525             if(t == playing) {
526               /* scratching the playing track */
527               sm.type = SM_FINISHED;
528               playing = 0;
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;
537             }
538             strcpy(sm.id, t->id);
539             destroy(t);
540             pthread_mutex_unlock(&lock);
541           } else {
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. */
544             sm.type = SM_UNKNOWN;
545             error(0, "SM_CANCEL for unknown track %s", sm.id);
546           }
547           speaker_send(1, &sm);
548           force_report = 1;
549           break;
550         case SM_RELOAD:
551           D(("SM_RELOAD"));
552           if(config_read(1))
553             error(0, "cannot read configuration");
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)
562       if(t->fd != -1
563          && t->slot != -1
564          && (fds[t->slot].revents & (POLLIN | POLLHUP)))
565          speaker_fill(t);
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)
600       report();
601   }
602 }
603
604 int main(int argc, char **argv) {
605   int n, logsyslog = !isatty(2);
606   struct sockaddr_un addr;
607   static const int one = 1;
608   struct speaker_message sm;
609   const char *d;
610   char *dir;
611   struct rlimit rl[1];
612
613   set_progname(argv);
614   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
615   while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
616     switch(n) {
617     case 'h': help();
618     case 'V': version("disorder-speaker");
619     case 'c': configfile = optarg; break;
620     case 'd': debugging = 1; break;
621     case 'D': debugging = 0; break;
622     case 'S': logsyslog = 0; break;
623     case 's': logsyslog = 1; break;
624     default: fatal(0, "invalid option");
625     }
626   }
627   if((d = getenv("DISORDER_DEBUG_SPEAKER"))) debugging = atoi(d);
628   if(logsyslog) {
629     openlog(progname, LOG_PID, LOG_DAEMON);
630     log_default = &log_syslog;
631   }
632   config_uaudio_apis = uaudio_apis;
633   if(config_read(1)) fatal(0, "cannot read configuration");
634   /* ignore SIGPIPE */
635   signal(SIGPIPE, SIG_IGN);
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 */
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);
665   /* backend-specific initialization */
666   backend->start(speaker_callback, NULL);
667   /* create the socket directory */
668   byte_xasprintf(&dir, "%s/speaker", config->home);
669   unlink(dir);                          /* might be a leftover socket */
670   if(mkdir(dir, 0700) < 0 && errno != EEXIST)
671     fatal(errno, "error creating %s", dir);
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;
676   snprintf(addr.sun_path, sizeof addr.sun_path, "%s/speaker/socket",
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);
681   if(bind(listenfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
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);
686   memset(&sm, 0, sizeof sm);
687   sm.type = SM_READY;
688   speaker_send(1, &sm);
689   mainloop();
690   info("stopped (parent terminated)");
691   exit(0);
692 }
693
694 /*
695 Local Variables:
696 c-basic-offset:2
697 comment-column:40
698 fill-column:79
699 indent-tabs-mode:nil
700 End:
701 */