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