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