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
27 #include <sys/socket.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
37 #include "configuration.h"
43 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
44 # include <CoreAudio/AudioHardware.h>
47 #include <alsa/asoundlib.h>
50 #define readahead linux_headers_are_borked
52 /** @brief RTP socket */
55 /** @brief Log output */
58 /** @brief Output device */
59 static const char *device;
61 /** @brief Maximum samples per packet we'll support
63 * NB that two channels = two samples in this program.
65 #define MAXSAMPLES 2048
67 /** @brief Minimum low watermark
69 * We'll stop playing if there's only this many samples in the buffer. */
70 static unsigned minbuffer = 2 * 44100 / 10; /* 0.2 seconds */
72 /** @brief Maximum sample size
74 * The maximum supported size (in bytes) of one sample. */
75 #define MAXSAMPLESIZE 2
77 /** @brief Buffer high watermark
79 * We'll only start playing when this many samples are available. */
80 static unsigned readahead = 2 * 2 * 44100;
82 /** @brief Maximum buffer size
84 * We'll stop reading from the network if we have this many samples. */
85 static unsigned maxbuffer;
87 /** @brief Number of samples to infill by in one go */
88 #define INFILL_SAMPLES (44100 * 2) /* 1s */
90 /** @brief Received packet */
92 /** @brief Number of samples in this packet */
94 /** @brief Timestamp from RTP packet
96 * NB that "timestamps" are really sample counters.*/
98 /** @brief Raw sample data */
99 unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE];
102 /** @brief Total number of samples available */
103 static unsigned long nsamples;
105 /** @brief Mapping of sequence numbers to packets
107 * This isn't very efficient - 256KB on 32-bit machines, 512KB if you do a
108 * 64-bit build for some reason. It can be optimized later if need be. */
109 static struct packet *packets[65536];
111 /** @brief Total number of packets */
112 static unsigned npackets;
114 /** @brief Timestamp of next packet to play.
116 * This is set to the timestamp of the last packet, plus the number of
117 * samples it contained. Only valid if @ref active is nonzero.
119 static uint32_t next_timestamp;
121 /** @brief True if actively playing
123 * This is true when playing and false when just buffering. */
126 /** @brief Sequence number of next packet we expxect to play */
127 static uint16_t sequence;
129 /** @brief Structure of free packet list */
132 union free_packet *next;
135 /** @brief Linked list of free packets */
136 static union free_packet *free_packets;
138 /** @brief Array of new free packets */
139 static union free_packet *next_free_packet;
141 /** @brief Count of new free packets */
142 static size_t count_free_packets;
144 /** @brief Lock protecting @ref packets */
145 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
147 /** @brief Condition variable signalled whenever @ref packets is changed */
148 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
150 static const struct option options[] = {
151 { "help", no_argument, 0, 'h' },
152 { "version", no_argument, 0, 'V' },
153 { "debug", no_argument, 0, 'd' },
154 { "device", required_argument, 0, 'D' },
155 { "min", required_argument, 0, 'm' },
156 { "max", required_argument, 0, 'x' },
157 { "buffer", required_argument, 0, 'b' },
161 /** @brief Return a new packet
163 * Assumes that @ref lock is held. */
164 static struct packet *new_packet(void) {
168 p = &free_packets->p;
169 free_packets = free_packets->next;
171 if(!count_free_packets) {
172 next_free_packet = xcalloc(1024, sizeof (union free_packet));
173 count_free_packets = 1024;
175 p = &(next_free_packet++)->p;
176 --count_free_packets;
181 /** @brief Free a packet
183 * Assumes that @ref lock is held. */
184 static void free_packet(struct packet *p) {
185 union free_packet *u = (union free_packet *)p;
186 u->next = free_packets;
190 /** @brief Return true iff a < b in sequence-space arithmetic */
191 static inline int lt(uint32_t a, uint32_t b) {
192 return (uint32_t)(a - b) & 0x80000000;
195 /** @brief Return true iff a >= b in sequence-space arithmetic */
196 static inline int ge(uint32_t a, uint32_t b) {
200 /** @brief Return true iff a > b in sequence-space arithmetic */
201 static inline int gt(uint32_t a, uint32_t b) {
205 /** @brief Return true iff a <= b in sequence-space arithmetic */
206 static inline int le(uint32_t a, uint32_t b) {
210 /** @brief Drop the packet at the head of the queue */
211 static void drop_packet(unsigned sequence) {
212 if(packets[sequence]) {
213 nsamples -= packets[sequence]->nsamples;
214 free_packet(packets[sequence]);
215 packets[sequence] = 0;
216 pthread_cond_broadcast(&cond);
221 /** @brief Background thread collecting samples
223 * This function collects samples, perhaps converts them to the target format,
224 * and adds them to the packet list. */
225 static void *listen_thread(void attribute((unused)) *arg) {
226 struct packet *p = 0;
228 struct rtp_header header;
235 pthread_mutex_lock(&lock);
237 pthread_mutex_unlock(&lock);
239 iov[0].iov_base = &header;
240 iov[0].iov_len = sizeof header;
241 iov[1].iov_base = p->samples_raw;
242 iov[1].iov_len = sizeof p->samples_raw;
243 n = readv(rtpfd, iov, 2);
249 fatal(errno, "error reading from socket");
252 /* Ignore too-short packets */
253 if((size_t)n <= sizeof (struct rtp_header)) {
254 info("ignored a short packet");
257 timestamp = htonl(header.timestamp);
258 seq = htons(header.seq);
259 /* Ignore packets in the past */
260 if(active && lt(timestamp, next_timestamp)) {
261 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
262 timestamp, next_timestamp);
265 pthread_mutex_lock(&lock);
267 p->timestamp = timestamp;
268 /* Convert to target format */
269 switch(header.mpt & 0x7F) {
271 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
272 /* ALSA can do any necessary conversion itself (though it might be better
273 * to do any necessary conversion in the background) */
274 /* TODO we could readv into the buffer */
276 /* TODO support other RFC3551 media types (when the speaker does) */
278 fatal(0, "unsupported RTP payload type %d",
282 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
283 seq, timestamp, p->nsamples, timestamp + p->nsamples);
284 /* Stop reading if we've reached the maximum.
286 * This is rather unsatisfactory: it means that if packets get heavily
287 * out of order then we guarantee dropouts. But for now... */
288 if(nsamples >= maxbuffer) {
290 while(nsamples >= maxbuffer)
291 pthread_cond_wait(&cond, &lock);
293 /* If there's a packet there already we overwrite it; perhaps it is left
294 * over from an earlier stage. */
296 /* Record this packet */
298 /* If we currently have no idea where to start playing, this is it */
302 nsamples += p->nsamples;
303 pthread_cond_broadcast(&cond);
304 pthread_mutex_unlock(&lock);
308 /** @brief Return true if @p p contains @p timestamp */
309 static inline int contains(const struct packet *p, uint32_t timestamp) {
310 const uint32_t packet_start = p->timestamp;
311 const uint32_t packet_end = p->timestamp + p->nsamples;
313 return (ge(timestamp, packet_start)
314 && lt(timestamp, packet_end));
317 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
318 /** @brief Callback from Core Audio */
319 static OSStatus adioproc
320 (AudioDeviceID attribute((unused)) inDevice,
321 const AudioTimeStamp attribute((unused)) *inNow,
322 const AudioBufferList attribute((unused)) *inInputData,
323 const AudioTimeStamp attribute((unused)) *inInputTime,
324 AudioBufferList *outOutputData,
325 const AudioTimeStamp attribute((unused)) *inOutputTime,
326 void attribute((unused)) *inClientData) {
327 UInt32 nbuffers = outOutputData->mNumberBuffers;
328 AudioBuffer *ab = outOutputData->mBuffers;
329 const struct packet *p;
331 pthread_mutex_lock(&lock);
332 while(nbuffers > 0) {
333 float *samplesOut = ab->mData;
334 size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
336 while(samplesOutLeft > 0) {
337 /* Look for a suitable packet, dropping any unsuitable ones along the
338 * way. Unsuitable packets are ones that are in the past. */
340 && (!packets[sequence]
341 || le(packets[sequence]->timestamp
342 + packets[sequence]->nsamples,
344 drop_packet(sequence++);
345 p = packets[sequence];
347 if(contains(p, next_timestamp)) {
348 /* This packet is suitable */
349 const uint32_t packet_end = p->timestamp + p->nsamples;
350 const uint32_t offset = next_timestamp - p->timestamp;
351 const uint16_t *ptr =
352 (void *)(p->samples_raw + offset * sizeof (uint16_t));
353 uint32_t samples_available = packet_end - next_timestamp;
354 if(samples_available > samplesOutLeft)
355 samples_available = samplesOutLeft;
356 next_timestamp += samples_available;
357 samplesOutLeft -= samples_available;
358 while(samples_available-- > 0)
359 *samplesOut++ = (int16_t)ntohs(*ptr++) * (0.5 / 32767);
360 /* We don't bother junking the packet or advancing sequence - that'll
361 * be dealt with next time round */
365 /* We didn't find a suitable packet (though there might still be
366 * unsuitable ones). We infill with 0s. */
368 /* There is a next packet, only infill up to that point */
369 uint32_t samples_available = p->timestamp - next_timestamp;
371 if(samples_available > samplesOutLeft)
372 samples_available = samplesOutLeft;
373 info("infill by %"PRIu32, samples_available);
374 /* Convniently the buffer is 0 to start with */
375 next_timestamp += samples_available;
376 samplesOut += samples_available;
377 samplesOutLeft -= samples_available;
379 /* There's no next packet at all */
380 info("infilled by %zu", samplesOutLeft);
381 next_timestamp += samplesOutLeft;
382 samplesOut += samplesOutLeft;
389 pthread_mutex_unlock(&lock);
394 /** @brief Play an RTP stream
396 * This is the guts of the program. It is responsible for:
397 * - starting the listening thread
398 * - opening the audio device
399 * - reading ahead to build up a buffer
400 * - arranging for audio to be played
401 * - detecting when the buffer has got too small and re-buffering
403 static void play_rtp(void) {
406 /* We receive and convert audio data in a background thread */
407 pthread_create(<id, 0, listen_thread, 0);
411 snd_pcm_hw_params_t *hwparams;
412 snd_pcm_sw_params_t *swparams;
413 /* Only support one format for now */
414 const int sample_format = SND_PCM_FORMAT_S16_BE;
415 unsigned rate = 44100;
416 const int channels = 2;
417 const int samplesize = channels * sizeof(uint16_t);
418 snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
419 /* If we can write more than this many samples we'll get a wakeup */
420 const int avail_min = 256;
421 snd_pcm_sframes_t frames_written;
422 size_t samples_written;
425 int infilling = 0, escape = 0;
427 uint32_t packet_start, packet_end;
430 if((err = snd_pcm_open(&pcm,
431 device ? device : "default",
432 SND_PCM_STREAM_PLAYBACK,
434 fatal(0, "error from snd_pcm_open: %d", err);
435 /* Set up 'hardware' parameters */
436 snd_pcm_hw_params_alloca(&hwparams);
437 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
438 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
439 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
440 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
441 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
442 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
444 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
446 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
447 fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
449 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
451 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
453 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
455 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
456 MAXSAMPLES * samplesize * 3, err);
457 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
458 fatal(0, "error calling snd_pcm_hw_params: %d", err);
459 /* Set up 'software' parameters */
460 snd_pcm_sw_params_alloca(&swparams);
461 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
462 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
463 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
464 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
466 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
467 fatal(0, "error calling snd_pcm_sw_params: %d", err);
472 pthread_mutex_lock(&lock);
474 /* Wait for the buffer to fill up a bit */
476 info("%lu samples in buffer (%lus)", nsamples,
477 nsamples / (44100 * 2));
478 info("Buffering...");
479 while(nsamples < readahead)
480 pthread_cond_wait(&cond, &lock);
482 if((err = snd_pcm_prepare(pcm)))
483 fatal(0, "error calling snd_pcm_prepare: %d", err);
486 assert(sequence != -1);
487 /* Start at the first available packet */
488 next_timestamp = packets[sequence]->timestamp;
493 info("%lu samples in buffer (%lus)", nsamples,
494 nsamples / (44100 * 2));
496 /* Wait until the buffer empties out */
497 while(nsamples >= minbuffer && !escape) {
499 if(now > logged + 10) {
501 info("%lu samples in buffer (%lus)", nsamples,
502 nsamples / (44100 * 2));
505 && ge(next_timestamp, packets->timestamp + packets->nsamples)) {
506 info("dropping buffered past packet %"PRIx32" < %"PRIx32,
507 packets->timestamp, next_timestamp);
511 /* Wait for ALSA to ask us for more data */
512 pthread_mutex_unlock(&lock);
513 write(2, ".", 1); /* TODO remove me sometime */
514 switch(err = snd_pcm_wait(pcm, -1)) {
516 info("snd_pcm_wait timed out");
521 fatal(0, "snd_pcm_wait returned %d", err);
523 pthread_mutex_lock(&lock);
524 /* ALSA is ready for more data */
525 packet_start = packets->timestamp;
526 packet_end = packets->timestamp + packets->nsamples;
527 if(ge(next_timestamp, packet_start)
528 && lt(next_timestamp, packet_end)) {
529 /* The target timestamp is somewhere in this packet */
530 const uint32_t offset = next_timestamp - packets->timestamp;
531 const uint32_t samples_available = (packets->timestamp + packets->nsamples) - next_timestamp;
532 const size_t frames_available = samples_available / 2;
534 frames_written = snd_pcm_writei(pcm,
535 packets->samples_raw + offset,
537 if(frames_written < 0) {
538 switch(frames_written) {
540 info("snd_pcm_wait() returned but we got -EAGAIN!");
543 error(0, "error calling snd_pcm_writei: %ld",
544 (long)frames_written);
548 fatal(0, "error calling snd_pcm_writei: %ld",
549 (long)frames_written);
552 samples_written = frames_written * 2;
553 next_timestamp += samples_written;
554 if(ge(next_timestamp, packet_end))
559 /* We don't have anything to play! We'd better play some 0s. */
560 static const uint16_t zeros[INFILL_SAMPLES];
561 size_t samples_available = INFILL_SAMPLES, frames_available;
563 /* If the maximum infill would take us past the start of the next
564 * packet then we truncate the infill to the right amount. */
565 if(lt(packets->timestamp,
566 next_timestamp + samples_available))
567 samples_available = packets->timestamp - next_timestamp;
568 if((int)samples_available < 0) {
569 info("packets->timestamp: %"PRIx32" next_timestamp: %"PRIx32" next+max: %"PRIx32" available: %"PRIx32,
570 packets->timestamp, next_timestamp,
571 next_timestamp + INFILL_SAMPLES, samples_available);
573 frames_available = samples_available / 2;
575 info("Infilling %d samples, next=%"PRIx32" packet=[%"PRIx32",%"PRIx32"]",
576 samples_available, next_timestamp,
577 packets->timestamp, packets->timestamp + packets->nsamples);
580 frames_written = snd_pcm_writei(pcm,
583 if(frames_written < 0) {
584 switch(frames_written) {
586 info("snd_pcm_wait() returned but we got -EAGAIN!");
589 error(0, "error calling snd_pcm_writei: %ld",
590 (long)frames_written);
594 fatal(0, "error calling snd_pcm_writei: %ld",
595 (long)frames_written);
598 samples_written = frames_written * 2;
599 next_timestamp += samples_written;
604 /* We stop playing for a bit until the buffer re-fills */
605 pthread_mutex_unlock(&lock);
606 if((err = snd_pcm_nonblock(pcm, 0)))
607 fatal(0, "error calling snd_pcm_nonblock: %d", err);
609 if((err = snd_pcm_drop(pcm)))
610 fatal(0, "error calling snd_pcm_drop: %d", err);
613 if((err = snd_pcm_drain(pcm)))
614 fatal(0, "error calling snd_pcm_drain: %d", err);
615 if((err = snd_pcm_nonblock(pcm, 1)))
616 fatal(0, "error calling snd_pcm_nonblock: %d", err);
618 pthread_mutex_lock(&lock);
622 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
627 AudioStreamBasicDescription asbd;
629 /* If this looks suspiciously like libao's macosx driver there's an
630 * excellent reason for that... */
632 /* TODO report errors as strings not numbers */
633 propertySize = sizeof adid;
634 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
635 &propertySize, &adid);
637 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
638 if(adid == kAudioDeviceUnknown)
639 fatal(0, "no output device");
640 propertySize = sizeof asbd;
641 status = AudioDeviceGetProperty(adid, 0, false,
642 kAudioDevicePropertyStreamFormat,
643 &propertySize, &asbd);
645 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
646 D(("mSampleRate %f", asbd.mSampleRate));
647 D(("mFormatID %08lx", asbd.mFormatID));
648 D(("mFormatFlags %08lx", asbd.mFormatFlags));
649 D(("mBytesPerPacket %08lx", asbd.mBytesPerPacket));
650 D(("mFramesPerPacket %08lx", asbd.mFramesPerPacket));
651 D(("mBytesPerFrame %08lx", asbd.mBytesPerFrame));
652 D(("mChannelsPerFrame %08lx", asbd.mChannelsPerFrame));
653 D(("mBitsPerChannel %08lx", asbd.mBitsPerChannel));
654 D(("mReserved %08lx", asbd.mReserved));
655 if(asbd.mFormatID != kAudioFormatLinearPCM)
656 fatal(0, "audio device does not support kAudioFormatLinearPCM");
657 status = AudioDeviceAddIOProc(adid, adioproc, 0);
659 fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
660 pthread_mutex_lock(&lock);
662 /* Wait for the buffer to fill up a bit */
663 info("Buffering...");
664 while(nsamples < readahead)
665 pthread_cond_wait(&cond, &lock);
666 /* Start playing now */
668 next_timestamp = packets[sequence]->timestamp;
670 status = AudioDeviceStart(adid, adioproc);
672 fatal(0, "AudioDeviceStart: %d", (int)status);
673 /* Wait until the buffer empties out */
674 while(nsamples >= minbuffer)
675 pthread_cond_wait(&cond, &lock);
676 /* Stop playing for a bit until the buffer re-fills */
677 status = AudioDeviceStop(adid, adioproc);
679 fatal(0, "AudioDeviceStop: %d", (int)status);
685 # error No known audio API
689 /* display usage message and terminate */
690 static void help(void) {
692 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
694 " --device, -D DEVICE Output device\n"
695 " --min, -m FRAMES Buffer low water mark\n"
696 " --buffer, -b FRAMES Buffer high water mark\n"
697 " --max, -x FRAMES Buffer maximum size\n"
698 " --help, -h Display usage message\n"
699 " --version, -V Display version number\n"
705 /* display version number and terminate */
706 static void version(void) {
707 xprintf("disorder-playrtp version %s\n", disorder_version_string);
712 int main(int argc, char **argv) {
714 struct addrinfo *res;
715 struct stringlist sl;
718 static const struct addrinfo prefs = {
730 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
731 while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:", options, 0)) >= 0) {
735 case 'd': debugging = 1; break;
736 case 'D': device = optarg; break;
737 case 'm': minbuffer = 2 * atol(optarg); break;
738 case 'b': readahead = 2 * atol(optarg); break;
739 case 'x': maxbuffer = 2 * atol(optarg); break;
740 case 'L': logfp = fopen(optarg, "w"); break;
741 default: fatal(0, "invalid option");
745 maxbuffer = 4 * readahead;
748 if(argc < 1 || argc > 2)
749 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
752 /* Listen for inbound audio data */
753 if(!(res = get_address(&sl, &prefs, &sockname)))
755 if((rtpfd = socket(res->ai_family,
757 res->ai_protocol)) < 0)
758 fatal(errno, "error creating socket");
759 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
760 fatal(errno, "error binding socket to %s", sockname);