chiark / gitweb /
playrtp junks old sample data in fill_buffer()
[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  * When communicating with a subprocess, <a
33  * href="http://sox.sourceforge.net/">sox</a> is invoked to convert the inbound
34  * data to a single consistent format.  The same applies for network (RTP)
35  * play, though in that case currently only 44.1KHz 16-bit stereo is supported.
36  *
37  * The inbound data starts with a structure defining the data format.  Note
38  * that this is NOT portable between different platforms or even necessarily
39  * between versions; the speaker is assumed to be built from the same source
40  * and run on the same host as the main server.
41  *
42  * @b Garbage @b Collection.  This program deliberately does not use the
43  * garbage collector even though it might be convenient to do so.  This is for
44  * two reasons.  Firstly some sound APIs use thread threads and we do not want
45  * to have to deal with potential interactions between threading and garbage
46  * collection.  Secondly this process needs to be able to respond quickly and
47  * this is not compatible with the collector hanging the program even
48  * relatively briefly.
49  *
50  * @b Units.  This program thinks at various times in three different units.
51  * Bytes are obvious.  A sample is a single sample on a single channel.  A
52  * frame is several samples on different channels at the same point in time.
53  * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of
54  * 2-byte samples.
55  */
56
57 #include <config.h>
58 #include "types.h"
59
60 #include <getopt.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <locale.h>
64 #include <syslog.h>
65 #include <unistd.h>
66 #include <errno.h>
67 #include <ao/ao.h>
68 #include <string.h>
69 #include <assert.h>
70 #include <sys/select.h>
71 #include <sys/wait.h>
72 #include <time.h>
73 #include <fcntl.h>
74 #include <poll.h>
75 #include <sys/socket.h>
76 #include <netdb.h>
77 #include <gcrypt.h>
78 #include <sys/uio.h>
79
80 #include "configuration.h"
81 #include "syscalls.h"
82 #include "log.h"
83 #include "defs.h"
84 #include "mem.h"
85 #include "speaker-protocol.h"
86 #include "user.h"
87 #include "addr.h"
88 #include "timeval.h"
89 #include "rtp.h"
90 #include "speaker.h"
91
92 #if API_ALSA
93 #include <alsa/asoundlib.h>
94 #endif
95
96 /** @brief Linked list of all prepared tracks */
97 struct track *tracks;
98
99 /** @brief Playing track, or NULL */
100 struct track *playing;
101
102 static time_t last_report;              /* when we last reported */
103 static int paused;                      /* pause status */
104 static size_t bpf;                      /* bytes per frame */
105 static struct pollfd fds[NFDS];         /* if we need more than that */
106 static int fdno;                        /* fd number */
107 #if API_ALSA
108 /** @brief The current PCM handle */
109 static snd_pcm_t *pcm;
110 static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
111 #endif
112
113 /** @brief The current device state */
114 enum device_states device_state;
115
116 /** @brief The current device sample format
117  *
118  * Only meaningful if @ref device_state = @ref device_open or perhaps @ref
119  * device_error.  For @ref FIXED_FORMAT backends, this should always match @c
120  * config->sample_format.
121  */
122 ao_sample_format device_format;
123
124 /** @brief Pipe to subprocess
125  *
126  * This is the file descriptor to write to for @ref BACKEND_COMMAND.
127  */
128 static int cmdfd = -1;
129
130 /** @brief Network socket
131  *
132  * This is the file descriptor to write to for @ref BACKEND_NETWORK.
133  */
134 static int bfd = -1;
135
136 /** @brief RTP timestamp
137  *
138  * This counts the number of samples played (NB not the number of frames
139  * played).
140  *
141  * The timestamp in the packet header is only 32 bits wide.  With 44100Hz
142  * stereo, that only gives about half a day before wrapping, which is not
143  * particularly convenient for certain debugging purposes.  Therefore the
144  * timestamp is maintained as a 64-bit integer, giving around six million years
145  * before wrapping, and truncated to 32 bits when transmitting.
146  */
147 static uint64_t rtp_time;
148
149 /** @brief RTP base timestamp
150  *
151  * This is the real time correspoding to an @ref rtp_time of 0.  It is used
152  * to recalculate the timestamp after idle periods.
153  */
154 static struct timeval rtp_time_0;
155
156 /** @brief RTP packet sequence number */
157 static uint16_t rtp_seq;
158
159 /** @brief RTP SSRC */
160 static uint32_t rtp_id;
161
162 /** @brief Set when idled
163  *
164  * This is set when the sound device is deliberately closed by idle().
165  */
166 static int idled;                       /* set when idled */
167
168 /** @brief Error counter */
169 static int audio_errors;
170
171 /** @brief Selected backend */
172 static const struct speaker_backend *backend;
173
174 static const struct option options[] = {
175   { "help", no_argument, 0, 'h' },
176   { "version", no_argument, 0, 'V' },
177   { "config", required_argument, 0, 'c' },
178   { "debug", no_argument, 0, 'd' },
179   { "no-debug", no_argument, 0, 'D' },
180   { 0, 0, 0, 0 }
181 };
182
183 /* Display usage message and terminate. */
184 static void help(void) {
185   xprintf("Usage:\n"
186           "  disorder-speaker [OPTIONS]\n"
187           "Options:\n"
188           "  --help, -h              Display usage message\n"
189           "  --version, -V           Display version number\n"
190           "  --config PATH, -c PATH  Set configuration file\n"
191           "  --debug, -d             Turn on debugging\n"
192           "\n"
193           "Speaker process for DisOrder.  Not intended to be run\n"
194           "directly.\n");
195   xfclose(stdout);
196   exit(0);
197 }
198
199 /* Display version number and terminate. */
200 static void version(void) {
201   xprintf("disorder-speaker version %s\n", disorder_version_string);
202   xfclose(stdout);
203   exit(0);
204 }
205
206 /** @brief Return the number of bytes per frame in @p format */
207 static size_t bytes_per_frame(const ao_sample_format *format) {
208   return format->channels * format->bits / 8;
209 }
210
211 /** @brief Find track @p id, maybe creating it if not found */
212 static struct track *findtrack(const char *id, int create) {
213   struct track *t;
214
215   D(("findtrack %s %d", id, create));
216   for(t = tracks; t && strcmp(id, t->id); t = t->next)
217     ;
218   if(!t && create) {
219     t = xmalloc(sizeof *t);
220     t->next = tracks;
221     strcpy(t->id, id);
222     t->fd = -1;
223     tracks = t;
224     /* The initial input buffer will be the sample format. */
225     t->buffer = (void *)&t->format;
226     t->size = sizeof t->format;
227   }
228   return t;
229 }
230
231 /** @brief Remove track @p id (but do not destroy it) */
232 static struct track *removetrack(const char *id) {
233   struct track *t, **tt;
234
235   D(("removetrack %s", id));
236   for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
237     ;
238   if(t)
239     *tt = t->next;
240   return t;
241 }
242
243 /** @brief Destroy a track */
244 static void destroy(struct track *t) {
245   D(("destroy %s", t->id));
246   if(t->fd != -1) xclose(t->fd);
247   if(t->buffer != (void *)&t->format) free(t->buffer);
248   free(t);
249 }
250
251 /** @brief Notice a new connection */
252 static void acquire(struct track *t, int fd) {
253   D(("acquire %s %d", t->id, fd));
254   if(t->fd != -1)
255     xclose(t->fd);
256   t->fd = fd;
257   nonblock(fd);
258 }
259
260 /** @brief Return true if A and B denote identical libao formats, else false */
261 static int formats_equal(const ao_sample_format *a,
262                          const ao_sample_format *b) {
263   return (a->bits == b->bits
264           && a->rate == b->rate
265           && a->channels == b->channels
266           && a->byte_format == b->byte_format);
267 }
268
269 /** @brief Compute arguments to sox */
270 static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
271   int n;
272
273   *(*pp)++ = "-t.raw";
274   *(*pp)++ = "-s";
275   *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
276   *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
277   /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
278    * deployed! */
279   switch(config->sox_generation) {
280   case 0:
281     if(ao->bits != 8
282        && ao->byte_format != AO_FMT_NATIVE
283        && ao->byte_format != MACHINE_AO_FMT) {
284       *(*pp)++ = "-x";
285     }
286     switch(ao->bits) {
287     case 8: *(*pp)++ = "-b"; break;
288     case 16: *(*pp)++ = "-w"; break;
289     case 32: *(*pp)++ = "-l"; break;
290     case 64: *(*pp)++ = "-d"; break;
291     default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
292     }
293     break;
294   case 1:
295     switch(ao->byte_format) {
296     case AO_FMT_NATIVE: break;
297     case AO_FMT_BIG: *(*pp)++ = "-B"; break;
298     case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
299     }
300     *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
301     break;
302   }
303 }
304
305 /** @brief Enable format translation
306  *
307  * If necessary, replaces a tracks inbound file descriptor with one connected
308  * to a sox invocation, which performs the required translation.
309  */
310 static void enable_translation(struct track *t) {
311   if((backend->flags & FIXED_FORMAT)
312      && !formats_equal(&t->format, &config->sample_format)) {
313     char argbuf[1024], *q = argbuf;
314     const char *av[18], **pp = av;
315     int soxpipe[2];
316     pid_t soxkid;
317
318     *pp++ = "sox";
319     soxargs(&pp, &q, &t->format);
320     *pp++ = "-";
321     soxargs(&pp, &q, &config->sample_format);
322     *pp++ = "-";
323     *pp++ = 0;
324     if(debugging) {
325       for(pp = av; *pp; pp++)
326         D(("sox arg[%d] = %s", pp - av, *pp));
327       D(("end args"));
328     }
329     xpipe(soxpipe);
330     soxkid = xfork();
331     if(soxkid == 0) {
332       signal(SIGPIPE, SIG_DFL);
333       xdup2(t->fd, 0);
334       xdup2(soxpipe[1], 1);
335       fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
336       close(soxpipe[0]);
337       close(soxpipe[1]);
338       close(t->fd);
339       execvp("sox", (char **)av);
340       _exit(1);
341     }
342     D(("forking sox for format conversion (kid = %d)", soxkid));
343     close(t->fd);
344     close(soxpipe[1]);
345     t->fd = soxpipe[0];
346     t->format = config->sample_format;
347   }
348 }
349
350 /** @brief Read data into a sample buffer
351  * @param t Pointer to track
352  * @return 0 on success, -1 on EOF
353  *
354  * This is effectively the read callback on @c t->fd.  It is called from the
355  * main loop whenever the track's file descriptor is readable, assuming the
356  * buffer has not reached the maximum allowed occupancy.
357  */
358 static int fill(struct track *t) {
359   size_t where, left;
360   int n;
361
362   D(("fill %s: eof=%d used=%zu size=%zu  got_format=%d",
363      t->id, t->eof, t->used, t->size, t->got_format));
364   if(t->eof) return -1;
365   if(t->used < t->size) {
366     /* there is room left in the buffer */
367     where = (t->start + t->used) % t->size;
368     if(t->got_format) {
369       /* We are reading audio data, get as much as we can */
370       if(where >= t->start) left = t->size - where;
371       else left = t->start - where;
372     } else
373       /* We are still waiting for the format, only get that */
374       left = sizeof (ao_sample_format) - t->used;
375     do {
376       n = read(t->fd, t->buffer + where, left);
377     } while(n < 0 && errno == EINTR);
378     if(n < 0) {
379       if(errno != EAGAIN) fatal(errno, "error reading sample stream");
380       return 0;
381     }
382     if(n == 0) {
383       D(("fill %s: eof detected", t->id));
384       t->eof = 1;
385       return -1;
386     }
387     t->used += n;
388     if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
389       assert(t->used == sizeof (ao_sample_format));
390       /* Check that our assumptions are met. */
391       if(t->format.bits & 7)
392         fatal(0, "bits per sample not a multiple of 8");
393       /* If the input format is unsuitable, arrange to translate it */
394       enable_translation(t);
395       /* Make a new buffer for audio data. */
396       t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
397       t->buffer = xmalloc(t->size);
398       t->used = 0;
399       t->got_format = 1;
400       D(("got format for %s", t->id));
401     }
402   }
403   return 0;
404 }
405
406 /** @brief Close the sound device
407  *
408  * This is called to deactivate the output device when pausing, and also by the
409  * ALSA backend when changing encoding (in which case the sound device will be
410  * immediately reactivated).
411  */
412 static void idle(void) {
413   D(("idle"));
414   if(backend->deactivate) 
415     backend->deactivate();
416   else
417     device_state = device_closed;
418   idled = 1;
419 }
420
421 /** @brief Abandon the current track */
422 static void abandon(void) {
423   struct speaker_message sm;
424
425   D(("abandon"));
426   memset(&sm, 0, sizeof sm);
427   sm.type = SM_FINISHED;
428   strcpy(sm.id, playing->id);
429   speaker_send(1, &sm, 0);
430   removetrack(playing->id);
431   destroy(playing);
432   playing = 0;
433 }
434
435 /** @brief Enable sound output
436  *
437  * Makes sure the sound device is open and has the right sample format.  Return
438  * 0 on success and -1 on error.
439  */
440 static void activate(void) {
441   /* If we don't know the format yet we cannot start. */
442   if(!playing->got_format) {
443     D((" - not got format for %s", playing->id));
444     return;
445   }
446   if(backend->flags & FIXED_FORMAT)
447     device_format = config->sample_format;
448   if(backend->activate) {
449     backend->activate();
450   } else {
451     assert(backend->flags & FIXED_FORMAT);
452     /* ...otherwise device_format not set */
453     device_state = device_open;
454   }
455   if(device_state == device_open)
456     bpf = bytes_per_frame(&device_format);
457 }
458
459 /** @brief Check whether the current track has finished
460  *
461  * The current track is determined to have finished either if the input stream
462  * eded before the format could be determined (i.e. it is malformed) or the
463  * input is at end of file and there is less than a frame left unplayed.  (So
464  * it copes with decoders that crash mid-frame.)
465  */
466 static void maybe_finished(void) {
467   if(playing
468      && playing->eof
469      && (!playing->got_format
470          || playing->used < bytes_per_frame(&playing->format)))
471     abandon();
472 }
473
474 /** @brief Play up to @p frames frames of audio
475  *
476  * It is always safe to call this function.
477  * - If @ref playing is 0 then it will just return
478  * - If @ref paused is non-0 then it will just return
479  * - If @ref device_state != @ref device_open then it will call activate() and
480  * return if it it fails.
481  * - If there is not enough audio to play then it play what is available.
482  *
483  * If there are not enough frames to play then whatever is available is played
484  * instead.  It is up to mainloop() to ensure that play() is not called when
485  * unreasonably only an small amounts of data is available to play.
486  */
487 static void play(size_t frames) {
488   size_t avail_frames, avail_bytes, written_frames;
489   ssize_t written_bytes;
490
491   /* Make sure there's a track to play and it is not pasued */
492   if(!playing || paused)
493     return;
494   /* Make sure the output device is open and has the right sample format */
495   if(device_state != device_open
496      || !formats_equal(&device_format, &playing->format)) {
497     activate(); 
498     if(device_state != device_open)
499       return;
500   }
501   D(("play: play %zu/%zu%s %dHz %db %dc",  frames, playing->used / bpf,
502      playing->eof ? " EOF" : "",
503      playing->format.rate,
504      playing->format.bits,
505      playing->format.channels));
506   /* Figure out how many frames there are available to write */
507   if(playing->start + playing->used > playing->size)
508     /* The ring buffer is currently wrapped, only play up to the wrap point */
509     avail_bytes = playing->size - playing->start;
510   else
511     /* The ring buffer is not wrapped, can play the lot */
512     avail_bytes = playing->used;
513   avail_frames = avail_bytes / bpf;
514   /* Only play up to the requested amount */
515   if(avail_frames > frames)
516     avail_frames = frames;
517   if(!avail_frames)
518     return;
519   /* Play it, Sam */
520   written_frames = backend->play(avail_frames);
521   written_bytes = written_frames * bpf;
522   /* written_bytes and written_frames had better both be set and correct by
523    * this point */
524   playing->start += written_bytes;
525   playing->used -= written_bytes;
526   playing->played += written_frames;
527   /* If the pointer is at the end of the buffer (or the buffer is completely
528    * empty) wrap it back to the start. */
529   if(!playing->used || playing->start == playing->size)
530     playing->start = 0;
531   frames -= written_frames;
532   return;
533 }
534
535 /* Notify the server what we're up to. */
536 static void report(void) {
537   struct speaker_message sm;
538
539   if(playing && playing->buffer != (void *)&playing->format) {
540     memset(&sm, 0, sizeof sm);
541     sm.type = paused ? SM_PAUSED : SM_PLAYING;
542     strcpy(sm.id, playing->id);
543     sm.data = playing->played / playing->format.rate;
544     speaker_send(1, &sm, 0);
545   }
546   time(&last_report);
547 }
548
549 static void reap(int __attribute__((unused)) sig) {
550   pid_t cmdpid;
551   int st;
552
553   do
554     cmdpid = waitpid(-1, &st, WNOHANG);
555   while(cmdpid > 0);
556   signal(SIGCHLD, reap);
557 }
558
559 static int addfd(int fd, int events) {
560   if(fdno < NFDS) {
561     fds[fdno].fd = fd;
562     fds[fdno].events = events;
563     return fdno++;
564   } else
565     return -1;
566 }
567
568 #if API_ALSA
569 /** @brief ALSA backend initialization */
570 static void alsa_init(void) {
571   info("selected ALSA backend");
572 }
573
574 /** @brief Log ALSA parameters */
575 static void log_params(snd_pcm_hw_params_t *hwparams,
576                        snd_pcm_sw_params_t *swparams) {
577   snd_pcm_uframes_t f;
578   unsigned u;
579
580   return;                               /* too verbose */
581   if(hwparams) {
582     /* TODO */
583   }
584   if(swparams) {
585     snd_pcm_sw_params_get_silence_size(swparams, &f);
586     info("sw silence_size=%lu", (unsigned long)f);
587     snd_pcm_sw_params_get_silence_threshold(swparams, &f);
588     info("sw silence_threshold=%lu", (unsigned long)f);
589     snd_pcm_sw_params_get_sleep_min(swparams, &u);
590     info("sw sleep_min=%lu", (unsigned long)u);
591     snd_pcm_sw_params_get_start_threshold(swparams, &f);
592     info("sw start_threshold=%lu", (unsigned long)f);
593     snd_pcm_sw_params_get_stop_threshold(swparams, &f);
594     info("sw stop_threshold=%lu", (unsigned long)f);
595     snd_pcm_sw_params_get_xfer_align(swparams, &f);
596     info("sw xfer_align=%lu", (unsigned long)f);
597   }
598 }
599
600 /** @brief ALSA deactivation */
601 static void alsa_deactivate(void) {
602   if(pcm) {
603     int err;
604     
605     if((err = snd_pcm_nonblock(pcm, 0)) < 0)
606       fatal(0, "error calling snd_pcm_nonblock: %d", err);
607     D(("draining pcm"));
608     snd_pcm_drain(pcm);
609     D(("closing pcm"));
610     snd_pcm_close(pcm);
611     pcm = 0;
612     device_state = device_closed;
613     D(("released audio device"));
614   }
615 }
616
617 /** @brief ALSA backend activation */
618 static void alsa_activate(void) {
619   /* If we need to change format then close the current device. */
620   if(pcm && !formats_equal(&playing->format, &device_format))
621     alsa_deactivate();
622   /* Now if the sound device is open it must have the right format */
623   if(!pcm) {
624     snd_pcm_hw_params_t *hwparams;
625     snd_pcm_sw_params_t *swparams;
626     snd_pcm_uframes_t pcm_bufsize;
627     int err;
628     int sample_format = 0;
629     unsigned rate;
630
631     D(("snd_pcm_open"));
632     if((err = snd_pcm_open(&pcm,
633                            config->device,
634                            SND_PCM_STREAM_PLAYBACK,
635                            SND_PCM_NONBLOCK))) {
636       error(0, "error from snd_pcm_open: %d", err);
637       goto error;
638     }
639     snd_pcm_hw_params_alloca(&hwparams);
640     D(("set up hw params"));
641     if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
642       fatal(0, "error from snd_pcm_hw_params_any: %d", err);
643     if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
644                                            SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
645       fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
646     switch(playing->format.bits) {
647     case 8:
648       sample_format = SND_PCM_FORMAT_S8;
649       break;
650     case 16:
651       switch(playing->format.byte_format) {
652       case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
653       case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
654       case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
655         error(0, "unrecognized byte format %d", playing->format.byte_format);
656         goto fatal;
657       }
658       break;
659     default:
660       error(0, "unsupported sample size %d", playing->format.bits);
661       goto fatal;
662     }
663     if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
664                                            sample_format)) < 0) {
665       error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
666             sample_format, err);
667       goto fatal;
668     }
669     rate = playing->format.rate;
670     if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
671       error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
672             playing->format.rate, err);
673       goto fatal;
674     }
675     if(rate != (unsigned)playing->format.rate)
676       info("want rate %d, got %u", playing->format.rate, rate);
677     if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
678                                              playing->format.channels)) < 0) {
679       error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
680             playing->format.channels, err);
681       goto fatal;
682     }
683     pcm_bufsize = 3 * FRAMES;
684     if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
685                                                      &pcm_bufsize)) < 0)
686       fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
687             3 * FRAMES, err);
688     if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
689       info("asked for PCM buffer of %d frames, got %d",
690            3 * FRAMES, (int)pcm_bufsize);
691     last_pcm_bufsize = pcm_bufsize;
692     if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
693       fatal(0, "error calling snd_pcm_hw_params: %d", err);
694     D(("set up sw params"));
695     snd_pcm_sw_params_alloca(&swparams);
696     if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
697       fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
698     if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
699       fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
700             FRAMES, err);
701     if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
702       fatal(0, "error calling snd_pcm_sw_params: %d", err);
703     device_format = playing->format;
704     D(("acquired audio device"));
705     log_params(hwparams, swparams);
706     device_state = device_open;
707   }
708   return;
709 fatal:
710   abandon();
711 error:
712   /* We assume the error is temporary and that we'll retry in a bit. */
713   if(pcm) {
714     snd_pcm_close(pcm);
715     pcm = 0;
716     device_state = device_error;
717   }
718   return;
719 }
720
721 /** @brief Play via ALSA */
722 static size_t alsa_play(size_t frames) {
723   snd_pcm_sframes_t pcm_written_frames;
724   int err;
725   
726   pcm_written_frames = snd_pcm_writei(pcm,
727                                       playing->buffer + playing->start,
728                                       frames);
729   D(("actually play %zu frames, wrote %d",
730      frames, (int)pcm_written_frames));
731   if(pcm_written_frames < 0) {
732     switch(pcm_written_frames) {
733     case -EPIPE:                        /* underrun */
734       error(0, "snd_pcm_writei reports underrun");
735       if((err = snd_pcm_prepare(pcm)) < 0)
736         fatal(0, "error calling snd_pcm_prepare: %d", err);
737       return 0;
738     case -EAGAIN:
739       return 0;
740     default:
741       fatal(0, "error calling snd_pcm_writei: %d",
742             (int)pcm_written_frames);
743     }
744   } else
745     return pcm_written_frames;
746 }
747
748 static int alsa_slots, alsa_nslots = -1;
749
750 /** @brief Fill in poll fd array for ALSA */
751 static void alsa_beforepoll(void) {
752   /* We send sample data to ALSA as fast as it can accept it, relying on
753    * the fact that it has a relatively small buffer to minimize pause
754    * latency. */
755   int retry = 3, err;
756   
757   alsa_slots = fdno;
758   do {
759     retry = 0;
760     alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
761     if((alsa_nslots <= 0
762         || !(fds[alsa_slots].events & POLLOUT))
763        && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
764       error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
765       if((err = snd_pcm_prepare(pcm)))
766         fatal(0, "error calling snd_pcm_prepare: %d", err);
767     } else
768       break;
769   } while(retry-- > 0);
770   if(alsa_nslots >= 0)
771     fdno += alsa_nslots;
772 }
773
774 /** @brief Process poll() results for ALSA */
775 static int alsa_ready(void) {
776   int err;
777
778   unsigned short alsa_revents;
779   
780   if((err = snd_pcm_poll_descriptors_revents(pcm,
781                                              &fds[alsa_slots],
782                                              alsa_nslots,
783                                              &alsa_revents)) < 0)
784     fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
785   if(alsa_revents & (POLLOUT | POLLERR))
786     return 1;
787   else
788     return 0;
789 }
790 #endif
791
792 /** @brief Start the subprocess for @ref BACKEND_COMMAND */
793 static void fork_cmd(void) {
794   pid_t cmdpid;
795   int pfd[2];
796   if(cmdfd != -1) close(cmdfd);
797   xpipe(pfd);
798   cmdpid = xfork();
799   if(!cmdpid) {
800     signal(SIGPIPE, SIG_DFL);
801     xdup2(pfd[0], 0);
802     close(pfd[0]);
803     close(pfd[1]);
804     execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
805     fatal(errno, "error execing /bin/sh");
806   }
807   close(pfd[0]);
808   cmdfd = pfd[1];
809   D(("forked cmd %d, fd = %d", cmdpid, cmdfd));
810 }
811
812 /** @brief Command backend initialization */
813 static void command_init(void) {
814   info("selected command backend");
815   fork_cmd();
816 }
817
818 /** @brief Play to a subprocess */
819 static size_t command_play(size_t frames) {
820   size_t bytes = frames * bpf;
821   int written_bytes;
822
823   written_bytes = write(cmdfd, playing->buffer + playing->start, bytes);
824   D(("actually play %zu bytes, wrote %d",
825      bytes, written_bytes));
826   if(written_bytes < 0) {
827     switch(errno) {
828     case EPIPE:
829       error(0, "hmm, command died; trying another");
830       fork_cmd();
831       return 0;
832     case EAGAIN:
833       return 0;
834     default:
835       fatal(errno, "error writing to subprocess");
836     }
837   } else
838     return written_bytes / bpf;
839 }
840
841 static int cmdfd_slot;
842
843 /** @brief Update poll array for writing to subprocess */
844 static void command_beforepoll(void) {
845   /* We send sample data to the subprocess as fast as it can accept it.
846    * This isn't ideal as pause latency can be very high as a result. */
847   if(cmdfd >= 0)
848     cmdfd_slot = addfd(cmdfd, POLLOUT);
849 }
850
851 /** @brief Process poll() results for subprocess play */
852 static int command_ready(void) {
853   if(fds[cmdfd_slot].revents & (POLLOUT | POLLERR))
854     return 1;
855   else
856     return 0;
857 }
858
859 /** @brief Network backend initialization */
860 static void network_init(void) {
861   struct addrinfo *res, *sres;
862   static const struct addrinfo pref = {
863     0,
864     PF_INET,
865     SOCK_DGRAM,
866     IPPROTO_UDP,
867     0,
868     0,
869     0,
870     0
871   };
872   static const struct addrinfo prefbind = {
873     AI_PASSIVE,
874     PF_INET,
875     SOCK_DGRAM,
876     IPPROTO_UDP,
877     0,
878     0,
879     0,
880     0
881   };
882   static const int one = 1;
883   int sndbuf, target_sndbuf = 131072;
884   socklen_t len;
885   char *sockname, *ssockname;
886
887   res = get_address(&config->broadcast, &pref, &sockname);
888   if(!res) exit(-1);
889   if(config->broadcast_from.n) {
890     sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
891     if(!sres) exit(-1);
892   } else
893     sres = 0;
894   if((bfd = socket(res->ai_family,
895                    res->ai_socktype,
896                    res->ai_protocol)) < 0)
897     fatal(errno, "error creating broadcast socket");
898   if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
899     fatal(errno, "error setting SO_BROADCAST on broadcast socket");
900   len = sizeof sndbuf;
901   if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
902                 &sndbuf, &len) < 0)
903     fatal(errno, "error getting SO_SNDBUF");
904   if(target_sndbuf > sndbuf) {
905     if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
906                   &target_sndbuf, sizeof target_sndbuf) < 0)
907       error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
908     else
909       info("changed socket send buffer size from %d to %d",
910            sndbuf, target_sndbuf);
911   } else
912     info("default socket send buffer is %d",
913          sndbuf);
914   /* We might well want to set additional broadcast- or multicast-related
915    * options here */
916   if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
917     fatal(errno, "error binding broadcast socket to %s", ssockname);
918   if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
919     fatal(errno, "error connecting broadcast socket to %s", sockname);
920   /* Select an SSRC */
921   gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
922   info("selected network backend, sending to %s", sockname);
923   if(config->sample_format.byte_format != AO_FMT_BIG) {
924     info("forcing big-endian sample format");
925     config->sample_format.byte_format = AO_FMT_BIG;
926   }
927 }
928
929 /** @brief Play over the network */
930 static size_t network_play(size_t frames) {
931   struct rtp_header header;
932   struct iovec vec[2];
933   size_t bytes = frames * bpf, written_frames;
934   int written_bytes;
935   /* We transmit using RTP (RFC3550) and attempt to conform to the internet
936    * AVT profile (RFC3551). */
937
938   if(idled) {
939     /* There may have been a gap.  Fix up the RTP time accordingly. */
940     struct timeval now;
941     uint64_t delta;
942     uint64_t target_rtp_time;
943
944     /* Find the current time */
945     xgettimeofday(&now, 0);
946     /* Find the number of microseconds elapsed since rtp_time=0 */
947     delta = tvsub_us(now, rtp_time_0);
948     assert(delta <= UINT64_MAX / 88200);
949     target_rtp_time = (delta * playing->format.rate
950                        * playing->format.channels) / 1000000;
951     /* Overflows at ~6 years uptime with 44100Hz stereo */
952
953     /* rtp_time is the number of samples we've played.  NB that we play
954      * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
955      * the value we deduce from time comparison.
956      *
957      * Suppose we have 1s track started at t=0, and another track begins to
958      * play at t=2s.  Suppose RTP_AHEAD_MS=1000 and 44100Hz stereo.  In that
959      * case we'll send 1s of audio as fast as we can, giving rtp_time=88200.
960      * rtp_time stops at this point.
961      *
962      * At t=2s we'll have calculated target_rtp_time=176400.  In this case we
963      * set rtp_time=176400 and the player can correctly conclude that it
964      * should leave 1s between the tracks.
965      *
966      * Suppose instead that the second track arrives at t=0.5s, and that
967      * we've managed to transmit the whole of the first track already.  We'll
968      * have target_rtp_time=44100.
969      *
970      * The desired behaviour is to play the second track back to back with
971      * first.  In this case therefore we do not modify rtp_time.
972      *
973      * Is it ever right to reduce rtp_time?  No; for that would imply
974      * transmitting packets with overlapping timestamp ranges, which does not
975      * make sense.
976      */
977     target_rtp_time &= ~(uint64_t)1;    /* stereo! */
978     if(target_rtp_time > rtp_time) {
979       /* More time has elapsed than we've transmitted samples.  That implies
980        * we've been 'sending' silence.  */
981       info("advancing rtp_time by %"PRIu64" samples",
982            target_rtp_time - rtp_time);
983       rtp_time = target_rtp_time;
984     } else if(target_rtp_time < rtp_time) {
985       const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
986                                      * config->sample_format.rate
987                                      * config->sample_format.channels
988                                      / 1000);
989         
990       if(target_rtp_time + samples_ahead < rtp_time) {
991         info("reversing rtp_time by %"PRIu64" samples",
992              rtp_time - target_rtp_time);
993       }
994     }
995   }
996   header.vpxcc = 2 << 6;              /* V=2, P=0, X=0, CC=0 */
997   header.seq = htons(rtp_seq++);
998   header.timestamp = htonl((uint32_t)rtp_time);
999   header.ssrc = rtp_id;
1000   header.mpt = (idled ? 0x80 : 0x00) | 10;
1001   /* 10 = L16 = 16-bit x 2 x 44100KHz.  We ought to deduce this value from
1002    * the sample rate (in a library somewhere so that configuration.c can rule
1003    * out invalid rates).
1004    */
1005   idled = 0;
1006   if(bytes > NETWORK_BYTES - sizeof header) {
1007     bytes = NETWORK_BYTES - sizeof header;
1008     /* Always send a whole number of frames */
1009     bytes -= bytes % bpf;
1010   }
1011   /* "The RTP clock rate used for generating the RTP timestamp is independent
1012    * of the number of channels and the encoding; it equals the number of
1013    * sampling periods per second.  For N-channel encodings, each sampling
1014    * period (say, 1/8000 of a second) generates N samples. (This terminology
1015    * is standard, but somewhat confusing, as the total number of samples
1016    * generated per second is then the sampling rate times the channel
1017    * count.)"
1018    */
1019   vec[0].iov_base = (void *)&header;
1020   vec[0].iov_len = sizeof header;
1021   vec[1].iov_base = playing->buffer + playing->start;
1022   vec[1].iov_len = bytes;
1023   do {
1024     written_bytes = writev(bfd, vec, 2);
1025   } while(written_bytes < 0 && errno == EINTR);
1026   if(written_bytes < 0) {
1027     error(errno, "error transmitting audio data");
1028     ++audio_errors;
1029     if(audio_errors == 10)
1030       fatal(0, "too many audio errors");
1031     return 0;
1032   } else
1033     audio_errors /= 2;
1034   written_bytes -= sizeof (struct rtp_header);
1035   written_frames = written_bytes / bpf;
1036   /* Advance RTP's notion of the time */
1037   rtp_time += written_frames * playing->format.channels;
1038   return written_frames;
1039 }
1040
1041 static int bfd_slot;
1042
1043 /** @brief Set up poll array for network play */
1044 static void network_beforepoll(void) {
1045   struct timeval now;
1046   uint64_t target_us;
1047   uint64_t target_rtp_time;
1048   const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
1049                                  * config->sample_format.rate
1050                                  * config->sample_format.channels
1051                                  / 1000);
1052   
1053   /* If we're starting then initialize the base time */
1054   if(!rtp_time)
1055     xgettimeofday(&rtp_time_0, 0);
1056   /* We send audio data whenever we get RTP_AHEAD seconds or more
1057    * behind */
1058   xgettimeofday(&now, 0);
1059   target_us = tvsub_us(now, rtp_time_0);
1060   assert(target_us <= UINT64_MAX / 88200);
1061   target_rtp_time = (target_us * config->sample_format.rate
1062                                * config->sample_format.channels)
1063                      / 1000000;
1064   if((int64_t)(rtp_time - target_rtp_time) < samples_ahead)
1065     bfd_slot = addfd(bfd, POLLOUT);
1066 }
1067
1068 /** @brief Process poll() results for network play */
1069 static int network_ready(void) {
1070   if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
1071     return 1;
1072   else
1073     return 0;
1074 }
1075
1076 /** @brief Table of speaker backends */
1077 static const struct speaker_backend backends[] = {
1078 #if API_ALSA
1079   {
1080     BACKEND_ALSA,
1081     0,
1082     alsa_init,
1083     alsa_activate,
1084     alsa_play,
1085     alsa_deactivate,
1086     alsa_beforepoll,
1087     alsa_ready
1088   },
1089 #endif
1090   {
1091     BACKEND_COMMAND,
1092     FIXED_FORMAT,
1093     command_init,
1094     0,                                  /* activate */
1095     command_play,
1096     0,                                  /* deactivate */
1097     command_beforepoll,
1098     command_ready
1099   },
1100   {
1101     BACKEND_NETWORK,
1102     FIXED_FORMAT,
1103     network_init,
1104     0,                                  /* activate */
1105     network_play,
1106     0,                                  /* deactivate */
1107     network_beforepoll,
1108     network_ready
1109   },
1110   { -1, 0, 0, 0, 0, 0, 0, 0 }           /* end of list */
1111 };
1112
1113 /** @brief Return nonzero if we want to play some audio
1114  *
1115  * We want to play audio if there is a current track; and it is not paused; and
1116  * there are at least @ref FRAMES frames of audio to play, or we are in sight
1117  * of the end of the current track.
1118  */
1119 static int playable(void) {
1120   return playing
1121          && !paused
1122          && (playing->used >= FRAMES || playing->eof);
1123 }
1124
1125 /** @brief Main event loop */
1126 static void mainloop(void) {
1127   struct track *t;
1128   struct speaker_message sm;
1129   int n, fd, stdin_slot, timeout;
1130
1131   while(getppid() != 1) {
1132     fdno = 0;
1133     /* By default we will wait up to a second before thinking about current
1134      * state. */
1135     timeout = 1000;
1136     /* Always ready for commands from the main server. */
1137     stdin_slot = addfd(0, POLLIN);
1138     /* Try to read sample data for the currently playing track if there is
1139      * buffer space. */
1140     if(playing && !playing->eof && playing->used < playing->size)
1141       playing->slot = addfd(playing->fd, POLLIN);
1142     else if(playing)
1143       playing->slot = -1;
1144     if(playable()) {
1145       /* We want to play some audio.  If the device is closed then we attempt
1146        * to open it. */
1147       if(device_state == device_closed)
1148         activate();
1149       /* If the device is (now) open then we will wait up until it is ready for
1150        * more.  If something went wrong then we should have device_error
1151        * instead, but the post-poll code will cope even if it's
1152        * device_closed. */
1153       if(device_state == device_open)
1154         backend->beforepoll();
1155     }
1156     /* If any other tracks don't have a full buffer, try to read sample data
1157      * from them.  We do this last of all, so that if we run out of slots,
1158      * nothing important can't be monitored. */
1159     for(t = tracks; t; t = t->next)
1160       if(t != playing) {
1161         if(!t->eof && t->used < t->size) {
1162           t->slot = addfd(t->fd,  POLLIN | POLLHUP);
1163         } else
1164           t->slot = -1;
1165       }
1166     /* Wait for something interesting to happen */
1167     n = poll(fds, fdno, timeout);
1168     if(n < 0) {
1169       if(errno == EINTR) continue;
1170       fatal(errno, "error calling poll");
1171     }
1172     /* Play some sound before doing anything else */
1173     if(playable()) {
1174       /* We want to play some audio */
1175       if(device_state == device_open) {
1176         if(backend->ready())
1177           play(3 * FRAMES);
1178       } else {
1179         /* We must be in _closed or _error, and it should be the latter, but we
1180          * cope with either.
1181          *
1182          * We most likely timed out, so now is a good time to retry.  play()
1183          * knows to re-activate the device if necessary.
1184          */
1185         play(3 * FRAMES);
1186       }
1187     }
1188     /* Perhaps we have a command to process */
1189     if(fds[stdin_slot].revents & POLLIN) {
1190       /* There might (in theory) be several commands queued up, but in general
1191        * this won't be the case, so we don't bother looping around to pick them
1192        * all up. */ 
1193       n = speaker_recv(0, &sm, &fd);
1194       if(n > 0)
1195         switch(sm.type) {
1196         case SM_PREPARE:
1197           D(("SM_PREPARE %s %d", sm.id, fd));
1198           if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
1199           t = findtrack(sm.id, 1);
1200           acquire(t, fd);
1201           break;
1202         case SM_PLAY:
1203           D(("SM_PLAY %s %d", sm.id, fd));
1204           if(playing) fatal(0, "got SM_PLAY but already playing something");
1205           t = findtrack(sm.id, 1);
1206           if(fd != -1) acquire(t, fd);
1207           playing = t;
1208           /* We attempt to play straight away rather than going round the loop.
1209            * play() is clever enough to perform any activation that is
1210            * required. */
1211           play(3 * FRAMES);
1212           report();
1213           break;
1214         case SM_PAUSE:
1215           D(("SM_PAUSE"));
1216           paused = 1;
1217           report();
1218           break;
1219         case SM_RESUME:
1220           D(("SM_RESUME"));
1221           if(paused) {
1222             paused = 0;
1223             /* As for SM_PLAY we attempt to play straight away. */
1224             if(playing)
1225               play(3 * FRAMES);
1226           }
1227           report();
1228           break;
1229         case SM_CANCEL:
1230           D(("SM_CANCEL %s",  sm.id));
1231           t = removetrack(sm.id);
1232           if(t) {
1233             if(t == playing) {
1234               sm.type = SM_FINISHED;
1235               strcpy(sm.id, playing->id);
1236               speaker_send(1, &sm, 0);
1237               playing = 0;
1238             }
1239             destroy(t);
1240           } else
1241             error(0, "SM_CANCEL for unknown track %s", sm.id);
1242           report();
1243           break;
1244         case SM_RELOAD:
1245           D(("SM_RELOAD"));
1246           if(config_read()) error(0, "cannot read configuration");
1247           info("reloaded configuration");
1248           break;
1249         default:
1250           error(0, "unknown message type %d", sm.type);
1251         }
1252     }
1253     /* Read in any buffered data */
1254     for(t = tracks; t; t = t->next)
1255       if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
1256          fill(t);
1257     /* Maybe we finished playing a track somewhere in the above */
1258     maybe_finished();
1259     /* If we don't need the sound device for now then close it for the benefit
1260      * of anyone else who wants it. */
1261     if((!playing || paused) && device_state == device_open)
1262       idle();
1263     /* If we've not reported out state for a second do so now. */
1264     if(time(0) > last_report)
1265       report();
1266   }
1267 }
1268
1269 int main(int argc, char **argv) {
1270   int n;
1271
1272   set_progname(argv);
1273   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
1274   while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
1275     switch(n) {
1276     case 'h': help();
1277     case 'V': version();
1278     case 'c': configfile = optarg; break;
1279     case 'd': debugging = 1; break;
1280     case 'D': debugging = 0; break;
1281     default: fatal(0, "invalid option");
1282     }
1283   }
1284   if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
1285   /* If stderr is a TTY then log there, otherwise to syslog. */
1286   if(!isatty(2)) {
1287     openlog(progname, LOG_PID, LOG_DAEMON);
1288     log_default = &log_syslog;
1289   }
1290   if(config_read()) fatal(0, "cannot read configuration");
1291   /* ignore SIGPIPE */
1292   signal(SIGPIPE, SIG_IGN);
1293   /* reap kids */
1294   signal(SIGCHLD, reap);
1295   /* set nice value */
1296   xnice(config->nice_speaker);
1297   /* change user */
1298   become_mortal();
1299   /* make sure we're not root, whatever the config says */
1300   if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
1301   /* identify the backend used to play */
1302   for(n = 0; backends[n].backend != -1; ++n)
1303     if(backends[n].backend == config->speaker_backend)
1304       break;
1305   if(backends[n].backend == -1)
1306     fatal(0, "unsupported backend %d", config->speaker_backend);
1307   backend = &backends[n];
1308   /* backend-specific initialization */
1309   backend->init();
1310   mainloop();
1311   info("stopped (parent terminated)");
1312   exit(0);
1313 }
1314
1315 /*
1316 Local Variables:
1317 c-basic-offset:2
1318 comment-column:40
1319 fill-column:79
1320 indent-tabs-mode:nil
1321 End:
1322 */