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 Buffer high watermark
82 * We'll only start playing when this many samples are available. */
83 static unsigned readahead = 2 * 2 * 44100;
85 /** @brief Maximum buffer size
87 * We'll stop reading from the network if we have this many samples. */
88 static unsigned maxbuffer;
90 /** @brief Number of samples to infill by in one go
92 * This is an upper bound - in practice we expect the underlying audio API to
93 * only ask for a much smaller number of samples in any one go.
95 #define INFILL_SAMPLES (44100 * 2) /* 1s */
97 /** @brief Received packet
99 * Received packets are kept in a binary heap (see @ref pheap) ordered by
103 /** @brief Number of samples in this packet */
106 /** @brief Timestamp from RTP packet
108 * NB that "timestamps" are really sample counters. Use lt() or lt_packet()
109 * to compare timestamps.
116 * - @ref IDLE: the idle bit was set in the RTP packet
119 #define IDLE 0x0001 /**< idle bit set in RTP packet */
121 /** @brief Raw sample data
123 * Only the first @p nsamples samples are defined; the rest is uninitialized
126 uint16_t samples_raw[MAXSAMPLES];
129 /** @brief Return true iff \f$a < b\f$ in sequence-space arithmetic
131 * Specifically it returns true if \f$(a-b) mod 2^{32} < 2^{31}\f$.
133 * See also lt_packet().
135 static inline int lt(uint32_t a, uint32_t b) {
136 return (uint32_t)(a - b) & 0x80000000;
139 /** @brief Return true iff a >= b in sequence-space arithmetic */
140 static inline int ge(uint32_t a, uint32_t b) {
144 /** @brief Return true iff a > b in sequence-space arithmetic */
145 static inline int gt(uint32_t a, uint32_t b) {
149 /** @brief Return true iff a <= b in sequence-space arithmetic */
150 static inline int le(uint32_t a, uint32_t b) {
154 /** @brief Ordering for packets, used by @ref pheap */
155 static inline int lt_packet(const struct packet *a, const struct packet *b) {
156 return lt(a->timestamp, b->timestamp);
160 * @brief Binary heap of packets ordered by timestamp */
161 HEAP_TYPE(pheap, struct packet *, lt_packet);
163 /** @brief Binary heap of received packets */
164 static struct pheap packets;
166 /** @brief Total number of samples available */
167 static unsigned long nsamples;
169 /** @brief Timestamp of next packet to play.
171 * This is set to the timestamp of the last packet, plus the number of
172 * samples it contained. Only valid if @ref active is nonzero.
174 static uint32_t next_timestamp;
176 /** @brief True if actively playing
178 * This is true when playing and false when just buffering. */
181 /** @brief Structure of free packet list */
184 union free_packet *next;
187 /** @brief Linked list of free packets
189 * This is a linked list of formerly used packets. For preference we re-use
190 * packets that have already been used rather than unused ones, to limit the
191 * size of the program's working set. If there are no free packets in the list
192 * we try @ref next_free_packet instead.
194 * Must hold @ref lock when accessing this.
196 static union free_packet *free_packets;
198 /** @brief Array of new free packets
200 * There are @ref count_free_packets ready to use at this address. If there
201 * are none left we allocate more memory.
203 * Must hold @ref lock when accessing this.
205 static union free_packet *next_free_packet;
207 /** @brief Count of new free packets at @ref next_free_packet
209 * Must hold @ref lock when accessing this.
211 static size_t count_free_packets;
213 /** @brief Lock protecting @ref packets
215 * This also protects the packet memory allocation infrastructure, @ref
216 * free_packets and @ref next_free_packet. */
217 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
219 /** @brief Condition variable signalled whenever @ref packets is changed */
220 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
222 static const struct option options[] = {
223 { "help", no_argument, 0, 'h' },
224 { "version", no_argument, 0, 'V' },
225 { "debug", no_argument, 0, 'd' },
226 { "device", required_argument, 0, 'D' },
227 { "min", required_argument, 0, 'm' },
228 { "max", required_argument, 0, 'x' },
229 { "buffer", required_argument, 0, 'b' },
233 /** @brief Return a new packet
235 * Assumes that @ref lock is held. */
236 static struct packet *new_packet(void) {
240 p = &free_packets->p;
241 free_packets = free_packets->next;
243 if(!count_free_packets) {
244 next_free_packet = xcalloc(1024, sizeof (union free_packet));
245 count_free_packets = 1024;
247 p = &(next_free_packet++)->p;
248 --count_free_packets;
253 /** @brief Free a packet
255 * Assumes that @ref lock is held. */
256 static void free_packet(struct packet *p) {
257 union free_packet *u = (union free_packet *)p;
258 u->next = free_packets;
262 /** @brief Drop the first packet
264 * Assumes that @ref lock is held.
266 static void drop_first_packet(void) {
267 if(pheap_count(&packets)) {
268 struct packet *const p = pheap_remove(&packets);
269 nsamples -= p->nsamples;
271 pthread_cond_broadcast(&cond);
275 /** @brief Background thread collecting samples
277 * This function collects samples, perhaps converts them to the target format,
278 * and adds them to the packet list. */
279 static void *listen_thread(void attribute((unused)) *arg) {
280 struct packet *p = 0;
282 struct rtp_header header;
289 pthread_mutex_lock(&lock);
291 pthread_mutex_unlock(&lock);
293 iov[0].iov_base = &header;
294 iov[0].iov_len = sizeof header;
295 iov[1].iov_base = p->samples_raw;
296 iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
297 n = readv(rtpfd, iov, 2);
303 fatal(errno, "error reading from socket");
306 /* Ignore too-short packets */
307 if((size_t)n <= sizeof (struct rtp_header)) {
308 info("ignored a short packet");
311 timestamp = htonl(header.timestamp);
312 seq = htons(header.seq);
313 /* Ignore packets in the past */
314 if(active && lt(timestamp, next_timestamp)) {
315 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
316 timestamp, next_timestamp);
319 pthread_mutex_lock(&lock);
321 p->timestamp = timestamp;
322 /* Convert to target format */
323 if(header.mpt & 0x80)
325 switch(header.mpt & 0x7F) {
327 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
328 /* ALSA can do any necessary conversion itself (though it might be better
329 * to do any necessary conversion in the background) */
330 /* TODO we could readv into the buffer */
332 /* TODO support other RFC3551 media types (when the speaker does) */
334 fatal(0, "unsupported RTP payload type %d",
338 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
339 seq, timestamp, p->nsamples, timestamp + p->nsamples);
340 /* Stop reading if we've reached the maximum.
342 * This is rather unsatisfactory: it means that if packets get heavily
343 * out of order then we guarantee dropouts. But for now... */
344 if(nsamples >= maxbuffer) {
346 while(nsamples >= maxbuffer)
347 pthread_cond_wait(&cond, &lock);
349 /* Add the packet to the heap */
350 pheap_insert(&packets, p);
351 nsamples += p->nsamples;
352 /* We'll need a new packet */
354 pthread_cond_broadcast(&cond);
355 pthread_mutex_unlock(&lock);
359 /** @brief Return true if @p p contains @p timestamp */
360 static inline int contains(const struct packet *p, uint32_t timestamp) {
361 const uint32_t packet_start = p->timestamp;
362 const uint32_t packet_end = p->timestamp + p->nsamples;
364 return (ge(timestamp, packet_start)
365 && lt(timestamp, packet_end));
368 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
369 /** @brief Callback from Core Audio */
370 static OSStatus adioproc
371 (AudioDeviceID attribute((unused)) inDevice,
372 const AudioTimeStamp attribute((unused)) *inNow,
373 const AudioBufferList attribute((unused)) *inInputData,
374 const AudioTimeStamp attribute((unused)) *inInputTime,
375 AudioBufferList *outOutputData,
376 const AudioTimeStamp attribute((unused)) *inOutputTime,
377 void attribute((unused)) *inClientData) {
378 UInt32 nbuffers = outOutputData->mNumberBuffers;
379 AudioBuffer *ab = outOutputData->mBuffers;
380 const struct packet *p;
381 uint32_t samples_available;
382 struct timeval in, out;
384 gettimeofday(&in, 0);
385 pthread_mutex_lock(&lock);
386 while(nbuffers > 0) {
387 float *samplesOut = ab->mData;
388 size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
390 while(samplesOutLeft > 0) {
391 /* Look for a suitable packet, dropping any unsuitable ones along the
392 * way. Unsuitable packets are ones that are in the past. */
393 while(pheap_count(&packets)) {
394 p = pheap_first(&packets);
395 if(le(p->timestamp + p->nsamples, next_timestamp))
396 /* This packet is in the past. Drop it and try another one. */
399 /* This packet is NOT in the past. (It might be in the future
403 p = pheap_count(&packets) ? pheap_first(&packets) : 0;
404 if(p && contains(p, next_timestamp)) {
406 fprintf(stderr, "\nIDLE\n");
407 /* This packet is ready to play */
408 const uint32_t packet_end = p->timestamp + p->nsamples;
409 const uint32_t offset = next_timestamp - p->timestamp;
410 const uint16_t *ptr = (void *)(p->samples_raw + offset);
412 samples_available = packet_end - next_timestamp;
413 if(samples_available > samplesOutLeft)
414 samples_available = samplesOutLeft;
415 next_timestamp += samples_available;
416 samplesOutLeft -= samples_available;
417 while(samples_available-- > 0)
418 *samplesOut++ = (int16_t)ntohs(*ptr++) * (0.5 / 32767);
419 /* We don't bother junking the packet - that'll be dealt with next time
423 /* No packet is ready to play (and there might be no packet at all) */
424 samples_available = p ? p->timestamp - next_timestamp
426 if(samples_available > samplesOutLeft)
427 samples_available = samplesOutLeft;
428 //info("infill by %"PRIu32, samples_available);
429 /* Conveniently the buffer is 0 to start with */
430 next_timestamp += samples_available;
431 samplesOut += samples_available;
432 samplesOutLeft -= samples_available;
439 pthread_mutex_unlock(&lock);
440 gettimeofday(&out, 0);
443 double thistime = (out.tv_sec - in.tv_sec) + (out.tv_usec - in.tv_usec) / 1000000.0;
445 fprintf(stderr, "adioproc: %8.8fs\n", max = thistime);
453 /** @brief PCM handle */
454 static snd_pcm_t *pcm;
456 /** @brief True when @ref pcm is up and running */
457 static int alsa_prepared = 1;
459 /** @brief Initialize @ref pcm */
460 static void setup_alsa(void) {
461 snd_pcm_hw_params_t *hwparams;
462 snd_pcm_sw_params_t *swparams;
463 /* Only support one format for now */
464 const int sample_format = SND_PCM_FORMAT_S16_BE;
465 unsigned rate = 44100;
466 const int channels = 2;
467 const int samplesize = channels * sizeof(uint16_t);
468 snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
469 /* If we can write more than this many samples we'll get a wakeup */
470 const int avail_min = 256;
474 if((err = snd_pcm_open(&pcm,
475 device ? device : "default",
476 SND_PCM_STREAM_PLAYBACK,
478 fatal(0, "error from snd_pcm_open: %d", err);
479 /* Set up 'hardware' parameters */
480 snd_pcm_hw_params_alloca(&hwparams);
481 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
482 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
483 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
484 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
485 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
486 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
489 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
491 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
492 fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
494 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
496 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
498 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
500 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
501 MAXSAMPLES * samplesize * 3, err);
502 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
503 fatal(0, "error calling snd_pcm_hw_params: %d", err);
504 /* Set up 'software' parameters */
505 snd_pcm_sw_params_alloca(&swparams);
506 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
507 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
508 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
509 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
511 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
512 fatal(0, "error calling snd_pcm_sw_params: %d", err);
515 /** @brief Wait until ALSA wants some audio */
516 static void wait_alsa(void) {
517 struct pollfd fds[64];
519 unsigned short events;
523 if((nfds = snd_pcm_poll_descriptors(pcm,
524 fds, sizeof fds / sizeof *fds)) < 0)
525 fatal(0, "error calling snd_pcm_poll_descriptors: %d", nfds);
526 } while(poll(fds, nfds, -1) < 0 && errno == EINTR);
527 if((err = snd_pcm_poll_descriptors_revents(pcm, fds, nfds, &events)))
528 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
534 /** @brief Play some sound
535 * @param s Pointer to sample data
536 * @param n Number of samples
537 * @return 0 on success, -1 on non-fatal error
539 static int alsa_writei(const void *s, size_t n) {
541 const snd_pcm_sframes_t frames_written = snd_pcm_writei(pcm, s, n / 2);
542 if(frames_written < 0) {
543 /* Something went wrong */
544 switch(frames_written) {
548 error(0, "error calling snd_pcm_writei: %ld",
549 (long)frames_written);
552 fatal(0, "error calling snd_pcm_writei: %ld",
553 (long)frames_written);
557 next_timestamp += frames_written * 2;
562 /** @brief Play the relevant part of a packet
563 * @param p Packet to play
564 * @return 0 on success, -1 on non-fatal error
566 static int alsa_play(const struct packet *p) {
568 return alsa_writei(p->samples_raw + next_timestamp - p->timestamp,
569 (p->timestamp + p->nsamples) - next_timestamp);
572 /** @brief Play some silence
573 * @param p Next packet or NULL
574 * @return 0 on success, -1 on non-fatal error
576 static int alsa_infill(const struct packet *p) {
577 static const uint16_t zeros[INFILL_SAMPLES];
578 size_t samples_available = INFILL_SAMPLES;
580 if(p && samples_available > p->timestamp - next_timestamp)
581 samples_available = p->timestamp - next_timestamp;
583 return alsa_writei(zeros, samples_available);
586 /** @brief Reset ALSA state after we lost synchronization */
587 static void alsa_reset(int hard_reset) {
590 if((err = snd_pcm_nonblock(pcm, 0)))
591 fatal(0, "error calling snd_pcm_nonblock: %d", err);
593 if((err = snd_pcm_drop(pcm)))
594 fatal(0, "error calling snd_pcm_drop: %d", err);
596 if((err = snd_pcm_drain(pcm)))
597 fatal(0, "error calling snd_pcm_drain: %d", err);
598 if((err = snd_pcm_nonblock(pcm, 1)))
599 fatal(0, "error calling snd_pcm_nonblock: %d", err);
604 /** @brief Wait until the buffer is adequately full
606 * Must be called with @ref lock held.
608 static void fill_buffer(void) {
609 info("Buffering...");
610 while(nsamples < readahead)
611 pthread_cond_wait(&cond, &lock);
612 next_timestamp = pheap_first(&packets)->timestamp;
616 /** @brief Find next packet
617 * @return Packet to play or NULL if none found
619 * The return packet is merely guaranteed not to be in the past: it might be
620 * the first packet in the future rather than one that is actually suitable to
623 * Must be called with @ref lock held.
625 static struct packet *next_packet(void) {
626 while(pheap_count(&packets)) {
627 struct packet *const p = pheap_first(&packets);
628 if(le(p->timestamp + p->nsamples, next_timestamp)) {
629 /* This packet is in the past. Drop it and try another one. */
632 /* This packet is NOT in the past. (It might be in the future
639 /** @brief Play an RTP stream
641 * This is the guts of the program. It is responsible for:
642 * - starting the listening thread
643 * - opening the audio device
644 * - reading ahead to build up a buffer
645 * - arranging for audio to be played
646 * - detecting when the buffer has got too small and re-buffering
648 static void play_rtp(void) {
651 /* We receive and convert audio data in a background thread */
652 pthread_create(<id, 0, listen_thread, 0);
658 /* Open the sound device */
660 pthread_mutex_lock(&lock);
662 /* Wait for the buffer to fill up a bit */
665 if((err = snd_pcm_prepare(pcm)))
666 fatal(0, "error calling snd_pcm_prepare: %d", err);
671 /* Keep playing until the buffer empties out, or ALSA tells us to get
673 while(nsamples >= minbuffer && !escape) {
674 /* Wait for ALSA to ask us for more data */
675 pthread_mutex_unlock(&lock);
677 pthread_mutex_lock(&lock);
678 /* ALSA is ready for more data, find something to play */
680 /* Play it or play some silence */
681 if(contains(p, next_timestamp))
682 escape = alsa_play(p);
684 escape = alsa_infill(p);
687 /* We stop playing for a bit until the buffer re-fills */
688 pthread_mutex_unlock(&lock);
690 pthread_mutex_lock(&lock);
694 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
699 AudioStreamBasicDescription asbd;
701 /* If this looks suspiciously like libao's macosx driver there's an
702 * excellent reason for that... */
704 /* TODO report errors as strings not numbers */
705 propertySize = sizeof adid;
706 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
707 &propertySize, &adid);
709 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
710 if(adid == kAudioDeviceUnknown)
711 fatal(0, "no output device");
712 propertySize = sizeof asbd;
713 status = AudioDeviceGetProperty(adid, 0, false,
714 kAudioDevicePropertyStreamFormat,
715 &propertySize, &asbd);
717 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
718 D(("mSampleRate %f", asbd.mSampleRate));
719 D(("mFormatID %08lx", asbd.mFormatID));
720 D(("mFormatFlags %08lx", asbd.mFormatFlags));
721 D(("mBytesPerPacket %08lx", asbd.mBytesPerPacket));
722 D(("mFramesPerPacket %08lx", asbd.mFramesPerPacket));
723 D(("mBytesPerFrame %08lx", asbd.mBytesPerFrame));
724 D(("mChannelsPerFrame %08lx", asbd.mChannelsPerFrame));
725 D(("mBitsPerChannel %08lx", asbd.mBitsPerChannel));
726 D(("mReserved %08lx", asbd.mReserved));
727 if(asbd.mFormatID != kAudioFormatLinearPCM)
728 fatal(0, "audio device does not support kAudioFormatLinearPCM");
729 status = AudioDeviceAddIOProc(adid, adioproc, 0);
731 fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
732 pthread_mutex_lock(&lock);
734 /* Wait for the buffer to fill up a bit */
736 /* Start playing now */
738 next_timestamp = pheap_first(&packets)->timestamp;
740 status = AudioDeviceStart(adid, adioproc);
742 fatal(0, "AudioDeviceStart: %d", (int)status);
743 /* Wait until the buffer empties out */
744 while(nsamples >= minbuffer)
745 pthread_cond_wait(&cond, &lock);
746 /* Stop playing for a bit until the buffer re-fills */
747 status = AudioDeviceStop(adid, adioproc);
749 fatal(0, "AudioDeviceStop: %d", (int)status);
755 # error No known audio API
759 /* display usage message and terminate */
760 static void help(void) {
762 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
764 " --device, -D DEVICE Output device\n"
765 " --min, -m FRAMES Buffer low water mark\n"
766 " --buffer, -b FRAMES Buffer high water mark\n"
767 " --max, -x FRAMES Buffer maximum size\n"
768 " --help, -h Display usage message\n"
769 " --version, -V Display version number\n"
775 /* display version number and terminate */
776 static void version(void) {
777 xprintf("disorder-playrtp version %s\n", disorder_version_string);
782 int main(int argc, char **argv) {
784 struct addrinfo *res;
785 struct stringlist sl;
788 static const struct addrinfo prefs = {
800 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
801 while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:", options, 0)) >= 0) {
805 case 'd': debugging = 1; break;
806 case 'D': device = optarg; break;
807 case 'm': minbuffer = 2 * atol(optarg); break;
808 case 'b': readahead = 2 * atol(optarg); break;
809 case 'x': maxbuffer = 2 * atol(optarg); break;
810 case 'L': logfp = fopen(optarg, "w"); break;
811 default: fatal(0, "invalid option");
815 maxbuffer = 4 * readahead;
818 if(argc < 1 || argc > 2)
819 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
822 /* Listen for inbound audio data */
823 if(!(res = get_address(&sl, &prefs, &sockname)))
825 if((rtpfd = socket(res->ai_family,
827 res->ai_protocol)) < 0)
828 fatal(errno, "error creating socket");
829 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
830 fatal(errno, "error binding socket to %s", sockname);