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