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>
36 #include "configuration.h"
42 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
43 # include <CoreAudio/AudioHardware.h>
46 #include <alsa/asoundlib.h>
49 /** @brief RTP socket */
52 /** @brief Output device */
53 static const char *device;
55 /** @brief Maximum samples per packet we'll support
57 * NB that two channels = two samples in this program.
59 #define MAXSAMPLES 2048
61 /** @brief Minimum buffer size
63 * We'll stop playing if there's only this many samples in the buffer. */
64 #define MINBUFFER 8820
66 /** @brief Maximum sample size
68 * The maximum supported size (in bytes) of one sample. */
69 #define MAXSAMPLESIZE 2
71 #define READAHEAD 88200 /* how far to read ahead */
73 #define MAXBUFFER (3 * 88200) /* maximum buffer contents */
75 /** @brief Received packet
77 * Packets are recorded in an ordered linked list. */
79 /** @brief Pointer to next packet
80 * The next packet might not be immediately next: if packets are dropped
81 * or mis-ordered there may be gaps at any given moment. */
83 /** @brief Number of samples in this packet */
85 /** @brief Number of samples used from this packet */
87 /** @brief Timestamp from RTP packet
89 * NB that "timestamps" are really sample counters.*/
91 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
92 /** @brief Converted sample data */
93 float samples_float[MAXSAMPLES];
95 /** @brief Raw sample data */
96 unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE];
100 /** @brief Total number of samples available */
101 static unsigned long nsamples;
103 /** @brief Linked list of packets
105 * In ascending order of timestamp. */
106 static struct packet *packets;
108 /** @brief Timestamp of next packet to play.
110 * This is set to the timestamp of the last packet, plus the number of
111 * samples it contained. Only valid if @ref active is nonzero.
113 static uint32_t next_timestamp;
115 /** @brief True if actively playing
117 * This is true when playing and false when just buffering. */
120 /** @brief Lock protecting @ref packets */
121 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
123 /** @brief Condition variable signalled whenever @ref packets is changed */
124 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
126 static const struct option options[] = {
127 { "help", no_argument, 0, 'h' },
128 { "version", no_argument, 0, 'V' },
129 { "debug", no_argument, 0, 'd' },
130 { "device", required_argument, 0, 'D' },
134 /** @brief Return true iff a < b in sequence-space arithmetic */
135 static inline int lt(uint32_t a, uint32_t b) {
136 return (uint32_t)(a - b) & 0x80000000;
139 /** @brief Background thread collecting samples
141 * This function collects samples, perhaps converts them to the target format,
142 * and adds them to the packet list. */
143 static void *listen_thread(void attribute((unused)) *arg) {
144 struct packet *p = 0, **pp;
147 struct rtp_header header;
148 uint8_t bytes[sizeof(uint16_t) * MAXSAMPLES + sizeof (struct rtp_header)];
150 const uint16_t *const samples = (uint16_t *)(packet.bytes
151 + sizeof (struct rtp_header));
155 p = xmalloc(sizeof *p);
156 n = read(rtpfd, packet.bytes, sizeof packet.bytes);
162 fatal(errno, "error reading from socket");
165 /* Ignore too-short packets */
166 if((size_t)n <= sizeof (struct rtp_header))
169 p->timestamp = ntohl(packet.header.timestamp);
170 /* Ignore packets in the past */
171 if(active && lt(p->timestamp, next_timestamp))
173 /* Convert to target format */
174 switch(packet.header.mpt & 0x7F) {
176 p->nsamples = (n - sizeof (struct rtp_header)) / sizeof(uint16_t);
177 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
178 /* Convert to what Core Audio expects */
179 for(n = 0; n < p->nsamples; ++n)
180 p->samples_float[n] = (int16_t)ntohs(samples[n]) * (0.5f / 32767);
182 /* ALSA can do any necessary conversion itself (though it might be better
183 * to do any necessary conversion in the background) */
184 memcpy(p->samples_raw, samples, n - sizeof (struct rtp_header));
187 /* TODO support other RFC3551 media types (when the speaker does) */
189 fatal(0, "unsupported RTP payload type %d",
190 packet.header.mpt & 0x7F);
192 pthread_mutex_lock(&lock);
193 /* Stop reading if we've reached the maximum.
195 * This is rather unsatisfactory: it means that if packets get heavily
196 * out of order then we guarantee dropouts. But for now... */
197 while(nsamples >= MAXBUFFER)
198 pthread_cond_wait(&cond, &lock);
200 *pp && lt((*pp)->timestamp, p->timestamp);
203 /* So now either !*pp or *pp >= p */
204 if(*pp && p->timestamp == (*pp)->timestamp) {
205 /* *pp == p; a duplicate. Ideally we avoid the translation step here,
206 * but we'll worry about that another time. */
210 nsamples += p->nsamples;
211 pthread_cond_broadcast(&cond);
212 p = 0; /* we've consumed this packet */
214 pthread_mutex_unlock(&lock);
218 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
219 /** @brief Callback from Core Audio */
220 static OSStatus adioproc(AudioDeviceID inDevice,
221 const AudioTimeStamp *inNow,
222 const AudioBufferList *inInputData,
223 const AudioTimeStamp *inInputTime,
224 AudioBufferList *outOutputData,
225 const AudioTimeStamp *inOutputTime,
226 void *inClientData) {
227 UInt32 nbuffers = outOutputData->mNumberBuffers;
228 AudioBuffer *ab = outOutputData->mBuffers;
229 float *samplesOut; /* where to write samples to */
230 size_t samplesOutLeft; /* space left */
231 size_t samplesInLeft;
232 size_t samplesToCopy;
234 pthread_mutex_lock(&lock);
235 samplesOut = ab->data;
236 samplesOutLeft = ab->mDataByteSize / sizeof (float);
237 while(packets && nbuffers > 0) {
238 if(packets->used == packets->nsamples) {
239 /* TODO if we dropped a packet then we should introduce a gap here */
240 struct packet *const p = packets;
243 pthread_cond_broadcast(&cond);
246 if(samplesOutLeft == 0) {
249 samplesOut = ab->data;
250 samplesOutLeft = ab->mDataByteSize / sizeof (float);
253 /* Now: (1) there is some data left to read
254 * (2) there is some space to put it */
255 samplesInLeft = packets->nsamples - packets->used;
256 samplesToCopy = (samplesInLeft < samplesOutLeft
257 ? samplesInLeft : samplesOutLeft);
258 memcpy(samplesOut, packet->samples + packets->used, samplesToCopy);
259 packets->used += samplesToCopy;
260 samplesOut += samplesToCopy;
261 samesOutLeft -= samplesToCopy;
263 pthread_mutex_unlock(&lock);
268 /** @brief Play an RTP stream
270 * This is the guts of the program. It is responsible for:
271 * - starting the listening thread
272 * - opening the audio device
273 * - reading ahead to build up a buffer
274 * - arranging for audio to be played
275 * - detecting when the buffer has got too small and re-buffering
277 static void play_rtp(void) {
280 /* We receive and convert audio data in a background thread */
281 pthread_create(<id, 0, listen_thread, 0);
285 snd_pcm_hw_params_t *hwparams;
286 snd_pcm_sw_params_t *swparams;
287 /* Only support one format for now */
288 const int sample_format = SND_PCM_FORMAT_S16_BE;
289 unsigned rate = 44100;
290 const int channels = 2;
291 const int samplesize = channels * sizeof(uint16_t);
292 snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
293 /* If we can write more than this many samples we'll get a wakeup */
294 const int avail_min = 256;
295 snd_pcm_sframes_t frames_written;
296 size_t samples_written;
301 if((err = snd_pcm_open(&pcm,
302 device ? device : "default",
303 SND_PCM_STREAM_PLAYBACK,
305 fatal(0, "error from snd_pcm_open: %d", err);
306 /* Set up 'hardware' parameters */
307 snd_pcm_hw_params_alloca(&hwparams);
308 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
309 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
310 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
311 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
312 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
313 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
315 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
317 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
318 fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
320 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
322 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
324 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
326 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
327 MAXSAMPLES * samplesize * 3, err);
328 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
329 fatal(0, "error calling snd_pcm_hw_params: %d", err);
330 /* Set up 'software' parameters */
331 snd_pcm_sw_params_alloca(&swparams);
332 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
333 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
334 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
335 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
337 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
338 fatal(0, "error calling snd_pcm_sw_params: %d", err);
342 pthread_mutex_lock(&lock);
344 /* Wait for the buffer to fill up a bit */
345 while(nsamples < READAHEAD)
346 pthread_cond_wait(&cond, &lock);
348 if((err = snd_pcm_prepare(pcm)))
349 fatal(0, "error calling snd_pcm_prepare: %d", err);
352 /* Start at the first available packet */
353 next_timestamp = packets->timestamp;
355 /* Wait until the buffer empties out */
356 while(nsamples >= MINBUFFER) {
357 /* Wait for ALSA to ask us for more data */
358 pthread_mutex_unlock(&lock);
359 snd_pcm_wait(pcm, -1);
360 pthread_mutex_lock(&lock);
361 /* ALSA is ready for more data */
362 if(packets && packets->timestamp + packets->nused == next_timestamp) {
363 /* Hooray, we have a packet we can play */
364 const size_t samples_available = packets->nsamples - packets->nused;
365 const size_t frames_available = samples_available / 2;
367 frames_written = snd_pcm_writei(pcm,
368 packets->samples_raw + packets->nused,
370 if(frames_written < 0)
371 fatal(0, "error calling snd_pcm_writei: %d", err);
372 samples_written = frames_written * 2;
373 packets->nused += samples_written;
374 next_timestamp += samples_written;
375 if(packets->nused == packets->nsamples) {
376 /* We're done with this packet */
377 struct packet *p = packets;
380 nsamples -= p->nsamples;
382 pthread_cond_broadcast(&cond);
385 /* We don't have anything to play! We'd better play some 0s. */
386 static const uint16_t zeros[1024];
387 size_t samples_available = 1024, frames_available;
388 if(packets && next_timestamp + samples_available > packets->timestamp)
389 samples_available = packets->timestamp - next_timestamp;
390 frames_available = samples_available / 2;
391 frames_written = snd_pcm_writei(pcm,
394 if(frames_written < 0)
395 fatal(0, "error calling snd_pcm_writei: %d", err);
396 next_timestamp += samples_written;
400 /* We stop playing for a bit until the buffer re-fills */
401 pthread_mutex_unlock(&lock);
402 if((err = snd_pcm_drain(pcm)))
403 fatal(0, "error calling snd_pcm_drain: %d", err);
405 pthread_mutex_lock(&lock);
409 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
414 AudioStreamBasicDescription asbd;
416 /* If this looks suspiciously like libao's macosx driver there's an
417 * excellent reason for that... */
419 /* TODO report errors as strings not numbers */
420 propertySize = sizeof adid;
421 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
422 &propertySize, &adid);
424 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
425 if(adid == kAudioDeviceUnknown)
426 fatal(0, "no output device");
427 propertySize = sizeof asbd;
428 status = AudioDeviceGetProperty(adid, 0, false,
429 kAudioDevicePropertyStreamFormat,
430 &propertySize, &asbd);
432 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
433 D(("mSampleRate %f", asbd.mSampleRate));
434 D(("mFormatID %08"PRIx32, asbd.mFormatID));
435 D(("mFormatFlags %08"PRIx32, asbd.mFormatFlags));
436 D(("mBytesPerPacket %08"PRIx32, asbd.mBytesPerPacket));
437 D(("mFramesPerPacket %08"PRIx32, asbd.mFramesPerPacket));
438 D(("mBytesPerFrame %08"PRIx32, asbd.mBytesPerFrame));
439 D(("mChannelsPerFrame %08"PRIx32, asbd.mChannelsPerFrame));
440 D(("mBitsPerChannel %08"PRIx32, asbd.mBitsPerChannel));
441 D(("mReserved %08"PRIx32, asbd.mReserved));
442 if(asbd.mFormatID != kAudioFormatLinearPCM)
443 fatal(0, "audio device does not support kAudioFormatLinearPCM");
444 status = AudioDeviceAddIOProc(adid, adioproc, 0);
446 fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
447 pthread_mutex_lock(&lock);
449 /* Wait for the buffer to fill up a bit */
450 while(nsamples < READAHEAD)
451 pthread_cond_wait(&cond, &lock);
452 /* Start playing now */
453 status = AudioDeviceStart(adid, adioproc);
455 fatal(0, "AudioDeviceStart: %d", (int)status);
456 /* Wait until the buffer empties out */
457 while(nsamples >= MINBUFFER)
458 pthread_cond_wait(&cond, &lock);
459 /* Stop playing for a bit until the buffer re-fills */
460 status = AudioDeviceStop(adid, adioproc);
462 fatal(0, "AudioDeviceStop: %d", (int)status);
467 # error No known audio API
471 /* display usage message and terminate */
472 static void help(void) {
474 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
476 " --help, -h Display usage message\n"
477 " --version, -V Display version number\n"
478 " --debug, -d Turn on debugging\n"
479 " --device, -D DEVICE Output device\n");
484 /* display version number and terminate */
485 static void version(void) {
486 xprintf("disorder-playrtp version %s\n", disorder_version_string);
491 int main(int argc, char **argv) {
493 struct addrinfo *res;
494 struct stringlist sl;
497 static const struct addrinfo prefs = {
509 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
510 while((n = getopt_long(argc, argv, "hVdD", options, 0)) >= 0) {
514 case 'd': debugging = 1; break;
515 case 'D': device = optarg; break;
516 default: fatal(0, "invalid option");
521 if(argc < 1 || argc > 2)
522 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
525 /* Listen for inbound audio data */
526 if(!(res = get_address(&sl, &prefs, &sockname)))
528 if((rtpfd = socket(res->ai_family,
530 res->ai_protocol)) < 0)
531 fatal(errno, "error creating socket");
532 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
533 fatal(errno, "error binding socket to %s", sockname);