chiark / gitweb /
banish fd passing. currently a bit ugly but seems to work
[disorder] / server / speaker.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2005, 2006, 2007 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20 /** @file server/speaker.c
21  * @brief Speaker process
22  *
23  * This program is responsible for transmitting a single coherent audio stream
24  * to its destination (over the network, to some sound API, to some
25  * subprocess).  It receives connections from decoders via file descriptor
26  * passing from the main server and plays them in the right order.
27  *
28  * @b Encodings.  For the <a href="http://www.alsa-project.org/">ALSA</a> API,
29  * 8- and 16- bit stereo and mono are supported, with any sample rate (within
30  * the limits that ALSA can deal with.)
31  *
32  * Inbound data is expected to match @c config->sample_format.  In normal use
33  * this is arranged by the @c disorder-normalize program (see @ref
34  * server/normalize.c).
35  *
36  * @b Garbage @b Collection.  This program deliberately does not use the
37  * garbage collector even though it might be convenient to do so.  This is for
38  * two reasons.  Firstly some sound APIs use thread threads and we do not want
39  * to have to deal with potential interactions between threading and garbage
40  * collection.  Secondly this process needs to be able to respond quickly and
41  * this is not compatible with the collector hanging the program even
42  * relatively briefly.
43  *
44  * @b Units.  This program thinks at various times in three different units.
45  * Bytes are obvious.  A sample is a single sample on a single channel.  A
46  * frame is several samples on different channels at the same point in time.
47  * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
48  * 2-byte samples.
49  */
50
51 #include <config.h>
52 #include "types.h"
53
54 #include <getopt.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <locale.h>
58 #include <syslog.h>
59 #include <unistd.h>
60 #include <errno.h>
61 #include <ao/ao.h>
62 #include <string.h>
63 #include <assert.h>
64 #include <sys/select.h>
65 #include <sys/wait.h>
66 #include <time.h>
67 #include <fcntl.h>
68 #include <poll.h>
69 #include <sys/un.h>
70
71 #include "configuration.h"
72 #include "syscalls.h"
73 #include "log.h"
74 #include "defs.h"
75 #include "mem.h"
76 #include "speaker-protocol.h"
77 #include "user.h"
78 #include "speaker.h"
79
80 /** @brief Linked list of all prepared tracks */
81 struct track *tracks;
82
83 /** @brief Playing track, or NULL */
84 struct track *playing;
85
86 /** @brief Number of bytes pre frame */
87 size_t bpf;
88
89 /** @brief Array of file descriptors for poll() */
90 struct pollfd fds[NFDS];
91
92 /** @brief Next free slot in @ref fds */
93 int fdno;
94
95 /** @brief Listen socket */
96 static int listenfd;
97
98 static time_t last_report;              /* when we last reported */
99 static int paused;                      /* pause status */
100
101 /** @brief The current device state */
102 enum device_states device_state;
103
104 /** @brief Set when idled
105  *
106  * This is set when the sound device is deliberately closed by idle().
107  */
108 int idled;
109
110 /** @brief Selected backend */
111 static const struct speaker_backend *backend;
112
113 static const struct option options[] = {
114   { "help", no_argument, 0, 'h' },
115   { "version", no_argument, 0, 'V' },
116   { "config", required_argument, 0, 'c' },
117   { "debug", no_argument, 0, 'd' },
118   { "no-debug", no_argument, 0, 'D' },
119   { 0, 0, 0, 0 }
120 };
121
122 /* Display usage message and terminate. */
123 static void help(void) {
124   xprintf("Usage:\n"
125           "  disorder-speaker [OPTIONS]\n"
126           "Options:\n"
127           "  --help, -h              Display usage message\n"
128           "  --version, -V           Display version number\n"
129           "  --config PATH, -c PATH  Set configuration file\n"
130           "  --debug, -d             Turn on debugging\n"
131           "\n"
132           "Speaker process for DisOrder.  Not intended to be run\n"
133           "directly.\n");
134   xfclose(stdout);
135   exit(0);
136 }
137
138 /* Display version number and terminate. */
139 static void version(void) {
140   xprintf("disorder-speaker version %s\n", disorder_version_string);
141   xfclose(stdout);
142   exit(0);
143 }
144
145 /** @brief Return the number of bytes per frame in @p format */
146 static size_t bytes_per_frame(const struct stream_header *format) {
147   return format->channels * format->bits / 8;
148 }
149
150 /** @brief Find track @p id, maybe creating it if not found */
151 static struct track *findtrack(const char *id, int create) {
152   struct track *t;
153
154   D(("findtrack %s %d", id, create));
155   for(t = tracks; t && strcmp(id, t->id); t = t->next)
156     ;
157   if(!t && create) {
158     t = xmalloc(sizeof *t);
159     t->next = tracks;
160     strcpy(t->id, id);
161     t->fd = -1;
162     tracks = t;
163   }
164   return t;
165 }
166
167 /** @brief Remove track @p id (but do not destroy it) */
168 static struct track *removetrack(const char *id) {
169   struct track *t, **tt;
170
171   D(("removetrack %s", id));
172   for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
173     ;
174   if(t)
175     *tt = t->next;
176   return t;
177 }
178
179 /** @brief Destroy a track */
180 static void destroy(struct track *t) {
181   D(("destroy %s", t->id));
182   if(t->fd != -1) xclose(t->fd);
183   free(t);
184 }
185
186 /** @brief Read data into a sample buffer
187  * @param t Pointer to track
188  * @return 0 on success, -1 on EOF
189  *
190  * This is effectively the read callback on @c t->fd.  It is called from the
191  * main loop whenever the track's file descriptor is readable, assuming the
192  * buffer has not reached the maximum allowed occupancy.
193  */
194 static int fill(struct track *t) {
195   size_t where, left;
196   int n;
197
198   D(("fill %s: eof=%d used=%zu",
199      t->id, t->eof, t->used));
200   if(t->eof) return -1;
201   if(t->used < sizeof t->buffer) {
202     /* there is room left in the buffer */
203     where = (t->start + t->used) % sizeof t->buffer;
204     /* Get as much data as we can */
205     if(where >= t->start) left = (sizeof t->buffer) - where;
206     else left = t->start - where;
207     do {
208       n = read(t->fd, t->buffer + where, left);
209     } while(n < 0 && errno == EINTR);
210     if(n < 0) {
211       if(errno != EAGAIN) fatal(errno, "error reading sample stream");
212       return 0;
213     }
214     if(n == 0) {
215       D(("fill %s: eof detected", t->id));
216       t->eof = 1;
217       return -1;
218     }
219     t->used += n;
220   }
221   return 0;
222 }
223
224 /** @brief Close the sound device
225  *
226  * This is called to deactivate the output device when pausing, and also by the
227  * ALSA backend when changing encoding (in which case the sound device will be
228  * immediately reactivated).
229  */
230 static void idle(void) {
231   D(("idle"));
232   if(backend->deactivate) 
233     backend->deactivate();
234   else
235     device_state = device_closed;
236   idled = 1;
237 }
238
239 /** @brief Abandon the current track */
240 void abandon(void) {
241   struct speaker_message sm;
242
243   D(("abandon"));
244   memset(&sm, 0, sizeof sm);
245   sm.type = SM_FINISHED;
246   strcpy(sm.id, playing->id);
247   speaker_send(1, &sm);
248   removetrack(playing->id);
249   destroy(playing);
250   playing = 0;
251 }
252
253 /** @brief Enable sound output
254  *
255  * Makes sure the sound device is open and has the right sample format.  Return
256  * 0 on success and -1 on error.
257  */
258 static void activate(void) {
259   if(backend->activate)
260     backend->activate();
261   else
262     device_state = device_open;
263 }
264
265 /** @brief Check whether the current track has finished
266  *
267  * The current track is determined to have finished either if the input stream
268  * eded before the format could be determined (i.e. it is malformed) or the
269  * input is at end of file and there is less than a frame left unplayed.  (So
270  * it copes with decoders that crash mid-frame.)
271  */
272 static void maybe_finished(void) {
273   if(playing
274      && playing->eof
275      && playing->used < bytes_per_frame(&config->sample_format))
276     abandon();
277 }
278
279 /** @brief Play up to @p frames frames of audio
280  *
281  * It is always safe to call this function.
282  * - If @ref playing is 0 then it will just return
283  * - If @ref paused is non-0 then it will just return
284  * - If @ref device_state != @ref device_open then it will call activate() and
285  * return if it it fails.
286  * - If there is not enough audio to play then it play what is available.
287  *
288  * If there are not enough frames to play then whatever is available is played
289  * instead.  It is up to mainloop() to ensure that play() is not called when
290  * unreasonably only an small amounts of data is available to play.
291  */
292 static void play(size_t frames) {
293   size_t avail_frames, avail_bytes, written_frames;
294   ssize_t written_bytes;
295
296   /* Make sure there's a track to play and it is not pasued */
297   if(!playing || paused)
298     return;
299   /* Make sure the output device is open */
300   if(device_state != device_open) {
301     activate(); 
302     if(device_state != device_open)
303       return;
304   }
305   D(("play: play %zu/%zu%s %dHz %db %dc",  frames, playing->used / bpf,
306      playing->eof ? " EOF" : "",
307      config->sample_format.rate,
308      config->sample_format.bits,
309      config->sample_format.channels));
310   /* Figure out how many frames there are available to write */
311   if(playing->start + playing->used > sizeof playing->buffer)
312     /* The ring buffer is currently wrapped, only play up to the wrap point */
313     avail_bytes = (sizeof playing->buffer) - playing->start;
314   else
315     /* The ring buffer is not wrapped, can play the lot */
316     avail_bytes = playing->used;
317   avail_frames = avail_bytes / bpf;
318   /* Only play up to the requested amount */
319   if(avail_frames > frames)
320     avail_frames = frames;
321   if(!avail_frames)
322     return;
323   /* Play it, Sam */
324   written_frames = backend->play(avail_frames);
325   written_bytes = written_frames * bpf;
326   /* written_bytes and written_frames had better both be set and correct by
327    * this point */
328   playing->start += written_bytes;
329   playing->used -= written_bytes;
330   playing->played += written_frames;
331   /* If the pointer is at the end of the buffer (or the buffer is completely
332    * empty) wrap it back to the start. */
333   if(!playing->used || playing->start == (sizeof playing->buffer))
334     playing->start = 0;
335   frames -= written_frames;
336   return;
337 }
338
339 /* Notify the server what we're up to. */
340 static void report(void) {
341   struct speaker_message sm;
342
343   if(playing) {
344     memset(&sm, 0, sizeof sm);
345     sm.type = paused ? SM_PAUSED : SM_PLAYING;
346     strcpy(sm.id, playing->id);
347     sm.data = playing->played / config->sample_format.rate;
348     speaker_send(1, &sm);
349   }
350   time(&last_report);
351 }
352
353 static void reap(int __attribute__((unused)) sig) {
354   pid_t cmdpid;
355   int st;
356
357   do
358     cmdpid = waitpid(-1, &st, WNOHANG);
359   while(cmdpid > 0);
360   signal(SIGCHLD, reap);
361 }
362
363 int addfd(int fd, int events) {
364   if(fdno < NFDS) {
365     fds[fdno].fd = fd;
366     fds[fdno].events = events;
367     return fdno++;
368   } else
369     return -1;
370 }
371
372 /** @brief Table of speaker backends */
373 static const struct speaker_backend *backends[] = {
374 #if API_ALSA
375   &alsa_backend,
376 #endif
377   &command_backend,
378   &network_backend,
379   0
380 };
381
382 /** @brief Return nonzero if we want to play some audio
383  *
384  * We want to play audio if there is a current track; and it is not paused; and
385  * there are at least @ref FRAMES frames of audio to play, or we are in sight
386  * of the end of the current track.
387  */
388 static int playable(void) {
389   return playing
390          && !paused
391          && (playing->used >= FRAMES || playing->eof);
392 }
393
394 /** @brief Main event loop */
395 static void mainloop(void) {
396   struct track *t;
397   struct speaker_message sm;
398   int n, fd, stdin_slot, timeout, listen_slot;
399
400   while(getppid() != 1) {
401     fdno = 0;
402     /* By default we will wait up to a second before thinking about current
403      * state. */
404     timeout = 1000;
405     /* Always ready for commands from the main server. */
406     stdin_slot = addfd(0, POLLIN);
407     /* Also always ready for inbound connections */
408     listen_slot = addfd(listenfd, POLLIN);
409     /* Try to read sample data for the currently playing track if there is
410      * buffer space. */
411     if(playing
412        && playing->fd >= 0
413        && !playing->eof
414        && playing->used < (sizeof playing->buffer))
415       playing->slot = addfd(playing->fd, POLLIN);
416     else if(playing)
417       playing->slot = -1;
418     if(playable()) {
419       /* We want to play some audio.  If the device is closed then we attempt
420        * to open it. */
421       if(device_state == device_closed)
422         activate();
423       /* If the device is (now) open then we will wait up until it is ready for
424        * more.  If something went wrong then we should have device_error
425        * instead, but the post-poll code will cope even if it's
426        * device_closed. */
427       if(device_state == device_open)
428         backend->beforepoll();
429     }
430     /* If any other tracks don't have a full buffer, try to read sample data
431      * from them.  We do this last of all, so that if we run out of slots,
432      * nothing important can't be monitored. */
433     for(t = tracks; t; t = t->next)
434       if(t != playing) {
435         if(t->fd >= 0
436            && !t->eof
437            && t->used < sizeof t->buffer) {
438           t->slot = addfd(t->fd,  POLLIN | POLLHUP);
439         } else
440           t->slot = -1;
441       }
442     /* Wait for something interesting to happen */
443     n = poll(fds, fdno, timeout);
444     if(n < 0) {
445       if(errno == EINTR) continue;
446       fatal(errno, "error calling poll");
447     }
448     /* Play some sound before doing anything else */
449     if(playable()) {
450       /* We want to play some audio */
451       if(device_state == device_open) {
452         if(backend->ready())
453           play(3 * FRAMES);
454       } else {
455         /* We must be in _closed or _error, and it should be the latter, but we
456          * cope with either.
457          *
458          * We most likely timed out, so now is a good time to retry.  play()
459          * knows to re-activate the device if necessary.
460          */
461         play(3 * FRAMES);
462       }
463     }
464     /* Perhaps a connection has arrived */
465     if(fds[listen_slot].revents & POLLIN) {
466       struct sockaddr_un addr;
467       socklen_t addrlen = sizeof addr;
468       uint32_t l;
469       char id[24];
470
471       if((fd = accept(listenfd, &addr, &addrlen)) >= 0) {
472         if(read(fd, &l, sizeof l) < 4) {
473           error(errno, "reading length from inbound connection");
474           xclose(fd);
475         } else if(l >= sizeof id) {
476           error(0, "id length too long");
477           xclose(fd);
478         } else if(read(fd, id, l) < (ssize_t)l) {
479           error(errno, "reading id from inbound connection");
480           xclose(fd);
481         } else {
482           id[l] = 0;
483           D(("id %s fd %d", id, fd));
484           t = findtrack(id, 1/*create*/);
485           write(fd, "", 1);             /* write an ack */
486           if(t->fd != -1) {
487             error(0, "got a connection for a track that already has one");
488             xclose(fd);
489           } else {
490             nonblock(fd);
491             t->fd = fd;               /* yay */
492           }
493         }
494       } else
495         error(errno, "accept");
496     }
497     /* Perhaps we have a command to process */
498     if(fds[stdin_slot].revents & POLLIN) {
499       /* There might (in theory) be several commands queued up, but in general
500        * this won't be the case, so we don't bother looping around to pick them
501        * all up. */ 
502       n = speaker_recv(0, &sm);
503       /* TODO */
504       if(n > 0)
505         switch(sm.type) {
506         case SM_PLAY:
507           if(playing) fatal(0, "got SM_PLAY but already playing something");
508           t = findtrack(sm.id, 1);
509           D(("SM_PLAY %s fd %d", t->id, t->fd));
510           if(t->fd == -1)
511             error(0, "cannot play track because no connection arrived");
512           playing = t;
513           /* We attempt to play straight away rather than going round the loop.
514            * play() is clever enough to perform any activation that is
515            * required. */
516           play(3 * FRAMES);
517           report();
518           break;
519         case SM_PAUSE:
520           D(("SM_PAUSE"));
521           paused = 1;
522           report();
523           break;
524         case SM_RESUME:
525           D(("SM_RESUME"));
526           if(paused) {
527             paused = 0;
528             /* As for SM_PLAY we attempt to play straight away. */
529             if(playing)
530               play(3 * FRAMES);
531           }
532           report();
533           break;
534         case SM_CANCEL:
535           D(("SM_CANCEL %s",  sm.id));
536           t = removetrack(sm.id);
537           if(t) {
538             if(t == playing) {
539               sm.type = SM_FINISHED;
540               strcpy(sm.id, playing->id);
541               speaker_send(1, &sm);
542               playing = 0;
543             }
544             destroy(t);
545           } else
546             error(0, "SM_CANCEL for unknown track %s", sm.id);
547           report();
548           break;
549         case SM_RELOAD:
550           D(("SM_RELOAD"));
551           if(config_read(1)) error(0, "cannot read configuration");
552           info("reloaded configuration");
553           break;
554         default:
555           error(0, "unknown message type %d", sm.type);
556         }
557     }
558     /* Read in any buffered data */
559     for(t = tracks; t; t = t->next)
560       if(t->fd != -1
561          && t->slot != -1
562          && (fds[t->slot].revents & (POLLIN | POLLHUP)))
563          fill(t);
564     /* Maybe we finished playing a track somewhere in the above */
565     maybe_finished();
566     /* If we don't need the sound device for now then close it for the benefit
567      * of anyone else who wants it. */
568     if((!playing || paused) && device_state == device_open)
569       idle();
570     /* If we've not reported out state for a second do so now. */
571     if(time(0) > last_report)
572       report();
573   }
574 }
575
576 int main(int argc, char **argv) {
577   int n;
578   struct sockaddr_un addr;
579   static const int one = 1;
580
581   set_progname(argv);
582   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
583   while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
584     switch(n) {
585     case 'h': help();
586     case 'V': version();
587     case 'c': configfile = optarg; break;
588     case 'd': debugging = 1; break;
589     case 'D': debugging = 0; break;
590     default: fatal(0, "invalid option");
591     }
592   }
593   if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
594   /* If stderr is a TTY then log there, otherwise to syslog. */
595   if(!isatty(2)) {
596     openlog(progname, LOG_PID, LOG_DAEMON);
597     log_default = &log_syslog;
598   }
599   if(config_read(1)) fatal(0, "cannot read configuration");
600   bpf = bytes_per_frame(&config->sample_format);
601   /* ignore SIGPIPE */
602   signal(SIGPIPE, SIG_IGN);
603   /* reap kids */
604   signal(SIGCHLD, reap);
605   /* set nice value */
606   xnice(config->nice_speaker);
607   /* change user */
608   become_mortal();
609   /* make sure we're not root, whatever the config says */
610   if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
611   /* identify the backend used to play */
612   for(n = 0; backends[n]; ++n)
613     if(backends[n]->backend == config->speaker_backend)
614       break;
615   if(!backends[n])
616     fatal(0, "unsupported backend %d", config->speaker_backend);
617   backend = backends[n];
618   /* backend-specific initialization */
619   backend->init();
620   /* set up the listen socket */
621   listenfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
622   memset(&addr, 0, sizeof addr);
623   addr.sun_family = AF_UNIX;
624   snprintf(addr.sun_path, sizeof addr.sun_path, "%s/speaker",
625            config->home);
626   if(unlink(addr.sun_path) < 0 && errno != ENOENT)
627     error(errno, "removing %s", addr.sun_path);
628   xsetsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
629   if(bind(listenfd, &addr, sizeof addr) < 0)
630     fatal(errno, "error binding socket to %s", addr.sun_path);
631   xlisten(listenfd, 128);
632   nonblock(listenfd);
633   info("listening on %s", addr.sun_path);
634   mainloop();
635   info("stopped (parent terminated)");
636   exit(0);
637 }
638
639 /*
640 Local Variables:
641 c-basic-offset:2
642 comment-column:40
643 fill-column:79
644 indent-tabs-mode:nil
645 End:
646 */