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