chiark / gitweb /
abolish linked list of packets. (linux still to do.)
[disorder] / clients / playrtp.c
... / ...
CommitLineData
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 */
20
21#include <config.h>
22#include "types.h"
23
24#include <getopt.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <sys/socket.h>
28#include <sys/types.h>
29#include <sys/socket.h>
30#include <netdb.h>
31#include <pthread.h>
32#include <locale.h>
33#include <sys/uio.h>
34
35#include "log.h"
36#include "mem.h"
37#include "configuration.h"
38#include "addr.h"
39#include "syscalls.h"
40#include "rtp.h"
41#include "defs.h"
42
43#if HAVE_COREAUDIO_AUDIOHARDWARE_H
44# include <CoreAudio/AudioHardware.h>
45#endif
46#if API_ALSA
47#include <alsa/asoundlib.h>
48#endif
49
50#define readahead linux_headers_are_borked
51
52/** @brief RTP socket */
53static int rtpfd;
54
55/** @brief Log output */
56static FILE *logfp;
57
58/** @brief Output device */
59static const char *device;
60
61/** @brief Maximum samples per packet we'll support
62 *
63 * NB that two channels = two samples in this program.
64 */
65#define MAXSAMPLES 2048
66
67/** @brief Minimum low watermark
68 *
69 * We'll stop playing if there's only this many samples in the buffer. */
70static unsigned minbuffer = 2 * 44100 / 10; /* 0.2 seconds */
71
72/** @brief Maximum sample size
73 *
74 * The maximum supported size (in bytes) of one sample. */
75#define MAXSAMPLESIZE 2
76
77/** @brief Buffer high watermark
78 *
79 * We'll only start playing when this many samples are available. */
80static unsigned readahead = 2 * 2 * 44100;
81
82/** @brief Maximum buffer size
83 *
84 * We'll stop reading from the network if we have this many samples. */
85static unsigned maxbuffer;
86
87/** @brief Number of samples to infill by in one go */
88#define INFILL_SAMPLES (44100 * 2) /* 1s */
89
90/** @brief Received packet */
91struct packet {
92 /** @brief Number of samples in this packet */
93 uint32_t nsamples;
94 /** @brief Timestamp from RTP packet
95 *
96 * NB that "timestamps" are really sample counters.*/
97 uint32_t timestamp;
98 /** @brief Raw sample data */
99 unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE];
100};
101
102/** @brief Total number of samples available */
103static unsigned long nsamples;
104
105/** @brief Mapping of sequence numbers to packets
106 *
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. */
109static struct packet *packets[65536];
110
111/** @brief Total number of packets */
112static unsigned npackets;
113
114/** @brief Timestamp of next packet to play.
115 *
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.
118 */
119static uint32_t next_timestamp;
120
121/** @brief True if actively playing
122 *
123 * This is true when playing and false when just buffering. */
124static int active;
125
126/** @brief Sequence number of next packet we expxect to play */
127static uint16_t sequence;
128
129/** @brief Structure of free packet list */
130union free_packet {
131 struct packet p;
132 union free_packet *next;
133};
134
135/** @brief Linked list of free packets */
136static union free_packet *free_packets;
137
138/** @brief Array of new free packets */
139static union free_packet *next_free_packet;
140
141/** @brief Count of new free packets */
142static size_t count_free_packets;
143
144/** @brief Lock protecting @ref packets */
145static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
146
147/** @brief Condition variable signalled whenever @ref packets is changed */
148static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
149
150static 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' },
158 { 0, 0, 0, 0 }
159};
160
161/** @brief Return a new packet
162 *
163 * Assumes that @ref lock is held. */
164static struct packet *new_packet(void) {
165 struct packet *p;
166
167 if(free_packets) {
168 p = &free_packets->p;
169 free_packets = free_packets->next;
170 } else {
171 if(!count_free_packets) {
172 next_free_packet = xcalloc(1024, sizeof (union free_packet));
173 count_free_packets = 1024;
174 }
175 p = &(next_free_packet++)->p;
176 --count_free_packets;
177 }
178 return p;
179}
180
181/** @brief Free a packet
182 *
183 * Assumes that @ref lock is held. */
184static void free_packet(struct packet *p) {
185 union free_packet *u = (union free_packet *)p;
186 u->next = free_packets;
187 free_packets = u;
188}
189
190/** @brief Return true iff a < b in sequence-space arithmetic */
191static inline int lt(uint32_t a, uint32_t b) {
192 return (uint32_t)(a - b) & 0x80000000;
193}
194
195/** @brief Return true iff a >= b in sequence-space arithmetic */
196static inline int ge(uint32_t a, uint32_t b) {
197 return !lt(a, b);
198}
199
200/** @brief Return true iff a > b in sequence-space arithmetic */
201static inline int gt(uint32_t a, uint32_t b) {
202 return lt(b, a);
203}
204
205/** @brief Return true iff a <= b in sequence-space arithmetic */
206static inline int le(uint32_t a, uint32_t b) {
207 return !lt(b, a);
208}
209
210/** @brief Drop the packet at the head of the queue */
211static 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);
217 --npackets;
218 }
219}
220
221/** @brief Background thread collecting samples
222 *
223 * This function collects samples, perhaps converts them to the target format,
224 * and adds them to the packet list. */
225static void *listen_thread(void attribute((unused)) *arg) {
226 struct packet *p = 0;
227 int n;
228 struct rtp_header header;
229 uint16_t seq;
230 uint32_t timestamp;
231 struct iovec iov[2];
232
233 for(;;) {
234 if(!p) {
235 pthread_mutex_lock(&lock);
236 p = new_packet();
237 pthread_mutex_unlock(&lock);
238 }
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);
244 if(n < 0) {
245 switch(errno) {
246 case EINTR:
247 continue;
248 default:
249 fatal(errno, "error reading from socket");
250 }
251 }
252 /* Ignore too-short packets */
253 if((size_t)n <= sizeof (struct rtp_header)) {
254 info("ignored a short packet");
255 continue;
256 }
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);
263 continue;
264 }
265 pthread_mutex_lock(&lock);
266 p = new_packet();
267 p->timestamp = timestamp;
268 /* Convert to target format */
269 switch(header.mpt & 0x7F) {
270 case 10:
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 */
275 break;
276 /* TODO support other RFC3551 media types (when the speaker does) */
277 default:
278 fatal(0, "unsupported RTP payload type %d",
279 header.mpt & 0x7F);
280 }
281 if(logfp)
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.
285 *
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) {
289 info("buffer full");
290 while(nsamples >= maxbuffer)
291 pthread_cond_wait(&cond, &lock);
292 }
293 /* If there's a packet there already we overwrite it; perhaps it is left
294 * over from an earlier stage. */
295 drop_packet(seq);
296 /* Record this packet */
297 packets[seq] = p;
298 /* If we currently have no idea where to start playing, this is it */
299 if(!npackets)
300 sequence = seq;
301 ++npackets;
302 nsamples += p->nsamples;
303 pthread_cond_broadcast(&cond);
304 pthread_mutex_unlock(&lock);
305 }
306}
307
308/** @brief Return true if @p p contains @p timestamp */
309static 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;
312
313 return (ge(timestamp, packet_start)
314 && lt(timestamp, packet_end));
315}
316
317#if HAVE_COREAUDIO_AUDIOHARDWARE_H
318/** @brief Callback from Core Audio */
319static 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;
330
331 pthread_mutex_lock(&lock);
332 while(nbuffers > 0) {
333 float *samplesOut = ab->mData;
334 size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
335
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. */
339 while(npackets
340 && (!packets[sequence]
341 || le(packets[sequence]->timestamp
342 + packets[sequence]->nsamples,
343 next_timestamp)))
344 drop_packet(sequence++);
345 p = packets[sequence];
346 if(p) {
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 */
362 continue;
363 }
364 }
365 /* We didn't find a suitable packet (though there might still be
366 * unsuitable ones). We infill with 0s. */
367 if(p) {
368 /* There is a next packet, only infill up to that point */
369 uint32_t samples_available = p->timestamp - next_timestamp;
370
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;
378 } else {
379 /* There's no next packet at all */
380 info("infilled by %zu", samplesOutLeft);
381 next_timestamp += samplesOutLeft;
382 samplesOut += samplesOutLeft;
383 samplesOutLeft = 0;
384 }
385 }
386 ++ab;
387 --nbuffers;
388 }
389 pthread_mutex_unlock(&lock);
390 return 0;
391}
392#endif
393
394/** @brief Play an RTP stream
395 *
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
402 */
403static void play_rtp(void) {
404 pthread_t ltid;
405
406 /* We receive and convert audio data in a background thread */
407 pthread_create(&ltid, 0, listen_thread, 0);
408#if API_ALSA
409 {
410 snd_pcm_t *pcm;
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;
423 int prepared = 1;
424 int err;
425 int infilling = 0, escape = 0;
426 time_t logged, now;
427 uint32_t packet_start, packet_end;
428
429 /* Open ALSA */
430 if((err = snd_pcm_open(&pcm,
431 device ? device : "default",
432 SND_PCM_STREAM_PLAYBACK,
433 SND_PCM_NONBLOCK)))
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,
443 sample_format)) < 0)
444 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
445 sample_format, err);
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",
448 rate, err);
449 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
450 channels)) < 0)
451 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
452 channels, err);
453 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
454 &pcm_bufsize)) < 0)
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",
465 avail_min, err);
466 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
467 fatal(0, "error calling snd_pcm_sw_params: %d", err);
468
469 /* Ready to go */
470
471 time(&logged);
472 pthread_mutex_lock(&lock);
473 for(;;) {
474 /* Wait for the buffer to fill up a bit */
475 logged = now;
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);
481 if(!prepared) {
482 if((err = snd_pcm_prepare(pcm)))
483 fatal(0, "error calling snd_pcm_prepare: %d", err);
484 prepared = 1;
485 }
486 assert(sequence != -1);
487 /* Start at the first available packet */
488 next_timestamp = packets[sequence]->timestamp;
489 active = 1;
490 infilling = 0;
491 escape = 0;
492 logged = now;
493 info("%lu samples in buffer (%lus)", nsamples,
494 nsamples / (44100 * 2));
495 info("Playing...");
496 /* Wait until the buffer empties out */
497 while(nsamples >= minbuffer && !escape) {
498 time(&now);
499 if(now > logged + 10) {
500 logged = now;
501 info("%lu samples in buffer (%lus)", nsamples,
502 nsamples / (44100 * 2));
503 }
504 if(packets
505 && ge(next_timestamp, packets->timestamp + packets->nsamples)) {
506 info("dropping buffered past packet %"PRIx32" < %"PRIx32,
507 packets->timestamp, next_timestamp);
508 drop_first_packet();
509 continue;
510 }
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)) {
515 case 0:
516 info("snd_pcm_wait timed out");
517 break;
518 case 1:
519 break;
520 default:
521 fatal(0, "snd_pcm_wait returned %d", err);
522 }
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;
533
534 frames_written = snd_pcm_writei(pcm,
535 packets->samples_raw + offset,
536 frames_available);
537 if(frames_written < 0) {
538 switch(frames_written) {
539 case -EAGAIN:
540 info("snd_pcm_wait() returned but we got -EAGAIN!");
541 break;
542 case -EPIPE:
543 error(0, "error calling snd_pcm_writei: %ld",
544 (long)frames_written);
545 escape = 1;
546 break;
547 default:
548 fatal(0, "error calling snd_pcm_writei: %ld",
549 (long)frames_written);
550 }
551 } else {
552 samples_written = frames_written * 2;
553 next_timestamp += samples_written;
554 if(ge(next_timestamp, packet_end))
555 drop_first_packet();
556 infilling = 0;
557 }
558 } else {
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;
562
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);
572 }
573 frames_available = samples_available / 2;
574 if(!infilling) {
575 info("Infilling %d samples, next=%"PRIx32" packet=[%"PRIx32",%"PRIx32"]",
576 samples_available, next_timestamp,
577 packets->timestamp, packets->timestamp + packets->nsamples);
578 //infilling++;
579 }
580 frames_written = snd_pcm_writei(pcm,
581 zeros,
582 frames_available);
583 if(frames_written < 0) {
584 switch(frames_written) {
585 case -EAGAIN:
586 info("snd_pcm_wait() returned but we got -EAGAIN!");
587 break;
588 case -EPIPE:
589 error(0, "error calling snd_pcm_writei: %ld",
590 (long)frames_written);
591 escape = 1;
592 break;
593 default:
594 fatal(0, "error calling snd_pcm_writei: %ld",
595 (long)frames_written);
596 }
597 } else {
598 samples_written = frames_written * 2;
599 next_timestamp += samples_written;
600 }
601 }
602 }
603 active = 0;
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);
608 if(escape) {
609 if((err = snd_pcm_drop(pcm)))
610 fatal(0, "error calling snd_pcm_drop: %d", err);
611 escape = 0;
612 } else
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);
617 prepared = 0;
618 pthread_mutex_lock(&lock);
619 }
620
621 }
622#elif HAVE_COREAUDIO_AUDIOHARDWARE_H
623 {
624 OSStatus status;
625 UInt32 propertySize;
626 AudioDeviceID adid;
627 AudioStreamBasicDescription asbd;
628
629 /* If this looks suspiciously like libao's macosx driver there's an
630 * excellent reason for that... */
631
632 /* TODO report errors as strings not numbers */
633 propertySize = sizeof adid;
634 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
635 &propertySize, &adid);
636 if(status)
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);
644 if(status)
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);
658 if(status)
659 fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
660 pthread_mutex_lock(&lock);
661 for(;;) {
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 */
667 info("Playing...");
668 next_timestamp = packets[sequence]->timestamp;
669 active = 1;
670 status = AudioDeviceStart(adid, adioproc);
671 if(status)
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);
678 if(status)
679 fatal(0, "AudioDeviceStop: %d", (int)status);
680 active = 0;
681 /* Go back round */
682 }
683 }
684#else
685# error No known audio API
686#endif
687}
688
689/* display usage message and terminate */
690static void help(void) {
691 xprintf("Usage:\n"
692 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
693 "Options:\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"
700 );
701 xfclose(stdout);
702 exit(0);
703}
704
705/* display version number and terminate */
706static void version(void) {
707 xprintf("disorder-playrtp version %s\n", disorder_version_string);
708 xfclose(stdout);
709 exit(0);
710}
711
712int main(int argc, char **argv) {
713 int n;
714 struct addrinfo *res;
715 struct stringlist sl;
716 char *sockname;
717
718 static const struct addrinfo prefs = {
719 AI_PASSIVE,
720 PF_INET,
721 SOCK_DGRAM,
722 IPPROTO_UDP,
723 0,
724 0,
725 0,
726 0
727 };
728
729 mem_init();
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) {
732 switch(n) {
733 case 'h': help();
734 case 'V': version();
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");
742 }
743 }
744 if(!maxbuffer)
745 maxbuffer = 4 * readahead;
746 argc -= optind;
747 argv += optind;
748 if(argc < 1 || argc > 2)
749 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
750 sl.n = argc;
751 sl.s = argv;
752 /* Listen for inbound audio data */
753 if(!(res = get_address(&sl, &prefs, &sockname)))
754 exit(1);
755 if((rtpfd = socket(res->ai_family,
756 res->ai_socktype,
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);
761 play_rtp();
762 return 0;
763}
764
765/*
766Local Variables:
767c-basic-offset:2
768comment-column:40
769fill-column:79
770indent-tabs-mode:nil
771End:
772*/