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 RTP player supports Linux (ALSA) and Darwin (Core Audio) systems.
32 #include <sys/socket.h>
33 #include <sys/types.h>
34 #include <sys/socket.h>
43 #include "configuration.h"
51 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
52 # include <CoreAudio/AudioHardware.h>
55 #include <alsa/asoundlib.h>
58 #define readahead linux_headers_are_borked
60 /** @brief RTP socket */
63 /** @brief Log output */
66 /** @brief Output device */
67 static const char *device;
69 /** @brief Maximum samples per packet we'll support
71 * NB that two channels = two samples in this program.
73 #define MAXSAMPLES 2048
75 /** @brief Minimum low watermark
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 */
80 /** @brief Maximum sample size
82 * The maximum supported size (in bytes) of one sample. */
83 #define MAXSAMPLESIZE 2
85 /** @brief Buffer high watermark
87 * We'll only start playing when this many samples are available. */
88 static unsigned readahead = 2 * 2 * 44100;
90 /** @brief Maximum buffer size
92 * We'll stop reading from the network if we have this many samples. */
93 static unsigned maxbuffer;
95 /** @brief Number of samples to infill by in one go
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.
100 #define INFILL_SAMPLES (44100 * 2) /* 1s */
102 /** @brief Received packet
104 * Received packets are kept in a binary heap (see @ref pheap) ordered by
108 /** @brief Number of samples in this packet */
110 /** @brief Timestamp from RTP packet
112 * NB that "timestamps" are really sample counters. Use lt() or lt_packet()
113 * to compare timestamps.
116 /** @brief Raw sample data
118 * Only the first @p nsamples samples are defined; the rest is uninitialized
121 unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE];
124 /** @brief Return true iff \f$a < b\f$ in sequence-space arithmetic
126 * Specifically it returns true if \f$(a-b) mod 2^{32} < 2^{31}\f$.
128 * See also lt_packet().
130 static inline int lt(uint32_t a, uint32_t b) {
131 return (uint32_t)(a - b) & 0x80000000;
134 /** @brief Return true iff a >= b in sequence-space arithmetic */
135 static inline int ge(uint32_t a, uint32_t b) {
139 /** @brief Return true iff a > b in sequence-space arithmetic */
140 static inline int gt(uint32_t a, uint32_t b) {
144 /** @brief Return true iff a <= b in sequence-space arithmetic */
145 static inline int le(uint32_t a, uint32_t b) {
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);
155 * @brief Binary heap of packets ordered by timestamp */
156 HEAP_TYPE(pheap, struct packet *, lt_packet);
158 /** @brief Binary heap of received packets */
159 static struct pheap packets;
161 /** @brief Total number of samples available */
162 static unsigned long nsamples;
164 /** @brief Timestamp of next packet to play.
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.
169 static uint32_t next_timestamp;
171 /** @brief True if actively playing
173 * This is true when playing and false when just buffering. */
176 /** @brief Structure of free packet list */
179 union free_packet *next;
182 /** @brief Linked list of free packets
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.
189 * Must hold @ref lock when accessing this.
191 static union free_packet *free_packets;
193 /** @brief Array of new free packets
195 * There are @ref count_free_packets ready to use at this address. If there
196 * are none left we allocate more memory.
198 * Must hold @ref lock when accessing this.
200 static union free_packet *next_free_packet;
202 /** @brief Count of new free packets at @ref next_free_packet
204 * Must hold @ref lock when accessing this.
206 static size_t count_free_packets;
208 /** @brief Lock protecting @ref packets
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;
214 /** @brief Condition variable signalled whenever @ref packets is changed */
215 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
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' },
228 /** @brief Return a new packet
230 * Assumes that @ref lock is held. */
231 static struct packet *new_packet(void) {
235 p = &free_packets->p;
236 free_packets = free_packets->next;
238 if(!count_free_packets) {
239 next_free_packet = xcalloc(1024, sizeof (union free_packet));
240 count_free_packets = 1024;
242 p = &(next_free_packet++)->p;
243 --count_free_packets;
248 /** @brief Free a packet
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;
257 /** @brief Drop the first packet
259 * Assumes that @ref lock is held.
261 static void drop_first_packet(void) {
262 if(pheap_count(&packets)) {
263 struct packet *const p = pheap_remove(&packets);
264 nsamples -= p->nsamples;
266 pthread_cond_broadcast(&cond);
270 /** @brief Background thread collecting samples
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;
277 struct rtp_header header;
284 pthread_mutex_lock(&lock);
286 pthread_mutex_unlock(&lock);
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);
298 fatal(errno, "error reading from socket");
301 /* Ignore too-short packets */
302 if((size_t)n <= sizeof (struct rtp_header)) {
303 info("ignored a short packet");
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);
314 pthread_mutex_lock(&lock);
316 p->timestamp = timestamp;
317 /* Convert to target format */
318 switch(header.mpt & 0x7F) {
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 */
325 /* TODO support other RFC3551 media types (when the speaker does) */
327 fatal(0, "unsupported RTP payload type %d",
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.
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) {
339 while(nsamples >= maxbuffer)
340 pthread_cond_wait(&cond, &lock);
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);
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;
355 return (ge(timestamp, packet_start)
356 && lt(timestamp, packet_end));
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;
374 pthread_mutex_lock(&lock);
375 while(nbuffers > 0) {
376 float *samplesOut = ab->mData;
377 size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
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. */
388 /* This packet is NOT in the past. (It might be in the future
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));
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
410 /* No packet is ready to play (and there might be no packet at all) */
411 samples_available = p ? p->timestamp - next_timestamp
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;
425 pthread_mutex_unlock(&lock);
430 /** @brief Play an RTP stream
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
439 static void play_rtp(void) {
442 /* We receive and convert audio data in a background thread */
443 pthread_create(<id, 0, listen_thread, 0);
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;
461 int infilling = 0, escape = 0;
463 uint32_t packet_start, packet_end;
466 if((err = snd_pcm_open(&pcm,
467 device ? device : "default",
468 SND_PCM_STREAM_PLAYBACK,
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,
480 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
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",
485 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
487 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
489 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
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",
502 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
503 fatal(0, "error calling snd_pcm_sw_params: %d", err);
508 pthread_mutex_lock(&lock);
510 /* Wait for the buffer to fill up a bit */
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);
518 if((err = snd_pcm_prepare(pcm)))
519 fatal(0, "error calling snd_pcm_prepare: %d", err);
526 info("%lu samples in buffer (%lus)", nsamples,
527 nsamples / (44100 * 2));
529 /* Wait until the buffer empties out */
530 while(nsamples >= minbuffer && !escape) {
532 if(now > logged + 10) {
534 info("%lu samples in buffer (%lus)", nsamples,
535 nsamples / (44100 * 2));
538 && ge(next_timestamp, packets->timestamp + packets->nsamples)) {
539 info("dropping buffered past packet %"PRIx32" < %"PRIx32,
540 packets->timestamp, next_timestamp);
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)) {
549 info("snd_pcm_wait timed out");
554 fatal(0, "snd_pcm_wait returned %d", err);
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;
567 frames_written = snd_pcm_writei(pcm,
568 packets->samples_raw + offset,
570 if(frames_written < 0) {
571 switch(frames_written) {
573 info("snd_pcm_wait() returned but we got -EAGAIN!");
576 error(0, "error calling snd_pcm_writei: %ld",
577 (long)frames_written);
581 fatal(0, "error calling snd_pcm_writei: %ld",
582 (long)frames_written);
585 samples_written = frames_written * 2;
586 next_timestamp += samples_written;
587 if(ge(next_timestamp, packet_end))
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;
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);
606 frames_available = samples_available / 2;
608 info("Infilling %d samples, next=%"PRIx32" packet=[%"PRIx32",%"PRIx32"]",
609 samples_available, next_timestamp,
610 packets->timestamp, packets->timestamp + packets->nsamples);
613 frames_written = snd_pcm_writei(pcm,
616 if(frames_written < 0) {
617 switch(frames_written) {
619 info("snd_pcm_wait() returned but we got -EAGAIN!");
622 error(0, "error calling snd_pcm_writei: %ld",
623 (long)frames_written);
627 fatal(0, "error calling snd_pcm_writei: %ld",
628 (long)frames_written);
631 samples_written = frames_written * 2;
632 next_timestamp += samples_written;
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);
642 if((err = snd_pcm_drop(pcm)))
643 fatal(0, "error calling snd_pcm_drop: %d", err);
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);
651 pthread_mutex_lock(&lock);
655 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
660 AudioStreamBasicDescription asbd;
662 /* If this looks suspiciously like libao's macosx driver there's an
663 * excellent reason for that... */
665 /* TODO report errors as strings not numbers */
666 propertySize = sizeof adid;
667 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
668 &propertySize, &adid);
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);
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);
692 fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
693 pthread_mutex_lock(&lock);
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 */
701 next_timestamp = pheap_first(&packets)->timestamp;
703 status = AudioDeviceStart(adid, adioproc);
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);
712 fatal(0, "AudioDeviceStop: %d", (int)status);
718 # error No known audio API
722 /* display usage message and terminate */
723 static void help(void) {
725 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\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"
738 /* display version number and terminate */
739 static void version(void) {
740 xprintf("disorder-playrtp version %s\n", disorder_version_string);
745 int main(int argc, char **argv) {
747 struct addrinfo *res;
748 struct stringlist sl;
751 static const struct addrinfo prefs = {
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) {
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");
778 maxbuffer = 4 * readahead;
781 if(argc < 1 || argc > 2)
782 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
785 /* Listen for inbound audio data */
786 if(!(res = get_address(&sl, &prefs, &sockname)))
788 if((rtpfd = socket(res->ai_family,
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);