chiark / gitweb /
Import from Arch revision:
[disorder] / server / speaker.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2005, 2006 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
21 /* This program deliberately does not use the garbage collector even though it
22  * might be convenient to do so.  This is for two reasons.  Firstly some libao
23  * drivers are implemented using threads and we do not want to have to deal
24  * with potential interactions between threading and garbage collection.
25  * Secondly this process needs to be able to respond quickly and this is not
26  * compatible with the collector hanging the program even relatively
27  * briefly. */
28
29 #include <config.h>
30 #include "types.h"
31
32 #include <getopt.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <locale.h>
36 #include <syslog.h>
37 #include <unistd.h>
38 #include <errno.h>
39 #include <ao/ao.h>
40 #include <string.h>
41 #include <assert.h>
42 #include <sys/select.h>
43 #include <time.h>
44 #include <alsa/asoundlib.h>
45
46 #include "configuration.h"
47 #include "syscalls.h"
48 #include "log.h"
49 #include "defs.h"
50 #include "mem.h"
51 #include "speaker.h"
52 #include "user.h"
53
54 #define BUFFER_SECONDS 5                /* How many seconds of input to
55                                          * buffer. */
56
57 #define FRAMES 4096                     /* Frame batch size */
58
59 #define NFDS 256                        /* Max FDs to poll for */
60
61 /* Known tracks are kept in a linked list.  We don't normally to have
62  * more than two - maybe three at the outside. */
63 static struct track {
64   struct track *next;                   /* next track */
65   int fd;                               /* input FD */
66   char id[24];                          /* ID */
67   size_t start, used;                   /* start + bytes used */
68   int eof;                              /* input is at EOF */
69   int got_format;                       /* got format yet? */
70   ao_sample_format format;              /* sample format */
71   unsigned long long played;            /* number of frames played */
72   char *buffer;                         /* sample buffer */
73   size_t size;                          /* sample buffer size */
74   int slot;                             /* poll array slot */
75 } *tracks, *playing;                    /* all tracks + playing track */
76
77 static time_t last_report;              /* when we last reported */
78 static int paused;                      /* pause status */
79 static snd_pcm_t *pcm;                  /* current pcm handle */
80 static ao_sample_format pcm_format;     /* current format if aodev != 0 */
81 static size_t bpf;                      /* bytes per frame */
82 static struct pollfd fds[NFDS];         /* if we need more than that */
83 static int fdno;                        /* fd number */
84 static snd_pcm_uframes_t pcm_bufsize;   /* buffer size */
85 static int forceplay;                   /* frames to force play */
86
87 static const struct option options[] = {
88   { "help", no_argument, 0, 'h' },
89   { "version", no_argument, 0, 'V' },
90   { "config", required_argument, 0, 'c' },
91   { "debug", no_argument, 0, 'd' },
92   { "no-debug", no_argument, 0, 'D' },
93   { 0, 0, 0, 0 }
94 };
95
96 /* Display usage message and terminate. */
97 static void help(void) {
98   xprintf("Usage:\n"
99           "  disorder-speaker [OPTIONS]\n"
100           "Options:\n"
101           "  --help, -h              Display usage message\n"
102           "  --version, -V           Display version number\n"
103           "  --config PATH, -c PATH  Set configuration file\n"
104           "  --debug, -d             Turn on debugging\n"
105           "\n"
106           "Speaker process for DisOrder.  Not intended to be run\n"
107           "directly.\n");
108   xfclose(stdout);
109   exit(0);
110 }
111
112 /* Display version number and terminate. */
113 static void version(void) {
114   xprintf("disorder-speaker version %s\n", disorder_version_string);
115   xfclose(stdout);
116   exit(0);
117 }
118
119 /* Return the number of bytes per frame in FORMAT. */
120 static size_t bytes_per_frame(const ao_sample_format *format) {
121   return format->channels * format->bits / 8;
122 }
123
124 /* Find track ID, maybe creating it if not found. */
125 static struct track *findtrack(const char *id, int create) {
126   struct track *t;
127
128   D(("findtrack %s %d", id, create));
129   for(t = tracks; t && strcmp(id, t->id); t = t->next)
130     ;
131   if(!t && create) {
132     t = xmalloc(sizeof *t);
133     t->next = tracks;
134     strcpy(t->id, id);
135     t->fd = -1;
136     tracks = t;
137     /* The initial input buffer will be the sample format. */
138     t->buffer = (void *)&t->format;
139     t->size = sizeof t->format;
140   }
141   return t;
142 }
143
144 /* Remove track ID (but do not destroy it). */
145 static struct track *removetrack(const char *id) {
146   struct track *t, **tt;
147
148   D(("removetrack %s", id));
149   for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
150     ;
151   if(t)
152     *tt = t->next;
153   return t;
154 }
155
156 /* Destroy a track. */
157 static void destroy(struct track *t) {
158   D(("destroy %s", t->id));
159   if(t->fd != -1) xclose(t->fd);
160   if(t->buffer != (void *)&t->format) free(t->buffer);
161   free(t);
162 }
163
164 /* Notice a new FD. */
165 static void acquire(struct track *t, int fd) {
166   D(("acquire %s %d", t->id, fd));
167   if(t->fd != -1)
168     xclose(t->fd);
169   t->fd = fd;
170   nonblock(fd);
171 }
172
173 /* Read data into a sample buffer.  Return 0 on success, -1 on EOF. */
174 static int fill(struct track *t) {
175   size_t where, left;
176   int n;
177
178   D(("fill %s: eof=%d used=%zu size=%zu  got_format=%d",
179      t->id, t->eof, t->used, t->size, t->got_format));
180   if(t->eof) return -1;
181   if(t->used < t->size) {
182     /* there is room left in the buffer */
183     where = (t->start + t->used) % t->size;
184     if(t->got_format) {
185       /* We are reading audio data, get as much as we can */
186       if(where >= t->start) left = t->size - where;
187       else left = t->start - where;
188     } else
189       /* We are still waiting for the format, only get that */
190       left = sizeof (ao_sample_format) - t->used;
191     do {
192       n = read(t->fd, t->buffer + where, left);
193     } while(n < 0 && errno == EINTR);
194     if(n < 0) {
195       if(errno != EAGAIN) fatal(errno, "error reading sample stream");
196       return 0;
197     }
198     if(n == 0) {
199       D(("fill %s: eof detected", t->id));
200       t->eof = 1;
201       return -1;
202     }
203     t->used += n;
204     if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
205       assert(t->used == sizeof (ao_sample_format));
206       /* Check that our assumptions are met. */
207       if(t->format.bits & 7)
208         fatal(0, "bits per sample not a multiple of 8");
209       /* Make a new buffer for audio data. */
210       t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
211       t->buffer = xmalloc(t->size);
212       t->used = 0;
213       t->got_format = 1;
214       D(("got format for %s", t->id));
215     }
216   }
217   return 0;
218 }
219
220 /* Return true if A and B denote identical libao formats, else false. */
221 static int formats_equal(const ao_sample_format *a,
222                          const ao_sample_format *b) {
223   return (a->bits == b->bits
224           && a->rate == b->rate
225           && a->channels == b->channels
226           && a->byte_format == b->byte_format);
227 }
228
229 /* Close the sound device. */
230 static void idle(void) {
231   int  err;
232
233   D(("idle"));
234   if(pcm) {
235     if((err = snd_pcm_nonblock(pcm, 0)) < 0)
236       fatal(0, "error calling snd_pcm_nonblock: %d", err);
237     D(("draining pcm"));
238     snd_pcm_drain(pcm);
239     D(("closing pcm"));
240     snd_pcm_close(pcm);
241     pcm = 0;
242     forceplay = 0;
243     D(("released audio device"));
244   }
245 }
246
247 /* Abandon the current track */
248 static void abandon(void) {
249   struct speaker_message sm;
250
251   D(("abandon"));
252   memset(&sm, 0, sizeof sm);
253   sm.type = SM_FINISHED;
254   strcpy(sm.id, playing->id);
255   speaker_send(1, &sm, 0);
256   removetrack(playing->id);
257   destroy(playing);
258   playing = 0;
259   forceplay = 0;
260 }
261
262 /* Make sure the sound device is open and has the right sample format.  Return
263  * 0 on success and -1 on error. */
264 static int activate(void) {
265   int err;
266   snd_pcm_hw_params_t *hwparams;
267   snd_pcm_sw_params_t *swparams;
268   int sample_format = 0;
269   unsigned rate;
270
271   /* If we don't know the format yet we cannot start. */
272   if(!playing->got_format) {
273     D((" - not got format for %s", playing->id));
274     return -1;
275   }
276   /* If we need to change format then close the current device. */
277   if(pcm && !formats_equal(&playing->format, &pcm_format))
278      idle();
279   if(!pcm) {
280     D(("snd_pcm_open"));
281     if((err = snd_pcm_open(&pcm,
282                            config->device,
283                            SND_PCM_STREAM_PLAYBACK,
284                            SND_PCM_NONBLOCK))) {
285       error(0, "error from snd_pcm_open: %d", err);
286       goto error;
287     }
288     snd_pcm_hw_params_alloca(&hwparams);
289     D(("set up hw params"));
290     if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
291       fatal(0, "error from snd_pcm_hw_params_any: %d", err);
292     if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
293                                            SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
294       fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
295     switch(playing->format.bits) {
296     case 8:
297       sample_format = SND_PCM_FORMAT_S8;
298       break;
299     case 16:
300       switch(playing->format.byte_format) {
301       case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
302       case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
303       case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
304         error(0, "unrecognized byte format %d", playing->format.byte_format);
305         goto fatal;
306       }
307       break;
308     default:
309       error(0, "unsupported sample size %d", playing->format.bits);
310       goto fatal;
311     }
312     if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
313                                            sample_format)) < 0) {
314       error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
315             sample_format, err);
316       goto fatal;
317     }
318     rate = playing->format.rate;
319     if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
320       error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
321             playing->format.rate, err);
322       goto fatal;
323     }
324     if(rate != (unsigned)playing->format.rate)
325       info("want rate %d, got %u", playing->format.rate, rate);
326     if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
327                                              playing->format.channels)) < 0) {
328       error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
329             playing->format.channels, err);
330       goto fatal;
331     }
332     pcm_bufsize = 3 * FRAMES;
333     if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
334                                                      &pcm_bufsize)) < 0)
335       fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
336             3 * FRAMES, err);
337     if(pcm_bufsize != 3 * FRAMES)
338       info("asked for PCM buffer of %d frames, got %d",
339            3 * FRAMES, (int)pcm_bufsize);
340     if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
341       fatal(0, "error calling snd_pcm_hw_params: %d", err);
342     D(("set up sw params"));
343     snd_pcm_sw_params_alloca(&swparams);
344     if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
345       fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
346     if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
347       fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
348             FRAMES, err);
349     if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
350       fatal(0, "error calling snd_pcm_sw_params: %d", err);
351     pcm_format = playing->format;
352     bpf = bytes_per_frame(&pcm_format);
353     D(("acquired audio device"));
354   }
355   return 0;
356 fatal:
357   abandon();
358 error:
359   /* We assume the error is temporary and that we'll retry in a bit. */
360   if(pcm) {
361     snd_pcm_close(pcm);
362     pcm = 0;
363   }
364   return -1;
365 }
366
367 /* Check to see whether the current track has finished playing */
368 static void maybe_finished(void) {
369   if(playing
370      && playing->eof
371      && (!playing->got_format
372          || playing->used < bytes_per_frame(&playing->format)))
373     abandon();
374 }
375
376 static void play(size_t frames) {
377   snd_pcm_sframes_t written_frames;
378   size_t avail_bytes, avail_frames, written_bytes;
379   int err;
380
381   if(activate()) {
382     if(playing)
383       forceplay = frames;
384     else
385       forceplay = 0;                    /* Must have called abandon() */
386     return;
387   }
388   D(("play: play %zu/%zu%s %dHz %db %dc",  frames, playing->used / bpf,
389      playing->eof ? " EOF" : "",
390      playing->format.rate,
391      playing->format.bits,
392      playing->format.channels));
393   /* If we haven't got enough bytes yet wait until we have.  Exception: when
394    * we are at eof. */
395   if(playing->used < frames * bpf && !playing->eof) {
396     forceplay = frames;
397     return;
398   }
399   /* We have got enough data so don't force play again */
400   forceplay = 0;
401   /* Figure out how many frames there are available to write */
402   if(playing->start + playing->used > playing->size)
403     avail_bytes = playing->size - playing->start;
404   else
405     avail_bytes = playing->used;
406   avail_frames = avail_bytes / bpf;
407   if(avail_frames > frames)
408     avail_frames = frames;
409   if(!avail_frames)
410     return;
411   written_frames = snd_pcm_writei(pcm,
412                                   playing->buffer + playing->start,
413                                   avail_frames);
414   D(("actually play %zu frames, wrote %d",
415      avail_frames, (int)written_frames));
416   if(written_frames < 0) {
417     switch(written_frames) {
418     case -EPIPE:                        /* underrun */
419       error(0, "snd_pcm_writei reports underrun");
420       if((err = snd_pcm_prepare(pcm)) < 0)
421         fatal(0, "error calling snd_pcm_prepare: %d", err);
422       return;
423     case -EAGAIN:
424       return;
425     default:
426       fatal(0, "error calling snd_pcm_writei: %d", (int)written_frames);
427     }
428   }
429   written_bytes = written_frames * bpf;
430   playing->start += written_bytes;
431   playing->used -= written_bytes;
432   playing->played += written_frames;
433   /* If the pointer is at the end of the buffer (or the buffer is completely
434    * empty) wrap it back to the start. */
435   if(!playing->used || playing->start == playing->size)
436     playing->start = 0;
437   frames -= written_frames;
438 }
439
440 /* Notify the server what we're up to. */
441 static void report(void) {
442   struct speaker_message sm;
443
444   if(playing && playing->buffer != (void *)&playing->format) {
445     memset(&sm, 0, sizeof sm);
446     sm.type = paused ? SM_PAUSED : SM_PLAYING;
447     strcpy(sm.id, playing->id);
448     sm.data = playing->played / playing->format.rate;
449     speaker_send(1, &sm, 0);
450   }
451   time(&last_report);
452 }
453
454 static int addfd(int fd, int events) {
455   if(fdno < NFDS) {
456     fds[fdno].fd = fd;
457     fds[fdno].events = events;
458     return fdno++;
459   } else
460     return -1;
461 }
462
463 int main(int argc, char **argv) {
464   int n, fd, stdin_slot, alsa_slots, alsa_nslots = -1, err;
465   unsigned short alsa_revents;
466   struct track *t;
467   struct speaker_message sm;
468
469   set_progname(argv);
470   mem_init(0);
471   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
472   while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
473     switch(n) {
474     case 'h': help();
475     case 'V': version();
476     case 'c': configfile = optarg; break;
477     case 'd': debugging = 1; break;
478     case 'D': debugging = 0; break;
479     default: fatal(0, "invalid option");
480     }
481   }
482   if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
483   /* If stderr is a TTY then log there, otherwise to syslog. */
484   if(!isatty(2)) {
485     openlog(progname, LOG_PID, LOG_DAEMON);
486     log_default = &log_syslog;
487   }
488   if(config_read()) fatal(0, "cannot read configuration");
489   /* ignore SIGPIPE */
490   signal(SIGPIPE, SIG_IGN);
491   /* set nice value */
492   xnice(config->nice_speaker);
493   /* change user */
494   become_mortal();
495   /* make sure we're not root, whatever the config says */
496   if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
497   info("started");
498   while(getppid() != 1) {
499     fdno = 0;
500     /* Always ready for commands from the main server. */
501     stdin_slot = addfd(0, POLLIN);
502     /* Try to read sample data for the currently playing track if there is
503      * buffer space. */
504     if(playing && !playing->eof && playing->used < playing->size) {
505       playing->slot = addfd(playing->fd, POLLIN);
506     } else if(playing)
507       playing->slot = -1;
508     /* If forceplay is set then wait until it succeeds before waiting on the
509      * sound device. */
510     if(pcm && !forceplay) {
511       alsa_slots = fdno;
512       alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
513       fdno += alsa_nslots;
514     } else
515       alsa_slots = -1;
516     /* If any other tracks don't have a full buffer, try to read sample data
517      * from them. */
518     for(t = tracks; t; t = t->next)
519       if(t != playing) {
520         if(!t->eof && t->used < t->size) {
521           t->slot = addfd(t->fd,  POLLIN);
522         } else
523           t->slot = -1;
524       }
525     /* Wait up to a second before thinking about current state */
526     n = poll(fds, fdno, 1000);
527     if(n < 0) {
528       if(errno == EINTR) continue;
529       fatal(errno, "error calling poll");
530     }
531     /* Play some sound before doing anything else */
532     if(alsa_slots != -1) {
533       if((err = snd_pcm_poll_descriptors_revents(pcm,
534                                                  &fds[alsa_slots],
535                                                  alsa_nslots,
536                                                  &alsa_revents)) < 0)
537         fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
538       if(alsa_revents & POLLOUT)
539         play(3 * FRAMES);
540     } else {
541       /* Some attempt to play must have failed */
542       if(playing && !paused)
543         play(forceplay);
544       else
545         forceplay = 0;                  /* just in case */
546     }
547     /* Perhaps we have a command to process */
548     if(fds[stdin_slot].revents & POLLIN) {
549       n = speaker_recv(0, &sm, &fd);
550       if(n > 0)
551         switch(sm.type) {
552         case SM_PREPARE:
553           D(("SM_PREPARE %s %d", sm.id, fd));
554           if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
555           t = findtrack(sm.id, 1);
556           acquire(t, fd);
557           break;
558         case SM_PLAY:
559           D(("SM_PLAY %s %d", sm.id, fd));
560           if(playing) fatal(0, "got SM_PLAY but already playing something");
561           t = findtrack(sm.id, 1);
562           if(fd != -1) acquire(t, fd);
563           playing = t;
564           play(pcm_bufsize);
565           report();
566           break;
567         case SM_PAUSE:
568           D(("SM_PAUSE"));
569           paused = 1;
570           report();
571           break;
572         case SM_RESUME:
573           D(("SM_RESUME"));
574           if(paused) {
575             paused = 0;
576             if(playing)
577               play(pcm_bufsize);
578           }
579           report();
580           break;
581         case SM_CANCEL:
582           D(("SM_CANCEL %s",  sm.id));
583           t = removetrack(sm.id);
584           if(t) {
585             if(t == playing) {
586               sm.type = SM_FINISHED;
587               strcpy(sm.id, playing->id);
588               speaker_send(1, &sm, 0);
589               playing = 0;
590             }
591             destroy(t);
592           } else
593             error(0, "SM_CANCEL for unknown track %s", sm.id);
594           report();
595           break;
596         case SM_RELOAD:
597           D(("SM_RELOAD"));
598           if(config_read()) error(0, "cannot read configuration");
599           info("reloaded configuration");
600           break;
601         default:
602           error(0, "unknown message type %d", sm.type);
603         }
604     }
605     /* Read in any buffered data */
606     for(t = tracks; t; t = t->next)
607       if(t->slot != -1 && (fds[t->slot].revents & POLLIN))
608          fill(t);
609     /* We might be able to play now */
610     if(pcm && forceplay && playing && !paused)
611       play(forceplay);
612     /* Maybe we finished playing a track somewhere in the above */
613     maybe_finished();
614     /* If we don't need the sound device for now then close it for the benefit
615      * of anyone else who wants it. */
616     if((!playing || paused) && pcm)
617       idle();
618     /* If we've not reported out state for a second do so now. */
619     if(time(0) > last_report)
620       report();
621   }
622   info("stopped (parent terminated)");
623   exit(0);
624 }
625
626 /*
627 Local Variables:
628 c-basic-offset:2
629 comment-column:40
630 fill-column:79
631 indent-tabs-mode:nil
632 End:
633 */
634 /* arch-tag:HQ4ayCGCjeBF97RuRnvcyg */