chiark / gitweb /
move audio translation to the right place
[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 processs
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  * For the <a href="http://www.alsa-project.org/">ALSA</a> API, 8- and 16- bit
29  * stereo and mono are supported, with any sample rate (within the limits that
30  * 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  * This program deliberately does not use the garbage collector even though it
43  * might be convenient to do so.  This is for two reasons.  Firstly some sound
44  * APIs use thread threads and we do not want to have to deal with potential
45  * interactions between threading and garbage collection.  Secondly this
46  * process needs to be able to respond quickly and this is not compatible with
47  * the collector hanging the program even relatively briefly.
48  */
49
50 #include <config.h>
51 #include "types.h"
52
53 #include <getopt.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <locale.h>
57 #include <syslog.h>
58 #include <unistd.h>
59 #include <errno.h>
60 #include <ao/ao.h>
61 #include <string.h>
62 #include <assert.h>
63 #include <sys/select.h>
64 #include <sys/wait.h>
65 #include <time.h>
66 #include <fcntl.h>
67 #include <poll.h>
68 #include <sys/socket.h>
69 #include <netdb.h>
70 #include <gcrypt.h>
71 #include <sys/uio.h>
72
73 #include "configuration.h"
74 #include "syscalls.h"
75 #include "log.h"
76 #include "defs.h"
77 #include "mem.h"
78 #include "speaker.h"
79 #include "user.h"
80 #include "addr.h"
81 #include "timeval.h"
82 #include "rtp.h"
83
84 #if API_ALSA
85 #include <alsa/asoundlib.h>
86 #endif
87
88 #ifdef WORDS_BIGENDIAN
89 # define MACHINE_AO_FMT AO_FMT_BIG
90 #else
91 # define MACHINE_AO_FMT AO_FMT_LITTLE
92 #endif
93
94 /** @brief How many seconds of input to buffer
95  *
96  * While any given connection has this much audio buffered, no more reads will
97  * be issued for that connection.  The decoder will have to wait.
98  */
99 #define BUFFER_SECONDS 5
100
101 #define FRAMES 4096                     /* Frame batch size */
102
103 /** @brief Bytes to send per network packet
104  *
105  * Don't make this too big or arithmetic will start to overflow.
106  */
107 #define NETWORK_BYTES 1024
108
109 /** @brief Maximum RTP playahead (seconds) */
110 #define RTP_AHEAD 2
111
112 /** @brief Maximum number of FDs to poll for */
113 #define NFDS 256
114
115 /** @brief Track structure
116  *
117  * Known tracks are kept in a linked list.  Usually there will be at most two
118  * of these but rearranging the queue can cause there to be more.
119  */
120 static struct track {
121   struct track *next;                   /* next track */
122   int fd;                               /* input FD */
123   char id[24];                          /* ID */
124   size_t start, used;                   /* start + bytes used */
125   int eof;                              /* input is at EOF */
126   int got_format;                       /* got format yet? */
127   ao_sample_format format;              /* sample format */
128   unsigned long long played;            /* number of frames played */
129   char *buffer;                         /* sample buffer */
130   size_t size;                          /* sample buffer size */
131   int slot;                             /* poll array slot */
132 } *tracks, *playing;                    /* all tracks + playing track */
133
134 static time_t last_report;              /* when we last reported */
135 static int paused;                      /* pause status */
136 static ao_sample_format pcm_format;     /* current format if aodev != 0 */
137 static size_t bpf;                      /* bytes per frame */
138 static struct pollfd fds[NFDS];         /* if we need more than that */
139 static int fdno;                        /* fd number */
140 static size_t bufsize;                  /* buffer size */
141 #if API_ALSA
142 static snd_pcm_t *pcm;                  /* current pcm handle */
143 static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
144 #endif
145 static int ready;                       /* ready to send audio */
146 static int forceplay;                   /* frames to force play */
147 static int cmdfd = -1;                  /* child process input */
148 static int bfd = -1;                    /* broadcast FD */
149 static uint32_t rtp_time;               /* RTP timestamp */
150 static struct timeval rtp_time_real;    /* corresponding real time */
151 static uint16_t rtp_seq;                /* frame sequence number */
152 static uint32_t rtp_id;                 /* RTP SSRC */
153 static int idled;                       /* set when idled */
154 static int audio_errors;                /* audio error counter */
155
156 static const struct option options[] = {
157   { "help", no_argument, 0, 'h' },
158   { "version", no_argument, 0, 'V' },
159   { "config", required_argument, 0, 'c' },
160   { "debug", no_argument, 0, 'd' },
161   { "no-debug", no_argument, 0, 'D' },
162   { 0, 0, 0, 0 }
163 };
164
165 /* Display usage message and terminate. */
166 static void help(void) {
167   xprintf("Usage:\n"
168           "  disorder-speaker [OPTIONS]\n"
169           "Options:\n"
170           "  --help, -h              Display usage message\n"
171           "  --version, -V           Display version number\n"
172           "  --config PATH, -c PATH  Set configuration file\n"
173           "  --debug, -d             Turn on debugging\n"
174           "\n"
175           "Speaker process for DisOrder.  Not intended to be run\n"
176           "directly.\n");
177   xfclose(stdout);
178   exit(0);
179 }
180
181 /* Display version number and terminate. */
182 static void version(void) {
183   xprintf("disorder-speaker version %s\n", disorder_version_string);
184   xfclose(stdout);
185   exit(0);
186 }
187
188 /** @brief Return the number of bytes per frame in @p format */
189 static size_t bytes_per_frame(const ao_sample_format *format) {
190   return format->channels * format->bits / 8;
191 }
192
193 /** @brief Find track @p id, maybe creating it if not found */
194 static struct track *findtrack(const char *id, int create) {
195   struct track *t;
196
197   D(("findtrack %s %d", id, create));
198   for(t = tracks; t && strcmp(id, t->id); t = t->next)
199     ;
200   if(!t && create) {
201     t = xmalloc(sizeof *t);
202     t->next = tracks;
203     strcpy(t->id, id);
204     t->fd = -1;
205     tracks = t;
206     /* The initial input buffer will be the sample format. */
207     t->buffer = (void *)&t->format;
208     t->size = sizeof t->format;
209   }
210   return t;
211 }
212
213 /** @brief Remove track @p id (but do not destroy it) */
214 static struct track *removetrack(const char *id) {
215   struct track *t, **tt;
216
217   D(("removetrack %s", id));
218   for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
219     ;
220   if(t)
221     *tt = t->next;
222   return t;
223 }
224
225 /** @brief Destroy a track */
226 static void destroy(struct track *t) {
227   D(("destroy %s", t->id));
228   if(t->fd != -1) xclose(t->fd);
229   if(t->buffer != (void *)&t->format) free(t->buffer);
230   free(t);
231 }
232
233 /** @brief Notice a new connection */
234 static void acquire(struct track *t, int fd) {
235   D(("acquire %s %d", t->id, fd));
236   if(t->fd != -1)
237     xclose(t->fd);
238   t->fd = fd;
239   nonblock(fd);
240 }
241
242 /** @brief Return true if A and B denote identical libao formats, else false */
243 static int formats_equal(const ao_sample_format *a,
244                          const ao_sample_format *b) {
245   return (a->bits == b->bits
246           && a->rate == b->rate
247           && a->channels == b->channels
248           && a->byte_format == b->byte_format);
249 }
250
251 /** @brief Compute arguments to sox */
252 static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) {
253   int n;
254
255   *(*pp)++ = "-t.raw";
256   *(*pp)++ = "-s";
257   *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
258   *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
259   /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
260    * deployed! */
261   switch(config->sox_generation) {
262   case 0:
263     if(ao->bits != 8
264        && ao->byte_format != AO_FMT_NATIVE
265        && ao->byte_format != MACHINE_AO_FMT) {
266       *(*pp)++ = "-x";
267     }
268     switch(ao->bits) {
269     case 8: *(*pp)++ = "-b"; break;
270     case 16: *(*pp)++ = "-w"; break;
271     case 32: *(*pp)++ = "-l"; break;
272     case 64: *(*pp)++ = "-d"; break;
273     default: fatal(0, "cannot handle sample size %d", (int)ao->bits);
274     }
275     break;
276   case 1:
277     switch(ao->byte_format) {
278     case AO_FMT_NATIVE: break;
279     case AO_FMT_BIG: *(*pp)++ = "-B"; break;
280     case AO_FMT_LITTLE: *(*pp)++ = "-L"; break;
281     }
282     *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
283     break;
284   }
285 }
286
287 /** @brief Enable format translation
288  *
289  * If necessary, replaces a tracks inbound file descriptor with one connected
290  * to a sox invocation, which performs the required translation.
291  */
292 static void enable_translation(struct track *t) {
293   switch(config->speaker_backend) {
294   case BACKEND_COMMAND:
295   case BACKEND_NETWORK:
296     /* These backends need a specific sample format */
297     break;
298   case BACKEND_ALSA:
299     /* ALSA can cope */
300     return;
301   }
302   if(!formats_equal(&t->format, &config->sample_format)) {
303     char argbuf[1024], *q = argbuf;
304     const char *av[18], **pp = av;
305     int soxpipe[2];
306     pid_t soxkid;
307
308     *pp++ = "sox";
309     soxargs(&pp, &q, &t->format);
310     *pp++ = "-";
311     soxargs(&pp, &q, &config->sample_format);
312     *pp++ = "-";
313     *pp++ = 0;
314     if(debugging) {
315       for(pp = av; *pp; pp++)
316         D(("sox arg[%d] = %s", pp - av, *pp));
317       D(("end args"));
318     }
319     xpipe(soxpipe);
320     soxkid = xfork();
321     if(soxkid == 0) {
322       signal(SIGPIPE, SIG_DFL);
323       xdup2(t->fd, 0);
324       xdup2(soxpipe[1], 1);
325       fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
326       close(soxpipe[0]);
327       close(soxpipe[1]);
328       close(t->fd);
329       execvp("sox", (char **)av);
330       _exit(1);
331     }
332     D(("forking sox for format conversion (kid = %d)", soxkid));
333     close(t->fd);
334     close(soxpipe[1]);
335     t->fd = soxpipe[0];
336     t->format = config->sample_format;
337     ready = 0;
338   }
339 }
340
341 /** @brief Read data into a sample buffer
342  * @param t Pointer to track
343  * @return 0 on success, -1 on EOF
344  *
345  * This is effectively the read callback on @c t->fd.
346  */
347 static int fill(struct track *t) {
348   size_t where, left;
349   int n;
350
351   D(("fill %s: eof=%d used=%zu size=%zu  got_format=%d",
352      t->id, t->eof, t->used, t->size, t->got_format));
353   if(t->eof) return -1;
354   if(t->used < t->size) {
355     /* there is room left in the buffer */
356     where = (t->start + t->used) % t->size;
357     if(t->got_format) {
358       /* We are reading audio data, get as much as we can */
359       if(where >= t->start) left = t->size - where;
360       else left = t->start - where;
361     } else
362       /* We are still waiting for the format, only get that */
363       left = sizeof (ao_sample_format) - t->used;
364     do {
365       n = read(t->fd, t->buffer + where, left);
366     } while(n < 0 && errno == EINTR);
367     if(n < 0) {
368       if(errno != EAGAIN) fatal(errno, "error reading sample stream");
369       return 0;
370     }
371     if(n == 0) {
372       D(("fill %s: eof detected", t->id));
373       t->eof = 1;
374       return -1;
375     }
376     t->used += n;
377     if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
378       assert(t->used == sizeof (ao_sample_format));
379       /* Check that our assumptions are met. */
380       if(t->format.bits & 7)
381         fatal(0, "bits per sample not a multiple of 8");
382       /* If the input format is unsuitable, arrange to translate it */
383       enable_translation(t);
384       /* Make a new buffer for audio data. */
385       t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
386       t->buffer = xmalloc(t->size);
387       t->used = 0;
388       t->got_format = 1;
389       D(("got format for %s", t->id));
390     }
391   }
392   return 0;
393 }
394
395 /** @brief Close the sound device */
396 static void idle(void) {
397   D(("idle"));
398 #if API_ALSA
399   if(config->speaker_backend == BACKEND_ALSA && pcm) {
400     int  err;
401
402     if((err = snd_pcm_nonblock(pcm, 0)) < 0)
403       fatal(0, "error calling snd_pcm_nonblock: %d", err);
404     D(("draining pcm"));
405     snd_pcm_drain(pcm);
406     D(("closing pcm"));
407     snd_pcm_close(pcm);
408     pcm = 0;
409     forceplay = 0;
410     D(("released audio device"));
411   }
412 #endif
413   idled = 1;
414   ready = 0;
415 }
416
417 /** @brief Abandon the current track */
418 static void abandon(void) {
419   struct speaker_message sm;
420
421   D(("abandon"));
422   memset(&sm, 0, sizeof sm);
423   sm.type = SM_FINISHED;
424   strcpy(sm.id, playing->id);
425   speaker_send(1, &sm, 0);
426   removetrack(playing->id);
427   destroy(playing);
428   playing = 0;
429   forceplay = 0;
430 }
431
432 #if API_ALSA
433 /** @brief Log ALSA parameters */
434 static void log_params(snd_pcm_hw_params_t *hwparams,
435                        snd_pcm_sw_params_t *swparams) {
436   snd_pcm_uframes_t f;
437   unsigned u;
438
439   return;                               /* too verbose */
440   if(hwparams) {
441     /* TODO */
442   }
443   if(swparams) {
444     snd_pcm_sw_params_get_silence_size(swparams, &f);
445     info("sw silence_size=%lu", (unsigned long)f);
446     snd_pcm_sw_params_get_silence_threshold(swparams, &f);
447     info("sw silence_threshold=%lu", (unsigned long)f);
448     snd_pcm_sw_params_get_sleep_min(swparams, &u);
449     info("sw sleep_min=%lu", (unsigned long)u);
450     snd_pcm_sw_params_get_start_threshold(swparams, &f);
451     info("sw start_threshold=%lu", (unsigned long)f);
452     snd_pcm_sw_params_get_stop_threshold(swparams, &f);
453     info("sw stop_threshold=%lu", (unsigned long)f);
454     snd_pcm_sw_params_get_xfer_align(swparams, &f);
455     info("sw xfer_align=%lu", (unsigned long)f);
456   }
457 }
458 #endif
459
460 /** @brief Enable sound output
461  *
462  * Makes sure the sound device is open and has the right sample format.  Return
463  * 0 on success and -1 on error.
464  */
465 static int activate(void) {
466   /* If we don't know the format yet we cannot start. */
467   if(!playing->got_format) {
468     D((" - not got format for %s", playing->id));
469     return -1;
470   }
471   switch(config->speaker_backend) {
472   case BACKEND_COMMAND:
473   case BACKEND_NETWORK:
474     if(!ready) {
475       pcm_format = config->sample_format;
476       bufsize = 3 * FRAMES;
477       bpf = bytes_per_frame(&config->sample_format);
478       D(("acquired audio device"));
479       ready = 1;
480     }
481     return 0;
482   case BACKEND_ALSA:
483 #if API_ALSA
484     /* If we need to change format then close the current device. */
485     if(pcm && !formats_equal(&playing->format, &pcm_format))
486       idle();
487     if(!pcm) {
488       snd_pcm_hw_params_t *hwparams;
489       snd_pcm_sw_params_t *swparams;
490       snd_pcm_uframes_t pcm_bufsize;
491       int err;
492       int sample_format = 0;
493       unsigned rate;
494
495       D(("snd_pcm_open"));
496       if((err = snd_pcm_open(&pcm,
497                              config->device,
498                              SND_PCM_STREAM_PLAYBACK,
499                              SND_PCM_NONBLOCK))) {
500         error(0, "error from snd_pcm_open: %d", err);
501         goto error;
502       }
503       snd_pcm_hw_params_alloca(&hwparams);
504       D(("set up hw params"));
505       if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
506         fatal(0, "error from snd_pcm_hw_params_any: %d", err);
507       if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
508                                              SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
509         fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
510       switch(playing->format.bits) {
511       case 8:
512         sample_format = SND_PCM_FORMAT_S8;
513         break;
514       case 16:
515         switch(playing->format.byte_format) {
516         case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
517         case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
518         case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
519           error(0, "unrecognized byte format %d", playing->format.byte_format);
520           goto fatal;
521         }
522         break;
523       default:
524         error(0, "unsupported sample size %d", playing->format.bits);
525         goto fatal;
526       }
527       if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
528                                              sample_format)) < 0) {
529         error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
530               sample_format, err);
531         goto fatal;
532       }
533       rate = playing->format.rate;
534       if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
535         error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
536               playing->format.rate, err);
537         goto fatal;
538       }
539       if(rate != (unsigned)playing->format.rate)
540         info("want rate %d, got %u", playing->format.rate, rate);
541       if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
542                                                playing->format.channels)) < 0) {
543         error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
544               playing->format.channels, err);
545         goto fatal;
546       }
547       bufsize = 3 * FRAMES;
548       pcm_bufsize = bufsize;
549       if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
550                                                        &pcm_bufsize)) < 0)
551         fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
552               3 * FRAMES, err);
553       if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
554         info("asked for PCM buffer of %d frames, got %d",
555              3 * FRAMES, (int)pcm_bufsize);
556       last_pcm_bufsize = pcm_bufsize;
557       if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
558         fatal(0, "error calling snd_pcm_hw_params: %d", err);
559       D(("set up sw params"));
560       snd_pcm_sw_params_alloca(&swparams);
561       if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
562         fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
563       if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
564         fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
565               FRAMES, err);
566       if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
567         fatal(0, "error calling snd_pcm_sw_params: %d", err);
568       pcm_format = playing->format;
569       bpf = bytes_per_frame(&pcm_format);
570       D(("acquired audio device"));
571       log_params(hwparams, swparams);
572       ready = 1;
573     }
574     return 0;
575   fatal:
576     abandon();
577   error:
578     /* We assume the error is temporary and that we'll retry in a bit. */
579     if(pcm) {
580       snd_pcm_close(pcm);
581       pcm = 0;
582     }
583     return -1;
584 #endif
585   default:
586     assert(!"reached");
587   }
588 }
589
590 /* Check to see whether the current track has finished playing */
591 static void maybe_finished(void) {
592   if(playing
593      && playing->eof
594      && (!playing->got_format
595          || playing->used < bytes_per_frame(&playing->format)))
596     abandon();
597 }
598
599 static void fork_cmd(void) {
600   pid_t cmdpid;
601   int pfd[2];
602   if(cmdfd != -1) close(cmdfd);
603   xpipe(pfd);
604   cmdpid = xfork();
605   if(!cmdpid) {
606     signal(SIGPIPE, SIG_DFL);
607     xdup2(pfd[0], 0);
608     close(pfd[0]);
609     close(pfd[1]);
610     execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
611     fatal(errno, "error execing /bin/sh");
612   }
613   close(pfd[0]);
614   cmdfd = pfd[1];
615   D(("forked cmd %d, fd = %d", cmdpid, cmdfd));
616 }
617
618 static void play(size_t frames) {
619   size_t avail_bytes, write_bytes, written_frames;
620   ssize_t written_bytes;
621   struct rtp_header header;
622   struct iovec vec[2];
623
624   if(activate()) {
625     if(playing)
626       forceplay = frames;
627     else
628       forceplay = 0;                    /* Must have called abandon() */
629     return;
630   }
631   D(("play: play %zu/%zu%s %dHz %db %dc",  frames, playing->used / bpf,
632      playing->eof ? " EOF" : "",
633      playing->format.rate,
634      playing->format.bits,
635      playing->format.channels));
636   /* If we haven't got enough bytes yet wait until we have.  Exception: when
637    * we are at eof. */
638   if(playing->used < frames * bpf && !playing->eof) {
639     forceplay = frames;
640     return;
641   }
642   /* We have got enough data so don't force play again */
643   forceplay = 0;
644   /* Figure out how many frames there are available to write */
645   if(playing->start + playing->used > playing->size)
646     avail_bytes = playing->size - playing->start;
647   else
648     avail_bytes = playing->used;
649
650   switch(config->speaker_backend) {
651 #if API_ALSA
652   case BACKEND_ALSA: {
653     snd_pcm_sframes_t pcm_written_frames;
654     size_t avail_frames;
655     int err;
656
657     avail_frames = avail_bytes / bpf;
658     if(avail_frames > frames)
659       avail_frames = frames;
660     if(!avail_frames)
661       return;
662     pcm_written_frames = snd_pcm_writei(pcm,
663                                         playing->buffer + playing->start,
664                                         avail_frames);
665     D(("actually play %zu frames, wrote %d",
666        avail_frames, (int)pcm_written_frames));
667     if(pcm_written_frames < 0) {
668       switch(pcm_written_frames) {
669         case -EPIPE:                        /* underrun */
670           error(0, "snd_pcm_writei reports underrun");
671           if((err = snd_pcm_prepare(pcm)) < 0)
672             fatal(0, "error calling snd_pcm_prepare: %d", err);
673           return;
674         case -EAGAIN:
675           return;
676         default:
677           fatal(0, "error calling snd_pcm_writei: %d",
678                 (int)pcm_written_frames);
679       }
680     }
681     written_frames = pcm_written_frames;
682     written_bytes = written_frames * bpf;
683     break;
684   }
685 #endif
686   case BACKEND_COMMAND:
687     if(avail_bytes > frames * bpf)
688       avail_bytes = frames * bpf;
689     written_bytes = write(cmdfd, playing->buffer + playing->start,
690                           avail_bytes);
691     D(("actually play %zu bytes, wrote %d",
692        avail_bytes, (int)written_bytes));
693     if(written_bytes < 0) {
694       switch(errno) {
695         case EPIPE:
696           error(0, "hmm, command died; trying another");
697           fork_cmd();
698           return;
699         case EAGAIN:
700           return;
701       }
702     }
703     written_frames = written_bytes / bpf; /* good enough */
704     break;
705   case BACKEND_NETWORK:
706     /* We transmit using RTP (RFC3550) and attempt to conform to the internet
707      * AVT profile (RFC3551). */
708     if(rtp_time_real.tv_sec == 0)
709       xgettimeofday(&rtp_time_real, 0);
710     if(idled) {
711       struct timeval now;
712       xgettimeofday(&now, 0);
713       /* There's been a gap.  Fix up the RTP time accordingly. */
714       const long offset =  (((now.tv_sec + now.tv_usec /1000000.0)
715                              - (rtp_time_real.tv_sec + rtp_time_real.tv_usec / 1000000.0)) 
716                             * playing->format.rate * playing->format.channels);
717       if(offset >= 0) {
718         info("offset RTP timestamp by %ld", offset);
719         rtp_time += offset;
720       }
721       rtp_time_real = now;
722     }
723     header.vpxcc = 2 << 6;              /* V=2, P=0, X=0, CC=0 */
724     header.seq = htons(rtp_seq++);
725     header.timestamp = htonl(rtp_time);
726     header.ssrc = rtp_id;
727     header.mpt = (idled ? 0x80 : 0x00) | 10;
728     /* 10 = L16 = 16-bit x 2 x 44100KHz.  We ought to deduce this value from
729      * the sample rate (in a library somewhere so that configuration.c can rule
730      * out invalid rates).
731      */
732     idled = 0;
733     if(avail_bytes > NETWORK_BYTES - sizeof header) {
734       avail_bytes = NETWORK_BYTES - sizeof header;
735       avail_bytes -= avail_bytes % bpf;
736     }
737     /* "The RTP clock rate used for generating the RTP timestamp is independent
738      * of the number of channels and the encoding; it equals the number of
739      * sampling periods per second.  For N-channel encodings, each sampling
740      * period (say, 1/8000 of a second) generates N samples. (This terminology
741      * is standard, but somewhat confusing, as the total number of samples
742      * generated per second is then the sampling rate times the channel
743      * count.)"
744      */
745     write_bytes = avail_bytes;
746 #if 0
747     while(write_bytes > 0 && (uint32_t)(playing->buffer + playing->start + write_bytes - 4) == 0)
748       write_bytes -= 4;
749 #endif
750     if(write_bytes) {
751       vec[0].iov_base = (void *)&header;
752       vec[0].iov_len = sizeof header;
753       vec[1].iov_base = playing->buffer + playing->start;
754       vec[1].iov_len = avail_bytes;
755 #if 0
756       {
757         char buffer[3 * sizeof header + 1];
758         size_t n;
759         const uint8_t *ptr = (void *)&header;
760         
761         for(n = 0; n < sizeof header; ++n)
762           sprintf(&buffer[3 * n], "%02x ", *ptr++);
763         info(buffer);
764       }
765 #endif
766       do {
767         written_bytes = writev(bfd,
768                                vec,
769                                2);
770       } while(written_bytes < 0 && errno == EINTR);
771       if(written_bytes < 0) {
772         error(errno, "error transmitting audio data");
773         ++audio_errors;
774         if(audio_errors == 10)
775           fatal(0, "too many audio errors");
776       return;
777       }
778     } else
779     audio_errors /= 2;
780     written_bytes = avail_bytes;
781     written_frames = written_bytes / bpf;
782     /* Advance RTP's notion of the time */
783     rtp_time += written_frames * playing->format.channels;
784     /* Advance the corresponding real time */
785     assert(NETWORK_BYTES <= 2000);      /* else risk overflowing 32 bits */
786     rtp_time_real.tv_usec += written_frames * 1000000 / playing->format.rate;
787     if(rtp_time_real.tv_usec >= 1000000) {
788       ++rtp_time_real.tv_sec;
789       rtp_time_real.tv_usec -= 1000000;
790     }
791     assert(rtp_time_real.tv_usec < 1000000);
792     break;
793   default:
794     assert(!"reached");
795   }
796   /* written_bytes and written_frames had better both be set and correct by
797    * this point */
798   playing->start += written_bytes;
799   playing->used -= written_bytes;
800   playing->played += written_frames;
801   /* If the pointer is at the end of the buffer (or the buffer is completely
802    * empty) wrap it back to the start. */
803   if(!playing->used || playing->start == playing->size)
804     playing->start = 0;
805   frames -= written_frames;
806 }
807
808 /* Notify the server what we're up to. */
809 static void report(void) {
810   struct speaker_message sm;
811
812   if(playing && playing->buffer != (void *)&playing->format) {
813     memset(&sm, 0, sizeof sm);
814     sm.type = paused ? SM_PAUSED : SM_PLAYING;
815     strcpy(sm.id, playing->id);
816     sm.data = playing->played / playing->format.rate;
817     speaker_send(1, &sm, 0);
818   }
819   time(&last_report);
820 }
821
822 static void reap(int __attribute__((unused)) sig) {
823   pid_t cmdpid;
824   int st;
825
826   do
827     cmdpid = waitpid(-1, &st, WNOHANG);
828   while(cmdpid > 0);
829   signal(SIGCHLD, reap);
830 }
831
832 static int addfd(int fd, int events) {
833   if(fdno < NFDS) {
834     fds[fdno].fd = fd;
835     fds[fdno].events = events;
836     return fdno++;
837   } else
838     return -1;
839 }
840
841 int main(int argc, char **argv) {
842   int n, fd, stdin_slot, alsa_slots, cmdfd_slot, bfd_slot, poke, timeout;
843   struct timeval now, delta;
844   struct track *t;
845   struct speaker_message sm;
846   struct addrinfo *res, *sres;
847   static const struct addrinfo pref = {
848     0,
849     PF_INET,
850     SOCK_DGRAM,
851     IPPROTO_UDP,
852     0,
853     0,
854     0,
855     0
856   };
857   static const struct addrinfo prefbind = {
858     AI_PASSIVE,
859     PF_INET,
860     SOCK_DGRAM,
861     IPPROTO_UDP,
862     0,
863     0,
864     0,
865     0
866   };
867   static const int one = 1;
868   char *sockname, *ssockname;
869 #if API_ALSA
870   int alsa_nslots = -1, err;
871 #endif
872
873   set_progname(argv);
874   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
875   while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
876     switch(n) {
877     case 'h': help();
878     case 'V': version();
879     case 'c': configfile = optarg; break;
880     case 'd': debugging = 1; break;
881     case 'D': debugging = 0; break;
882     default: fatal(0, "invalid option");
883     }
884   }
885   if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
886   /* If stderr is a TTY then log there, otherwise to syslog. */
887   if(!isatty(2)) {
888     openlog(progname, LOG_PID, LOG_DAEMON);
889     log_default = &log_syslog;
890   }
891   if(config_read()) fatal(0, "cannot read configuration");
892   /* ignore SIGPIPE */
893   signal(SIGPIPE, SIG_IGN);
894   /* reap kids */
895   signal(SIGCHLD, reap);
896   /* set nice value */
897   xnice(config->nice_speaker);
898   /* change user */
899   become_mortal();
900   /* make sure we're not root, whatever the config says */
901   if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
902   switch(config->speaker_backend) {
903   case BACKEND_ALSA:
904     info("selected ALSA backend");
905   case BACKEND_COMMAND:
906     info("selected command backend");
907     fork_cmd();
908     break;
909   case BACKEND_NETWORK:
910     res = get_address(&config->broadcast, &pref, &sockname);
911     if(!res) return -1;
912     if(config->broadcast_from.n) {
913       sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
914       if(!sres) return -1;
915     } else
916       sres = 0;
917     if((bfd = socket(res->ai_family,
918                      res->ai_socktype,
919                      res->ai_protocol)) < 0)
920       fatal(errno, "error creating broadcast socket");
921     if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
922       fatal(errno, "error settting SO_BROADCAST on broadcast socket");
923     /* We might well want to set additional broadcast- or multicast-related
924      * options here */
925     if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
926       fatal(errno, "error binding broadcast socket to %s", ssockname);
927     if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
928       fatal(errno, "error connecting broadcast socket to %s", sockname);
929     /* Select an SSRC */
930     gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
931     info("selected network backend, sending to %s", sockname);
932     if(config->sample_format.byte_format != AO_FMT_BIG) {
933       info("forcing big-endian sample format");
934       config->sample_format.byte_format = AO_FMT_BIG;
935     }
936     break;
937   default:
938     fatal(0, "unknown backend %d", config->speaker_backend);
939   }
940   while(getppid() != 1) {
941     fdno = 0;
942     /* Always ready for commands from the main server. */
943     stdin_slot = addfd(0, POLLIN);
944     /* Try to read sample data for the currently playing track if there is
945      * buffer space. */
946     if(playing && !playing->eof && playing->used < playing->size) {
947       playing->slot = addfd(playing->fd, POLLIN);
948     } else if(playing)
949       playing->slot = -1;
950     /* If forceplay is set then wait until it succeeds before waiting on the
951      * sound device. */
952     alsa_slots = -1;
953     cmdfd_slot = -1;
954     bfd_slot = -1;
955     /* By default we will wait up to a second before thinking about current
956      * state. */
957     timeout = 1000;
958     if(ready && !forceplay) {
959       switch(config->speaker_backend) {
960       case BACKEND_COMMAND:
961         /* We send sample data to the subprocess as fast as it can accept it.
962          * This isn't ideal as pause latency can be very high as a result. */
963         if(cmdfd >= 0)
964           cmdfd_slot = addfd(cmdfd, POLLOUT);
965         break;
966       case BACKEND_NETWORK:
967         /* We want to keep the notional playing point somewhere in the near
968          * future.  If it's too near then clients that attempt even the
969          * slightest amount of read-ahead will never catch up, and those that
970          * don't will skip whenever there's a trivial network delay.  If it's
971          * too far ahead then pause latency will be too high.
972          */
973         xgettimeofday(&now, 0);
974         delta = tvsub(rtp_time_real, now);
975         if(delta.tv_sec < RTP_AHEAD) {
976           D(("delta = %ld.%06ld", (long)delta.tv_sec, (long)delta.tv_usec));
977           bfd_slot = addfd(bfd, POLLOUT);
978           if(delta.tv_sec < 0)
979             rtp_time_real = now;        /* catch up */
980         }
981         break;
982 #if API_ALSA
983       case BACKEND_ALSA: {
984         /* We send sample data to ALSA as fast as it can accept it, relying on
985          * the fact that it has a relatively small buffer to minimize pause
986          * latency. */
987         int retry = 3;
988         
989         alsa_slots = fdno;
990         do {
991           retry = 0;
992           alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
993           if((alsa_nslots <= 0
994               || !(fds[alsa_slots].events & POLLOUT))
995              && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
996             error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
997             if((err = snd_pcm_prepare(pcm)))
998               fatal(0, "error calling snd_pcm_prepare: %d", err);
999           } else
1000             break;
1001         } while(retry-- > 0);
1002         if(alsa_nslots >= 0)
1003           fdno += alsa_nslots;
1004         break;
1005       }
1006 #endif
1007       default:
1008         assert(!"unknown backend");
1009       }
1010     }
1011     /* If any other tracks don't have a full buffer, try to read sample data
1012      * from them. */
1013     for(t = tracks; t; t = t->next)
1014       if(t != playing) {
1015         if(!t->eof && t->used < t->size) {
1016           t->slot = addfd(t->fd,  POLLIN | POLLHUP);
1017         } else
1018           t->slot = -1;
1019       }
1020     /* Wait for something interesting to happen */
1021     n = poll(fds, fdno, timeout);
1022     if(n < 0) {
1023       if(errno == EINTR) continue;
1024       fatal(errno, "error calling poll");
1025     }
1026     /* Play some sound before doing anything else */
1027     poke = 0;
1028     switch(config->speaker_backend) {
1029 #if API_ALSA
1030     case BACKEND_ALSA:
1031       if(alsa_slots != -1) {
1032         unsigned short alsa_revents;
1033         
1034         if((err = snd_pcm_poll_descriptors_revents(pcm,
1035                                                    &fds[alsa_slots],
1036                                                    alsa_nslots,
1037                                                    &alsa_revents)) < 0)
1038           fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
1039         if(alsa_revents & (POLLOUT | POLLERR))
1040           play(3 * FRAMES);
1041       } else
1042         poke = 1;
1043       break;
1044 #endif
1045     case BACKEND_COMMAND:
1046       if(cmdfd_slot != -1) {
1047         if(fds[cmdfd_slot].revents & (POLLOUT | POLLERR))
1048           play(3 * FRAMES);
1049       } else
1050         poke = 1;
1051       break;
1052     case BACKEND_NETWORK:
1053       if(bfd_slot != -1) {
1054         if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
1055           play(3 * FRAMES);
1056       } else
1057         poke = 1;
1058       break;
1059     }
1060     if(poke) {
1061       /* Some attempt to play must have failed */
1062       if(playing && !paused)
1063         play(forceplay);
1064       else
1065         forceplay = 0;                  /* just in case */
1066     }
1067     /* Perhaps we have a command to process */
1068     if(fds[stdin_slot].revents & POLLIN) {
1069       n = speaker_recv(0, &sm, &fd);
1070       if(n > 0)
1071         switch(sm.type) {
1072         case SM_PREPARE:
1073           D(("SM_PREPARE %s %d", sm.id, fd));
1074           if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
1075           t = findtrack(sm.id, 1);
1076           acquire(t, fd);
1077           break;
1078         case SM_PLAY:
1079           D(("SM_PLAY %s %d", sm.id, fd));
1080           if(playing) fatal(0, "got SM_PLAY but already playing something");
1081           t = findtrack(sm.id, 1);
1082           if(fd != -1) acquire(t, fd);
1083           playing = t;
1084           play(bufsize);
1085           report();
1086           break;
1087         case SM_PAUSE:
1088           D(("SM_PAUSE"));
1089           paused = 1;
1090           report();
1091           break;
1092         case SM_RESUME:
1093           D(("SM_RESUME"));
1094           if(paused) {
1095             paused = 0;
1096             if(playing)
1097               play(bufsize);
1098           }
1099           report();
1100           break;
1101         case SM_CANCEL:
1102           D(("SM_CANCEL %s",  sm.id));
1103           t = removetrack(sm.id);
1104           if(t) {
1105             if(t == playing) {
1106               sm.type = SM_FINISHED;
1107               strcpy(sm.id, playing->id);
1108               speaker_send(1, &sm, 0);
1109               playing = 0;
1110             }
1111             destroy(t);
1112           } else
1113             error(0, "SM_CANCEL for unknown track %s", sm.id);
1114           report();
1115           break;
1116         case SM_RELOAD:
1117           D(("SM_RELOAD"));
1118           if(config_read()) error(0, "cannot read configuration");
1119           info("reloaded configuration");
1120           break;
1121         default:
1122           error(0, "unknown message type %d", sm.type);
1123         }
1124     }
1125     /* Read in any buffered data */
1126     for(t = tracks; t; t = t->next)
1127       if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
1128          fill(t);
1129     /* We might be able to play now */
1130     if(ready && forceplay && playing && !paused)
1131       play(forceplay);
1132     /* Maybe we finished playing a track somewhere in the above */
1133     maybe_finished();
1134     /* If we don't need the sound device for now then close it for the benefit
1135      * of anyone else who wants it. */
1136     if((!playing || paused) && ready)
1137       idle();
1138     /* If we've not reported out state for a second do so now. */
1139     if(time(0) > last_report)
1140       report();
1141   }
1142   info("stopped (parent terminated)");
1143   exit(0);
1144 }
1145
1146 /*
1147 Local Variables:
1148 c-basic-offset:2
1149 comment-column:40
1150 fill-column:79
1151 indent-tabs-mode:nil
1152 End:
1153 */