Commit | Line | Data |
---|---|---|
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 | */ | |
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> | |
0b75463f | 32 | #include <locale.h> |
2c7c9eae | 33 | #include <sys/uio.h> |
e83d0967 RK |
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" | |
0b75463f | 41 | #include "defs.h" |
e83d0967 RK |
42 | |
43 | #if HAVE_COREAUDIO_AUDIOHARDWARE_H | |
44 | # include <CoreAudio/AudioHardware.h> | |
45 | #endif | |
0b75463f | 46 | #if API_ALSA |
47 | #include <alsa/asoundlib.h> | |
48 | #endif | |
e83d0967 | 49 | |
1153fd23 | 50 | #define readahead linux_headers_are_borked |
51 | ||
0b75463f | 52 | /** @brief RTP socket */ |
e83d0967 RK |
53 | static int rtpfd; |
54 | ||
345ebe66 RK |
55 | /** @brief Log output */ |
56 | static FILE *logfp; | |
57 | ||
0b75463f | 58 | /** @brief Output device */ |
59 | static 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 | ||
9086a105 | 67 | /** @brief Minimum low watermark |
0b75463f | 68 | * |
69 | * We'll stop playing if there's only this many samples in the buffer. */ | |
1153fd23 | 70 | static unsigned minbuffer = 2 * 44100 / 10; /* 0.2 seconds */ |
0b75463f | 71 | |
72 | /** @brief Maximum sample size | |
73 | * | |
74 | * The maximum supported size (in bytes) of one sample. */ | |
75 | #define MAXSAMPLESIZE 2 | |
76 | ||
9086a105 | 77 | /** @brief Buffer high watermark |
1153fd23 | 78 | * |
79 | * We'll only start playing when this many samples are available. */ | |
8d0c14d7 | 80 | static unsigned readahead = 2 * 2 * 44100; |
0b75463f | 81 | |
9086a105 RK |
82 | /** @brief Maximum buffer size |
83 | * | |
84 | * We'll stop reading from the network if we have this many samples. */ | |
85 | static unsigned maxbuffer; | |
86 | ||
c0e41690 | 87 | /** @brief Number of samples to infill by in one go */ |
88 | #define INFILL_SAMPLES (44100 * 2) /* 1s */ | |
89 | ||
2c7c9eae | 90 | /** @brief Received packet */ |
0b75463f | 91 | struct packet { |
0b75463f | 92 | /** @brief Number of samples in this packet */ |
c0e41690 | 93 | uint32_t nsamples; |
0b75463f | 94 | /** @brief Timestamp from RTP packet |
95 | * | |
96 | * NB that "timestamps" are really sample counters.*/ | |
97 | uint32_t timestamp; | |
0b75463f | 98 | /** @brief Raw sample data */ |
99 | unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE]; | |
e83d0967 RK |
100 | }; |
101 | ||
0b75463f | 102 | /** @brief Total number of samples available */ |
103 | static unsigned long nsamples; | |
104 | ||
2c7c9eae | 105 | /** @brief Mapping of sequence numbers to packets |
0b75463f | 106 | * |
2c7c9eae RK |
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. */ | |
109 | static struct packet *packets[65536]; | |
110 | ||
111 | /** @brief Total number of packets */ | |
112 | static unsigned npackets; | |
0b75463f | 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 | |
09ee2f0d | 117 | * samples it contained. Only valid if @ref active is nonzero. |
0b75463f | 118 | */ |
119 | static uint32_t next_timestamp; | |
e83d0967 | 120 | |
09ee2f0d | 121 | /** @brief True if actively playing |
122 | * | |
123 | * This is true when playing and false when just buffering. */ | |
124 | static int active; | |
125 | ||
2c7c9eae RK |
126 | /** @brief Sequence number of next packet we expxect to play */ |
127 | static uint16_t sequence; | |
128 | ||
129 | /** @brief Structure of free packet list */ | |
130 | union free_packet { | |
131 | struct packet p; | |
132 | union free_packet *next; | |
133 | }; | |
134 | ||
135 | /** @brief Linked list of free packets */ | |
136 | static union free_packet *free_packets; | |
137 | ||
138 | /** @brief Array of new free packets */ | |
139 | static union free_packet *next_free_packet; | |
140 | ||
141 | /** @brief Count of new free packets */ | |
142 | static size_t count_free_packets; | |
143 | ||
0b75463f | 144 | /** @brief Lock protecting @ref packets */ |
e83d0967 | 145 | static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; |
e83d0967 | 146 | |
0b75463f | 147 | /** @brief Condition variable signalled whenever @ref packets is changed */ |
148 | static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; | |
e83d0967 RK |
149 | |
150 | static const struct option options[] = { | |
151 | { "help", no_argument, 0, 'h' }, | |
152 | { "version", no_argument, 0, 'V' }, | |
153 | { "debug", no_argument, 0, 'd' }, | |
0b75463f | 154 | { "device", required_argument, 0, 'D' }, |
1153fd23 | 155 | { "min", required_argument, 0, 'm' }, |
9086a105 | 156 | { "max", required_argument, 0, 'x' }, |
1153fd23 | 157 | { "buffer", required_argument, 0, 'b' }, |
e83d0967 RK |
158 | { 0, 0, 0, 0 } |
159 | }; | |
160 | ||
2c7c9eae RK |
161 | /** @brief Return a new packet |
162 | * | |
163 | * Assumes that @ref lock is held. */ | |
164 | static 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. */ | |
184 | static 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 | ||
0b75463f | 190 | /** @brief Return true iff a < b in sequence-space arithmetic */ |
09ee2f0d | 191 | static inline int lt(uint32_t a, uint32_t b) { |
192 | return (uint32_t)(a - b) & 0x80000000; | |
e83d0967 RK |
193 | } |
194 | ||
c0e41690 | 195 | /** @brief Return true iff a >= b in sequence-space arithmetic */ |
196 | static 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 */ | |
201 | static 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 */ | |
206 | static inline int le(uint32_t a, uint32_t b) { | |
207 | return !lt(b, a); | |
208 | } | |
209 | ||
9086a105 | 210 | /** @brief Drop the packet at the head of the queue */ |
2c7c9eae RK |
211 | static 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 | } | |
9086a105 RK |
219 | } |
220 | ||
09ee2f0d | 221 | /** @brief Background thread collecting samples |
0b75463f | 222 | * |
223 | * This function collects samples, perhaps converts them to the target format, | |
224 | * and adds them to the packet list. */ | |
225 | static void *listen_thread(void attribute((unused)) *arg) { | |
2c7c9eae | 226 | struct packet *p = 0; |
0b75463f | 227 | int n; |
2c7c9eae RK |
228 | struct rtp_header header; |
229 | uint16_t seq; | |
230 | uint32_t timestamp; | |
231 | struct iovec iov[2]; | |
e83d0967 RK |
232 | |
233 | for(;;) { | |
2c7c9eae RK |
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); | |
e83d0967 RK |
244 | if(n < 0) { |
245 | switch(errno) { | |
246 | case EINTR: | |
247 | continue; | |
248 | default: | |
249 | fatal(errno, "error reading from socket"); | |
250 | } | |
251 | } | |
0b75463f | 252 | /* Ignore too-short packets */ |
345ebe66 RK |
253 | if((size_t)n <= sizeof (struct rtp_header)) { |
254 | info("ignored a short packet"); | |
0b75463f | 255 | continue; |
345ebe66 | 256 | } |
2c7c9eae RK |
257 | timestamp = htonl(header.timestamp); |
258 | seq = htons(header.seq); | |
09ee2f0d | 259 | /* Ignore packets in the past */ |
2c7c9eae | 260 | if(active && lt(timestamp, next_timestamp)) { |
c0e41690 | 261 | info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32, |
2c7c9eae | 262 | timestamp, next_timestamp); |
09ee2f0d | 263 | continue; |
c0e41690 | 264 | } |
2c7c9eae RK |
265 | pthread_mutex_lock(&lock); |
266 | p = new_packet(); | |
267 | p->timestamp = timestamp; | |
e83d0967 | 268 | /* Convert to target format */ |
2c7c9eae | 269 | switch(header.mpt & 0x7F) { |
e83d0967 | 270 | case 10: |
2c7c9eae | 271 | p->nsamples = (n - sizeof header) / sizeof(uint16_t); |
0b75463f | 272 | /* ALSA can do any necessary conversion itself (though it might be better |
273 | * to do any necessary conversion in the background) */ | |
2c7c9eae | 274 | /* TODO we could readv into the buffer */ |
e83d0967 RK |
275 | break; |
276 | /* TODO support other RFC3551 media types (when the speaker does) */ | |
277 | default: | |
0b75463f | 278 | fatal(0, "unsupported RTP payload type %d", |
2c7c9eae | 279 | header.mpt & 0x7F); |
e83d0967 | 280 | } |
345ebe66 RK |
281 | if(logfp) |
282 | fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n", | |
2c7c9eae | 283 | seq, timestamp, p->nsamples, timestamp + p->nsamples); |
0b75463f | 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... */ | |
345ebe66 RK |
288 | if(nsamples >= maxbuffer) { |
289 | info("buffer full"); | |
290 | while(nsamples >= maxbuffer) | |
291 | pthread_cond_wait(&cond, &lock); | |
292 | } | |
2c7c9eae RK |
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); | |
e83d0967 | 304 | pthread_mutex_unlock(&lock); |
e83d0967 RK |
305 | } |
306 | } | |
307 | ||
2c7c9eae RK |
308 | /** @brief Return true if @p p contains @p timestamp */ |
309 | static 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 | ||
e83d0967 | 317 | #if HAVE_COREAUDIO_AUDIOHARDWARE_H |
09ee2f0d | 318 | /** @brief Callback from Core Audio */ |
9086a105 RK |
319 | static 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) { | |
e83d0967 RK |
327 | UInt32 nbuffers = outOutputData->mNumberBuffers; |
328 | AudioBuffer *ab = outOutputData->mBuffers; | |
2c7c9eae | 329 | const struct packet *p; |
e83d0967 | 330 | |
0b75463f | 331 | pthread_mutex_lock(&lock); |
9086a105 RK |
332 | while(nbuffers > 0) { |
333 | float *samplesOut = ab->mData; | |
334 | size_t samplesOutLeft = ab->mDataByteSize / sizeof (float); | |
2c7c9eae | 335 | |
9086a105 | 336 | while(samplesOutLeft > 0) { |
2c7c9eae RK |
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)) { | |
9086a105 | 348 | /* This packet is suitable */ |
2c7c9eae RK |
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)); | |
9086a105 RK |
353 | uint32_t samples_available = packet_end - next_timestamp; |
354 | if(samples_available > samplesOutLeft) | |
355 | samples_available = samplesOutLeft; | |
9086a105 | 356 | next_timestamp += samples_available; |
8dcb5ff0 | 357 | samplesOutLeft -= samples_available; |
2c7c9eae RK |
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 */ | |
9086a105 RK |
362 | continue; |
363 | } | |
364 | } | |
365 | /* We didn't find a suitable packet (though there might still be | |
366 | * unsuitable ones). We infill with 0s. */ | |
2c7c9eae | 367 | if(p) { |
9086a105 | 368 | /* There is a next packet, only infill up to that point */ |
2c7c9eae | 369 | uint32_t samples_available = p->timestamp - next_timestamp; |
9086a105 RK |
370 | |
371 | if(samples_available > samplesOutLeft) | |
372 | samples_available = samplesOutLeft; | |
8dcb5ff0 | 373 | info("infill by %"PRIu32, samples_available); |
9086a105 RK |
374 | /* Convniently the buffer is 0 to start with */ |
375 | next_timestamp += samples_available; | |
376 | samplesOut += samples_available; | |
377 | samplesOutLeft -= samples_available; | |
9086a105 RK |
378 | } else { |
379 | /* There's no next packet at all */ | |
8dcb5ff0 | 380 | info("infilled by %zu", samplesOutLeft); |
9086a105 RK |
381 | next_timestamp += samplesOutLeft; |
382 | samplesOut += samplesOutLeft; | |
383 | samplesOutLeft = 0; | |
9086a105 | 384 | } |
e83d0967 | 385 | } |
9086a105 RK |
386 | ++ab; |
387 | --nbuffers; | |
e83d0967 RK |
388 | } |
389 | pthread_mutex_unlock(&lock); | |
390 | return 0; | |
391 | } | |
392 | #endif | |
393 | ||
09ee2f0d | 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 | */ | |
0b75463f | 403 | static void play_rtp(void) { |
404 | pthread_t ltid; | |
e83d0967 RK |
405 | |
406 | /* We receive and convert audio data in a background thread */ | |
0b75463f | 407 | pthread_create(<id, 0, listen_thread, 0); |
e83d0967 | 408 | #if API_ALSA |
0b75463f | 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; | |
c0e41690 | 425 | int infilling = 0, escape = 0; |
426 | time_t logged, now; | |
427 | uint32_t packet_start, packet_end; | |
0b75463f | 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 | ||
c0e41690 | 471 | time(&logged); |
0b75463f | 472 | pthread_mutex_lock(&lock); |
473 | for(;;) { | |
474 | /* Wait for the buffer to fill up a bit */ | |
8d0c14d7 | 475 | logged = now; |
476 | info("%lu samples in buffer (%lus)", nsamples, | |
477 | nsamples / (44100 * 2)); | |
ed13cbc8 | 478 | info("Buffering..."); |
1153fd23 | 479 | while(nsamples < readahead) |
0b75463f | 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 | } | |
2c7c9eae | 486 | assert(sequence != -1); |
09ee2f0d | 487 | /* Start at the first available packet */ |
2c7c9eae | 488 | next_timestamp = packets[sequence]->timestamp; |
09ee2f0d | 489 | active = 1; |
ed13cbc8 | 490 | infilling = 0; |
c0e41690 | 491 | escape = 0; |
8d0c14d7 | 492 | logged = now; |
493 | info("%lu samples in buffer (%lus)", nsamples, | |
494 | nsamples / (44100 * 2)); | |
ed13cbc8 | 495 | info("Playing..."); |
0b75463f | 496 | /* Wait until the buffer empties out */ |
c0e41690 | 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)) { | |
c0e41690 | 506 | info("dropping buffered past packet %"PRIx32" < %"PRIx32, |
507 | packets->timestamp, next_timestamp); | |
9086a105 | 508 | drop_first_packet(); |
c0e41690 | 509 | continue; |
510 | } | |
0b75463f | 511 | /* Wait for ALSA to ask us for more data */ |
512 | pthread_mutex_unlock(&lock); | |
9ae1516d | 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 | } | |
0b75463f | 523 | pthread_mutex_lock(&lock); |
09ee2f0d | 524 | /* ALSA is ready for more data */ |
c0e41690 | 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; | |
0b75463f | 532 | const size_t frames_available = samples_available / 2; |
533 | ||
534 | frames_written = snd_pcm_writei(pcm, | |
c0e41690 | 535 | packets->samples_raw + offset, |
0b75463f | 536 | frames_available); |
1153fd23 | 537 | if(frames_written < 0) { |
c0e41690 | 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: | |
1153fd23 | 548 | fatal(0, "error calling snd_pcm_writei: %ld", |
549 | (long)frames_written); | |
c0e41690 | 550 | } |
1153fd23 | 551 | } else { |
552 | samples_written = frames_written * 2; | |
1153fd23 | 553 | next_timestamp += samples_written; |
9086a105 RK |
554 | if(ge(next_timestamp, packet_end)) |
555 | drop_first_packet(); | |
1153fd23 | 556 | infilling = 0; |
0b75463f | 557 | } |
558 | } else { | |
559 | /* We don't have anything to play! We'd better play some 0s. */ | |
c0e41690 | 560 | static const uint16_t zeros[INFILL_SAMPLES]; |
561 | size_t samples_available = INFILL_SAMPLES, frames_available; | |
ed13cbc8 | 562 | |
c0e41690 | 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)) | |
0b75463f | 567 | samples_available = packets->timestamp - next_timestamp; |
c0e41690 | 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 | } | |
0b75463f | 573 | frames_available = samples_available / 2; |
c0e41690 | 574 | if(!infilling) { |
8d0c14d7 | 575 | info("Infilling %d samples, next=%"PRIx32" packet=[%"PRIx32",%"PRIx32"]", |
576 | samples_available, next_timestamp, | |
577 | packets->timestamp, packets->timestamp + packets->nsamples); | |
c0e41690 | 578 | //infilling++; |
579 | } | |
0b75463f | 580 | frames_written = snd_pcm_writei(pcm, |
581 | zeros, | |
582 | frames_available); | |
1153fd23 | 583 | if(frames_written < 0) { |
c0e41690 | 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: | |
1153fd23 | 594 | fatal(0, "error calling snd_pcm_writei: %ld", |
595 | (long)frames_written); | |
c0e41690 | 596 | } |
74a94bd0 | 597 | } else { |
598 | samples_written = frames_written * 2; | |
1153fd23 | 599 | next_timestamp += samples_written; |
74a94bd0 | 600 | } |
0b75463f | 601 | } |
602 | } | |
09ee2f0d | 603 | active = 0; |
0b75463f | 604 | /* We stop playing for a bit until the buffer re-fills */ |
605 | pthread_mutex_unlock(&lock); | |
ed13cbc8 | 606 | if((err = snd_pcm_nonblock(pcm, 0))) |
607 | fatal(0, "error calling snd_pcm_nonblock: %d", err); | |
c0e41690 | 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); | |
ed13cbc8 | 615 | if((err = snd_pcm_nonblock(pcm, 1))) |
616 | fatal(0, "error calling snd_pcm_nonblock: %d", err); | |
0b75463f | 617 | prepared = 0; |
618 | pthread_mutex_lock(&lock); | |
619 | } | |
620 | ||
621 | } | |
e83d0967 RK |
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)); | |
9086a105 RK |
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)); | |
e83d0967 RK |
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 */ | |
8dcb5ff0 | 663 | info("Buffering..."); |
1153fd23 | 664 | while(nsamples < readahead) |
e83d0967 RK |
665 | pthread_cond_wait(&cond, &lock); |
666 | /* Start playing now */ | |
8dcb5ff0 | 667 | info("Playing..."); |
2c7c9eae | 668 | next_timestamp = packets[sequence]->timestamp; |
8dcb5ff0 | 669 | active = 1; |
e83d0967 RK |
670 | status = AudioDeviceStart(adid, adioproc); |
671 | if(status) | |
672 | fatal(0, "AudioDeviceStart: %d", (int)status); | |
673 | /* Wait until the buffer empties out */ | |
1153fd23 | 674 | while(nsamples >= minbuffer) |
e83d0967 RK |
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); | |
8dcb5ff0 | 680 | active = 0; |
e83d0967 RK |
681 | /* Go back round */ |
682 | } | |
683 | } | |
684 | #else | |
685 | # error No known audio API | |
686 | #endif | |
687 | } | |
688 | ||
689 | /* display usage message and terminate */ | |
690 | static void help(void) { | |
691 | xprintf("Usage:\n" | |
692 | " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n" | |
693 | "Options:\n" | |
1153fd23 | 694 | " --device, -D DEVICE Output device\n" |
695 | " --min, -m FRAMES Buffer low water mark\n" | |
9086a105 RK |
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 | ); | |
e83d0967 RK |
701 | xfclose(stdout); |
702 | exit(0); | |
703 | } | |
704 | ||
705 | /* display version number and terminate */ | |
706 | static void version(void) { | |
707 | xprintf("disorder-playrtp version %s\n", disorder_version_string); | |
708 | xfclose(stdout); | |
709 | exit(0); | |
710 | } | |
711 | ||
712 | int main(int argc, char **argv) { | |
713 | int n; | |
714 | struct addrinfo *res; | |
715 | struct stringlist sl; | |
0b75463f | 716 | char *sockname; |
e83d0967 | 717 | |
0b75463f | 718 | static const struct addrinfo prefs = { |
e83d0967 RK |
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"); | |
345ebe66 | 731 | while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:", options, 0)) >= 0) { |
e83d0967 RK |
732 | switch(n) { |
733 | case 'h': help(); | |
734 | case 'V': version(); | |
735 | case 'd': debugging = 1; break; | |
0b75463f | 736 | case 'D': device = optarg; break; |
1153fd23 | 737 | case 'm': minbuffer = 2 * atol(optarg); break; |
738 | case 'b': readahead = 2 * atol(optarg); break; | |
9086a105 | 739 | case 'x': maxbuffer = 2 * atol(optarg); break; |
345ebe66 | 740 | case 'L': logfp = fopen(optarg, "w"); break; |
e83d0967 RK |
741 | default: fatal(0, "invalid option"); |
742 | } | |
743 | } | |
9086a105 RK |
744 | if(!maxbuffer) |
745 | maxbuffer = 4 * readahead; | |
e83d0967 RK |
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 */ | |
0b75463f | 753 | if(!(res = get_address(&sl, &prefs, &sockname))) |
e83d0967 RK |
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 | /* | |
766 | Local Variables: | |
767 | c-basic-offset:2 | |
768 | comment-column:40 | |
769 | fill-column:79 | |
770 | indent-tabs-mode:nil | |
771 | End: | |
772 | */ |