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 *
58b5a68f 97 * This is an upper bound - in practice we expect the underlying audio API to
28bacdc0
RK
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;
58b5a68f 110
0b75463f 111 /** @brief Timestamp from RTP packet
112 *
28bacdc0
RK
113 * NB that "timestamps" are really sample counters. Use lt() or lt_packet()
114 * to compare timestamps.
115 */
0b75463f 116 uint32_t timestamp;
58b5a68f
RK
117
118 /** @brief Flags
119 *
120 * Valid values are:
121 * - @ref IDLE: the idle bit was set in the RTP packet
122 */
123 unsigned flags;
124#define IDLE 0x0001 /**< idle bit set in RTP packet */
125
28bacdc0
RK
126 /** @brief Raw sample data
127 *
128 * Only the first @p nsamples samples are defined; the rest is uninitialized
129 * data.
130 */
0b75463f 131 unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE];
e83d0967
RK
132};
133
28bacdc0 134/** @brief Return true iff \f$a < b\f$ in sequence-space arithmetic
0b75463f 135 *
28bacdc0
RK
136 * Specifically it returns true if \f$(a-b) mod 2^{32} < 2^{31}\f$.
137 *
138 * See also lt_packet().
139 */
140static inline int lt(uint32_t a, uint32_t b) {
141 return (uint32_t)(a - b) & 0x80000000;
142}
2c7c9eae 143
28bacdc0
RK
144/** @brief Return true iff a >= b in sequence-space arithmetic */
145static inline int ge(uint32_t a, uint32_t b) {
146 return !lt(a, b);
147}
148
149/** @brief Return true iff a > b in sequence-space arithmetic */
150static inline int gt(uint32_t a, uint32_t b) {
151 return lt(b, a);
152}
153
154/** @brief Return true iff a <= b in sequence-space arithmetic */
155static inline int le(uint32_t a, uint32_t b) {
156 return !lt(b, a);
157}
158
159/** @brief Ordering for packets, used by @ref pheap */
160static inline int lt_packet(const struct packet *a, const struct packet *b) {
161 return lt(a->timestamp, b->timestamp);
162}
163
164/** @struct pheap
165 * @brief Binary heap of packets ordered by timestamp */
166HEAP_TYPE(pheap, struct packet *, lt_packet);
167
168/** @brief Binary heap of received packets */
169static struct pheap packets;
170
171/** @brief Total number of samples available */
172static unsigned long nsamples;
0b75463f 173
174/** @brief Timestamp of next packet to play.
175 *
176 * This is set to the timestamp of the last packet, plus the number of
09ee2f0d 177 * samples it contained. Only valid if @ref active is nonzero.
0b75463f 178 */
179static uint32_t next_timestamp;
e83d0967 180
09ee2f0d 181/** @brief True if actively playing
182 *
183 * This is true when playing and false when just buffering. */
184static int active;
185
2c7c9eae
RK
186/** @brief Structure of free packet list */
187union free_packet {
188 struct packet p;
189 union free_packet *next;
190};
191
28bacdc0
RK
192/** @brief Linked list of free packets
193 *
194 * This is a linked list of formerly used packets. For preference we re-use
195 * packets that have already been used rather than unused ones, to limit the
196 * size of the program's working set. If there are no free packets in the list
197 * we try @ref next_free_packet instead.
198 *
199 * Must hold @ref lock when accessing this.
200 */
2c7c9eae
RK
201static union free_packet *free_packets;
202
28bacdc0
RK
203/** @brief Array of new free packets
204 *
205 * There are @ref count_free_packets ready to use at this address. If there
206 * are none left we allocate more memory.
207 *
208 * Must hold @ref lock when accessing this.
209 */
2c7c9eae
RK
210static union free_packet *next_free_packet;
211
28bacdc0
RK
212/** @brief Count of new free packets at @ref next_free_packet
213 *
214 * Must hold @ref lock when accessing this.
215 */
2c7c9eae
RK
216static size_t count_free_packets;
217
28bacdc0
RK
218/** @brief Lock protecting @ref packets
219 *
220 * This also protects the packet memory allocation infrastructure, @ref
221 * free_packets and @ref next_free_packet. */
e83d0967 222static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
e83d0967 223
0b75463f 224/** @brief Condition variable signalled whenever @ref packets is changed */
225static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
e83d0967
RK
226
227static const struct option options[] = {
228 { "help", no_argument, 0, 'h' },
229 { "version", no_argument, 0, 'V' },
230 { "debug", no_argument, 0, 'd' },
0b75463f 231 { "device", required_argument, 0, 'D' },
1153fd23 232 { "min", required_argument, 0, 'm' },
9086a105 233 { "max", required_argument, 0, 'x' },
1153fd23 234 { "buffer", required_argument, 0, 'b' },
e83d0967
RK
235 { 0, 0, 0, 0 }
236};
237
2c7c9eae
RK
238/** @brief Return a new packet
239 *
240 * Assumes that @ref lock is held. */
241static struct packet *new_packet(void) {
242 struct packet *p;
243
244 if(free_packets) {
245 p = &free_packets->p;
246 free_packets = free_packets->next;
247 } else {
248 if(!count_free_packets) {
249 next_free_packet = xcalloc(1024, sizeof (union free_packet));
250 count_free_packets = 1024;
251 }
252 p = &(next_free_packet++)->p;
253 --count_free_packets;
254 }
255 return p;
256}
257
258/** @brief Free a packet
259 *
260 * Assumes that @ref lock is held. */
261static void free_packet(struct packet *p) {
262 union free_packet *u = (union free_packet *)p;
263 u->next = free_packets;
264 free_packets = u;
265}
266
28bacdc0
RK
267/** @brief Drop the first packet
268 *
269 * Assumes that @ref lock is held.
270 */
271static void drop_first_packet(void) {
272 if(pheap_count(&packets)) {
273 struct packet *const p = pheap_remove(&packets);
274 nsamples -= p->nsamples;
275 free_packet(p);
2c7c9eae 276 pthread_cond_broadcast(&cond);
2c7c9eae 277 }
9086a105
RK
278}
279
09ee2f0d 280/** @brief Background thread collecting samples
0b75463f 281 *
282 * This function collects samples, perhaps converts them to the target format,
283 * and adds them to the packet list. */
284static void *listen_thread(void attribute((unused)) *arg) {
2c7c9eae 285 struct packet *p = 0;
0b75463f 286 int n;
2c7c9eae
RK
287 struct rtp_header header;
288 uint16_t seq;
289 uint32_t timestamp;
290 struct iovec iov[2];
e83d0967
RK
291
292 for(;;) {
2c7c9eae
RK
293 if(!p) {
294 pthread_mutex_lock(&lock);
295 p = new_packet();
296 pthread_mutex_unlock(&lock);
297 }
298 iov[0].iov_base = &header;
299 iov[0].iov_len = sizeof header;
300 iov[1].iov_base = p->samples_raw;
301 iov[1].iov_len = sizeof p->samples_raw;
302 n = readv(rtpfd, iov, 2);
e83d0967
RK
303 if(n < 0) {
304 switch(errno) {
305 case EINTR:
306 continue;
307 default:
308 fatal(errno, "error reading from socket");
309 }
310 }
0b75463f 311 /* Ignore too-short packets */
345ebe66
RK
312 if((size_t)n <= sizeof (struct rtp_header)) {
313 info("ignored a short packet");
0b75463f 314 continue;
345ebe66 315 }
2c7c9eae
RK
316 timestamp = htonl(header.timestamp);
317 seq = htons(header.seq);
09ee2f0d 318 /* Ignore packets in the past */
2c7c9eae 319 if(active && lt(timestamp, next_timestamp)) {
c0e41690 320 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
2c7c9eae 321 timestamp, next_timestamp);
09ee2f0d 322 continue;
c0e41690 323 }
2c7c9eae 324 pthread_mutex_lock(&lock);
58b5a68f 325 p->flags = 0;
2c7c9eae 326 p->timestamp = timestamp;
e83d0967 327 /* Convert to target format */
58b5a68f
RK
328 if(header.mpt & 0x80)
329 p->flags |= IDLE;
2c7c9eae 330 switch(header.mpt & 0x7F) {
e83d0967 331 case 10:
2c7c9eae 332 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
0b75463f 333 /* ALSA can do any necessary conversion itself (though it might be better
334 * to do any necessary conversion in the background) */
2c7c9eae 335 /* TODO we could readv into the buffer */
e83d0967
RK
336 break;
337 /* TODO support other RFC3551 media types (when the speaker does) */
338 default:
0b75463f 339 fatal(0, "unsupported RTP payload type %d",
2c7c9eae 340 header.mpt & 0x7F);
e83d0967 341 }
345ebe66
RK
342 if(logfp)
343 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
2c7c9eae 344 seq, timestamp, p->nsamples, timestamp + p->nsamples);
0b75463f 345 /* Stop reading if we've reached the maximum.
346 *
347 * This is rather unsatisfactory: it means that if packets get heavily
348 * out of order then we guarantee dropouts. But for now... */
345ebe66
RK
349 if(nsamples >= maxbuffer) {
350 info("buffer full");
351 while(nsamples >= maxbuffer)
352 pthread_cond_wait(&cond, &lock);
353 }
28bacdc0
RK
354 /* Add the packet to the heap */
355 pheap_insert(&packets, p);
2c7c9eae 356 nsamples += p->nsamples;
58b5a68f
RK
357 /* We'll need a new packet */
358 p = 0;
2c7c9eae 359 pthread_cond_broadcast(&cond);
e83d0967 360 pthread_mutex_unlock(&lock);
e83d0967
RK
361 }
362}
363
2c7c9eae
RK
364/** @brief Return true if @p p contains @p timestamp */
365static inline int contains(const struct packet *p, uint32_t timestamp) {
366 const uint32_t packet_start = p->timestamp;
367 const uint32_t packet_end = p->timestamp + p->nsamples;
368
369 return (ge(timestamp, packet_start)
370 && lt(timestamp, packet_end));
371}
372
e83d0967 373#if HAVE_COREAUDIO_AUDIOHARDWARE_H
09ee2f0d 374/** @brief Callback from Core Audio */
9086a105
RK
375static OSStatus adioproc
376 (AudioDeviceID attribute((unused)) inDevice,
377 const AudioTimeStamp attribute((unused)) *inNow,
378 const AudioBufferList attribute((unused)) *inInputData,
379 const AudioTimeStamp attribute((unused)) *inInputTime,
380 AudioBufferList *outOutputData,
381 const AudioTimeStamp attribute((unused)) *inOutputTime,
382 void attribute((unused)) *inClientData) {
e83d0967
RK
383 UInt32 nbuffers = outOutputData->mNumberBuffers;
384 AudioBuffer *ab = outOutputData->mBuffers;
2c7c9eae 385 const struct packet *p;
28bacdc0 386 uint32_t samples_available;
58b5a68f 387 struct timeval in, out;
e83d0967 388
58b5a68f 389 gettimeofday(&in, 0);
0b75463f 390 pthread_mutex_lock(&lock);
9086a105
RK
391 while(nbuffers > 0) {
392 float *samplesOut = ab->mData;
393 size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
2c7c9eae 394
9086a105 395 while(samplesOutLeft > 0) {
2c7c9eae
RK
396 /* Look for a suitable packet, dropping any unsuitable ones along the
397 * way. Unsuitable packets are ones that are in the past. */
28bacdc0
RK
398 while(pheap_count(&packets)) {
399 p = pheap_first(&packets);
400 if(le(p->timestamp + p->nsamples, next_timestamp))
401 /* This packet is in the past. Drop it and try another one. */
402 drop_first_packet();
403 else
404 /* This packet is NOT in the past. (It might be in the future
405 * however.) */
406 break;
9086a105 407 }
28bacdc0
RK
408 p = pheap_count(&packets) ? pheap_first(&packets) : 0;
409 if(p && contains(p, next_timestamp)) {
58b5a68f
RK
410 if(p->flags & IDLE)
411 fprintf(stderr, "\nIDLE\n");
28bacdc0
RK
412 /* This packet is ready to play */
413 const uint32_t packet_end = p->timestamp + p->nsamples;
414 const uint32_t offset = next_timestamp - p->timestamp;
415 const uint16_t *ptr =
416 (void *)(p->samples_raw + offset * sizeof (uint16_t));
417
418 samples_available = packet_end - next_timestamp;
419 if(samples_available > samplesOutLeft)
420 samples_available = samplesOutLeft;
421 next_timestamp += samples_available;
422 samplesOutLeft -= samples_available;
423 while(samples_available-- > 0)
424 *samplesOut++ = (int16_t)ntohs(*ptr++) * (0.5 / 32767);
425 /* We don't bother junking the packet - that'll be dealt with next time
426 * round */
58b5a68f 427 write(2, ".", 1);
28bacdc0
RK
428 } else {
429 /* No packet is ready to play (and there might be no packet at all) */
430 samples_available = p ? p->timestamp - next_timestamp
431 : samplesOutLeft;
9086a105
RK
432 if(samples_available > samplesOutLeft)
433 samples_available = samplesOutLeft;
58b5a68f 434 //info("infill by %"PRIu32, samples_available);
28bacdc0 435 /* Conveniently the buffer is 0 to start with */
9086a105
RK
436 next_timestamp += samples_available;
437 samplesOut += samples_available;
438 samplesOutLeft -= samples_available;
58b5a68f 439 write(2, "?", 1);
9086a105 440 }
e83d0967 441 }
9086a105
RK
442 ++ab;
443 --nbuffers;
e83d0967
RK
444 }
445 pthread_mutex_unlock(&lock);
58b5a68f
RK
446 gettimeofday(&out, 0);
447 {
448 static double max;
449 double thistime = (out.tv_sec - in.tv_sec) + (out.tv_usec - in.tv_usec) / 1000000.0;
450 if(thistime > max)
451 fprintf(stderr, "adioproc: %8.8fs\n", max = thistime);
452 }
e83d0967
RK
453 return 0;
454}
455#endif
456
09ee2f0d 457/** @brief Play an RTP stream
458 *
459 * This is the guts of the program. It is responsible for:
460 * - starting the listening thread
461 * - opening the audio device
462 * - reading ahead to build up a buffer
463 * - arranging for audio to be played
464 * - detecting when the buffer has got too small and re-buffering
465 */
0b75463f 466static void play_rtp(void) {
467 pthread_t ltid;
e83d0967
RK
468
469 /* We receive and convert audio data in a background thread */
0b75463f 470 pthread_create(&ltid, 0, listen_thread, 0);
e83d0967 471#if API_ALSA
0b75463f 472 {
473 snd_pcm_t *pcm;
474 snd_pcm_hw_params_t *hwparams;
475 snd_pcm_sw_params_t *swparams;
476 /* Only support one format for now */
477 const int sample_format = SND_PCM_FORMAT_S16_BE;
478 unsigned rate = 44100;
479 const int channels = 2;
480 const int samplesize = channels * sizeof(uint16_t);
481 snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
482 /* If we can write more than this many samples we'll get a wakeup */
483 const int avail_min = 256;
484 snd_pcm_sframes_t frames_written;
485 size_t samples_written;
486 int prepared = 1;
487 int err;
c0e41690 488 int infilling = 0, escape = 0;
489 time_t logged, now;
490 uint32_t packet_start, packet_end;
0b75463f 491
492 /* Open ALSA */
493 if((err = snd_pcm_open(&pcm,
494 device ? device : "default",
495 SND_PCM_STREAM_PLAYBACK,
496 SND_PCM_NONBLOCK)))
497 fatal(0, "error from snd_pcm_open: %d", err);
498 /* Set up 'hardware' parameters */
499 snd_pcm_hw_params_alloca(&hwparams);
500 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
501 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
502 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
503 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
504 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
505 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
506 sample_format)) < 0)
58b5a68f 507
0b75463f 508 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
509 sample_format, err);
510 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
511 fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
512 rate, err);
513 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
514 channels)) < 0)
515 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
516 channels, err);
517 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
518 &pcm_bufsize)) < 0)
519 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
520 MAXSAMPLES * samplesize * 3, err);
521 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
522 fatal(0, "error calling snd_pcm_hw_params: %d", err);
523 /* Set up 'software' parameters */
524 snd_pcm_sw_params_alloca(&swparams);
525 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
526 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
527 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
528 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
529 avail_min, err);
530 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
531 fatal(0, "error calling snd_pcm_sw_params: %d", err);
532
533 /* Ready to go */
534
c0e41690 535 time(&logged);
0b75463f 536 pthread_mutex_lock(&lock);
537 for(;;) {
538 /* Wait for the buffer to fill up a bit */
8d0c14d7 539 logged = now;
540 info("%lu samples in buffer (%lus)", nsamples,
541 nsamples / (44100 * 2));
ed13cbc8 542 info("Buffering...");
1153fd23 543 while(nsamples < readahead)
0b75463f 544 pthread_cond_wait(&cond, &lock);
545 if(!prepared) {
546 if((err = snd_pcm_prepare(pcm)))
547 fatal(0, "error calling snd_pcm_prepare: %d", err);
548 prepared = 1;
549 }
09ee2f0d 550 active = 1;
ed13cbc8 551 infilling = 0;
c0e41690 552 escape = 0;
8d0c14d7 553 logged = now;
554 info("%lu samples in buffer (%lus)", nsamples,
555 nsamples / (44100 * 2));
ed13cbc8 556 info("Playing...");
0b75463f 557 /* Wait until the buffer empties out */
c0e41690 558 while(nsamples >= minbuffer && !escape) {
559 time(&now);
560 if(now > logged + 10) {
561 logged = now;
562 info("%lu samples in buffer (%lus)", nsamples,
563 nsamples / (44100 * 2));
564 }
565 if(packets
566 && ge(next_timestamp, packets->timestamp + packets->nsamples)) {
c0e41690 567 info("dropping buffered past packet %"PRIx32" < %"PRIx32,
568 packets->timestamp, next_timestamp);
9086a105 569 drop_first_packet();
c0e41690 570 continue;
571 }
0b75463f 572 /* Wait for ALSA to ask us for more data */
573 pthread_mutex_unlock(&lock);
9ae1516d 574 write(2, ".", 1); /* TODO remove me sometime */
575 switch(err = snd_pcm_wait(pcm, -1)) {
576 case 0:
577 info("snd_pcm_wait timed out");
578 break;
579 case 1:
580 break;
581 default:
582 fatal(0, "snd_pcm_wait returned %d", err);
583 }
0b75463f 584 pthread_mutex_lock(&lock);
09ee2f0d 585 /* ALSA is ready for more data */
c0e41690 586 packet_start = packets->timestamp;
587 packet_end = packets->timestamp + packets->nsamples;
588 if(ge(next_timestamp, packet_start)
589 && lt(next_timestamp, packet_end)) {
590 /* The target timestamp is somewhere in this packet */
591 const uint32_t offset = next_timestamp - packets->timestamp;
592 const uint32_t samples_available = (packets->timestamp + packets->nsamples) - next_timestamp;
0b75463f 593 const size_t frames_available = samples_available / 2;
594
595 frames_written = snd_pcm_writei(pcm,
c0e41690 596 packets->samples_raw + offset,
0b75463f 597 frames_available);
1153fd23 598 if(frames_written < 0) {
c0e41690 599 switch(frames_written) {
600 case -EAGAIN:
601 info("snd_pcm_wait() returned but we got -EAGAIN!");
602 break;
603 case -EPIPE:
604 error(0, "error calling snd_pcm_writei: %ld",
605 (long)frames_written);
606 escape = 1;
607 break;
608 default:
1153fd23 609 fatal(0, "error calling snd_pcm_writei: %ld",
610 (long)frames_written);
c0e41690 611 }
1153fd23 612 } else {
613 samples_written = frames_written * 2;
1153fd23 614 next_timestamp += samples_written;
9086a105
RK
615 if(ge(next_timestamp, packet_end))
616 drop_first_packet();
1153fd23 617 infilling = 0;
0b75463f 618 }
619 } else {
620 /* We don't have anything to play! We'd better play some 0s. */
c0e41690 621 static const uint16_t zeros[INFILL_SAMPLES];
622 size_t samples_available = INFILL_SAMPLES, frames_available;
ed13cbc8 623
c0e41690 624 /* If the maximum infill would take us past the start of the next
625 * packet then we truncate the infill to the right amount. */
626 if(lt(packets->timestamp,
627 next_timestamp + samples_available))
0b75463f 628 samples_available = packets->timestamp - next_timestamp;
c0e41690 629 if((int)samples_available < 0) {
630 info("packets->timestamp: %"PRIx32" next_timestamp: %"PRIx32" next+max: %"PRIx32" available: %"PRIx32,
631 packets->timestamp, next_timestamp,
632 next_timestamp + INFILL_SAMPLES, samples_available);
633 }
0b75463f 634 frames_available = samples_available / 2;
c0e41690 635 if(!infilling) {
8d0c14d7 636 info("Infilling %d samples, next=%"PRIx32" packet=[%"PRIx32",%"PRIx32"]",
637 samples_available, next_timestamp,
638 packets->timestamp, packets->timestamp + packets->nsamples);
c0e41690 639 //infilling++;
640 }
0b75463f 641 frames_written = snd_pcm_writei(pcm,
642 zeros,
643 frames_available);
1153fd23 644 if(frames_written < 0) {
c0e41690 645 switch(frames_written) {
646 case -EAGAIN:
647 info("snd_pcm_wait() returned but we got -EAGAIN!");
648 break;
649 case -EPIPE:
650 error(0, "error calling snd_pcm_writei: %ld",
651 (long)frames_written);
652 escape = 1;
653 break;
654 default:
1153fd23 655 fatal(0, "error calling snd_pcm_writei: %ld",
656 (long)frames_written);
c0e41690 657 }
74a94bd0 658 } else {
659 samples_written = frames_written * 2;
1153fd23 660 next_timestamp += samples_written;
74a94bd0 661 }
0b75463f 662 }
663 }
09ee2f0d 664 active = 0;
0b75463f 665 /* We stop playing for a bit until the buffer re-fills */
666 pthread_mutex_unlock(&lock);
ed13cbc8 667 if((err = snd_pcm_nonblock(pcm, 0)))
668 fatal(0, "error calling snd_pcm_nonblock: %d", err);
c0e41690 669 if(escape) {
670 if((err = snd_pcm_drop(pcm)))
671 fatal(0, "error calling snd_pcm_drop: %d", err);
672 escape = 0;
673 } else
674 if((err = snd_pcm_drain(pcm)))
675 fatal(0, "error calling snd_pcm_drain: %d", err);
ed13cbc8 676 if((err = snd_pcm_nonblock(pcm, 1)))
677 fatal(0, "error calling snd_pcm_nonblock: %d", err);
0b75463f 678 prepared = 0;
679 pthread_mutex_lock(&lock);
680 }
681
682 }
e83d0967
RK
683#elif HAVE_COREAUDIO_AUDIOHARDWARE_H
684 {
685 OSStatus status;
686 UInt32 propertySize;
687 AudioDeviceID adid;
688 AudioStreamBasicDescription asbd;
689
690 /* If this looks suspiciously like libao's macosx driver there's an
691 * excellent reason for that... */
692
693 /* TODO report errors as strings not numbers */
694 propertySize = sizeof adid;
695 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
696 &propertySize, &adid);
697 if(status)
698 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
699 if(adid == kAudioDeviceUnknown)
700 fatal(0, "no output device");
701 propertySize = sizeof asbd;
702 status = AudioDeviceGetProperty(adid, 0, false,
703 kAudioDevicePropertyStreamFormat,
704 &propertySize, &asbd);
705 if(status)
706 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
707 D(("mSampleRate %f", asbd.mSampleRate));
9086a105
RK
708 D(("mFormatID %08lx", asbd.mFormatID));
709 D(("mFormatFlags %08lx", asbd.mFormatFlags));
710 D(("mBytesPerPacket %08lx", asbd.mBytesPerPacket));
711 D(("mFramesPerPacket %08lx", asbd.mFramesPerPacket));
712 D(("mBytesPerFrame %08lx", asbd.mBytesPerFrame));
713 D(("mChannelsPerFrame %08lx", asbd.mChannelsPerFrame));
714 D(("mBitsPerChannel %08lx", asbd.mBitsPerChannel));
715 D(("mReserved %08lx", asbd.mReserved));
e83d0967
RK
716 if(asbd.mFormatID != kAudioFormatLinearPCM)
717 fatal(0, "audio device does not support kAudioFormatLinearPCM");
718 status = AudioDeviceAddIOProc(adid, adioproc, 0);
719 if(status)
720 fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
721 pthread_mutex_lock(&lock);
722 for(;;) {
723 /* Wait for the buffer to fill up a bit */
8dcb5ff0 724 info("Buffering...");
1153fd23 725 while(nsamples < readahead)
e83d0967
RK
726 pthread_cond_wait(&cond, &lock);
727 /* Start playing now */
8dcb5ff0 728 info("Playing...");
28bacdc0 729 next_timestamp = pheap_first(&packets)->timestamp;
8dcb5ff0 730 active = 1;
e83d0967
RK
731 status = AudioDeviceStart(adid, adioproc);
732 if(status)
733 fatal(0, "AudioDeviceStart: %d", (int)status);
734 /* Wait until the buffer empties out */
1153fd23 735 while(nsamples >= minbuffer)
e83d0967
RK
736 pthread_cond_wait(&cond, &lock);
737 /* Stop playing for a bit until the buffer re-fills */
738 status = AudioDeviceStop(adid, adioproc);
739 if(status)
740 fatal(0, "AudioDeviceStop: %d", (int)status);
8dcb5ff0 741 active = 0;
e83d0967
RK
742 /* Go back round */
743 }
744 }
745#else
746# error No known audio API
747#endif
748}
749
750/* display usage message and terminate */
751static void help(void) {
752 xprintf("Usage:\n"
753 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
754 "Options:\n"
1153fd23 755 " --device, -D DEVICE Output device\n"
756 " --min, -m FRAMES Buffer low water mark\n"
9086a105
RK
757 " --buffer, -b FRAMES Buffer high water mark\n"
758 " --max, -x FRAMES Buffer maximum size\n"
759 " --help, -h Display usage message\n"
760 " --version, -V Display version number\n"
761 );
e83d0967
RK
762 xfclose(stdout);
763 exit(0);
764}
765
766/* display version number and terminate */
767static void version(void) {
768 xprintf("disorder-playrtp version %s\n", disorder_version_string);
769 xfclose(stdout);
770 exit(0);
771}
772
773int main(int argc, char **argv) {
774 int n;
775 struct addrinfo *res;
776 struct stringlist sl;
0b75463f 777 char *sockname;
e83d0967 778
0b75463f 779 static const struct addrinfo prefs = {
e83d0967
RK
780 AI_PASSIVE,
781 PF_INET,
782 SOCK_DGRAM,
783 IPPROTO_UDP,
784 0,
785 0,
786 0,
787 0
788 };
789
790 mem_init();
791 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
345ebe66 792 while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:", options, 0)) >= 0) {
e83d0967
RK
793 switch(n) {
794 case 'h': help();
795 case 'V': version();
796 case 'd': debugging = 1; break;
0b75463f 797 case 'D': device = optarg; break;
1153fd23 798 case 'm': minbuffer = 2 * atol(optarg); break;
799 case 'b': readahead = 2 * atol(optarg); break;
9086a105 800 case 'x': maxbuffer = 2 * atol(optarg); break;
345ebe66 801 case 'L': logfp = fopen(optarg, "w"); break;
e83d0967
RK
802 default: fatal(0, "invalid option");
803 }
804 }
9086a105
RK
805 if(!maxbuffer)
806 maxbuffer = 4 * readahead;
e83d0967
RK
807 argc -= optind;
808 argv += optind;
809 if(argc < 1 || argc > 2)
810 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
811 sl.n = argc;
812 sl.s = argv;
813 /* Listen for inbound audio data */
0b75463f 814 if(!(res = get_address(&sl, &prefs, &sockname)))
e83d0967
RK
815 exit(1);
816 if((rtpfd = socket(res->ai_family,
817 res->ai_socktype,
818 res->ai_protocol)) < 0)
819 fatal(errno, "error creating socket");
820 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
821 fatal(errno, "error binding socket to %s", sockname);
822 play_rtp();
823 return 0;
824}
825
826/*
827Local Variables:
828c-basic-offset:2
829comment-column:40
830fill-column:79
831indent-tabs-mode:nil
832End:
833*/