chiark / gitweb /
arrange for a rounder number of samples per packet
[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 *
b0fdc63d 23 * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</a>)
24 * and Apple Mac (<a
25 * href="http://developer.apple.com/audio/coreaudio.html">Core Audio</a>)
26 * systems. There is no support for Microsoft Windows yet, and that will in
27 * fact probably an entirely separate program.
28 *
189e9830
RK
29 * The program runs (at least) three threads. listen_thread() is responsible
30 * for reading RTP packets off the wire and adding them to the linked list @ref
31 * received_packets, assuming they are basically sound. queue_thread() takes
32 * packets off this linked list and adds them to @ref packets (an operation
33 * which might be much slower due to contention for @ref lock).
b0fdc63d 34 *
35 * The main thread is responsible for actually playing audio. In ALSA this
36 * means it waits until ALSA says it's ready for more audio which it then
37 * plays.
38 *
39 * InCore Audio the main thread is only responsible for starting and stopping
40 * play: the system does the actual playback in its own private thread, and
41 * calls adioproc() to fetch the audio data.
42 *
43 * Sometimes it happens that there is no audio available to play. This may
44 * because the server went away, or a packet was dropped, or the server
45 * deliberately did not send any sound because it encountered a silence.
189e9830
RK
46 *
47 * Assumptions:
48 * - it is safe to read uint32_t values without a lock protecting them
28bacdc0 49 */
e83d0967
RK
50
51#include <config.h>
52#include "types.h"
53
54#include <getopt.h>
55#include <stdio.h>
56#include <stdlib.h>
57#include <sys/socket.h>
58#include <sys/types.h>
59#include <sys/socket.h>
60#include <netdb.h>
61#include <pthread.h>
0b75463f 62#include <locale.h>
2c7c9eae 63#include <sys/uio.h>
28bacdc0 64#include <string.h>
e83d0967
RK
65
66#include "log.h"
67#include "mem.h"
68#include "configuration.h"
69#include "addr.h"
70#include "syscalls.h"
71#include "rtp.h"
0b75463f 72#include "defs.h"
28bacdc0
RK
73#include "vector.h"
74#include "heap.h"
189e9830 75#include "timeval.h"
e83d0967
RK
76
77#if HAVE_COREAUDIO_AUDIOHARDWARE_H
78# include <CoreAudio/AudioHardware.h>
79#endif
0b75463f 80#if API_ALSA
81#include <alsa/asoundlib.h>
82#endif
e83d0967 83
1153fd23 84#define readahead linux_headers_are_borked
85
0b75463f 86/** @brief RTP socket */
e83d0967
RK
87static int rtpfd;
88
345ebe66
RK
89/** @brief Log output */
90static FILE *logfp;
91
0b75463f 92/** @brief Output device */
93static const char *device;
94
95/** @brief Maximum samples per packet we'll support
96 *
97 * NB that two channels = two samples in this program.
98 */
99#define MAXSAMPLES 2048
100
9086a105 101/** @brief Minimum low watermark
0b75463f 102 *
103 * We'll stop playing if there's only this many samples in the buffer. */
1153fd23 104static unsigned minbuffer = 2 * 44100 / 10; /* 0.2 seconds */
0b75463f 105
9086a105 106/** @brief Buffer high watermark
1153fd23 107 *
108 * We'll only start playing when this many samples are available. */
8d0c14d7 109static unsigned readahead = 2 * 2 * 44100;
0b75463f 110
9086a105
RK
111/** @brief Maximum buffer size
112 *
113 * We'll stop reading from the network if we have this many samples. */
114static unsigned maxbuffer;
115
28bacdc0
RK
116/** @brief Number of samples to infill by in one go
117 *
58b5a68f 118 * This is an upper bound - in practice we expect the underlying audio API to
28bacdc0
RK
119 * only ask for a much smaller number of samples in any one go.
120 */
c0e41690 121#define INFILL_SAMPLES (44100 * 2) /* 1s */
122
28bacdc0
RK
123/** @brief Received packet
124 *
125 * Received packets are kept in a binary heap (see @ref pheap) ordered by
126 * timestamp.
127 */
0b75463f 128struct packet {
189e9830
RK
129 /** @brief Next packet in @ref next_free_packet or @ref received_packets */
130 struct packet *next;
131
0b75463f 132 /** @brief Number of samples in this packet */
c0e41690 133 uint32_t nsamples;
58b5a68f 134
0b75463f 135 /** @brief Timestamp from RTP packet
136 *
28bacdc0
RK
137 * NB that "timestamps" are really sample counters. Use lt() or lt_packet()
138 * to compare timestamps.
139 */
0b75463f 140 uint32_t timestamp;
58b5a68f
RK
141
142 /** @brief Flags
143 *
144 * Valid values are:
b0fdc63d 145 * - @ref IDLE - the idle bit was set in the RTP packet
58b5a68f
RK
146 */
147 unsigned flags;
b0fdc63d 148/** @brief idle bit set in RTP packet*/
149#define IDLE 0x0001
58b5a68f 150
28bacdc0
RK
151 /** @brief Raw sample data
152 *
153 * Only the first @p nsamples samples are defined; the rest is uninitialized
154 * data.
155 */
b64efe7e 156 uint16_t samples_raw[MAXSAMPLES];
e83d0967
RK
157};
158
28bacdc0 159/** @brief Return true iff \f$a < b\f$ in sequence-space arithmetic
0b75463f 160 *
28bacdc0
RK
161 * Specifically it returns true if \f$(a-b) mod 2^{32} < 2^{31}\f$.
162 *
163 * See also lt_packet().
164 */
165static inline int lt(uint32_t a, uint32_t b) {
166 return (uint32_t)(a - b) & 0x80000000;
167}
2c7c9eae 168
28bacdc0
RK
169/** @brief Return true iff a >= b in sequence-space arithmetic */
170static inline int ge(uint32_t a, uint32_t b) {
171 return !lt(a, b);
172}
173
174/** @brief Return true iff a > b in sequence-space arithmetic */
175static inline int gt(uint32_t a, uint32_t b) {
176 return lt(b, a);
177}
178
179/** @brief Return true iff a <= b in sequence-space arithmetic */
180static inline int le(uint32_t a, uint32_t b) {
181 return !lt(b, a);
182}
183
184/** @brief Ordering for packets, used by @ref pheap */
185static inline int lt_packet(const struct packet *a, const struct packet *b) {
186 return lt(a->timestamp, b->timestamp);
187}
188
189e9830
RK
189/** @brief Received packets
190 * Protected by @ref receive_lock
191 *
192 * Received packets are added to this list, and queue_thread() picks them off
193 * it and adds them to @ref packets. Whenever a packet is added to it, @ref
194 * receive_cond is signalled.
195 */
196static struct packet *received_packets;
197
198/** @brief Tail of @ref received_packets
199 * Protected by @ref receive_lock
200 */
201static struct packet **received_tail = &received_packets;
202
203/** @brief Lock protecting @ref received_packets
204 *
205 * Only listen_thread() and queue_thread() ever hold this lock. It is vital
206 * that queue_thread() not hold it any longer than it strictly has to. */
207static pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER;
208
209/** @brief Condition variable signalled when @ref received_packets is updated
210 *
211 * Used by listen_thread() to notify queue_thread() that it has added another
212 * packet to @ref received_packets. */
213static pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER;
214
215/** @brief Length of @ref received_packets */
216static uint32_t nreceived;
217
28bacdc0
RK
218/** @struct pheap
219 * @brief Binary heap of packets ordered by timestamp */
220HEAP_TYPE(pheap, struct packet *, lt_packet);
221
222/** @brief Binary heap of received packets */
223static struct pheap packets;
224
189e9830
RK
225/** @brief Total number of samples available
226 *
227 * We make this volatile because we inspect it without a protecting lock,
228 * so the usual pthread_* guarantees aren't available.
229 */
230static volatile uint32_t nsamples;
0b75463f 231
232/** @brief Timestamp of next packet to play.
233 *
234 * This is set to the timestamp of the last packet, plus the number of
09ee2f0d 235 * samples it contained. Only valid if @ref active is nonzero.
0b75463f 236 */
237static uint32_t next_timestamp;
e83d0967 238
09ee2f0d 239/** @brief True if actively playing
240 *
241 * This is true when playing and false when just buffering. */
242static int active;
243
189e9830
RK
244/** @brief Lock protecting @ref packets */
245static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
246
247/** @brief Condition variable signalled whenever @ref packets is changed */
248static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
249
2c7c9eae
RK
250/** @brief Structure of free packet list */
251union free_packet {
252 struct packet p;
253 union free_packet *next;
254};
255
28bacdc0
RK
256/** @brief Linked list of free packets
257 *
258 * This is a linked list of formerly used packets. For preference we re-use
259 * packets that have already been used rather than unused ones, to limit the
260 * size of the program's working set. If there are no free packets in the list
261 * we try @ref next_free_packet instead.
262 *
263 * Must hold @ref lock when accessing this.
264 */
2c7c9eae
RK
265static union free_packet *free_packets;
266
28bacdc0
RK
267/** @brief Array of new free packets
268 *
269 * There are @ref count_free_packets ready to use at this address. If there
270 * are none left we allocate more memory.
271 *
272 * Must hold @ref lock when accessing this.
273 */
2c7c9eae
RK
274static union free_packet *next_free_packet;
275
28bacdc0
RK
276/** @brief Count of new free packets at @ref next_free_packet
277 *
278 * Must hold @ref lock when accessing this.
279 */
2c7c9eae
RK
280static size_t count_free_packets;
281
189e9830
RK
282/** @brief Lock protecting packet allocator */
283static pthread_mutex_t mem_lock = PTHREAD_MUTEX_INITIALIZER;
e83d0967
RK
284
285static const struct option options[] = {
286 { "help", no_argument, 0, 'h' },
287 { "version", no_argument, 0, 'V' },
288 { "debug", no_argument, 0, 'd' },
0b75463f 289 { "device", required_argument, 0, 'D' },
1153fd23 290 { "min", required_argument, 0, 'm' },
9086a105 291 { "max", required_argument, 0, 'x' },
1153fd23 292 { "buffer", required_argument, 0, 'b' },
e83d0967
RK
293 { 0, 0, 0, 0 }
294};
295
189e9830 296/** @Brief Return a new packet */
2c7c9eae
RK
297static struct packet *new_packet(void) {
298 struct packet *p;
189e9830
RK
299
300 pthread_mutex_lock(&mem_lock);
2c7c9eae
RK
301 if(free_packets) {
302 p = &free_packets->p;
303 free_packets = free_packets->next;
304 } else {
305 if(!count_free_packets) {
306 next_free_packet = xcalloc(1024, sizeof (union free_packet));
307 count_free_packets = 1024;
308 }
309 p = &(next_free_packet++)->p;
310 --count_free_packets;
311 }
189e9830 312 pthread_mutex_unlock(&mem_lock);
2c7c9eae
RK
313 return p;
314}
315
189e9830 316/** @brief Free a packet */
2c7c9eae
RK
317static void free_packet(struct packet *p) {
318 union free_packet *u = (union free_packet *)p;
189e9830 319 pthread_mutex_lock(&mem_lock);
2c7c9eae
RK
320 u->next = free_packets;
321 free_packets = u;
189e9830 322 pthread_mutex_unlock(&mem_lock);
2c7c9eae
RK
323}
324
28bacdc0
RK
325/** @brief Drop the first packet
326 *
327 * Assumes that @ref lock is held.
328 */
329static void drop_first_packet(void) {
330 if(pheap_count(&packets)) {
331 struct packet *const p = pheap_remove(&packets);
332 nsamples -= p->nsamples;
333 free_packet(p);
2c7c9eae 334 pthread_cond_broadcast(&cond);
2c7c9eae 335 }
9086a105
RK
336}
337
189e9830
RK
338/** @brief Background thread adding packets to heap
339 *
340 * This just transfers packets from @ref received_packets to @ref packets. It
341 * is important that it holds @ref receive_lock for as little time as possible,
342 * in order to minimize the interval between calls to read() in
343 * listen_thread().
344 */
345static void *queue_thread(void attribute((unused)) *arg) {
346 struct packet *p;
347
348 for(;;) {
349 /* Get the next packet */
350 pthread_mutex_lock(&receive_lock);
351 while(!received_packets)
352 pthread_cond_wait(&receive_cond, &receive_lock);
353 p = received_packets;
354 received_packets = p->next;
355 if(!received_packets)
356 received_tail = &received_packets;
357 --nreceived;
358 pthread_mutex_unlock(&receive_lock);
359 /* Add it to the heap */
360 pthread_mutex_lock(&lock);
361 pheap_insert(&packets, p);
362 nsamples += p->nsamples;
363 pthread_cond_broadcast(&cond);
364 pthread_mutex_unlock(&lock);
365 }
366}
367
09ee2f0d 368/** @brief Background thread collecting samples
0b75463f 369 *
370 * This function collects samples, perhaps converts them to the target format,
b0fdc63d 371 * and adds them to the packet list.
372 *
373 * It is crucial that the gap between successive calls to read() is as small as
374 * possible: otherwise packets will be dropped.
375 *
376 * We use a binary heap to ensure that the unavoidable effort is at worst
377 * logarithmic in the total number of packets - in fact if packets are mostly
378 * received in order then we will largely do constant work per packet since the
379 * newest packet will always be last.
380 *
381 * Of more concern is that we must acquire the lock on the heap to add a packet
382 * to it. If this proves a problem in practice then the answer would be
383 * (probably doubly) linked list with new packets added the end and a second
384 * thread which reads packets off the list and adds them to the heap.
385 *
386 * We keep memory allocation (mostly) very fast by keeping pre-allocated
387 * packets around; see @ref new_packet().
388 */
0b75463f 389static void *listen_thread(void attribute((unused)) *arg) {
2c7c9eae 390 struct packet *p = 0;
0b75463f 391 int n;
2c7c9eae
RK
392 struct rtp_header header;
393 uint16_t seq;
394 uint32_t timestamp;
395 struct iovec iov[2];
e83d0967
RK
396
397 for(;;) {
189e9830 398 if(!p)
2c7c9eae 399 p = new_packet();
2c7c9eae
RK
400 iov[0].iov_base = &header;
401 iov[0].iov_len = sizeof header;
402 iov[1].iov_base = p->samples_raw;
b64efe7e 403 iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
2c7c9eae 404 n = readv(rtpfd, iov, 2);
e83d0967
RK
405 if(n < 0) {
406 switch(errno) {
407 case EINTR:
408 continue;
409 default:
410 fatal(errno, "error reading from socket");
411 }
412 }
0b75463f 413 /* Ignore too-short packets */
345ebe66
RK
414 if((size_t)n <= sizeof (struct rtp_header)) {
415 info("ignored a short packet");
0b75463f 416 continue;
345ebe66 417 }
2c7c9eae
RK
418 timestamp = htonl(header.timestamp);
419 seq = htons(header.seq);
09ee2f0d 420 /* Ignore packets in the past */
2c7c9eae 421 if(active && lt(timestamp, next_timestamp)) {
c0e41690 422 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
2c7c9eae 423 timestamp, next_timestamp);
09ee2f0d 424 continue;
c0e41690 425 }
189e9830 426 p->next = 0;
58b5a68f 427 p->flags = 0;
2c7c9eae 428 p->timestamp = timestamp;
e83d0967 429 /* Convert to target format */
58b5a68f
RK
430 if(header.mpt & 0x80)
431 p->flags |= IDLE;
2c7c9eae 432 switch(header.mpt & 0x7F) {
e83d0967 433 case 10:
2c7c9eae 434 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
e83d0967
RK
435 break;
436 /* TODO support other RFC3551 media types (when the speaker does) */
437 default:
0b75463f 438 fatal(0, "unsupported RTP payload type %d",
2c7c9eae 439 header.mpt & 0x7F);
e83d0967 440 }
345ebe66
RK
441 if(logfp)
442 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
2c7c9eae 443 seq, timestamp, p->nsamples, timestamp + p->nsamples);
0b75463f 444 /* Stop reading if we've reached the maximum.
445 *
446 * This is rather unsatisfactory: it means that if packets get heavily
447 * out of order then we guarantee dropouts. But for now... */
345ebe66 448 if(nsamples >= maxbuffer) {
189e9830 449 pthread_mutex_lock(&lock);
345ebe66
RK
450 while(nsamples >= maxbuffer)
451 pthread_cond_wait(&cond, &lock);
189e9830 452 pthread_mutex_unlock(&lock);
345ebe66 453 }
189e9830
RK
454 /* Add the packet to the receive queue */
455 pthread_mutex_lock(&receive_lock);
456 *received_tail = p;
457 received_tail = &p->next;
458 ++nreceived;
459 pthread_cond_signal(&receive_cond);
460 pthread_mutex_unlock(&receive_lock);
58b5a68f
RK
461 /* We'll need a new packet */
462 p = 0;
e83d0967
RK
463 }
464}
465
b0fdc63d 466/** @brief Return true if @p p contains @p timestamp
467 *
468 * Containment implies that a sample @p timestamp exists within the packet.
469 */
2c7c9eae
RK
470static inline int contains(const struct packet *p, uint32_t timestamp) {
471 const uint32_t packet_start = p->timestamp;
472 const uint32_t packet_end = p->timestamp + p->nsamples;
473
474 return (ge(timestamp, packet_start)
475 && lt(timestamp, packet_end));
476}
477
5626f6d2
RK
478/** @brief Wait until the buffer is adequately full
479 *
480 * Must be called with @ref lock held.
481 */
482static void fill_buffer(void) {
483 info("Buffering...");
484 while(nsamples < readahead)
485 pthread_cond_wait(&cond, &lock);
486 next_timestamp = pheap_first(&packets)->timestamp;
487 active = 1;
488}
489
490/** @brief Find next packet
491 * @return Packet to play or NULL if none found
492 *
493 * The return packet is merely guaranteed not to be in the past: it might be
494 * the first packet in the future rather than one that is actually suitable to
495 * play.
496 *
497 * Must be called with @ref lock held.
498 */
499static struct packet *next_packet(void) {
500 while(pheap_count(&packets)) {
501 struct packet *const p = pheap_first(&packets);
502 if(le(p->timestamp + p->nsamples, next_timestamp)) {
503 /* This packet is in the past. Drop it and try another one. */
504 drop_first_packet();
505 } else
506 /* This packet is NOT in the past. (It might be in the future
507 * however.) */
508 return p;
509 }
510 return 0;
511}
512
e83d0967 513#if HAVE_COREAUDIO_AUDIOHARDWARE_H
09ee2f0d 514/** @brief Callback from Core Audio */
9086a105
RK
515static OSStatus adioproc
516 (AudioDeviceID attribute((unused)) inDevice,
517 const AudioTimeStamp attribute((unused)) *inNow,
518 const AudioBufferList attribute((unused)) *inInputData,
519 const AudioTimeStamp attribute((unused)) *inInputTime,
520 AudioBufferList *outOutputData,
521 const AudioTimeStamp attribute((unused)) *inOutputTime,
522 void attribute((unused)) *inClientData) {
e83d0967
RK
523 UInt32 nbuffers = outOutputData->mNumberBuffers;
524 AudioBuffer *ab = outOutputData->mBuffers;
28bacdc0 525 uint32_t samples_available;
e83d0967 526
0b75463f 527 pthread_mutex_lock(&lock);
9086a105
RK
528 while(nbuffers > 0) {
529 float *samplesOut = ab->mData;
530 size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
2c7c9eae 531
9086a105 532 while(samplesOutLeft > 0) {
5626f6d2 533 const struct packet *p = next_packet();
28bacdc0
RK
534 if(p && contains(p, next_timestamp)) {
535 /* This packet is ready to play */
536 const uint32_t packet_end = p->timestamp + p->nsamples;
537 const uint32_t offset = next_timestamp - p->timestamp;
b64efe7e 538 const uint16_t *ptr = (void *)(p->samples_raw + offset);
28bacdc0
RK
539
540 samples_available = packet_end - next_timestamp;
541 if(samples_available > samplesOutLeft)
542 samples_available = samplesOutLeft;
543 next_timestamp += samples_available;
544 samplesOutLeft -= samples_available;
545 while(samples_available-- > 0)
546 *samplesOut++ = (int16_t)ntohs(*ptr++) * (0.5 / 32767);
547 /* We don't bother junking the packet - that'll be dealt with next time
548 * round */
549 } else {
550 /* No packet is ready to play (and there might be no packet at all) */
551 samples_available = p ? p->timestamp - next_timestamp
552 : samplesOutLeft;
9086a105
RK
553 if(samples_available > samplesOutLeft)
554 samples_available = samplesOutLeft;
58b5a68f 555 //info("infill by %"PRIu32, samples_available);
28bacdc0 556 /* Conveniently the buffer is 0 to start with */
9086a105
RK
557 next_timestamp += samples_available;
558 samplesOut += samples_available;
559 samplesOutLeft -= samples_available;
9086a105 560 }
e83d0967 561 }
9086a105
RK
562 ++ab;
563 --nbuffers;
e83d0967
RK
564 }
565 pthread_mutex_unlock(&lock);
566 return 0;
567}
568#endif
569
b64efe7e 570
571#if API_ALSA
572/** @brief PCM handle */
573static snd_pcm_t *pcm;
574
575/** @brief True when @ref pcm is up and running */
576static int alsa_prepared = 1;
577
578/** @brief Initialize @ref pcm */
579static void setup_alsa(void) {
580 snd_pcm_hw_params_t *hwparams;
581 snd_pcm_sw_params_t *swparams;
582 /* Only support one format for now */
583 const int sample_format = SND_PCM_FORMAT_S16_BE;
584 unsigned rate = 44100;
585 const int channels = 2;
586 const int samplesize = channels * sizeof(uint16_t);
587 snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
588 /* If we can write more than this many samples we'll get a wakeup */
589 const int avail_min = 256;
590 int err;
591
592 /* Open ALSA */
593 if((err = snd_pcm_open(&pcm,
594 device ? device : "default",
595 SND_PCM_STREAM_PLAYBACK,
596 SND_PCM_NONBLOCK)))
597 fatal(0, "error from snd_pcm_open: %d", err);
598 /* Set up 'hardware' parameters */
599 snd_pcm_hw_params_alloca(&hwparams);
600 if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
601 fatal(0, "error from snd_pcm_hw_params_any: %d", err);
602 if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
603 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
604 fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
605 if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
606 sample_format)) < 0)
607
608 fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
609 sample_format, err);
610 if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
611 fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
612 rate, err);
613 if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
614 channels)) < 0)
615 fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
616 channels, err);
617 if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
618 &pcm_bufsize)) < 0)
619 fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
620 MAXSAMPLES * samplesize * 3, err);
621 if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
622 fatal(0, "error calling snd_pcm_hw_params: %d", err);
623 /* Set up 'software' parameters */
624 snd_pcm_sw_params_alloca(&swparams);
625 if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
626 fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
627 if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
628 fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
629 avail_min, err);
630 if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
631 fatal(0, "error calling snd_pcm_sw_params: %d", err);
632}
633
634/** @brief Wait until ALSA wants some audio */
635static void wait_alsa(void) {
636 struct pollfd fds[64];
637 int nfds, err;
638 unsigned short events;
639
640 for(;;) {
641 do {
642 if((nfds = snd_pcm_poll_descriptors(pcm,
643 fds, sizeof fds / sizeof *fds)) < 0)
644 fatal(0, "error calling snd_pcm_poll_descriptors: %d", nfds);
645 } while(poll(fds, nfds, -1) < 0 && errno == EINTR);
646 if((err = snd_pcm_poll_descriptors_revents(pcm, fds, nfds, &events)))
647 fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
648 if(events & POLLOUT)
649 return;
650 }
651}
652
b0fdc63d 653/** @brief Play some sound via ALSA
b64efe7e 654 * @param s Pointer to sample data
655 * @param n Number of samples
656 * @return 0 on success, -1 on non-fatal error
657 */
658static int alsa_writei(const void *s, size_t n) {
659 /* Do the write */
660 const snd_pcm_sframes_t frames_written = snd_pcm_writei(pcm, s, n / 2);
661 if(frames_written < 0) {
662 /* Something went wrong */
663 switch(frames_written) {
664 case -EAGAIN:
665 return 0;
666 case -EPIPE:
667 error(0, "error calling snd_pcm_writei: %ld",
668 (long)frames_written);
669 return -1;
670 default:
671 fatal(0, "error calling snd_pcm_writei: %ld",
672 (long)frames_written);
673 }
674 } else {
675 /* Success */
676 next_timestamp += frames_written * 2;
677 return 0;
678 }
679}
680
681/** @brief Play the relevant part of a packet
682 * @param p Packet to play
683 * @return 0 on success, -1 on non-fatal error
684 */
685static int alsa_play(const struct packet *p) {
b64efe7e 686 return alsa_writei(p->samples_raw + next_timestamp - p->timestamp,
687 (p->timestamp + p->nsamples) - next_timestamp);
688}
689
690/** @brief Play some silence
691 * @param p Next packet or NULL
692 * @return 0 on success, -1 on non-fatal error
693 */
694static int alsa_infill(const struct packet *p) {
695 static const uint16_t zeros[INFILL_SAMPLES];
696 size_t samples_available = INFILL_SAMPLES;
697
698 if(p && samples_available > p->timestamp - next_timestamp)
699 samples_available = p->timestamp - next_timestamp;
b64efe7e 700 return alsa_writei(zeros, samples_available);
701}
702
703/** @brief Reset ALSA state after we lost synchronization */
704static void alsa_reset(int hard_reset) {
705 int err;
706
707 if((err = snd_pcm_nonblock(pcm, 0)))
708 fatal(0, "error calling snd_pcm_nonblock: %d", err);
709 if(hard_reset) {
710 if((err = snd_pcm_drop(pcm)))
711 fatal(0, "error calling snd_pcm_drop: %d", err);
712 } else
713 if((err = snd_pcm_drain(pcm)))
714 fatal(0, "error calling snd_pcm_drain: %d", err);
715 if((err = snd_pcm_nonblock(pcm, 1)))
716 fatal(0, "error calling snd_pcm_nonblock: %d", err);
717 alsa_prepared = 0;
718}
719#endif
720
09ee2f0d 721/** @brief Play an RTP stream
722 *
723 * This is the guts of the program. It is responsible for:
724 * - starting the listening thread
725 * - opening the audio device
726 * - reading ahead to build up a buffer
727 * - arranging for audio to be played
728 * - detecting when the buffer has got too small and re-buffering
729 */
0b75463f 730static void play_rtp(void) {
731 pthread_t ltid;
e83d0967
RK
732
733 /* We receive and convert audio data in a background thread */
0b75463f 734 pthread_create(&ltid, 0, listen_thread, 0);
189e9830
RK
735 /* We have a second thread to add received packets to the queue */
736 pthread_create(&ltid, 0, queue_thread, 0);
e83d0967 737#if API_ALSA
0b75463f 738 {
b64efe7e 739 struct packet *p;
740 int escape, err;
741
742 /* Open the sound device */
743 setup_alsa();
0b75463f 744 pthread_mutex_lock(&lock);
745 for(;;) {
746 /* Wait for the buffer to fill up a bit */
b64efe7e 747 fill_buffer();
748 if(!alsa_prepared) {
0b75463f 749 if((err = snd_pcm_prepare(pcm)))
750 fatal(0, "error calling snd_pcm_prepare: %d", err);
b64efe7e 751 alsa_prepared = 1;
0b75463f 752 }
c0e41690 753 escape = 0;
ed13cbc8 754 info("Playing...");
b64efe7e 755 /* Keep playing until the buffer empties out, or ALSA tells us to get
756 * lost */
c0e41690 757 while(nsamples >= minbuffer && !escape) {
0b75463f 758 /* Wait for ALSA to ask us for more data */
759 pthread_mutex_unlock(&lock);
b64efe7e 760 wait_alsa();
0b75463f 761 pthread_mutex_lock(&lock);
b64efe7e 762 /* ALSA is ready for more data, find something to play */
763 p = next_packet();
764 /* Play it or play some silence */
765 if(contains(p, next_timestamp))
766 escape = alsa_play(p);
767 else
768 escape = alsa_infill(p);
0b75463f 769 }
09ee2f0d 770 active = 0;
0b75463f 771 /* We stop playing for a bit until the buffer re-fills */
772 pthread_mutex_unlock(&lock);
b64efe7e 773 alsa_reset(escape);
0b75463f 774 pthread_mutex_lock(&lock);
775 }
776
777 }
e83d0967
RK
778#elif HAVE_COREAUDIO_AUDIOHARDWARE_H
779 {
780 OSStatus status;
781 UInt32 propertySize;
782 AudioDeviceID adid;
783 AudioStreamBasicDescription asbd;
784
785 /* If this looks suspiciously like libao's macosx driver there's an
786 * excellent reason for that... */
787
788 /* TODO report errors as strings not numbers */
789 propertySize = sizeof adid;
790 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
791 &propertySize, &adid);
792 if(status)
793 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
794 if(adid == kAudioDeviceUnknown)
795 fatal(0, "no output device");
796 propertySize = sizeof asbd;
797 status = AudioDeviceGetProperty(adid, 0, false,
798 kAudioDevicePropertyStreamFormat,
799 &propertySize, &asbd);
800 if(status)
801 fatal(0, "AudioHardwareGetProperty: %d", (int)status);
802 D(("mSampleRate %f", asbd.mSampleRate));
9086a105
RK
803 D(("mFormatID %08lx", asbd.mFormatID));
804 D(("mFormatFlags %08lx", asbd.mFormatFlags));
805 D(("mBytesPerPacket %08lx", asbd.mBytesPerPacket));
806 D(("mFramesPerPacket %08lx", asbd.mFramesPerPacket));
807 D(("mBytesPerFrame %08lx", asbd.mBytesPerFrame));
808 D(("mChannelsPerFrame %08lx", asbd.mChannelsPerFrame));
809 D(("mBitsPerChannel %08lx", asbd.mBitsPerChannel));
810 D(("mReserved %08lx", asbd.mReserved));
e83d0967
RK
811 if(asbd.mFormatID != kAudioFormatLinearPCM)
812 fatal(0, "audio device does not support kAudioFormatLinearPCM");
813 status = AudioDeviceAddIOProc(adid, adioproc, 0);
814 if(status)
815 fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
816 pthread_mutex_lock(&lock);
817 for(;;) {
818 /* Wait for the buffer to fill up a bit */
b64efe7e 819 fill_buffer();
e83d0967 820 /* Start playing now */
8dcb5ff0 821 info("Playing...");
28bacdc0 822 next_timestamp = pheap_first(&packets)->timestamp;
8dcb5ff0 823 active = 1;
e83d0967
RK
824 status = AudioDeviceStart(adid, adioproc);
825 if(status)
826 fatal(0, "AudioDeviceStart: %d", (int)status);
827 /* Wait until the buffer empties out */
1153fd23 828 while(nsamples >= minbuffer)
e83d0967
RK
829 pthread_cond_wait(&cond, &lock);
830 /* Stop playing for a bit until the buffer re-fills */
831 status = AudioDeviceStop(adid, adioproc);
832 if(status)
833 fatal(0, "AudioDeviceStop: %d", (int)status);
8dcb5ff0 834 active = 0;
e83d0967
RK
835 /* Go back round */
836 }
837 }
838#else
839# error No known audio API
840#endif
841}
842
843/* display usage message and terminate */
844static void help(void) {
845 xprintf("Usage:\n"
846 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
847 "Options:\n"
1153fd23 848 " --device, -D DEVICE Output device\n"
849 " --min, -m FRAMES Buffer low water mark\n"
9086a105
RK
850 " --buffer, -b FRAMES Buffer high water mark\n"
851 " --max, -x FRAMES Buffer maximum size\n"
852 " --help, -h Display usage message\n"
853 " --version, -V Display version number\n"
854 );
e83d0967
RK
855 xfclose(stdout);
856 exit(0);
857}
858
859/* display version number and terminate */
860static void version(void) {
861 xprintf("disorder-playrtp version %s\n", disorder_version_string);
862 xfclose(stdout);
863 exit(0);
864}
865
866int main(int argc, char **argv) {
867 int n;
868 struct addrinfo *res;
869 struct stringlist sl;
0b75463f 870 char *sockname;
e83d0967 871
0b75463f 872 static const struct addrinfo prefs = {
e83d0967
RK
873 AI_PASSIVE,
874 PF_INET,
875 SOCK_DGRAM,
876 IPPROTO_UDP,
877 0,
878 0,
879 0,
880 0
881 };
882
883 mem_init();
884 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
345ebe66 885 while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:", options, 0)) >= 0) {
e83d0967
RK
886 switch(n) {
887 case 'h': help();
888 case 'V': version();
889 case 'd': debugging = 1; break;
0b75463f 890 case 'D': device = optarg; break;
1153fd23 891 case 'm': minbuffer = 2 * atol(optarg); break;
892 case 'b': readahead = 2 * atol(optarg); break;
9086a105 893 case 'x': maxbuffer = 2 * atol(optarg); break;
345ebe66 894 case 'L': logfp = fopen(optarg, "w"); break;
e83d0967
RK
895 default: fatal(0, "invalid option");
896 }
897 }
9086a105
RK
898 if(!maxbuffer)
899 maxbuffer = 4 * readahead;
e83d0967
RK
900 argc -= optind;
901 argv += optind;
902 if(argc < 1 || argc > 2)
903 fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
904 sl.n = argc;
905 sl.s = argv;
906 /* Listen for inbound audio data */
0b75463f 907 if(!(res = get_address(&sl, &prefs, &sockname)))
e83d0967
RK
908 exit(1);
909 if((rtpfd = socket(res->ai_family,
910 res->ai_socktype,
911 res->ai_protocol)) < 0)
912 fatal(errno, "error creating socket");
913 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
914 fatal(errno, "error binding socket to %s", sockname);
915 play_rtp();
916 return 0;
917}
918
919/*
920Local Variables:
921c-basic-offset:2
922comment-column:40
923fill-column:79
924indent-tabs-mode:nil
925End:
926*/