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