chiark / gitweb /
playrtp junks old sample data in fill_buffer()
[disorder] / clients / playrtp.c
index 85adfa2c72f86c664bb0f4906e2d8eb19a7335e6..33623ab3dcb4608e6d25ef8c285c20221a1c45b6 100644 (file)
 /** @file clients/playrtp.c
  * @brief RTP player
  *
- * This RTP player supports Linux (ALSA) and Darwin (Core Audio) systems.
+ * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</a>)
+ * and Apple Mac (<a
+ * href="http://developer.apple.com/audio/coreaudio.html">Core Audio</a>)
+ * systems.  There is no support for Microsoft Windows yet, and that will in
+ * fact probably an entirely separate program.
+ *
+ * The program runs (at least) three threads.  listen_thread() is responsible
+ * for reading RTP packets off the wire and adding them to the linked list @ref
+ * received_packets, assuming they are basically sound.  queue_thread() takes
+ * packets off this linked list and adds them to @ref packets (an operation
+ * which might be much slower due to contention for @ref lock).
+ *
+ * The main thread is responsible for actually playing audio.  In ALSA this
+ * means it waits until ALSA says it's ready for more audio which it then
+ * plays.
+ *
+ * InCore Audio the main thread is only responsible for starting and stopping
+ * play: the system does the actual playback in its own private thread, and
+ * calls adioproc() to fetch the audio data.
+ *
+ * Sometimes it happens that there is no audio available to play.  This may
+ * because the server went away, or a packet was dropped, or the server
+ * deliberately did not send any sound because it encountered a silence.
+ *
+ * Assumptions:
+ * - it is safe to read uint32_t values without a lock protecting them
  */
 
 #include <config.h>
@@ -47,6 +72,7 @@
 #include "defs.h"
 #include "vector.h"
 #include "heap.h"
+#include "timeval.h"
 
 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
 # include <CoreAudio/AudioHardware.h>
@@ -77,11 +103,6 @@ static const char *device;
  * We'll stop playing if there's only this many samples in the buffer. */
 static unsigned minbuffer = 2 * 44100 / 10;  /* 0.2 seconds */
 
-/** @brief Maximum sample size
- *
- * The maximum supported size (in bytes) of one sample. */
-#define MAXSAMPLESIZE 2
-
 /** @brief Buffer high watermark
  *
  * We'll only start playing when this many samples are available. */
@@ -105,6 +126,9 @@ static unsigned maxbuffer;
  * timestamp.
  */
 struct packet {
+  /** @brief Next packet in @ref next_free_packet or @ref received_packets */
+  struct packet *next;
+  
   /** @brief Number of samples in this packet */
   uint32_t nsamples;
 
@@ -118,17 +142,18 @@ struct packet {
   /** @brief Flags
    *
    * Valid values are:
-   * - @ref IDLE: the idle bit was set in the RTP packet
+   * - @ref IDLE - the idle bit was set in the RTP packet
    */
   unsigned flags;
-#define IDLE 0x0001                     /**< idle bit set in RTP packet */
+/** @brief idle bit set in RTP packet*/
+#define IDLE 0x0001
 
   /** @brief Raw sample data
    *
    * Only the first @p nsamples samples are defined; the rest is uninitialized
    * data.
    */
-  unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE];
+  uint16_t samples_raw[MAXSAMPLES];
 };
 
 /** @brief Return true iff \f$a < b\f$ in sequence-space arithmetic
@@ -161,6 +186,35 @@ static inline int lt_packet(const struct packet *a, const struct packet *b) {
   return lt(a->timestamp, b->timestamp);
 }
 
+/** @brief Received packets
+ * Protected by @ref receive_lock
+ *
+ * Received packets are added to this list, and queue_thread() picks them off
+ * it and adds them to @ref packets.  Whenever a packet is added to it, @ref
+ * receive_cond is signalled.
+ */
+static struct packet *received_packets;
+
+/** @brief Tail of @ref received_packets
+ * Protected by @ref receive_lock
+ */
+static struct packet **received_tail = &received_packets;
+
+/** @brief Lock protecting @ref received_packets 
+ *
+ * Only listen_thread() and queue_thread() ever hold this lock.  It is vital
+ * that queue_thread() not hold it any longer than it strictly has to. */
+static pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER;
+
+/** @brief Condition variable signalled when @ref received_packets is updated
+ *
+ * Used by listen_thread() to notify queue_thread() that it has added another
+ * packet to @ref received_packets. */
+static pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER;
+
+/** @brief Length of @ref received_packets */
+static uint32_t nreceived;
+
 /** @struct pheap 
  * @brief Binary heap of packets ordered by timestamp */
 HEAP_TYPE(pheap, struct packet *, lt_packet);
@@ -168,8 +222,12 @@ HEAP_TYPE(pheap, struct packet *, lt_packet);
 /** @brief Binary heap of received packets */
 static struct pheap packets;
 
-/** @brief Total number of samples available */
-static unsigned long nsamples;
+/** @brief Total number of samples available
+ *
+ * We make this volatile because we inspect it without a protecting lock,
+ * so the usual pthread_* guarantees aren't available.
+ */
+static volatile uint32_t nsamples;
 
 /** @brief Timestamp of next packet to play.
  *
@@ -183,6 +241,12 @@ static uint32_t next_timestamp;
  * This is true when playing and false when just buffering. */
 static int active;
 
+/** @brief Lock protecting @ref packets */
+static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
+
+/** @brief Condition variable signalled whenever @ref packets is changed */
+static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
+
 /** @brief Structure of free packet list */
 union free_packet {
   struct packet p;
@@ -215,14 +279,8 @@ static union free_packet *next_free_packet;
  */
 static size_t count_free_packets;
 
-/** @brief Lock protecting @ref packets 
- *
- * This also protects the packet memory allocation infrastructure, @ref
- * free_packets and @ref next_free_packet. */
-static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
-
-/** @brief Condition variable signalled whenever @ref packets is changed */
-static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
+/** @brief Lock protecting packet allocator */
+static pthread_mutex_t mem_lock = PTHREAD_MUTEX_INITIALIZER;
 
 static const struct option options[] = {
   { "help", no_argument, 0, 'h' },
@@ -232,15 +290,15 @@ static const struct option options[] = {
   { "min", required_argument, 0, 'm' },
   { "max", required_argument, 0, 'x' },
   { "buffer", required_argument, 0, 'b' },
+  { "rcvbuf", required_argument, 0, 'R' },
   { 0, 0, 0, 0 }
 };
 
-/** @brief Return a new packet
- *
- * Assumes that @ref lock is held. */
+/** @brief Return a new packet */
 static struct packet *new_packet(void) {
   struct packet *p;
-
+  
+  pthread_mutex_lock(&mem_lock);
   if(free_packets) {
     p = &free_packets->p;
     free_packets = free_packets->next;
@@ -252,16 +310,17 @@ static struct packet *new_packet(void) {
     p = &(next_free_packet++)->p;
     --count_free_packets;
   }
+  pthread_mutex_unlock(&mem_lock);
   return p;
 }
 
-/** @brief Free a packet
- *
- * Assumes that @ref lock is held. */
+/** @brief Free a packet */
 static void free_packet(struct packet *p) {
   union free_packet *u = (union free_packet *)p;
+  pthread_mutex_lock(&mem_lock);
   u->next = free_packets;
   free_packets = u;
+  pthread_mutex_unlock(&mem_lock);
 }
 
 /** @brief Drop the first packet
@@ -277,10 +336,57 @@ static void drop_first_packet(void) {
   }
 }
 
+/** @brief Background thread adding packets to heap
+ *
+ * This just transfers packets from @ref received_packets to @ref packets.  It
+ * is important that it holds @ref receive_lock for as little time as possible,
+ * in order to minimize the interval between calls to read() in
+ * listen_thread().
+ */
+static void *queue_thread(void attribute((unused)) *arg) {
+  struct packet *p;
+
+  for(;;) {
+    /* Get the next packet */
+    pthread_mutex_lock(&receive_lock);
+    while(!received_packets)
+      pthread_cond_wait(&receive_cond, &receive_lock);
+    p = received_packets;
+    received_packets = p->next;
+    if(!received_packets)
+      received_tail = &received_packets;
+    --nreceived;
+    pthread_mutex_unlock(&receive_lock);
+    /* Add it to the heap */
+    pthread_mutex_lock(&lock);
+    pheap_insert(&packets, p);
+    nsamples += p->nsamples;
+    pthread_cond_broadcast(&cond);
+    pthread_mutex_unlock(&lock);
+  }
+}
+
 /** @brief Background thread collecting samples
  *
  * This function collects samples, perhaps converts them to the target format,
- * and adds them to the packet list. */
+ * and adds them to the packet list.
+ *
+ * It is crucial that the gap between successive calls to read() is as small as
+ * possible: otherwise packets will be dropped.
+ *
+ * We use a binary heap to ensure that the unavoidable effort is at worst
+ * logarithmic in the total number of packets - in fact if packets are mostly
+ * received in order then we will largely do constant work per packet since the
+ * newest packet will always be last.
+ *
+ * Of more concern is that we must acquire the lock on the heap to add a packet
+ * to it.  If this proves a problem in practice then the answer would be
+ * (probably doubly) linked list with new packets added the end and a second
+ * thread which reads packets off the list and adds them to the heap.
+ *
+ * We keep memory allocation (mostly) very fast by keeping pre-allocated
+ * packets around; see @ref new_packet().
+ */
 static void *listen_thread(void attribute((unused)) *arg) {
   struct packet *p = 0;
   int n;
@@ -290,15 +396,12 @@ static void *listen_thread(void attribute((unused)) *arg) {
   struct iovec iov[2];
 
   for(;;) {
-    if(!p) {
-      pthread_mutex_lock(&lock);
+    if(!p)
       p = new_packet();
-      pthread_mutex_unlock(&lock);
-    }
     iov[0].iov_base = &header;
     iov[0].iov_len = sizeof header;
     iov[1].iov_base = p->samples_raw;
-    iov[1].iov_len = sizeof p->samples_raw;
+    iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
     n = readv(rtpfd, iov, 2);
     if(n < 0) {
       switch(errno) {
@@ -321,7 +424,7 @@ static void *listen_thread(void attribute((unused)) *arg) {
            timestamp, next_timestamp);
       continue;
     }
-    pthread_mutex_lock(&lock);
+    p->next = 0;
     p->flags = 0;
     p->timestamp = timestamp;
     /* Convert to target format */
@@ -330,9 +433,6 @@ static void *listen_thread(void attribute((unused)) *arg) {
     switch(header.mpt & 0x7F) {
     case 10:
       p->nsamples = (n - sizeof header) / sizeof(uint16_t);
-      /* ALSA can do any necessary conversion itself (though it might be better
-       * to do any necessary conversion in the background) */
-      /* TODO we could readv into the buffer */
       break;
       /* TODO support other RFC3551 media types (when the speaker does) */
     default:
@@ -347,21 +447,27 @@ static void *listen_thread(void attribute((unused)) *arg) {
      * This is rather unsatisfactory: it means that if packets get heavily
      * out of order then we guarantee dropouts.  But for now... */
     if(nsamples >= maxbuffer) {
-      info("buffer full");
+      pthread_mutex_lock(&lock);
       while(nsamples >= maxbuffer)
         pthread_cond_wait(&cond, &lock);
+      pthread_mutex_unlock(&lock);
     }
-    /* Add the packet to the heap */
-    pheap_insert(&packets, p);
-    nsamples += p->nsamples;
+    /* Add the packet to the receive queue */
+    pthread_mutex_lock(&receive_lock);
+    *received_tail = p;
+    received_tail = &p->next;
+    ++nreceived;
+    pthread_cond_signal(&receive_cond);
+    pthread_mutex_unlock(&receive_lock);
     /* We'll need a new packet */
     p = 0;
-    pthread_cond_broadcast(&cond);
-    pthread_mutex_unlock(&lock);
   }
 }
 
-/** @brief Return true if @p p contains @p timestamp */
+/** @brief Return true if @p p contains @p timestamp
+ *
+ * Containment implies that a sample @p timestamp exists within the packet.
+ */
 static inline int contains(const struct packet *p, uint32_t timestamp) {
   const uint32_t packet_start = p->timestamp;
   const uint32_t packet_end = p->timestamp + p->nsamples;
@@ -370,6 +476,43 @@ static inline int contains(const struct packet *p, uint32_t timestamp) {
           && lt(timestamp, packet_end));
 }
 
+/** @brief Wait until the buffer is adequately full
+ *
+ * Must be called with @ref lock held.
+ */
+static void fill_buffer(void) {
+  while(nsamples)
+    drop_first_packet();
+  info("Buffering...");
+  while(nsamples < readahead)
+    pthread_cond_wait(&cond, &lock);
+  next_timestamp = pheap_first(&packets)->timestamp;
+  active = 1;
+}
+
+/** @brief Find next packet
+ * @return Packet to play or NULL if none found
+ *
+ * The return packet is merely guaranteed not to be in the past: it might be
+ * the first packet in the future rather than one that is actually suitable to
+ * play.
+ *
+ * Must be called with @ref lock held.
+ */
+static struct packet *next_packet(void) {
+  while(pheap_count(&packets)) {
+    struct packet *const p = pheap_first(&packets);
+    if(le(p->timestamp + p->nsamples, next_timestamp)) {
+      /* This packet is in the past.  Drop it and try another one. */
+      drop_first_packet();
+    } else
+      /* This packet is NOT in the past.  (It might be in the future
+       * however.) */
+      return p;
+  }
+  return 0;
+}
+
 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
 /** @brief Callback from Core Audio */
 static OSStatus adioproc
@@ -382,38 +525,20 @@ static OSStatus adioproc
      void attribute((unused)) *inClientData) {
   UInt32 nbuffers = outOutputData->mNumberBuffers;
   AudioBuffer *ab = outOutputData->mBuffers;
-  const struct packet *p;
   uint32_t samples_available;
-  struct timeval in, out;
 
-  gettimeofday(&in, 0);
   pthread_mutex_lock(&lock);
   while(nbuffers > 0) {
     float *samplesOut = ab->mData;
     size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
 
     while(samplesOutLeft > 0) {
-      /* Look for a suitable packet, dropping any unsuitable ones along the
-       * way.  Unsuitable packets are ones that are in the past. */
-      while(pheap_count(&packets)) {
-        p = pheap_first(&packets);
-        if(le(p->timestamp + p->nsamples, next_timestamp))
-          /* This packet is in the past.  Drop it and try another one. */
-          drop_first_packet();
-        else
-          /* This packet is NOT in the past.  (It might be in the future
-           * however.) */
-          break;
-      }
-      p = pheap_count(&packets) ? pheap_first(&packets) : 0;
+      const struct packet *p = next_packet();
       if(p && contains(p, next_timestamp)) {
-        if(p->flags & IDLE)
-          fprintf(stderr, "\nIDLE\n");
         /* This packet is ready to play */
         const uint32_t packet_end = p->timestamp + p->nsamples;
         const uint32_t offset = next_timestamp - p->timestamp;
-        const uint16_t *ptr =
-          (void *)(p->samples_raw + offset * sizeof (uint16_t));
+        const uint16_t *ptr = (void *)(p->samples_raw + offset);
 
         samples_available = packet_end - next_timestamp;
         if(samples_available > samplesOutLeft)
@@ -424,7 +549,6 @@ static OSStatus adioproc
           *samplesOut++ = (int16_t)ntohs(*ptr++) * (0.5 / 32767);
         /* We don't bother junking the packet - that'll be dealt with next time
          * round */
-        write(2, ".", 1);
       } else {
         /* No packet is ready to play (and there might be no packet at all) */
         samples_available = p ? p->timestamp - next_timestamp
@@ -436,24 +560,167 @@ static OSStatus adioproc
         next_timestamp += samples_available;
         samplesOut += samples_available;
         samplesOutLeft -= samples_available;
-        write(2, "?", 1);
       }
     }
     ++ab;
     --nbuffers;
   }
   pthread_mutex_unlock(&lock);
-  gettimeofday(&out, 0);
-  {
-    static double max;
-    double thistime = (out.tv_sec - in.tv_sec) + (out.tv_usec - in.tv_usec) / 1000000.0;
-    if(thistime > max)
-      fprintf(stderr, "adioproc: %8.8fs\n", max = thistime);
-  }
   return 0;
 }
 #endif
 
+
+#if API_ALSA
+/** @brief PCM handle */
+static snd_pcm_t *pcm;
+
+/** @brief True when @ref pcm is up and running */
+static int alsa_prepared = 1;
+
+/** @brief Initialize @ref pcm */
+static void setup_alsa(void) {
+  snd_pcm_hw_params_t *hwparams;
+  snd_pcm_sw_params_t *swparams;
+  /* Only support one format for now */
+  const int sample_format = SND_PCM_FORMAT_S16_BE;
+  unsigned rate = 44100;
+  const int channels = 2;
+  const int samplesize = channels * sizeof(uint16_t);
+  snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
+  /* If we can write more than this many samples we'll get a wakeup */
+  const int avail_min = 256;
+  int err;
+  
+  /* Open ALSA */
+  if((err = snd_pcm_open(&pcm,
+                         device ? device : "default",
+                         SND_PCM_STREAM_PLAYBACK,
+                         SND_PCM_NONBLOCK)))
+    fatal(0, "error from snd_pcm_open: %d", err);
+  /* Set up 'hardware' parameters */
+  snd_pcm_hw_params_alloca(&hwparams);
+  if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
+    fatal(0, "error from snd_pcm_hw_params_any: %d", err);
+  if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
+                                         SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
+    fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
+  if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
+                                         sample_format)) < 0)
+    
+    fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
+          sample_format, err);
+  if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
+    fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
+          rate, err);
+  if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
+                                           channels)) < 0)
+    fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
+          channels, err);
+  if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
+                                                   &pcm_bufsize)) < 0)
+    fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
+          MAXSAMPLES * samplesize * 3, err);
+  if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
+    fatal(0, "error calling snd_pcm_hw_params: %d", err);
+  /* Set up 'software' parameters */
+  snd_pcm_sw_params_alloca(&swparams);
+  if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
+    fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
+  if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
+    fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
+          avail_min, err);
+  if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
+    fatal(0, "error calling snd_pcm_sw_params: %d", err);
+}
+
+/** @brief Wait until ALSA wants some audio */
+static void wait_alsa(void) {
+  struct pollfd fds[64];
+  int nfds, err;
+  unsigned short events;
+
+  for(;;) {
+    do {
+      if((nfds = snd_pcm_poll_descriptors(pcm,
+                                          fds, sizeof fds / sizeof *fds)) < 0)
+        fatal(0, "error calling snd_pcm_poll_descriptors: %d", nfds);
+    } while(poll(fds, nfds, -1) < 0 && errno == EINTR);
+    if((err = snd_pcm_poll_descriptors_revents(pcm, fds, nfds, &events)))
+      fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
+    if(events & POLLOUT)
+      return;
+  }
+}
+
+/** @brief Play some sound via ALSA
+ * @param s Pointer to sample data
+ * @param n Number of samples
+ * @return 0 on success, -1 on non-fatal error
+ */
+static int alsa_writei(const void *s, size_t n) {
+  /* Do the write */
+  const snd_pcm_sframes_t frames_written = snd_pcm_writei(pcm, s, n / 2);
+  if(frames_written < 0) {
+    /* Something went wrong */
+    switch(frames_written) {
+    case -EAGAIN:
+      return 0;
+    case -EPIPE:
+      error(0, "error calling snd_pcm_writei: %ld",
+            (long)frames_written);
+      return -1;
+    default:
+      fatal(0, "error calling snd_pcm_writei: %ld",
+            (long)frames_written);
+    }
+  } else {
+    /* Success */
+    next_timestamp += frames_written * 2;
+    return 0;
+  }
+}
+
+/** @brief Play the relevant part of a packet
+ * @param p Packet to play
+ * @return 0 on success, -1 on non-fatal error
+ */
+static int alsa_play(const struct packet *p) {
+  return alsa_writei(p->samples_raw + next_timestamp - p->timestamp,
+                     (p->timestamp + p->nsamples) - next_timestamp);
+}
+
+/** @brief Play some silence
+ * @param p Next packet or NULL
+ * @return 0 on success, -1 on non-fatal error
+ */
+static int alsa_infill(const struct packet *p) {
+  static const uint16_t zeros[INFILL_SAMPLES];
+  size_t samples_available = INFILL_SAMPLES;
+
+  if(p && samples_available > p->timestamp - next_timestamp)
+    samples_available = p->timestamp - next_timestamp;
+  return alsa_writei(zeros, samples_available);
+}
+
+/** @brief Reset ALSA state after we lost synchronization */
+static void alsa_reset(int hard_reset) {
+  int err;
+
+  if((err = snd_pcm_nonblock(pcm, 0)))
+    fatal(0, "error calling snd_pcm_nonblock: %d", err);
+  if(hard_reset) {
+    if((err = snd_pcm_drop(pcm)))
+      fatal(0, "error calling snd_pcm_drop: %d", err);
+  } else
+    if((err = snd_pcm_drain(pcm)))
+      fatal(0, "error calling snd_pcm_drain: %d", err);
+  if((err = snd_pcm_nonblock(pcm, 1)))
+    fatal(0, "error calling snd_pcm_nonblock: %d", err);
+  alsa_prepared = 0;
+}
+#endif
+
 /** @brief Play an RTP stream
  *
  * This is the guts of the program.  It is responsible for:
@@ -468,214 +735,45 @@ static void play_rtp(void) {
 
   /* We receive and convert audio data in a background thread */
   pthread_create(&ltid, 0, listen_thread, 0);
+  /* We have a second thread to add received packets to the queue */
+  pthread_create(&ltid, 0, queue_thread, 0);
 #if API_ALSA
   {
-    snd_pcm_t *pcm;
-    snd_pcm_hw_params_t *hwparams;
-    snd_pcm_sw_params_t *swparams;
-    /* Only support one format for now */
-    const int sample_format = SND_PCM_FORMAT_S16_BE;
-    unsigned rate = 44100;
-    const int channels = 2;
-    const int samplesize = channels * sizeof(uint16_t);
-    snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
-    /* If we can write more than this many samples we'll get a wakeup */
-    const int avail_min = 256;
-    snd_pcm_sframes_t frames_written;
-    size_t samples_written;
-    int prepared = 1;
-    int err;
-    int infilling = 0, escape = 0;
-    time_t logged, now;
-    uint32_t packet_start, packet_end;
-
-    /* Open ALSA */
-    if((err = snd_pcm_open(&pcm,
-                           device ? device : "default",
-                           SND_PCM_STREAM_PLAYBACK,
-                           SND_PCM_NONBLOCK)))
-      fatal(0, "error from snd_pcm_open: %d", err);
-    /* Set up 'hardware' parameters */
-    snd_pcm_hw_params_alloca(&hwparams);
-    if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
-      fatal(0, "error from snd_pcm_hw_params_any: %d", err);
-    if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
-                                           SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
-      fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
-    if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
-                                           sample_format)) < 0)
-
-      fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
-            sample_format, err);
-    if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
-      fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
-            rate, err);
-    if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
-                                             channels)) < 0)
-      fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
-            channels, err);
-    if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
-                                                     &pcm_bufsize)) < 0)
-      fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
-            MAXSAMPLES * samplesize * 3, err);
-    if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
-      fatal(0, "error calling snd_pcm_hw_params: %d", err);
-    /* Set up 'software' parameters */
-    snd_pcm_sw_params_alloca(&swparams);
-    if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
-      fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
-    if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
-      fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
-            avail_min, err);
-    if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
-      fatal(0, "error calling snd_pcm_sw_params: %d", err);
-
-    /* Ready to go */
-
-    time(&logged);
+    struct packet *p;
+    int escape, err;
+
+    /* Open the sound device */
+    setup_alsa();
     pthread_mutex_lock(&lock);
     for(;;) {
       /* Wait for the buffer to fill up a bit */
-      logged = now;
-      info("%lu samples in buffer (%lus)", nsamples,
-           nsamples / (44100 * 2));
-      info("Buffering...");
-      while(nsamples < readahead)
-        pthread_cond_wait(&cond, &lock);
-      if(!prepared) {
+      fill_buffer();
+      if(!alsa_prepared) {
         if((err = snd_pcm_prepare(pcm)))
           fatal(0, "error calling snd_pcm_prepare: %d", err);
-        prepared = 1;
+        alsa_prepared = 1;
       }
-      active = 1;
-      infilling = 0;
       escape = 0;
-      logged = now;
-      info("%lu samples in buffer (%lus)", nsamples,
-           nsamples / (44100 * 2));
       info("Playing...");
-      /* Wait until the buffer empties out */
+      /* Keep playing until the buffer empties out, or ALSA tells us to get
+       * lost */
       while(nsamples >= minbuffer && !escape) {
-        time(&now);
-        if(now > logged + 10) {
-          logged = now;
-          info("%lu samples in buffer (%lus)", nsamples,
-               nsamples / (44100 * 2));
-        }
-        if(packets
-           && ge(next_timestamp, packets->timestamp + packets->nsamples)) {
-          info("dropping buffered past packet %"PRIx32" < %"PRIx32,
-               packets->timestamp, next_timestamp);
-          drop_first_packet();
-          continue;
-        }
         /* Wait for ALSA to ask us for more data */
         pthread_mutex_unlock(&lock);
-        write(2, ".", 1);               /* TODO remove me sometime */
-        switch(err = snd_pcm_wait(pcm, -1)) {
-        case 0:
-          info("snd_pcm_wait timed out");
-          break;
-        case 1:
-          break;
-        default:
-          fatal(0, "snd_pcm_wait returned %d", err);
-        }
+        wait_alsa();
         pthread_mutex_lock(&lock);
-        /* ALSA is ready for more data */
-        packet_start = packets->timestamp;
-        packet_end = packets->timestamp + packets->nsamples;
-        if(ge(next_timestamp, packet_start)
-           && lt(next_timestamp, packet_end)) {
-          /* The target timestamp is somewhere in this packet */
-          const uint32_t offset = next_timestamp - packets->timestamp;
-          const uint32_t samples_available = (packets->timestamp + packets->nsamples) - next_timestamp;
-          const size_t frames_available = samples_available / 2;
-
-          frames_written = snd_pcm_writei(pcm,
-                                          packets->samples_raw + offset,
-                                          frames_available);
-          if(frames_written < 0) {
-            switch(frames_written) {
-            case -EAGAIN:
-              info("snd_pcm_wait() returned but we got -EAGAIN!");
-              break;
-            case -EPIPE:
-              error(0, "error calling snd_pcm_writei: %ld",
-                    (long)frames_written);
-              escape = 1;
-              break;
-            default:
-              fatal(0, "error calling snd_pcm_writei: %ld",
-                    (long)frames_written);
-            }
-          } else {
-            samples_written = frames_written * 2;
-            next_timestamp += samples_written;
-            if(ge(next_timestamp, packet_end))
-              drop_first_packet();
-            infilling = 0;
-          }
-        } else {
-          /* We don't have anything to play!  We'd better play some 0s. */
-          static const uint16_t zeros[INFILL_SAMPLES];
-          size_t samples_available = INFILL_SAMPLES, frames_available;
-
-          /* If the maximum infill would take us past the start of the next
-           * packet then we truncate the infill to the right amount. */
-          if(lt(packets->timestamp,
-                next_timestamp + samples_available))
-            samples_available = packets->timestamp - next_timestamp;
-          if((int)samples_available < 0) {
-            info("packets->timestamp: %"PRIx32"  next_timestamp: %"PRIx32"  next+max: %"PRIx32"  available: %"PRIx32,
-                 packets->timestamp, next_timestamp,
-                 next_timestamp + INFILL_SAMPLES, samples_available);
-          }
-          frames_available = samples_available / 2;
-          if(!infilling) {
-            info("Infilling %d samples, next=%"PRIx32" packet=[%"PRIx32",%"PRIx32"]",
-                 samples_available, next_timestamp,
-                 packets->timestamp, packets->timestamp + packets->nsamples);
-            //infilling++;
-          }
-          frames_written = snd_pcm_writei(pcm,
-                                          zeros,
-                                          frames_available);
-          if(frames_written < 0) {
-            switch(frames_written) {
-            case -EAGAIN:
-              info("snd_pcm_wait() returned but we got -EAGAIN!");
-              break;
-            case -EPIPE:
-              error(0, "error calling snd_pcm_writei: %ld",
-                    (long)frames_written);
-              escape = 1;
-              break;
-            default:
-              fatal(0, "error calling snd_pcm_writei: %ld",
-                    (long)frames_written);
-            }
-          } else {
-            samples_written = frames_written * 2;
-            next_timestamp += samples_written;
-          }
-        }
+        /* ALSA is ready for more data, find something to play */
+        p = next_packet();
+        /* Play it or play some silence */
+        if(contains(p, next_timestamp))
+          escape = alsa_play(p);
+        else
+          escape = alsa_infill(p);
       }
       active = 0;
       /* We stop playing for a bit until the buffer re-fills */
       pthread_mutex_unlock(&lock);
-      if((err = snd_pcm_nonblock(pcm, 0)))
-        fatal(0, "error calling snd_pcm_nonblock: %d", err);
-      if(escape) {
-        if((err = snd_pcm_drop(pcm)))
-          fatal(0, "error calling snd_pcm_drop: %d", err);
-        escape = 0;
-      } else
-        if((err = snd_pcm_drain(pcm)))
-          fatal(0, "error calling snd_pcm_drain: %d", err);
-      if((err = snd_pcm_nonblock(pcm, 1)))
-        fatal(0, "error calling snd_pcm_nonblock: %d", err);
-      prepared = 0;
+      alsa_reset(escape);
       pthread_mutex_lock(&lock);
     }
 
@@ -721,9 +819,7 @@ static void play_rtp(void) {
     pthread_mutex_lock(&lock);
     for(;;) {
       /* Wait for the buffer to fill up a bit */
-      info("Buffering...");
-      while(nsamples < readahead)
-        pthread_cond_wait(&cond, &lock);
+      fill_buffer();
       /* Start playing now */
       info("Playing...");
       next_timestamp = pheap_first(&packets)->timestamp;
@@ -756,6 +852,7 @@ static void help(void) {
           "  --min, -m FRAMES        Buffer low water mark\n"
           "  --buffer, -b FRAMES     Buffer high water mark\n"
           "  --max, -x FRAMES        Buffer maximum size\n"
+          "  --rcvbuf, -R BYTES      Socket receive buffer size\n"
          "  --help, -h              Display usage message\n"
          "  --version, -V           Display version number\n"
           );
@@ -775,6 +872,8 @@ int main(int argc, char **argv) {
   struct addrinfo *res;
   struct stringlist sl;
   char *sockname;
+  int rcvbuf, target_rcvbuf = 131072;
+  socklen_t len;
 
   static const struct addrinfo prefs = {
     AI_PASSIVE,
@@ -789,7 +888,7 @@ int main(int argc, char **argv) {
 
   mem_init();
   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
-  while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:", options, 0)) >= 0) {
+  while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:R:", options, 0)) >= 0) {
     switch(n) {
     case 'h': help();
     case 'V': version();
@@ -799,6 +898,7 @@ int main(int argc, char **argv) {
     case 'b': readahead = 2 * atol(optarg); break;
     case 'x': maxbuffer = 2 * atol(optarg); break;
     case 'L': logfp = fopen(optarg, "w"); break;
+    case 'R': target_rcvbuf = atoi(optarg); break;
     default: fatal(0, "invalid option");
     }
   }
@@ -819,6 +919,22 @@ int main(int argc, char **argv) {
     fatal(errno, "error creating socket");
   if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
     fatal(errno, "error binding socket to %s", sockname);
+  len = sizeof rcvbuf;
+  if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
+    fatal(errno, "error calling getsockopt SO_RCVBUF");
+  if(target_rcvbuf > rcvbuf) {
+    if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
+                  &target_rcvbuf, sizeof target_rcvbuf) < 0)
+      error(errno, "error calling setsockopt SO_RCVBUF %d", 
+            target_rcvbuf);
+      /* We try to carry on anyway */
+    else
+      info("changed socket receive buffer from %d to %d",
+           rcvbuf, target_rcvbuf);
+  } else
+    info("default socket receive buffer %d", rcvbuf);
+  if(logfp)
+    info("WARNING: -L option can impact performance");
   play_rtp();
   return 0;
 }