chiark / gitweb /
doxygen
[disorder] / clients / playrtp.c
CommitLineData
e83d0967
RK
1/*
2 * This file is part of DisOrder.
3 * Copyright (C) 2007 Richard Kettlewell
4 *
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.
9 *
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.
14 *
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
18 * USA
19 */
28bacdc0
RK
20/** @file clients/playrtp.c
21 * @brief RTP player
22 *
23 * This RTP player supports Linux (ALSA) and Darwin (Core Audio) systems.
24 */
e83d0967
RK
25
26#include <config.h>
27#include "types.h"
28
29#include <getopt.h>
30#include <stdio.h>
31#include <stdlib.h>
32#include <sys/socket.h>
33#include <sys/types.h>
34#include <sys/socket.h>
35#include <netdb.h>
36#include <pthread.h>
0b75463f 37#include <locale.h>
2c7c9eae 38#include <sys/uio.h>
28bacdc0 39#include <string.h>
e83d0967
RK
40
41#include "log.h"
42#include "mem.h"
43#include "configuration.h"
44#include "addr.h"
45#include "syscalls.h"
46#include "rtp.h"
0b75463f 47#include "defs.h"
28bacdc0
RK
48#include "vector.h"
49#include "heap.h"
e83d0967
RK
50
51#if HAVE_COREAUDIO_AUDIOHARDWARE_H
52# include <CoreAudio/AudioHardware.h>
53#endif
0b75463f 54#if API_ALSA
55#include <alsa/asoundlib.h>
56#endif
e83d0967 57
1153fd23 58#define readahead linux_headers_are_borked
59
0b75463f 60/** @brief RTP socket */
e83d0967
RK
61static int rtpfd;
62
345ebe66
RK
63/** @brief Log output */
64static FILE *logfp;
65
0b75463f 66/** @brief Output device */
67static const char *device;
68
69/** @brief Maximum samples per packet we'll support
70 *
71 * NB that two channels = two samples in this program.
72 */
73#define MAXSAMPLES 2048
74
9086a105 75/** @brief Minimum low watermark
0b75463f 76 *
77 * We'll stop playing if there's only this many samples in the buffer. */
1153fd23 78static unsigned minbuffer = 2 * 44100 / 10; /* 0.2 seconds */
0b75463f 79
80/** @brief Maximum sample size
81 *
82 * The maximum supported size (in bytes) of one sample. */
83#define MAXSAMPLESIZE 2
84
9086a105 85/** @brief Buffer high watermark
1153fd23 86 *
87 * We'll only start playing when this many samples are available. */
8d0c14d7 88static unsigned readahead = 2 * 2 * 44100;
0b75463f 89
9086a105
RK
90/** @brief Maximum buffer size
91 *
92 * We'll stop reading from the network if we have this many samples. */
93static unsigned maxbuffer;
94
28bacdc0
RK
95/** @brief Number of samples to infill by in one go
96 *
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.
99 */
c0e41690 100#define INFILL_SAMPLES (44100 * 2) /* 1s */
101
28bacdc0
RK
102/** @brief Received packet
103 *
104 * Received packets are kept in a binary heap (see @ref pheap) ordered by
105 * timestamp.
106 */
0b75463f 107struct packet {
0b75463f 108 /** @brief Number of samples in this packet */
c0e41690 109 uint32_t nsamples;
0b75463f 110 /** @brief Timestamp from RTP packet
111 *
28bacdc0
RK
112 * NB that "timestamps" are really sample counters. Use lt() or lt_packet()
113 * to compare timestamps.
114 */
0b75463f 115 uint32_t timestamp;
28bacdc0
RK
116 /** @brief Raw sample data
117 *
118 * Only the first @p nsamples samples are defined; the rest is uninitialized
119 * data.
120 */
0b75463f 121 unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE];
e83d0967
RK
122};
123
28bacdc0 124/** @brief Return true iff \f$a < b\f$ in sequence-space arithmetic
0b75463f 125 *
28bacdc0
RK
126 * Specifically it returns true if \f$(a-b) mod 2^{32} < 2^{31}\f$.
127 *
128 * See also lt_packet().
129 */
130static inline int lt(uint32_t a, uint32_t b) {
131 return (uint32_t)(a - b) & 0x80000000;
132}
2c7c9eae 133
28bacdc0
RK
134/** @brief Return true iff a >= b in sequence-space arithmetic */
135static inline int ge(uint32_t a, uint32_t b) {
136 return !lt(a, b);
137}
138
139/** @brief Return true iff a > b in sequence-space arithmetic */
140static inline int gt(uint32_t a, uint32_t b) {
141 return lt(b, a);
142}
143
144/** @brief Return true iff a <= b in sequence-space arithmetic */
145static inline int le(uint32_t a, uint32_t b) {
146 return !lt(b, a);
147}
148
149/** @brief Ordering for packets, used by @ref pheap */
150static inline int lt_packet(const struct packet *a, const struct packet *b) {
151 return lt(a->timestamp, b->timestamp);
152}
153
154/** @struct pheap
155 * @brief Binary heap of packets ordered by timestamp */
156HEAP_TYPE(pheap, struct packet *, lt_packet);
157
158/** @brief Binary heap of received packets */
159static struct pheap packets;
160
161/** @brief Total number of samples available */
162static unsigned long nsamples;
0b75463f 163
164/** @brief Timestamp of next packet to play.
165 *
166 * This is set to the timestamp of the last packet, plus the number of
09ee2f0d 167 * samples it contained. Only valid if @ref active is nonzero.
0b75463f 168 */
169static uint32_t next_timestamp;
e83d0967 170
09ee2f0d 171/** @brief True if actively playing
172 *
173 * This is true when playing and false when just buffering. */
174static int active;
175
2c7c9eae
RK
176/** @brief Structure of free packet list */
177union free_packet {
178 struct packet p;
179 union free_packet *next;
180};
181
28bacdc0
RK
182/** @brief Linked list of free packets
183 *
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.
188 *
189 * Must hold @ref lock when accessing this.
190 */
2c7c9eae
RK
191static union free_packet *free_packets;
192
28bacdc0
RK
193/** @brief Array of new free packets
194 *
195 * There are @ref count_free_packets ready to use at this address. If there
196 * are none left we allocate more memory.
197 *
198 * Must hold @ref lock when accessing this.
199 */
2c7c9eae
RK
200static union free_packet *next_free_packet;
201
28bacdc0
RK
202/** @brief Count of new free packets at @ref next_free_packet
203 *
204 * Must hold @ref lock when accessing this.
205 */
2c7c9eae
RK
206static size_t count_free_packets;
207
28bacdc0
RK
208/** @brief Lock protecting @ref packets
209 *
210 * This also protects the packet memory allocation infrastructure, @ref
211 * free_packets and @ref next_free_packet. */
e83d0967 212static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
e83d0967 213
0b75463f 214/** @brief Condition variable signalled whenever @ref packets is changed */
215static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
e83d0967
RK
216
217static const struct option options[] = {
218 { "help", no_argument, 0, 'h' },
219 { "version", no_argument, 0, 'V' },
220 { "debug", no_argument, 0, 'd' },
0b75463f 221 { "device", required_argument, 0, 'D' },
1153fd23 222 { "min", required_argument, 0, 'm' },
9086a105 223 { "max", required_argument, 0, 'x' },
1153fd23 224 { "buffer", required_argument, 0, 'b' },
e83d0967
RK
225 { 0, 0, 0, 0 }
226};
227
2c7c9eae
RK
228/** @brief Return a new packet
229 *
230 * Assumes that @ref lock is held. */
231static struct packet *new_packet(void) {
232 struct packet *p;
233
234 if(free_packets) {
235 p = &free_packets->p;
236 free_packets = free_packets->next;
237 } else {
238 if(!count_free_packets) {
239 next_free_packet = xcalloc(1024, sizeof (union free_packet));
240 count_free_packets = 1024;
241 }
242 p = &(next_free_packet++)->p;
243 --count_free_packets;
244 }
245 return p;
246}
247
248/** @brief Free a packet
249 *
250 * Assumes that @ref lock is held. */
251static void free_packet(struct packet *p) {
252 union free_packet *u = (union free_packet *)p;
253 u->next = free_packets;
254 free_packets = u;
255}
256
28bacdc0
RK
257/** @brief Drop the first packet
258 *
259 * Assumes that @ref lock is held.
260 */
261static void drop_first_packet(void) {
262 if(pheap_count(&packets)) {
263 struct packet *const p = pheap_remove(&packets);
264 nsamples -= p->nsamples;
265 free_packet(p);
2c7c9eae 266 pthread_cond_broadcast(&cond);
2c7c9eae 267 }
9086a105
RK
268}
269
09ee2f0d 270/** @brief Background thread collecting samples
0b75463f 271 *
272 * This function collects samples, perhaps converts them to the target format,
273 * and adds them to the packet list. */
274static void *listen_thread(void attribute((unused)) *arg) {
2c7c9eae 275 struct packet *p = 0;
0b75463f 276 int n;
2c7c9eae
RK
277 struct rtp_header header;
278 uint16_t seq;
279 uint32_t timestamp;
280 struct iovec iov[2];
e83d0967
RK
281
282 for(;;) {
2c7c9eae
RK
283 if(!p) {
284 pthread_mutex_lock(&lock);
285 p = new_packet();
286 pthread_mutex_unlock(&lock);
287 }
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);
e83d0967
RK
293 if(n < 0) {
294 switch(errno) {
295 case EINTR:
296 continue;
297 default:
298 fatal(errno, "error reading from socket");
299 }
300 }
0b75463f 301 /* Ignore too-short packets */
345ebe66
RK
302 if((size_t)n <= sizeof (struct rtp_header)) {
303 info("ignored a short packet");
0b75463f 304 continue;
345ebe66 305 }
2c7c9eae
RK
306 timestamp = htonl(header.timestamp);
307 seq = htons(header.seq);
09ee2f0d 308 /* Ignore packets in the past */
2c7c9eae 309 if(active && lt(timestamp, next_timestamp)) {
c0e41690 310 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
2c7c9eae 311 timestamp, next_timestamp);
09ee2f0d 312 continue;
c0e41690 313 }
2c7c9eae
RK
314 pthread_mutex_lock(&lock);
315 p = new_packet();
316 p->timestamp = timestamp;
e83d0967 317 /* Convert to target format */
2c7c9eae 318 switch(header.mpt & 0x7F) {
e83d0967 319 case 10:
2c7c9eae 320 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
0b75463f 321 /* ALSA can do any necessary conversion itself (though it might be better
322 * to do any necessary conversion in the background) */
2c7c9eae 323 /* TODO we could readv into the buffer */
e83d0967
RK
324 break;
325 /* TODO support other RFC3551 media types (when the speaker does) */
326 default:
0b75463f 327 fatal(0, "unsupported RTP payload type %d",
2c7c9eae 328 header.mpt & 0x7F);
e83d0967 329 }
345ebe66
RK
330 if(logfp)
331 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
2c7c9eae 332 seq, timestamp, p->nsamples, timestamp + p->nsamples);
0b75463f 333 /* Stop reading if we've reached the maximum.
334 *
335 * This is rather unsatisfactory: it means that if packets get heavily
336 * out of order then we guarantee dropouts. But for now... */
345ebe66
RK
337 if(nsamples >= maxbuffer) {
338 info("buffer full");
339 while(nsamples >= maxbuffer)
340 pthread_cond_wait(&cond, &lock);
341 }
28bacdc0
RK
342 /* Add the packet to the heap */
343 pheap_insert(&packets, p);
2c7c9eae
RK
344 nsamples += p->nsamples;
345 pthread_cond_broadcast(&cond);
e83d0967 346 pthread_mutex_unlock(&lock);
e83d0967
RK
347 }
348}
349
2c7c9eae
RK
350/** @brief Return true if @p p contains @p timestamp */
351static 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;
354
355 return (ge(timestamp, packet_start)
356 && lt(timestamp, packet_end));
357}
358
e83d0967 359#if HAVE_COREAUDIO_AUDIOHARDWARE_H
09ee2f0d 360/** @brief Callback from Core Audio */
9086a105
RK
361static 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) {
e83d0967
RK
369 UInt32 nbuffers = outOutputData->mNumberBuffers;
370 AudioBuffer *ab = outOutputData->mBuffers;
2c7c9eae 371 const struct packet *p;
28bacdc0 372 uint32_t samples_available;
e83d0967 373
0b75463f 374 pthread_mutex_lock(&lock);
9086a105
RK
375 while(nbuffers > 0) {
376 float *samplesOut = ab->mData;
377 size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
2c7c9eae 378
9086a105 379 while(samplesOutLeft > 0) {
2c7c9eae
RK
380 /* Look for a suitable packet, dropping any unsuitable ones along the
381 * way. Unsuitable packets are ones that are in the past. */
28bacdc0
RK
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. */
386 drop_first_packet();
387 else
388 /* This packet is NOT in the past. (It might be in the future
389 * however.) */
390 break;
9086a105 391 }
28bacdc0
RK
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));
399
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
408 * round */
409 } else {
410 /* No packet is ready to play (and there might be no packet at all) */
411 samples_available = p ? p->timestamp - next_timestamp
412 : samplesOutLeft;
9086a105
RK
413 if(samples_available > samplesOutLeft)
414 samples_available = samplesOutLeft;
8dcb5ff0 415 info("infill by %"PRIu32, samples_available);
28bacdc0 416 /* Conveniently the buffer is 0 to start with */
9086a105
RK
417 next_timestamp += samples_available;
418 samplesOut += samples_available;
419 samplesOutLeft -= samples_available;
9086a105 420 }
e83d0967 421 }
9086a105
RK
422 ++ab;
423 --nbuffers;
e83d0967
RK
424 }
425 pthread_mutex_unlock(&lock);
426 return 0;
427}
428#endif
429
09ee2f0d 430/** @brief Play an RTP stream
431 *
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
438 */
0b75463f 439static void play_rtp(void) {
440 pthread_t ltid;
e83d0967
RK
441
442 /* We receive and convert audio data in a background thread */
0b75463f 443 pthread_create(&ltid, 0, listen_thread, 0);
e83d0967 444#if API_ALSA
0b75463f 445 {
446 snd_pcm_t *pcm;
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;
459 int prepared = 1;
460 int err;
c0e41690 461 int infilling = 0, escape = 0;
462 time_t logged, now;
463 uint32_t packet_start, packet_end;
0b75463f 464
465 /* Open ALSA */
466 if((err = snd_pcm_open(&pcm,
467 device ? device : "default",
468 SND_PCM_STREAM_PLAYBACK,
469 SND_PCM_NONBLOCK)))
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,
479 sample_format)) < 0)
480 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
481 sample_format, err);
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",
484 rate, err);
485 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
486 channels)) < 0)
487 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
488 channels, err);
489 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
490 &pcm_bufsize)) < 0)
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",
501 avail_min, err);
502 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
503 fatal(0, "error calling snd_pcm_sw_params: %d", err);
504
505 /* Ready to go */
506
c0e41690 507 time(&logged);
0b75463f 508 pthread_mutex_lock(&lock);
509 for(;;) {
510 /* Wait for the buffer to fill up a bit */
8d0c14d7 511 logged = now;
512 info("%lu samples in buffer (%lus)", nsamples,
513 nsamples / (44100 * 2));
ed13cbc8 514 info("Buffering...");
1153fd23 515 while(nsamples < readahead)
0b75463f 516 pthread_cond_wait(&cond, &lock);
517 if(!prepared) {
518 if((err = snd_pcm_prepare(pcm)))
519 fatal(0, "error calling snd_pcm_prepare: %d", err);
520 prepared = 1;
521 }
09ee2f0d 522 active = 1;
ed13cbc8 523 infilling = 0;
c0e41690 524 escape = 0;
8d0c14d7 525 logged = now;
526 info("%lu samples in buffer (%lus)", nsamples,
527 nsamples / (44100 * 2));
ed13cbc8 528 info("Playing...");
0b75463f 529 /* Wait until the buffer empties out */
c0e41690 530 while(nsamples >= minbuffer && !escape) {
531 time(&now);
532 if(now > logged + 10) {
533 logged = now;
534 info("%lu samples in buffer (%lus)", nsamples,
535 nsamples / (44100 * 2));
536 }
537 if(packets
538 && ge(next_timestamp, packets->timestamp + packets->nsamples)) {
c0e41690 539 info("dropping buffered past packet %"PRIx32" < %"PRIx32,
540 packets->timestamp, next_timestamp);
9086a105 541 drop_first_packet();
c0e41690 542 continue;
543 }
0b75463f 544 /* Wait for ALSA to ask us for more data */
545 pthread_mutex_unlock(&lock);
9ae1516d 546 write(2, ".", 1); /* TODO remove me sometime */
547 switch(err = snd_pcm_wait(pcm, -1)) {
548 case 0:
549 info("snd_pcm_wait timed out");
550 break;
551 case 1:
552 break;
553 default:
554 fatal(0, "snd_pcm_wait returned %d", err);
555 }
0b75463f 556 pthread_mutex_lock(&lock);
09ee2f0d 557 /* ALSA is ready for more data */
c0e41690 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;
0b75463f 565 const size_t frames_available = samples_available / 2;
566
567 frames_written = snd_pcm_writei(pcm,
c0e41690 568 packets->samples_raw + offset,
0b75463f 569 frames_available);
1153fd23 570 if(frames_written < 0) {
c0e41690 571 switch(frames_written) {
572 case -EAGAIN:
573 info("snd_pcm_wait() returned but we got -EAGAIN!");
574 break;
575 case -EPIPE:
576 error(0, "error calling snd_pcm_writei: %ld",
577 (long)frames_written);
578 escape = 1;
579 break;
580 default:
1153fd23 581 fatal(0, "error calling snd_pcm_writei: %ld",
582 (long)frames_written);
c0e41690 583 }
1153fd23 584 } else {
585 samples_written = frames_written * 2;
1153fd23 586 next_timestamp += samples_written;
9086a105
RK
587 if(ge(next_timestamp, packet_end))
588 drop_first_packet();
1153fd23 589 infilling = 0;
0b75463f 590 }
591 } else {
592 /* We don't have anything to play! We'd better play some 0s. */
c0e41690 593 static const uint16_t zeros[INFILL_SAMPLES];
594 size_t samples_available = INFILL_SAMPLES, frames_available;
ed13cbc8 595
c0e41690 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))
0b75463f 600 samples_available = packets->timestamp - next_timestamp;
c0e41690 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);
605 }
0b75463f 606 frames_available = samples_available / 2;
c0e41690 607 if(!infilling) {
8d0c14d7 608 info("Infilling %d samples, next=%"PRIx32" packet=[%"PRIx32",%"PRIx32"]",
609 samples_available, next_timestamp,
610 packets->timestamp, packets->timestamp + packets->nsamples);
c0e41690 611 //infilling++;
612 }
0b75463f 613 frames_written = snd_pcm_writei(pcm,
614 zeros,
615 frames_available);
1153fd23 616 if(frames_written < 0) {
c0e41690 617 switch(frames_written) {
618 case -EAGAIN:
619 info("snd_pcm_wait() returned but we got -EAGAIN!");
620 break;
621 case -EPIPE:
622 error(0, "error calling snd_pcm_writei: %ld",
623 (long)frames_written);
624 escape = 1;
625 break;
626 default:
1153fd23 627 fatal(0, "error calling snd_pcm_writei: %ld",
628 (long)frames_written);
c0e41690 629 }
74a94bd0 630 } else {
631 samples_written = frames_written * 2;
1153fd23 632 next_timestamp += samples_written;
74a94bd0 633 }
0b75463f 634 }
635 }
09ee2f0d 636 active = 0;
0b75463f 637 /* We stop playing for a bit until the buffer re-fills */
638 pthread_mutex_unlock(&lock);
ed13cbc8 639 if((err = snd_pcm_nonblock(pcm, 0)))
640 fatal(0, "error calling snd_pcm_nonblock: %d", err);
c0e41690 641 if(escape) {
642 if((err = snd_pcm_drop(pcm)))
643 fatal(0, "error calling snd_pcm_drop: %d", err);
644 escape = 0;
645 } else
646 if((err = snd_pcm_drain(pcm)))
647 fatal(0, "error calling snd_pcm_drain: %d", err);
ed13cbc8 648 if((err = snd_pcm_nonblock(pcm, 1)))
649 fatal(0, "error calling snd_pcm_nonblock: %d", err);
0b75463f 650 prepared = 0;
651 pthread_mutex_lock(&lock);
652 }
653
654 }
e83d0967
RK
655#elif HAVE_COREAUDIO_AUDIOHARDWARE_H
656 {
657 OSStatus status;
658 UInt32 propertySize;
659 AudioDeviceID adid;
660 AudioStreamBasicDescription asbd;
661
662 /* If this looks suspiciously like libao's macosx driver there's an
663 * excellent reason for that... */
664
665 /* TODO report errors as strings not numbers */
666 propertySize = sizeof adid;
667 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
668 &propertySize, &adid);
669 if(status)
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);
677 if(status)
678 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
679 D(("mSampleRate %f", asbd.mSampleRate));
9086a105
RK
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));
e83d0967
RK
688 if(asbd.mFormatID != kAudioFormatLinearPCM)
689 fatal(0, "audio device does not support kAudioFormatLinearPCM");
690 status = AudioDeviceAddIOProc(adid, adioproc, 0);
691 if(status)
692 fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
693 pthread_mutex_lock(&lock);
694 for(;;) {
695 /* Wait for the buffer to fill up a bit */
8dcb5ff0 696 info("Buffering...");
1153fd23 697 while(nsamples < readahead)
e83d0967
RK
698 pthread_cond_wait(&cond, &lock);
699 /* Start playing now */
8dcb5ff0 700 info("Playing...");
28bacdc0 701 next_timestamp = pheap_first(&packets)->timestamp;
8dcb5ff0 702 active = 1;
e83d0967
RK
703 status = AudioDeviceStart(adid, adioproc);
704 if(status)
705 fatal(0, "AudioDeviceStart: %d", (int)status);
706 /* Wait until the buffer empties out */
1153fd23 707 while(nsamples >= minbuffer)
e83d0967
RK
708 pthread_cond_wait(&cond, &lock);
709 /* Stop playing for a bit until the buffer re-fills */
710 status = AudioDeviceStop(adid, adioproc);
711 if(status)
712 fatal(0, "AudioDeviceStop: %d", (int)status);
8dcb5ff0 713 active = 0;
e83d0967
RK
714 /* Go back round */
715 }
716 }
717#else
718# error No known audio API
719#endif
720}
721
722/* display usage message and terminate */
723static void help(void) {
724 xprintf("Usage:\n"
725 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
726 "Options:\n"
1153fd23 727 " --device, -D DEVICE Output device\n"
728 " --min, -m FRAMES Buffer low water mark\n"
9086a105
RK
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"
733 );
e83d0967
RK
734 xfclose(stdout);
735 exit(0);
736}
737
738/* display version number and terminate */
739static void version(void) {
740 xprintf("disorder-playrtp version %s\n", disorder_version_string);
741 xfclose(stdout);
742 exit(0);
743}
744
745int main(int argc, char **argv) {
746 int n;
747 struct addrinfo *res;
748 struct stringlist sl;
0b75463f 749 char *sockname;
e83d0967 750
0b75463f 751 static const struct addrinfo prefs = {
e83d0967
RK
752 AI_PASSIVE,
753 PF_INET,
754 SOCK_DGRAM,
755 IPPROTO_UDP,
756 0,
757 0,
758 0,
759 0
760 };
761
762 mem_init();
763 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
345ebe66 764 while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:", options, 0)) >= 0) {
e83d0967
RK
765 switch(n) {
766 case 'h': help();
767 case 'V': version();
768 case 'd': debugging = 1; break;
0b75463f 769 case 'D': device = optarg; break;
1153fd23 770 case 'm': minbuffer = 2 * atol(optarg); break;
771 case 'b': readahead = 2 * atol(optarg); break;
9086a105 772 case 'x': maxbuffer = 2 * atol(optarg); break;
345ebe66 773 case 'L': logfp = fopen(optarg, "w"); break;
e83d0967
RK
774 default: fatal(0, "invalid option");
775 }
776 }
9086a105
RK
777 if(!maxbuffer)
778 maxbuffer = 4 * readahead;
e83d0967
RK
779 argc -= optind;
780 argv += optind;
781 if(argc < 1 || argc > 2)
782 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
783 sl.n = argc;
784 sl.s = argv;
785 /* Listen for inbound audio data */
0b75463f 786 if(!(res = get_address(&sl, &prefs, &sockname)))
e83d0967
RK
787 exit(1);
788 if((rtpfd = socket(res->ai_family,
789 res->ai_socktype,
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);
794 play_rtp();
795 return 0;
796}
797
798/*
799Local Variables:
800c-basic-offset:2
801comment-column:40
802fill-column:79
803indent-tabs-mode:nil
804End:
805*/