chiark / gitweb /
d64162be33ee57437e3e37bfd1a5a433bf1ca0c0
[disorder] / clients / playrtp.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 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 clients/playrtp.c
21  * @brief RTP player
22  *
23  * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</a>)
24  * and Apple Mac (<a
25  * href="http://developer.apple.com/audio/coreaudio.html">Core Audio</a>)
26  * systems.  There is no support for Microsoft Windows yet, and that will in
27  * fact probably an entirely separate program.
28  *
29  * The program runs (at least) two threads.  listen_thread() is responsible for
30  * reading RTP packets off the wire and adding them to the binary heap @ref
31  * packets, assuming they are basically sound.
32  *
33  * The main thread is responsible for actually playing audio.  In ALSA this
34  * means it waits until ALSA says it's ready for more audio which it then
35  * plays.
36  *
37  * InCore Audio the main thread is only responsible for starting and stopping
38  * play: the system does the actual playback in its own private thread, and
39  * calls adioproc() to fetch the audio data.
40  *
41  * Sometimes it happens that there is no audio available to play.  This may
42  * because the server went away, or a packet was dropped, or the server
43  * deliberately did not send any sound because it encountered a silence.
44  */
45
46 #include <config.h>
47 #include "types.h"
48
49 #include <getopt.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <sys/socket.h>
53 #include <sys/types.h>
54 #include <sys/socket.h>
55 #include <netdb.h>
56 #include <pthread.h>
57 #include <locale.h>
58 #include <sys/uio.h>
59 #include <string.h>
60
61 #include "log.h"
62 #include "mem.h"
63 #include "configuration.h"
64 #include "addr.h"
65 #include "syscalls.h"
66 #include "rtp.h"
67 #include "defs.h"
68 #include "vector.h"
69 #include "heap.h"
70
71 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
72 # include <CoreAudio/AudioHardware.h>
73 #endif
74 #if API_ALSA
75 #include <alsa/asoundlib.h>
76 #endif
77
78 #define readahead linux_headers_are_borked
79
80 /** @brief RTP socket */
81 static int rtpfd;
82
83 /** @brief Log output */
84 static FILE *logfp;
85
86 /** @brief Output device */
87 static const char *device;
88
89 /** @brief Maximum samples per packet we'll support
90  *
91  * NB that two channels = two samples in this program.
92  */
93 #define MAXSAMPLES 2048
94
95 /** @brief Minimum low watermark
96  *
97  * We'll stop playing if there's only this many samples in the buffer. */
98 static unsigned minbuffer = 2 * 44100 / 10;  /* 0.2 seconds */
99
100 /** @brief Buffer high watermark
101  *
102  * We'll only start playing when this many samples are available. */
103 static unsigned readahead = 2 * 2 * 44100;
104
105 /** @brief Maximum buffer size
106  *
107  * We'll stop reading from the network if we have this many samples. */
108 static unsigned maxbuffer;
109
110 /** @brief Number of samples to infill by in one go
111  *
112  * This is an upper bound - in practice we expect the underlying audio API to
113  * only ask for a much smaller number of samples in any one go.
114  */
115 #define INFILL_SAMPLES (44100 * 2)      /* 1s */
116
117 /** @brief Received packet
118  *
119  * Received packets are kept in a binary heap (see @ref pheap) ordered by
120  * timestamp.
121  */
122 struct packet {
123   /** @brief Number of samples in this packet */
124   uint32_t nsamples;
125
126   /** @brief Timestamp from RTP packet
127    *
128    * NB that "timestamps" are really sample counters.  Use lt() or lt_packet()
129    * to compare timestamps. 
130    */
131   uint32_t timestamp;
132
133   /** @brief Flags
134    *
135    * Valid values are:
136    * - @ref IDLE - the idle bit was set in the RTP packet
137    */
138   unsigned flags;
139 /** @brief idle bit set in RTP packet*/
140 #define IDLE 0x0001
141
142   /** @brief Raw sample data
143    *
144    * Only the first @p nsamples samples are defined; the rest is uninitialized
145    * data.
146    */
147   uint16_t samples_raw[MAXSAMPLES];
148 };
149
150 /** @brief Return true iff \f$a < b\f$ in sequence-space arithmetic
151  *
152  * Specifically it returns true if \f$(a-b) mod 2^{32} < 2^{31}\f$.
153  *
154  * See also lt_packet().
155  */
156 static inline int lt(uint32_t a, uint32_t b) {
157   return (uint32_t)(a - b) & 0x80000000;
158 }
159
160 /** @brief Return true iff a >= b in sequence-space arithmetic */
161 static inline int ge(uint32_t a, uint32_t b) {
162   return !lt(a, b);
163 }
164
165 /** @brief Return true iff a > b in sequence-space arithmetic */
166 static inline int gt(uint32_t a, uint32_t b) {
167   return lt(b, a);
168 }
169
170 /** @brief Return true iff a <= b in sequence-space arithmetic */
171 static inline int le(uint32_t a, uint32_t b) {
172   return !lt(b, a);
173 }
174
175 /** @brief Ordering for packets, used by @ref pheap */
176 static inline int lt_packet(const struct packet *a, const struct packet *b) {
177   return lt(a->timestamp, b->timestamp);
178 }
179
180 /** @struct pheap 
181  * @brief Binary heap of packets ordered by timestamp */
182 HEAP_TYPE(pheap, struct packet *, lt_packet);
183
184 /** @brief Binary heap of received packets */
185 static struct pheap packets;
186
187 /** @brief Total number of samples available */
188 static unsigned long nsamples;
189
190 /** @brief Timestamp of next packet to play.
191  *
192  * This is set to the timestamp of the last packet, plus the number of
193  * samples it contained.  Only valid if @ref active is nonzero.
194  */
195 static uint32_t next_timestamp;
196
197 /** @brief True if actively playing
198  *
199  * This is true when playing and false when just buffering. */
200 static int active;
201
202 /** @brief Structure of free packet list */
203 union free_packet {
204   struct packet p;
205   union free_packet *next;
206 };
207
208 /** @brief Linked list of free packets
209  *
210  * This is a linked list of formerly used packets.  For preference we re-use
211  * packets that have already been used rather than unused ones, to limit the
212  * size of the program's working set.  If there are no free packets in the list
213  * we try @ref next_free_packet instead.
214  *
215  * Must hold @ref lock when accessing this.
216  */
217 static union free_packet *free_packets;
218
219 /** @brief Array of new free packets 
220  *
221  * There are @ref count_free_packets ready to use at this address.  If there
222  * are none left we allocate more memory.
223  *
224  * Must hold @ref lock when accessing this.
225  */
226 static union free_packet *next_free_packet;
227
228 /** @brief Count of new free packets at @ref next_free_packet
229  *
230  * Must hold @ref lock when accessing this.
231  */
232 static size_t count_free_packets;
233
234 /** @brief Lock protecting @ref packets 
235  *
236  * This also protects the packet memory allocation infrastructure, @ref
237  * free_packets and @ref next_free_packet. */
238 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
239
240 /** @brief Condition variable signalled whenever @ref packets is changed */
241 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
242
243 static const struct option options[] = {
244   { "help", no_argument, 0, 'h' },
245   { "version", no_argument, 0, 'V' },
246   { "debug", no_argument, 0, 'd' },
247   { "device", required_argument, 0, 'D' },
248   { "min", required_argument, 0, 'm' },
249   { "max", required_argument, 0, 'x' },
250   { "buffer", required_argument, 0, 'b' },
251   { 0, 0, 0, 0 }
252 };
253
254 /** @brief Return a new packet
255  *
256  * Assumes that @ref lock is held. */
257 static struct packet *new_packet(void) {
258   struct packet *p;
259
260   if(free_packets) {
261     p = &free_packets->p;
262     free_packets = free_packets->next;
263   } else {
264     if(!count_free_packets) {
265       next_free_packet = xcalloc(1024, sizeof (union free_packet));
266       count_free_packets = 1024;
267     }
268     p = &(next_free_packet++)->p;
269     --count_free_packets;
270   }
271   return p;
272 }
273
274 /** @brief Free a packet
275  *
276  * Assumes that @ref lock is held. */
277 static void free_packet(struct packet *p) {
278   union free_packet *u = (union free_packet *)p;
279   u->next = free_packets;
280   free_packets = u;
281 }
282
283 /** @brief Drop the first packet
284  *
285  * Assumes that @ref lock is held. 
286  */
287 static void drop_first_packet(void) {
288   if(pheap_count(&packets)) {
289     struct packet *const p = pheap_remove(&packets);
290     nsamples -= p->nsamples;
291     free_packet(p);
292     pthread_cond_broadcast(&cond);
293   }
294 }
295
296 /** @brief Background thread collecting samples
297  *
298  * This function collects samples, perhaps converts them to the target format,
299  * and adds them to the packet list.
300  *
301  * It is crucial that the gap between successive calls to read() is as small as
302  * possible: otherwise packets will be dropped.
303  *
304  * We use a binary heap to ensure that the unavoidable effort is at worst
305  * logarithmic in the total number of packets - in fact if packets are mostly
306  * received in order then we will largely do constant work per packet since the
307  * newest packet will always be last.
308  *
309  * Of more concern is that we must acquire the lock on the heap to add a packet
310  * to it.  If this proves a problem in practice then the answer would be
311  * (probably doubly) linked list with new packets added the end and a second
312  * thread which reads packets off the list and adds them to the heap.
313  *
314  * We keep memory allocation (mostly) very fast by keeping pre-allocated
315  * packets around; see @ref new_packet().
316  */
317 static void *listen_thread(void attribute((unused)) *arg) {
318   struct packet *p = 0;
319   int n;
320   struct rtp_header header;
321   uint16_t seq;
322   uint32_t timestamp;
323   struct iovec iov[2];
324
325   for(;;) {
326     if(!p) {
327       pthread_mutex_lock(&lock);
328       p = new_packet();
329       pthread_mutex_unlock(&lock);
330     }
331     iov[0].iov_base = &header;
332     iov[0].iov_len = sizeof header;
333     iov[1].iov_base = p->samples_raw;
334     iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
335     n = readv(rtpfd, iov, 2);
336     if(n < 0) {
337       switch(errno) {
338       case EINTR:
339         continue;
340       default:
341         fatal(errno, "error reading from socket");
342       }
343     }
344     /* Ignore too-short packets */
345     if((size_t)n <= sizeof (struct rtp_header)) {
346       info("ignored a short packet");
347       continue;
348     }
349     timestamp = htonl(header.timestamp);
350     seq = htons(header.seq);
351     /* Ignore packets in the past */
352     if(active && lt(timestamp, next_timestamp)) {
353       info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
354            timestamp, next_timestamp);
355       continue;
356     }
357     pthread_mutex_lock(&lock);
358     p->flags = 0;
359     p->timestamp = timestamp;
360     /* Convert to target format */
361     if(header.mpt & 0x80)
362       p->flags |= IDLE;
363     switch(header.mpt & 0x7F) {
364     case 10:
365       p->nsamples = (n - sizeof header) / sizeof(uint16_t);
366       break;
367       /* TODO support other RFC3551 media types (when the speaker does) */
368     default:
369       fatal(0, "unsupported RTP payload type %d",
370             header.mpt & 0x7F);
371     }
372     if(logfp)
373       fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
374               seq, timestamp, p->nsamples, timestamp + p->nsamples);
375     /* Stop reading if we've reached the maximum.
376      *
377      * This is rather unsatisfactory: it means that if packets get heavily
378      * out of order then we guarantee dropouts.  But for now... */
379     if(nsamples >= maxbuffer) {
380       //info("Buffer full");
381       write(2, "B", 1);
382       while(nsamples >= maxbuffer)
383         pthread_cond_wait(&cond, &lock);
384     }
385     /* Add the packet to the heap */
386     pheap_insert(&packets, p);
387     nsamples += p->nsamples;
388     /* We'll need a new packet */
389     p = 0;
390     pthread_cond_broadcast(&cond);
391     pthread_mutex_unlock(&lock);
392   }
393 }
394
395 /** @brief Return true if @p p contains @p timestamp
396  *
397  * Containment implies that a sample @p timestamp exists within the packet.
398  */
399 static inline int contains(const struct packet *p, uint32_t timestamp) {
400   const uint32_t packet_start = p->timestamp;
401   const uint32_t packet_end = p->timestamp + p->nsamples;
402
403   return (ge(timestamp, packet_start)
404           && lt(timestamp, packet_end));
405 }
406
407 /** @brief Wait until the buffer is adequately full
408  *
409  * Must be called with @ref lock held.
410  */
411 static void fill_buffer(void) {
412   info("Buffering...");
413   while(nsamples < readahead)
414     pthread_cond_wait(&cond, &lock);
415   next_timestamp = pheap_first(&packets)->timestamp;
416   active = 1;
417 }
418
419 /** @brief Find next packet
420  * @return Packet to play or NULL if none found
421  *
422  * The return packet is merely guaranteed not to be in the past: it might be
423  * the first packet in the future rather than one that is actually suitable to
424  * play.
425  *
426  * Must be called with @ref lock held.
427  */
428 static struct packet *next_packet(void) {
429   while(pheap_count(&packets)) {
430     struct packet *const p = pheap_first(&packets);
431     if(le(p->timestamp + p->nsamples, next_timestamp)) {
432       /* This packet is in the past.  Drop it and try another one. */
433       drop_first_packet();
434     } else
435       /* This packet is NOT in the past.  (It might be in the future
436        * however.) */
437       return p;
438   }
439   return 0;
440 }
441
442 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
443 /** @brief Callback from Core Audio */
444 static OSStatus adioproc
445     (AudioDeviceID attribute((unused)) inDevice,
446      const AudioTimeStamp attribute((unused)) *inNow,
447      const AudioBufferList attribute((unused)) *inInputData,
448      const AudioTimeStamp attribute((unused)) *inInputTime,
449      AudioBufferList *outOutputData,
450      const AudioTimeStamp attribute((unused)) *inOutputTime,
451      void attribute((unused)) *inClientData) {
452   UInt32 nbuffers = outOutputData->mNumberBuffers;
453   AudioBuffer *ab = outOutputData->mBuffers;
454   uint32_t samples_available;
455
456   pthread_mutex_lock(&lock);
457   while(nbuffers > 0) {
458     float *samplesOut = ab->mData;
459     size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
460
461     while(samplesOutLeft > 0) {
462       const struct packet *p = next_packet();
463       if(p && contains(p, next_timestamp)) {
464         if(p->flags & IDLE)
465           write(2, "I", 1);
466         /* This packet is ready to play */
467         const uint32_t packet_end = p->timestamp + p->nsamples;
468         const uint32_t offset = next_timestamp - p->timestamp;
469         const uint16_t *ptr = (void *)(p->samples_raw + offset);
470
471         samples_available = packet_end - next_timestamp;
472         if(samples_available > samplesOutLeft)
473           samples_available = samplesOutLeft;
474         next_timestamp += samples_available;
475         samplesOutLeft -= samples_available;
476         while(samples_available-- > 0)
477           *samplesOut++ = (int16_t)ntohs(*ptr++) * (0.5 / 32767);
478         /* We don't bother junking the packet - that'll be dealt with next time
479          * round */
480         write(2, ".", 1);
481       } else {
482         /* No packet is ready to play (and there might be no packet at all) */
483         samples_available = p ? p->timestamp - next_timestamp
484                               : samplesOutLeft;
485         if(samples_available > samplesOutLeft)
486           samples_available = samplesOutLeft;
487         //info("infill by %"PRIu32, samples_available);
488         /* Conveniently the buffer is 0 to start with */
489         next_timestamp += samples_available;
490         samplesOut += samples_available;
491         samplesOutLeft -= samples_available;
492         write(2, "?", 1);
493       }
494     }
495     ++ab;
496     --nbuffers;
497   }
498   pthread_mutex_unlock(&lock);
499   return 0;
500 }
501 #endif
502
503
504 #if API_ALSA
505 /** @brief PCM handle */
506 static snd_pcm_t *pcm;
507
508 /** @brief True when @ref pcm is up and running */
509 static int alsa_prepared = 1;
510
511 /** @brief Initialize @ref pcm */
512 static void setup_alsa(void) {
513   snd_pcm_hw_params_t *hwparams;
514   snd_pcm_sw_params_t *swparams;
515   /* Only support one format for now */
516   const int sample_format = SND_PCM_FORMAT_S16_BE;
517   unsigned rate = 44100;
518   const int channels = 2;
519   const int samplesize = channels * sizeof(uint16_t);
520   snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
521   /* If we can write more than this many samples we'll get a wakeup */
522   const int avail_min = 256;
523   int err;
524   
525   /* Open ALSA */
526   if((err = snd_pcm_open(&pcm,
527                          device ? device : "default",
528                          SND_PCM_STREAM_PLAYBACK,
529                          SND_PCM_NONBLOCK)))
530     fatal(0, "error from snd_pcm_open: %d", err);
531   /* Set up 'hardware' parameters */
532   snd_pcm_hw_params_alloca(&hwparams);
533   if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
534     fatal(0, "error from snd_pcm_hw_params_any: %d", err);
535   if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
536                                          SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
537     fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
538   if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
539                                          sample_format)) < 0)
540     
541     fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
542           sample_format, err);
543   if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
544     fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
545           rate, err);
546   if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
547                                            channels)) < 0)
548     fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
549           channels, err);
550   if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
551                                                    &pcm_bufsize)) < 0)
552     fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
553           MAXSAMPLES * samplesize * 3, err);
554   if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
555     fatal(0, "error calling snd_pcm_hw_params: %d", err);
556   /* Set up 'software' parameters */
557   snd_pcm_sw_params_alloca(&swparams);
558   if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
559     fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
560   if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
561     fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
562           avail_min, err);
563   if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
564     fatal(0, "error calling snd_pcm_sw_params: %d", err);
565 }
566
567 /** @brief Wait until ALSA wants some audio */
568 static void wait_alsa(void) {
569   struct pollfd fds[64];
570   int nfds, err;
571   unsigned short events;
572
573   for(;;) {
574     do {
575       if((nfds = snd_pcm_poll_descriptors(pcm,
576                                           fds, sizeof fds / sizeof *fds)) < 0)
577         fatal(0, "error calling snd_pcm_poll_descriptors: %d", nfds);
578     } while(poll(fds, nfds, -1) < 0 && errno == EINTR);
579     if((err = snd_pcm_poll_descriptors_revents(pcm, fds, nfds, &events)))
580       fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
581     if(events & POLLOUT)
582       return;
583   }
584 }
585
586 /** @brief Play some sound via ALSA
587  * @param s Pointer to sample data
588  * @param n Number of samples
589  * @return 0 on success, -1 on non-fatal error
590  */
591 static int alsa_writei(const void *s, size_t n) {
592   /* Do the write */
593   const snd_pcm_sframes_t frames_written = snd_pcm_writei(pcm, s, n / 2);
594   if(frames_written < 0) {
595     /* Something went wrong */
596     switch(frames_written) {
597     case -EAGAIN:
598       write(2, "#", 1);
599       return 0;
600     case -EPIPE:
601       error(0, "error calling snd_pcm_writei: %ld",
602             (long)frames_written);
603       return -1;
604     default:
605       fatal(0, "error calling snd_pcm_writei: %ld",
606             (long)frames_written);
607     }
608   } else {
609     /* Success */
610     next_timestamp += frames_written * 2;
611     return 0;
612   }
613 }
614
615 /** @brief Play the relevant part of a packet
616  * @param p Packet to play
617  * @return 0 on success, -1 on non-fatal error
618  */
619 static int alsa_play(const struct packet *p) {
620   if(p->flags & IDLE)
621     write(2, "I", 1);
622   write(2, ".", 1);
623   return alsa_writei(p->samples_raw + next_timestamp - p->timestamp,
624                      (p->timestamp + p->nsamples) - next_timestamp);
625 }
626
627 /** @brief Play some silence
628  * @param p Next packet or NULL
629  * @return 0 on success, -1 on non-fatal error
630  */
631 static int alsa_infill(const struct packet *p) {
632   static const uint16_t zeros[INFILL_SAMPLES];
633   size_t samples_available = INFILL_SAMPLES;
634
635   if(p && samples_available > p->timestamp - next_timestamp)
636     samples_available = p->timestamp - next_timestamp;
637   write(2, "?", 1);
638   return alsa_writei(zeros, samples_available);
639 }
640
641 /** @brief Reset ALSA state after we lost synchronization */
642 static void alsa_reset(int hard_reset) {
643   int err;
644
645   if((err = snd_pcm_nonblock(pcm, 0)))
646     fatal(0, "error calling snd_pcm_nonblock: %d", err);
647   if(hard_reset) {
648     if((err = snd_pcm_drop(pcm)))
649       fatal(0, "error calling snd_pcm_drop: %d", err);
650   } else
651     if((err = snd_pcm_drain(pcm)))
652       fatal(0, "error calling snd_pcm_drain: %d", err);
653   if((err = snd_pcm_nonblock(pcm, 1)))
654     fatal(0, "error calling snd_pcm_nonblock: %d", err);
655   alsa_prepared = 0;
656 }
657 #endif
658
659 /** @brief Play an RTP stream
660  *
661  * This is the guts of the program.  It is responsible for:
662  * - starting the listening thread
663  * - opening the audio device
664  * - reading ahead to build up a buffer
665  * - arranging for audio to be played
666  * - detecting when the buffer has got too small and re-buffering
667  */
668 static void play_rtp(void) {
669   pthread_t ltid;
670
671   /* We receive and convert audio data in a background thread */
672   pthread_create(&ltid, 0, listen_thread, 0);
673 #if API_ALSA
674   {
675     struct packet *p;
676     int escape, err;
677
678     /* Open the sound device */
679     setup_alsa();
680     pthread_mutex_lock(&lock);
681     for(;;) {
682       /* Wait for the buffer to fill up a bit */
683       fill_buffer();
684       if(!alsa_prepared) {
685         if((err = snd_pcm_prepare(pcm)))
686           fatal(0, "error calling snd_pcm_prepare: %d", err);
687         alsa_prepared = 1;
688       }
689       escape = 0;
690       info("Playing...");
691       /* Keep playing until the buffer empties out, or ALSA tells us to get
692        * lost */
693       while(nsamples >= minbuffer && !escape) {
694         /* Wait for ALSA to ask us for more data */
695         pthread_mutex_unlock(&lock);
696         wait_alsa();
697         pthread_mutex_lock(&lock);
698         /* ALSA is ready for more data, find something to play */
699         p = next_packet();
700         /* Play it or play some silence */
701         if(contains(p, next_timestamp))
702           escape = alsa_play(p);
703         else
704           escape = alsa_infill(p);
705       }
706       active = 0;
707       /* We stop playing for a bit until the buffer re-fills */
708       pthread_mutex_unlock(&lock);
709       alsa_reset(escape);
710       pthread_mutex_lock(&lock);
711     }
712
713   }
714 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
715   {
716     OSStatus status;
717     UInt32 propertySize;
718     AudioDeviceID adid;
719     AudioStreamBasicDescription asbd;
720
721     /* If this looks suspiciously like libao's macosx driver there's an
722      * excellent reason for that... */
723
724     /* TODO report errors as strings not numbers */
725     propertySize = sizeof adid;
726     status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
727                                       &propertySize, &adid);
728     if(status)
729       fatal(0, "AudioHardwareGetProperty: %d", (int)status);
730     if(adid == kAudioDeviceUnknown)
731       fatal(0, "no output device");
732     propertySize = sizeof asbd;
733     status = AudioDeviceGetProperty(adid, 0, false,
734                                     kAudioDevicePropertyStreamFormat,
735                                     &propertySize, &asbd);
736     if(status)
737       fatal(0, "AudioHardwareGetProperty: %d", (int)status);
738     D(("mSampleRate       %f", asbd.mSampleRate));
739     D(("mFormatID         %08lx", asbd.mFormatID));
740     D(("mFormatFlags      %08lx", asbd.mFormatFlags));
741     D(("mBytesPerPacket   %08lx", asbd.mBytesPerPacket));
742     D(("mFramesPerPacket  %08lx", asbd.mFramesPerPacket));
743     D(("mBytesPerFrame    %08lx", asbd.mBytesPerFrame));
744     D(("mChannelsPerFrame %08lx", asbd.mChannelsPerFrame));
745     D(("mBitsPerChannel   %08lx", asbd.mBitsPerChannel));
746     D(("mReserved         %08lx", asbd.mReserved));
747     if(asbd.mFormatID != kAudioFormatLinearPCM)
748       fatal(0, "audio device does not support kAudioFormatLinearPCM");
749     status = AudioDeviceAddIOProc(adid, adioproc, 0);
750     if(status)
751       fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
752     pthread_mutex_lock(&lock);
753     for(;;) {
754       /* Wait for the buffer to fill up a bit */
755       fill_buffer();
756       /* Start playing now */
757       info("Playing...");
758       next_timestamp = pheap_first(&packets)->timestamp;
759       active = 1;
760       status = AudioDeviceStart(adid, adioproc);
761       if(status)
762         fatal(0, "AudioDeviceStart: %d", (int)status);
763       /* Wait until the buffer empties out */
764       while(nsamples >= minbuffer)
765         pthread_cond_wait(&cond, &lock);
766       /* Stop playing for a bit until the buffer re-fills */
767       status = AudioDeviceStop(adid, adioproc);
768       if(status)
769         fatal(0, "AudioDeviceStop: %d", (int)status);
770       active = 0;
771       /* Go back round */
772     }
773   }
774 #else
775 # error No known audio API
776 #endif
777 }
778
779 /* display usage message and terminate */
780 static void help(void) {
781   xprintf("Usage:\n"
782           "  disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
783           "Options:\n"
784           "  --device, -D DEVICE     Output device\n"
785           "  --min, -m FRAMES        Buffer low water mark\n"
786           "  --buffer, -b FRAMES     Buffer high water mark\n"
787           "  --max, -x FRAMES        Buffer maximum size\n"
788           "  --help, -h              Display usage message\n"
789           "  --version, -V           Display version number\n"
790           );
791   xfclose(stdout);
792   exit(0);
793 }
794
795 /* display version number and terminate */
796 static void version(void) {
797   xprintf("disorder-playrtp version %s\n", disorder_version_string);
798   xfclose(stdout);
799   exit(0);
800 }
801
802 int main(int argc, char **argv) {
803   int n;
804   struct addrinfo *res;
805   struct stringlist sl;
806   char *sockname;
807
808   static const struct addrinfo prefs = {
809     AI_PASSIVE,
810     PF_INET,
811     SOCK_DGRAM,
812     IPPROTO_UDP,
813     0,
814     0,
815     0,
816     0
817   };
818
819   mem_init();
820   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
821   while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:", options, 0)) >= 0) {
822     switch(n) {
823     case 'h': help();
824     case 'V': version();
825     case 'd': debugging = 1; break;
826     case 'D': device = optarg; break;
827     case 'm': minbuffer = 2 * atol(optarg); break;
828     case 'b': readahead = 2 * atol(optarg); break;
829     case 'x': maxbuffer = 2 * atol(optarg); break;
830     case 'L': logfp = fopen(optarg, "w"); break;
831     default: fatal(0, "invalid option");
832     }
833   }
834   if(!maxbuffer)
835     maxbuffer = 4 * readahead;
836   argc -= optind;
837   argv += optind;
838   if(argc < 1 || argc > 2)
839     fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
840   sl.n = argc;
841   sl.s = argv;
842   /* Listen for inbound audio data */
843   if(!(res = get_address(&sl, &prefs, &sockname)))
844     exit(1);
845   if((rtpfd = socket(res->ai_family,
846                      res->ai_socktype,
847                      res->ai_protocol)) < 0)
848     fatal(errno, "error creating socket");
849   if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
850     fatal(errno, "error binding socket to %s", sockname);
851   play_rtp();
852   return 0;
853 }
854
855 /*
856 Local Variables:
857 c-basic-offset:2
858 comment-column:40
859 fill-column:79
860 indent-tabs-mode:nil
861 End:
862 */