2 * This file is part of DisOrder.
3 * Copyright (C) 2007 Richard Kettlewell
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.
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.
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
20 /** @file clients/playrtp.c
23 * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</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.
29 * The program runs (at least) three threads. listen_thread() is responsible
30 * for reading RTP packets off the wire and adding them to the linked list @ref
31 * received_packets, assuming they are basically sound. queue_thread() takes
32 * packets off this linked list and adds them to @ref packets (an operation
33 * which might be much slower due to contention for @ref lock).
35 * The main thread is responsible for actually playing audio. In ALSA this
36 * means it waits until ALSA says it's ready for more audio which it then
39 * InCore Audio the main thread is only responsible for starting and stopping
40 * play: the system does the actual playback in its own private thread, and
41 * calls adioproc() to fetch the audio data.
43 * Sometimes it happens that there is no audio available to play. This may
44 * because the server went away, or a packet was dropped, or the server
45 * deliberately did not send any sound because it encountered a silence.
48 * - it is safe to read uint32_t values without a lock protecting them
57 #include <sys/socket.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
68 #include "configuration.h"
77 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
78 # include <CoreAudio/AudioHardware.h>
81 #include <alsa/asoundlib.h>
84 #define readahead linux_headers_are_borked
86 /** @brief RTP socket */
89 /** @brief Log output */
92 /** @brief Output device */
93 static const char *device
;
95 /** @brief Maximum samples per packet we'll support
97 * NB that two channels = two samples in this program.
99 #define MAXSAMPLES 2048
101 /** @brief Minimum low watermark
103 * We'll stop playing if there's only this many samples in the buffer. */
104 static unsigned minbuffer
= 2 * 44100 / 10; /* 0.2 seconds */
106 /** @brief Buffer high watermark
108 * We'll only start playing when this many samples are available. */
109 static unsigned readahead
= 2 * 2 * 44100;
111 /** @brief Maximum buffer size
113 * We'll stop reading from the network if we have this many samples. */
114 static unsigned maxbuffer
;
116 /** @brief Number of samples to infill by in one go
118 * This is an upper bound - in practice we expect the underlying audio API to
119 * only ask for a much smaller number of samples in any one go.
121 #define INFILL_SAMPLES (44100 * 2) /* 1s */
123 /** @brief Received packet
125 * Received packets are kept in a binary heap (see @ref pheap) ordered by
129 /** @brief Next packet in @ref next_free_packet or @ref received_packets */
132 /** @brief Number of samples in this packet */
135 /** @brief Timestamp from RTP packet
137 * NB that "timestamps" are really sample counters. Use lt() or lt_packet()
138 * to compare timestamps.
145 * - @ref IDLE - the idle bit was set in the RTP packet
148 /** @brief idle bit set in RTP packet*/
151 /** @brief Raw sample data
153 * Only the first @p nsamples samples are defined; the rest is uninitialized
156 uint16_t samples_raw
[MAXSAMPLES
];
159 /** @brief Return true iff \f$a < b\f$ in sequence-space arithmetic
161 * Specifically it returns true if \f$(a-b) mod 2^{32} < 2^{31}\f$.
163 * See also lt_packet().
165 static inline int lt(uint32_t a
, uint32_t b
) {
166 return (uint32_t)(a
- b
) & 0x80000000;
169 /** @brief Return true iff a >= b in sequence-space arithmetic */
170 static inline int ge(uint32_t a
, uint32_t b
) {
174 /** @brief Return true iff a > b in sequence-space arithmetic */
175 static inline int gt(uint32_t a
, uint32_t b
) {
179 /** @brief Return true iff a <= b in sequence-space arithmetic */
180 static inline int le(uint32_t a
, uint32_t b
) {
184 /** @brief Ordering for packets, used by @ref pheap */
185 static inline int lt_packet(const struct packet
*a
, const struct packet
*b
) {
186 return lt(a
->timestamp
, b
->timestamp
);
189 /** @brief Received packets
190 * Protected by @ref receive_lock
192 * Received packets are added to this list, and queue_thread() picks them off
193 * it and adds them to @ref packets. Whenever a packet is added to it, @ref
194 * receive_cond is signalled.
196 static struct packet
*received_packets
;
198 /** @brief Tail of @ref received_packets
199 * Protected by @ref receive_lock
201 static struct packet
**received_tail
= &received_packets
;
203 /** @brief Lock protecting @ref received_packets
205 * Only listen_thread() and queue_thread() ever hold this lock. It is vital
206 * that queue_thread() not hold it any longer than it strictly has to. */
207 static pthread_mutex_t receive_lock
= PTHREAD_MUTEX_INITIALIZER
;
209 /** @brief Condition variable signalled when @ref received_packets is updated
211 * Used by listen_thread() to notify queue_thread() that it has added another
212 * packet to @ref received_packets. */
213 static pthread_cond_t receive_cond
= PTHREAD_COND_INITIALIZER
;
215 /** @brief Length of @ref received_packets */
216 static uint32_t nreceived
;
219 * @brief Binary heap of packets ordered by timestamp */
220 HEAP_TYPE(pheap
, struct packet
*, lt_packet
);
222 /** @brief Binary heap of received packets */
223 static struct pheap packets
;
225 /** @brief Total number of samples available
227 * We make this volatile because we inspect it without a protecting lock,
228 * so the usual pthread_* guarantees aren't available.
230 static volatile uint32_t nsamples
;
232 /** @brief Timestamp of next packet to play.
234 * This is set to the timestamp of the last packet, plus the number of
235 * samples it contained. Only valid if @ref active is nonzero.
237 static uint32_t next_timestamp
;
239 /** @brief True if actively playing
241 * This is true when playing and false when just buffering. */
244 /** @brief Lock protecting @ref packets */
245 static pthread_mutex_t lock
= PTHREAD_MUTEX_INITIALIZER
;
247 /** @brief Condition variable signalled whenever @ref packets is changed */
248 static pthread_cond_t cond
= PTHREAD_COND_INITIALIZER
;
250 /** @brief Structure of free packet list */
253 union free_packet
*next
;
256 /** @brief Linked list of free packets
258 * This is a linked list of formerly used packets. For preference we re-use
259 * packets that have already been used rather than unused ones, to limit the
260 * size of the program's working set. If there are no free packets in the list
261 * we try @ref next_free_packet instead.
263 * Must hold @ref lock when accessing this.
265 static union free_packet
*free_packets
;
267 /** @brief Array of new free packets
269 * There are @ref count_free_packets ready to use at this address. If there
270 * are none left we allocate more memory.
272 * Must hold @ref lock when accessing this.
274 static union free_packet
*next_free_packet
;
276 /** @brief Count of new free packets at @ref next_free_packet
278 * Must hold @ref lock when accessing this.
280 static size_t count_free_packets
;
282 /** @brief Lock protecting packet allocator */
283 static pthread_mutex_t mem_lock
= PTHREAD_MUTEX_INITIALIZER
;
285 static const struct option options
[] = {
286 { "help", no_argument
, 0, 'h' },
287 { "version", no_argument
, 0, 'V' },
288 { "debug", no_argument
, 0, 'd' },
289 { "device", required_argument
, 0, 'D' },
290 { "min", required_argument
, 0, 'm' },
291 { "max", required_argument
, 0, 'x' },
292 { "buffer", required_argument
, 0, 'b' },
293 { "rcvbuf", required_argument
, 0, 'R' },
297 /** @Brief Return a new packet */
298 static struct packet
*new_packet(void) {
301 pthread_mutex_lock(&mem_lock
);
303 p
= &free_packets
->p
;
304 free_packets
= free_packets
->next
;
306 if(!count_free_packets
) {
307 next_free_packet
= xcalloc(1024, sizeof (union free_packet
));
308 count_free_packets
= 1024;
310 p
= &(next_free_packet
++)->p
;
311 --count_free_packets
;
313 pthread_mutex_unlock(&mem_lock
);
317 /** @brief Free a packet */
318 static void free_packet(struct packet
*p
) {
319 union free_packet
*u
= (union free_packet
*)p
;
320 pthread_mutex_lock(&mem_lock
);
321 u
->next
= free_packets
;
323 pthread_mutex_unlock(&mem_lock
);
326 /** @brief Drop the first packet
328 * Assumes that @ref lock is held.
330 static void drop_first_packet(void) {
331 if(pheap_count(&packets
)) {
332 struct packet
*const p
= pheap_remove(&packets
);
333 nsamples
-= p
->nsamples
;
335 pthread_cond_broadcast(&cond
);
339 /** @brief Background thread adding packets to heap
341 * This just transfers packets from @ref received_packets to @ref packets. It
342 * is important that it holds @ref receive_lock for as little time as possible,
343 * in order to minimize the interval between calls to read() in
346 static void *queue_thread(void attribute((unused
)) *arg
) {
350 /* Get the next packet */
351 pthread_mutex_lock(&receive_lock
);
352 while(!received_packets
)
353 pthread_cond_wait(&receive_cond
, &receive_lock
);
354 p
= received_packets
;
355 received_packets
= p
->next
;
356 if(!received_packets
)
357 received_tail
= &received_packets
;
359 pthread_mutex_unlock(&receive_lock
);
360 /* Add it to the heap */
361 pthread_mutex_lock(&lock
);
362 pheap_insert(&packets
, p
);
363 nsamples
+= p
->nsamples
;
364 pthread_cond_broadcast(&cond
);
365 pthread_mutex_unlock(&lock
);
369 /** @brief Background thread collecting samples
371 * This function collects samples, perhaps converts them to the target format,
372 * and adds them to the packet list.
374 * It is crucial that the gap between successive calls to read() is as small as
375 * possible: otherwise packets will be dropped.
377 * We use a binary heap to ensure that the unavoidable effort is at worst
378 * logarithmic in the total number of packets - in fact if packets are mostly
379 * received in order then we will largely do constant work per packet since the
380 * newest packet will always be last.
382 * Of more concern is that we must acquire the lock on the heap to add a packet
383 * to it. If this proves a problem in practice then the answer would be
384 * (probably doubly) linked list with new packets added the end and a second
385 * thread which reads packets off the list and adds them to the heap.
387 * We keep memory allocation (mostly) very fast by keeping pre-allocated
388 * packets around; see @ref new_packet().
390 static void *listen_thread(void attribute((unused
)) *arg
) {
391 struct packet
*p
= 0;
393 struct rtp_header header
;
401 iov
[0].iov_base
= &header
;
402 iov
[0].iov_len
= sizeof header
;
403 iov
[1].iov_base
= p
->samples_raw
;
404 iov
[1].iov_len
= sizeof p
->samples_raw
/ sizeof *p
->samples_raw
;
405 n
= readv(rtpfd
, iov
, 2);
411 fatal(errno
, "error reading from socket");
414 /* Ignore too-short packets */
415 if((size_t)n
<= sizeof (struct rtp_header
)) {
416 info("ignored a short packet");
419 timestamp
= htonl(header
.timestamp
);
420 seq
= htons(header
.seq
);
421 /* Ignore packets in the past */
422 if(active
&& lt(timestamp
, next_timestamp
)) {
423 info("dropping old packet, timestamp=%"PRIx32
" < %"PRIx32
,
424 timestamp
, next_timestamp
);
429 p
->timestamp
= timestamp
;
430 /* Convert to target format */
431 if(header
.mpt
& 0x80)
433 switch(header
.mpt
& 0x7F) {
435 p
->nsamples
= (n
- sizeof header
) / sizeof(uint16_t);
437 /* TODO support other RFC3551 media types (when the speaker does) */
439 fatal(0, "unsupported RTP payload type %d",
443 fprintf(logfp
, "sequence %u timestamp %"PRIx32
" length %"PRIx32
" end %"PRIx32
"\n",
444 seq
, timestamp
, p
->nsamples
, timestamp
+ p
->nsamples
);
445 /* Stop reading if we've reached the maximum.
447 * This is rather unsatisfactory: it means that if packets get heavily
448 * out of order then we guarantee dropouts. But for now... */
449 if(nsamples
>= maxbuffer
) {
450 pthread_mutex_lock(&lock
);
451 while(nsamples
>= maxbuffer
)
452 pthread_cond_wait(&cond
, &lock
);
453 pthread_mutex_unlock(&lock
);
455 /* Add the packet to the receive queue */
456 pthread_mutex_lock(&receive_lock
);
458 received_tail
= &p
->next
;
460 pthread_cond_signal(&receive_cond
);
461 pthread_mutex_unlock(&receive_lock
);
462 /* We'll need a new packet */
467 /** @brief Return true if @p p contains @p timestamp
469 * Containment implies that a sample @p timestamp exists within the packet.
471 static inline int contains(const struct packet
*p
, uint32_t timestamp
) {
472 const uint32_t packet_start
= p
->timestamp
;
473 const uint32_t packet_end
= p
->timestamp
+ p
->nsamples
;
475 return (ge(timestamp
, packet_start
)
476 && lt(timestamp
, packet_end
));
479 /** @brief Wait until the buffer is adequately full
481 * Must be called with @ref lock held.
483 static void fill_buffer(void) {
484 info("Buffering...");
485 while(nsamples
< readahead
)
486 pthread_cond_wait(&cond
, &lock
);
487 next_timestamp
= pheap_first(&packets
)->timestamp
;
491 /** @brief Find next packet
492 * @return Packet to play or NULL if none found
494 * The return packet is merely guaranteed not to be in the past: it might be
495 * the first packet in the future rather than one that is actually suitable to
498 * Must be called with @ref lock held.
500 static struct packet
*next_packet(void) {
501 while(pheap_count(&packets
)) {
502 struct packet
*const p
= pheap_first(&packets
);
503 if(le(p
->timestamp
+ p
->nsamples
, next_timestamp
)) {
504 /* This packet is in the past. Drop it and try another one. */
507 /* This packet is NOT in the past. (It might be in the future
514 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
515 /** @brief Callback from Core Audio */
516 static OSStatus adioproc
517 (AudioDeviceID
attribute((unused
)) inDevice
,
518 const AudioTimeStamp
attribute((unused
)) *inNow
,
519 const AudioBufferList
attribute((unused
)) *inInputData
,
520 const AudioTimeStamp
attribute((unused
)) *inInputTime
,
521 AudioBufferList
*outOutputData
,
522 const AudioTimeStamp
attribute((unused
)) *inOutputTime
,
523 void attribute((unused
)) *inClientData
) {
524 UInt32 nbuffers
= outOutputData
->mNumberBuffers
;
525 AudioBuffer
*ab
= outOutputData
->mBuffers
;
526 uint32_t samples_available
;
528 pthread_mutex_lock(&lock
);
529 while(nbuffers
> 0) {
530 float *samplesOut
= ab
->mData
;
531 size_t samplesOutLeft
= ab
->mDataByteSize
/ sizeof (float);
533 while(samplesOutLeft
> 0) {
534 const struct packet
*p
= next_packet();
535 if(p
&& contains(p
, next_timestamp
)) {
536 /* This packet is ready to play */
537 const uint32_t packet_end
= p
->timestamp
+ p
->nsamples
;
538 const uint32_t offset
= next_timestamp
- p
->timestamp
;
539 const uint16_t *ptr
= (void *)(p
->samples_raw
+ offset
);
541 samples_available
= packet_end
- next_timestamp
;
542 if(samples_available
> samplesOutLeft
)
543 samples_available
= samplesOutLeft
;
544 next_timestamp
+= samples_available
;
545 samplesOutLeft
-= samples_available
;
546 while(samples_available
-- > 0)
547 *samplesOut
++ = (int16_t)ntohs(*ptr
++) * (0.5 / 32767);
548 /* We don't bother junking the packet - that'll be dealt with next time
551 /* No packet is ready to play (and there might be no packet at all) */
552 samples_available
= p ? p
->timestamp
- next_timestamp
554 if(samples_available
> samplesOutLeft
)
555 samples_available
= samplesOutLeft
;
556 //info("infill by %"PRIu32, samples_available);
557 /* Conveniently the buffer is 0 to start with */
558 next_timestamp
+= samples_available
;
559 samplesOut
+= samples_available
;
560 samplesOutLeft
-= samples_available
;
566 pthread_mutex_unlock(&lock
);
573 /** @brief PCM handle */
574 static snd_pcm_t
*pcm
;
576 /** @brief True when @ref pcm is up and running */
577 static int alsa_prepared
= 1;
579 /** @brief Initialize @ref pcm */
580 static void setup_alsa(void) {
581 snd_pcm_hw_params_t
*hwparams
;
582 snd_pcm_sw_params_t
*swparams
;
583 /* Only support one format for now */
584 const int sample_format
= SND_PCM_FORMAT_S16_BE
;
585 unsigned rate
= 44100;
586 const int channels
= 2;
587 const int samplesize
= channels
* sizeof(uint16_t);
588 snd_pcm_uframes_t pcm_bufsize
= MAXSAMPLES
* samplesize
* 3;
589 /* If we can write more than this many samples we'll get a wakeup */
590 const int avail_min
= 256;
594 if((err
= snd_pcm_open(&pcm
,
595 device ? device
: "default",
596 SND_PCM_STREAM_PLAYBACK
,
598 fatal(0, "error from snd_pcm_open: %d", err
);
599 /* Set up 'hardware' parameters */
600 snd_pcm_hw_params_alloca(&hwparams
);
601 if((err
= snd_pcm_hw_params_any(pcm
, hwparams
)) < 0)
602 fatal(0, "error from snd_pcm_hw_params_any: %d", err
);
603 if((err
= snd_pcm_hw_params_set_access(pcm
, hwparams
,
604 SND_PCM_ACCESS_RW_INTERLEAVED
)) < 0)
605 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err
);
606 if((err
= snd_pcm_hw_params_set_format(pcm
, hwparams
,
609 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
611 if((err
= snd_pcm_hw_params_set_rate_near(pcm
, hwparams
, &rate
, 0)) < 0)
612 fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
614 if((err
= snd_pcm_hw_params_set_channels(pcm
, hwparams
,
616 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
618 if((err
= snd_pcm_hw_params_set_buffer_size_near(pcm
, hwparams
,
620 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
621 MAXSAMPLES
* samplesize
* 3, err
);
622 if((err
= snd_pcm_hw_params(pcm
, hwparams
)) < 0)
623 fatal(0, "error calling snd_pcm_hw_params: %d", err
);
624 /* Set up 'software' parameters */
625 snd_pcm_sw_params_alloca(&swparams
);
626 if((err
= snd_pcm_sw_params_current(pcm
, swparams
)) < 0)
627 fatal(0, "error calling snd_pcm_sw_params_current: %d", err
);
628 if((err
= snd_pcm_sw_params_set_avail_min(pcm
, swparams
, avail_min
)) < 0)
629 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
631 if((err
= snd_pcm_sw_params(pcm
, swparams
)) < 0)
632 fatal(0, "error calling snd_pcm_sw_params: %d", err
);
635 /** @brief Wait until ALSA wants some audio */
636 static void wait_alsa(void) {
637 struct pollfd fds
[64];
639 unsigned short events
;
643 if((nfds
= snd_pcm_poll_descriptors(pcm
,
644 fds
, sizeof fds
/ sizeof *fds
)) < 0)
645 fatal(0, "error calling snd_pcm_poll_descriptors: %d", nfds
);
646 } while(poll(fds
, nfds
, -1) < 0 && errno
== EINTR
);
647 if((err
= snd_pcm_poll_descriptors_revents(pcm
, fds
, nfds
, &events
)))
648 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err
);
654 /** @brief Play some sound via ALSA
655 * @param s Pointer to sample data
656 * @param n Number of samples
657 * @return 0 on success, -1 on non-fatal error
659 static int alsa_writei(const void *s
, size_t n
) {
661 const snd_pcm_sframes_t frames_written
= snd_pcm_writei(pcm
, s
, n
/ 2);
662 if(frames_written
< 0) {
663 /* Something went wrong */
664 switch(frames_written
) {
668 error(0, "error calling snd_pcm_writei: %ld",
669 (long)frames_written
);
672 fatal(0, "error calling snd_pcm_writei: %ld",
673 (long)frames_written
);
677 next_timestamp
+= frames_written
* 2;
682 /** @brief Play the relevant part of a packet
683 * @param p Packet to play
684 * @return 0 on success, -1 on non-fatal error
686 static int alsa_play(const struct packet
*p
) {
687 return alsa_writei(p
->samples_raw
+ next_timestamp
- p
->timestamp
,
688 (p
->timestamp
+ p
->nsamples
) - next_timestamp
);
691 /** @brief Play some silence
692 * @param p Next packet or NULL
693 * @return 0 on success, -1 on non-fatal error
695 static int alsa_infill(const struct packet
*p
) {
696 static const uint16_t zeros
[INFILL_SAMPLES
];
697 size_t samples_available
= INFILL_SAMPLES
;
699 if(p
&& samples_available
> p
->timestamp
- next_timestamp
)
700 samples_available
= p
->timestamp
- next_timestamp
;
701 return alsa_writei(zeros
, samples_available
);
704 /** @brief Reset ALSA state after we lost synchronization */
705 static void alsa_reset(int hard_reset
) {
708 if((err
= snd_pcm_nonblock(pcm
, 0)))
709 fatal(0, "error calling snd_pcm_nonblock: %d", err
);
711 if((err
= snd_pcm_drop(pcm
)))
712 fatal(0, "error calling snd_pcm_drop: %d", err
);
714 if((err
= snd_pcm_drain(pcm
)))
715 fatal(0, "error calling snd_pcm_drain: %d", err
);
716 if((err
= snd_pcm_nonblock(pcm
, 1)))
717 fatal(0, "error calling snd_pcm_nonblock: %d", err
);
722 /** @brief Play an RTP stream
724 * This is the guts of the program. It is responsible for:
725 * - starting the listening thread
726 * - opening the audio device
727 * - reading ahead to build up a buffer
728 * - arranging for audio to be played
729 * - detecting when the buffer has got too small and re-buffering
731 static void play_rtp(void) {
734 /* We receive and convert audio data in a background thread */
735 pthread_create(<id
, 0, listen_thread
, 0);
736 /* We have a second thread to add received packets to the queue */
737 pthread_create(<id
, 0, queue_thread
, 0);
743 /* Open the sound device */
745 pthread_mutex_lock(&lock
);
747 /* Wait for the buffer to fill up a bit */
750 if((err
= snd_pcm_prepare(pcm
)))
751 fatal(0, "error calling snd_pcm_prepare: %d", err
);
756 /* Keep playing until the buffer empties out, or ALSA tells us to get
758 while(nsamples
>= minbuffer
&& !escape
) {
759 /* Wait for ALSA to ask us for more data */
760 pthread_mutex_unlock(&lock
);
762 pthread_mutex_lock(&lock
);
763 /* ALSA is ready for more data, find something to play */
765 /* Play it or play some silence */
766 if(contains(p
, next_timestamp
))
767 escape
= alsa_play(p
);
769 escape
= alsa_infill(p
);
772 /* We stop playing for a bit until the buffer re-fills */
773 pthread_mutex_unlock(&lock
);
775 pthread_mutex_lock(&lock
);
779 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
784 AudioStreamBasicDescription asbd
;
786 /* If this looks suspiciously like libao's macosx driver there's an
787 * excellent reason for that... */
789 /* TODO report errors as strings not numbers */
790 propertySize
= sizeof adid
;
791 status
= AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice
,
792 &propertySize
, &adid
);
794 fatal(0, "AudioHardwareGetProperty: %d", (int)status
);
795 if(adid
== kAudioDeviceUnknown
)
796 fatal(0, "no output device");
797 propertySize
= sizeof asbd
;
798 status
= AudioDeviceGetProperty(adid
, 0, false,
799 kAudioDevicePropertyStreamFormat
,
800 &propertySize
, &asbd
);
802 fatal(0, "AudioHardwareGetProperty: %d", (int)status
);
803 D(("mSampleRate %f", asbd
.mSampleRate
));
804 D(("mFormatID %08lx", asbd
.mFormatID
));
805 D(("mFormatFlags %08lx", asbd
.mFormatFlags
));
806 D(("mBytesPerPacket %08lx", asbd
.mBytesPerPacket
));
807 D(("mFramesPerPacket %08lx", asbd
.mFramesPerPacket
));
808 D(("mBytesPerFrame %08lx", asbd
.mBytesPerFrame
));
809 D(("mChannelsPerFrame %08lx", asbd
.mChannelsPerFrame
));
810 D(("mBitsPerChannel %08lx", asbd
.mBitsPerChannel
));
811 D(("mReserved %08lx", asbd
.mReserved
));
812 if(asbd
.mFormatID
!= kAudioFormatLinearPCM
)
813 fatal(0, "audio device does not support kAudioFormatLinearPCM");
814 status
= AudioDeviceAddIOProc(adid
, adioproc
, 0);
816 fatal(0, "AudioDeviceAddIOProc: %d", (int)status
);
817 pthread_mutex_lock(&lock
);
819 /* Wait for the buffer to fill up a bit */
821 /* Start playing now */
823 next_timestamp
= pheap_first(&packets
)->timestamp
;
825 status
= AudioDeviceStart(adid
, adioproc
);
827 fatal(0, "AudioDeviceStart: %d", (int)status
);
828 /* Wait until the buffer empties out */
829 while(nsamples
>= minbuffer
)
830 pthread_cond_wait(&cond
, &lock
);
831 /* Stop playing for a bit until the buffer re-fills */
832 status
= AudioDeviceStop(adid
, adioproc
);
834 fatal(0, "AudioDeviceStop: %d", (int)status
);
840 # error No known audio API
844 /* display usage message and terminate */
845 static void help(void) {
847 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
849 " --device, -D DEVICE Output device\n"
850 " --min, -m FRAMES Buffer low water mark\n"
851 " --buffer, -b FRAMES Buffer high water mark\n"
852 " --max, -x FRAMES Buffer maximum size\n"
853 " --rcvbuf, -R BYTES Socket receive buffer size\n"
854 " --help, -h Display usage message\n"
855 " --version, -V Display version number\n"
861 /* display version number and terminate */
862 static void version(void) {
863 xprintf("disorder-playrtp version %s\n", disorder_version_string
);
868 int main(int argc
, char **argv
) {
870 struct addrinfo
*res
;
871 struct stringlist sl
;
873 int rcvbuf
, target_rcvbuf
= 131072;
876 static const struct addrinfo prefs
= {
888 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
889 while((n
= getopt_long(argc
, argv
, "hVdD:m:b:x:L:R:", options
, 0)) >= 0) {
893 case 'd': debugging
= 1; break;
894 case 'D': device
= optarg
; break;
895 case 'm': minbuffer
= 2 * atol(optarg
); break;
896 case 'b': readahead
= 2 * atol(optarg
); break;
897 case 'x': maxbuffer
= 2 * atol(optarg
); break;
898 case 'L': logfp
= fopen(optarg
, "w"); break;
899 case 'R': target_rcvbuf
= atoi(optarg
); break;
900 default: fatal(0, "invalid option");
904 maxbuffer
= 4 * readahead
;
907 if(argc
< 1 || argc
> 2)
908 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
911 /* Listen for inbound audio data */
912 if(!(res
= get_address(&sl
, &prefs
, &sockname
)))
914 if((rtpfd
= socket(res
->ai_family
,
916 res
->ai_protocol
)) < 0)
917 fatal(errno
, "error creating socket");
918 if(bind(rtpfd
, res
->ai_addr
, res
->ai_addrlen
) < 0)
919 fatal(errno
, "error binding socket to %s", sockname
);
921 if(getsockopt(rtpfd
, SOL_SOCKET
, SO_RCVBUF
, &rcvbuf
, &len
) < 0)
922 fatal(errno
, "error calling getsockopt SO_RCVBUF");
923 if(target_rcvbuf
> rcvbuf
) {
924 if(setsockopt(rtpfd
, SOL_SOCKET
, SO_RCVBUF
,
925 &target_rcvbuf
, sizeof target_rcvbuf
) < 0)
926 error(errno
, "error calling setsockopt SO_RCVBUF %d",
928 /* We try to carry on anyway */
930 info("changed socket receive buffer from %d to %d",
931 rcvbuf
, target_rcvbuf
);
933 info("default socket receive buffer %d", rcvbuf
);
935 info("WARNING: -L option can impact performance");