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