Commit | Line | Data |
---|---|---|
e83d0967 RK |
1 | /* |
2 | * This file is part of DisOrder. | |
4778e044 | 3 | * Copyright (C) 2007-2009 Richard Kettlewell |
e83d0967 | 4 | * |
e7eb3a27 | 5 | * This program is free software: you can redistribute it and/or modify |
e83d0967 | 6 | * it under the terms of the GNU General Public License as published by |
e7eb3a27 | 7 | * the Free Software Foundation, either version 3 of the License, or |
e83d0967 RK |
8 | * (at your option) any later version. |
9 | * | |
e7eb3a27 RK |
10 | * This program is distributed in the hope that it will be useful, |
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 | * GNU General Public License for more details. | |
14 | * | |
e83d0967 | 15 | * You should have received a copy of the GNU General Public License |
e7eb3a27 | 16 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
e83d0967 | 17 | */ |
28bacdc0 RK |
18 | /** @file clients/playrtp.c |
19 | * @brief RTP player | |
20 | * | |
b0fdc63d | 21 | * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</a>) |
22 | * and Apple Mac (<a | |
23 | * href="http://developer.apple.com/audio/coreaudio.html">Core Audio</a>) | |
24 | * systems. There is no support for Microsoft Windows yet, and that will in | |
25 | * fact probably an entirely separate program. | |
26 | * | |
8d251217 RK |
27 | * The program runs (at least) three threads: |
28 | * | |
29 | * listen_thread() is responsible for reading RTP packets off the wire and | |
30 | * adding them to the linked list @ref received_packets, assuming they are | |
31 | * basically sound. | |
32 | * | |
33 | * queue_thread() takes packets off this linked list and adds them to @ref | |
34 | * packets (an operation which might be much slower due to contention for @ref | |
35 | * lock). | |
36 | * | |
37 | * control_thread() accepts commands from Disobedience (or anything else). | |
38 | * | |
39 | * The main thread activates and deactivates audio playing via the @ref | |
40 | * lib/uaudio.h API (which probably implies at least one further thread). | |
b0fdc63d | 41 | * |
42 | * Sometimes it happens that there is no audio available to play. This may | |
43 | * because the server went away, or a packet was dropped, or the server | |
44 | * deliberately did not send any sound because it encountered a silence. | |
189e9830 RK |
45 | * |
46 | * Assumptions: | |
47 | * - it is safe to read uint32_t values without a lock protecting them | |
28bacdc0 | 48 | */ |
e83d0967 | 49 | |
05b75f8d | 50 | #include "common.h" |
e83d0967 RK |
51 | |
52 | #include <getopt.h> | |
e83d0967 RK |
53 | #include <sys/socket.h> |
54 | #include <sys/types.h> | |
55 | #include <sys/socket.h> | |
56 | #include <netdb.h> | |
57 | #include <pthread.h> | |
0b75463f | 58 | #include <locale.h> |
2c7c9eae | 59 | #include <sys/uio.h> |
c593cf7c | 60 | #include <errno.h> |
e3426f7b | 61 | #include <netinet/in.h> |
2d2effe2 | 62 | #include <sys/time.h> |
a99c4e9a | 63 | #include <sys/un.h> |
9fbe0996 | 64 | #include <unistd.h> |
e9b635a3 RK |
65 | #include <sys/mman.h> |
66 | #include <fcntl.h> | |
b0619501 | 67 | #include <math.h> |
e83d0967 RK |
68 | |
69 | #include "log.h" | |
70 | #include "mem.h" | |
71 | #include "configuration.h" | |
72 | #include "addr.h" | |
73 | #include "syscalls.h" | |
74 | #include "rtp.h" | |
0b75463f | 75 | #include "defs.h" |
28bacdc0 RK |
76 | #include "vector.h" |
77 | #include "heap.h" | |
189e9830 | 78 | #include "timeval.h" |
a7e9570a | 79 | #include "client.h" |
8e3fe3d8 | 80 | #include "playrtp.h" |
a99c4e9a | 81 | #include "inputline.h" |
3fbdc96d | 82 | #include "version.h" |
7a2c7068 | 83 | #include "uaudio.h" |
e83d0967 | 84 | |
e3426f7b RK |
85 | /** @brief Obsolete synonym */ |
86 | #ifndef IPV6_JOIN_GROUP | |
87 | # define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP | |
88 | #endif | |
89 | ||
0b75463f | 90 | /** @brief RTP socket */ |
e83d0967 RK |
91 | static int rtpfd; |
92 | ||
345ebe66 RK |
93 | /** @brief Log output */ |
94 | static FILE *logfp; | |
95 | ||
0b75463f | 96 | /** @brief Output device */ |
0b75463f | 97 | |
ad535598 RK |
98 | /** @brief Buffer low watermark in samples */ |
99 | unsigned minbuffer = 4 * (2 * 44100) / 10; /* 0.4 seconds */ | |
0b75463f | 100 | |
ad535598 | 101 | /** @brief Maximum buffer size in samples |
9086a105 | 102 | * |
ad535598 RK |
103 | * We'll stop reading from the network if we have this many samples. |
104 | */ | |
9086a105 RK |
105 | static unsigned maxbuffer; |
106 | ||
189e9830 RK |
107 | /** @brief Received packets |
108 | * Protected by @ref receive_lock | |
109 | * | |
110 | * Received packets are added to this list, and queue_thread() picks them off | |
111 | * it and adds them to @ref packets. Whenever a packet is added to it, @ref | |
112 | * receive_cond is signalled. | |
113 | */ | |
8e3fe3d8 | 114 | struct packet *received_packets; |
189e9830 RK |
115 | |
116 | /** @brief Tail of @ref received_packets | |
117 | * Protected by @ref receive_lock | |
118 | */ | |
8e3fe3d8 | 119 | struct packet **received_tail = &received_packets; |
189e9830 RK |
120 | |
121 | /** @brief Lock protecting @ref received_packets | |
122 | * | |
123 | * Only listen_thread() and queue_thread() ever hold this lock. It is vital | |
124 | * that queue_thread() not hold it any longer than it strictly has to. */ | |
8e3fe3d8 | 125 | pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER; |
189e9830 RK |
126 | |
127 | /** @brief Condition variable signalled when @ref received_packets is updated | |
128 | * | |
129 | * Used by listen_thread() to notify queue_thread() that it has added another | |
130 | * packet to @ref received_packets. */ | |
8e3fe3d8 | 131 | pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER; |
189e9830 RK |
132 | |
133 | /** @brief Length of @ref received_packets */ | |
8e3fe3d8 | 134 | uint32_t nreceived; |
28bacdc0 RK |
135 | |
136 | /** @brief Binary heap of received packets */ | |
8e3fe3d8 | 137 | struct pheap packets; |
28bacdc0 | 138 | |
189e9830 RK |
139 | /** @brief Total number of samples available |
140 | * | |
141 | * We make this volatile because we inspect it without a protecting lock, | |
142 | * so the usual pthread_* guarantees aren't available. | |
143 | */ | |
8e3fe3d8 | 144 | volatile uint32_t nsamples; |
0b75463f | 145 | |
146 | /** @brief Timestamp of next packet to play. | |
147 | * | |
148 | * This is set to the timestamp of the last packet, plus the number of | |
09ee2f0d | 149 | * samples it contained. Only valid if @ref active is nonzero. |
0b75463f | 150 | */ |
8e3fe3d8 | 151 | uint32_t next_timestamp; |
e83d0967 | 152 | |
09ee2f0d | 153 | /** @brief True if actively playing |
154 | * | |
155 | * This is true when playing and false when just buffering. */ | |
8e3fe3d8 | 156 | int active; |
09ee2f0d | 157 | |
189e9830 | 158 | /** @brief Lock protecting @ref packets */ |
8e3fe3d8 | 159 | pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; |
189e9830 RK |
160 | |
161 | /** @brief Condition variable signalled whenever @ref packets is changed */ | |
8e3fe3d8 | 162 | pthread_cond_t cond = PTHREAD_COND_INITIALIZER; |
2c7c9eae | 163 | |
c593cf7c | 164 | /** @brief Backend to play with */ |
7a2c7068 | 165 | static const struct uaudio *backend; |
c593cf7c | 166 | |
8e3fe3d8 | 167 | HEAP_DEFINE(pheap, struct packet *, lt_packet); |
e83d0967 | 168 | |
a99c4e9a RK |
169 | /** @brief Control socket or NULL */ |
170 | const char *control_socket; | |
171 | ||
b28bddbb RK |
172 | /** @brief Buffer for debugging dump |
173 | * | |
174 | * The debug dump is enabled by the @c --dump option. It records the last 20s | |
175 | * of audio to the specified file (which will be about 3.5Mbytes). The file is | |
176 | * written as as ring buffer, so the start point will progress through it. | |
177 | * | |
178 | * Use clients/dump2wav to convert this to a WAV file, which can then be loaded | |
179 | * into (e.g.) Audacity for further inspection. | |
180 | * | |
181 | * All three backends (ALSA, OSS, Core Audio) now support this option. | |
182 | * | |
183 | * The idea is to allow the user a few seconds to react to an audible artefact. | |
184 | */ | |
e9b635a3 | 185 | int16_t *dump_buffer; |
b28bddbb RK |
186 | |
187 | /** @brief Current index within debugging dump */ | |
e9b635a3 | 188 | size_t dump_index; |
b28bddbb RK |
189 | |
190 | /** @brief Size of debugging dump in samples */ | |
191 | size_t dump_size = 44100/*Hz*/ * 2/*channels*/ * 20/*seconds*/; | |
e9b635a3 | 192 | |
e83d0967 RK |
193 | static const struct option options[] = { |
194 | { "help", no_argument, 0, 'h' }, | |
195 | { "version", no_argument, 0, 'V' }, | |
196 | { "debug", no_argument, 0, 'd' }, | |
0b75463f | 197 | { "device", required_argument, 0, 'D' }, |
1153fd23 | 198 | { "min", required_argument, 0, 'm' }, |
9086a105 | 199 | { "max", required_argument, 0, 'x' }, |
1f10f780 | 200 | { "rcvbuf", required_argument, 0, 'R' }, |
a9f0ad12 | 201 | #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST |
c593cf7c | 202 | { "oss", no_argument, 0, 'o' }, |
203 | #endif | |
146e86fb | 204 | #if HAVE_ALSA_ASOUNDLIB_H |
c593cf7c | 205 | { "alsa", no_argument, 0, 'a' }, |
206 | #endif | |
207 | #if HAVE_COREAUDIO_AUDIOHARDWARE_H | |
208 | { "core-audio", no_argument, 0, 'c' }, | |
209 | #endif | |
e9b635a3 | 210 | { "dump", required_argument, 0, 'r' }, |
e979b844 | 211 | { "command", required_argument, 0, 'e' }, |
287ad384 | 212 | { "pause-mode", required_argument, 0, 'P' }, |
a99c4e9a | 213 | { "socket", required_argument, 0, 's' }, |
a7e9570a | 214 | { "config", required_argument, 0, 'C' }, |
b0619501 | 215 | { "monitor", no_argument, 0, 'M' }, |
e83d0967 RK |
216 | { 0, 0, 0, 0 } |
217 | }; | |
218 | ||
a99c4e9a RK |
219 | /** @brief Control thread |
220 | * | |
221 | * This thread is responsible for accepting control commands from Disobedience | |
222 | * (or other controllers) over an AF_UNIX stream socket with a path specified | |
223 | * by the @c --socket option. The protocol uses simple string commands and | |
224 | * replies: | |
225 | * | |
226 | * - @c stop will shut the player down | |
227 | * - @c query will send back the reply @c running | |
228 | * - anything else is ignored | |
229 | * | |
230 | * Commands and response strings terminated by shutting down the connection or | |
231 | * by a newline. No attempt is made to multiplex multiple clients so it is | |
232 | * important that the command be sent as soon as the connection is made - it is | |
233 | * assumed that both parties to the protocol are entirely cooperating with one | |
234 | * another. | |
235 | */ | |
236 | static void *control_thread(void attribute((unused)) *arg) { | |
237 | struct sockaddr_un sa; | |
238 | int sfd, cfd; | |
239 | char *line; | |
240 | socklen_t salen; | |
241 | FILE *fp; | |
242 | ||
243 | assert(control_socket); | |
244 | unlink(control_socket); | |
245 | memset(&sa, 0, sizeof sa); | |
246 | sa.sun_family = AF_UNIX; | |
247 | strcpy(sa.sun_path, control_socket); | |
248 | sfd = xsocket(PF_UNIX, SOCK_STREAM, 0); | |
249 | if(bind(sfd, (const struct sockaddr *)&sa, sizeof sa) < 0) | |
2e9ba080 | 250 | disorder_fatal(errno, "error binding to %s", control_socket); |
a99c4e9a | 251 | if(listen(sfd, 128) < 0) |
2e9ba080 RK |
252 | disorder_fatal(errno, "error calling listen on %s", control_socket); |
253 | disorder_info("listening on %s", control_socket); | |
a99c4e9a RK |
254 | for(;;) { |
255 | salen = sizeof sa; | |
256 | cfd = accept(sfd, (struct sockaddr *)&sa, &salen); | |
257 | if(cfd < 0) { | |
258 | switch(errno) { | |
259 | case EINTR: | |
260 | case EAGAIN: | |
261 | break; | |
262 | default: | |
2e9ba080 | 263 | disorder_fatal(errno, "error calling accept on %s", control_socket); |
a99c4e9a RK |
264 | } |
265 | } | |
266 | if(!(fp = fdopen(cfd, "r+"))) { | |
2e9ba080 | 267 | disorder_error(errno, "error calling fdopen for %s connection", control_socket); |
a99c4e9a RK |
268 | close(cfd); |
269 | continue; | |
270 | } | |
271 | if(!inputline(control_socket, fp, &line, '\n')) { | |
272 | if(!strcmp(line, "stop")) { | |
2e9ba080 | 273 | disorder_info("stopped via %s", control_socket); |
a99c4e9a RK |
274 | exit(0); /* terminate immediately */ |
275 | } | |
276 | if(!strcmp(line, "query")) | |
277 | fprintf(fp, "running"); | |
278 | xfree(line); | |
279 | } | |
280 | if(fclose(fp) < 0) | |
2e9ba080 | 281 | disorder_error(errno, "error closing %s connection", control_socket); |
a99c4e9a RK |
282 | } |
283 | } | |
284 | ||
28bacdc0 RK |
285 | /** @brief Drop the first packet |
286 | * | |
287 | * Assumes that @ref lock is held. | |
288 | */ | |
289 | static void drop_first_packet(void) { | |
290 | if(pheap_count(&packets)) { | |
291 | struct packet *const p = pheap_remove(&packets); | |
292 | nsamples -= p->nsamples; | |
c593cf7c | 293 | playrtp_free_packet(p); |
2c7c9eae | 294 | pthread_cond_broadcast(&cond); |
2c7c9eae | 295 | } |
9086a105 RK |
296 | } |
297 | ||
189e9830 RK |
298 | /** @brief Background thread adding packets to heap |
299 | * | |
300 | * This just transfers packets from @ref received_packets to @ref packets. It | |
301 | * is important that it holds @ref receive_lock for as little time as possible, | |
302 | * in order to minimize the interval between calls to read() in | |
303 | * listen_thread(). | |
304 | */ | |
305 | static void *queue_thread(void attribute((unused)) *arg) { | |
306 | struct packet *p; | |
307 | ||
308 | for(;;) { | |
309 | /* Get the next packet */ | |
310 | pthread_mutex_lock(&receive_lock); | |
4dadf1a2 | 311 | while(!received_packets) { |
189e9830 | 312 | pthread_cond_wait(&receive_cond, &receive_lock); |
4dadf1a2 | 313 | } |
189e9830 RK |
314 | p = received_packets; |
315 | received_packets = p->next; | |
316 | if(!received_packets) | |
317 | received_tail = &received_packets; | |
318 | --nreceived; | |
319 | pthread_mutex_unlock(&receive_lock); | |
320 | /* Add it to the heap */ | |
321 | pthread_mutex_lock(&lock); | |
322 | pheap_insert(&packets, p); | |
323 | nsamples += p->nsamples; | |
324 | pthread_cond_broadcast(&cond); | |
325 | pthread_mutex_unlock(&lock); | |
326 | } | |
c6a70f38 RK |
327 | #if HAVE_STUPID_GCC44 |
328 | return NULL; | |
329 | #endif | |
189e9830 RK |
330 | } |
331 | ||
09ee2f0d | 332 | /** @brief Background thread collecting samples |
0b75463f | 333 | * |
334 | * This function collects samples, perhaps converts them to the target format, | |
b0fdc63d | 335 | * and adds them to the packet list. |
336 | * | |
337 | * It is crucial that the gap between successive calls to read() is as small as | |
338 | * possible: otherwise packets will be dropped. | |
339 | * | |
340 | * We use a binary heap to ensure that the unavoidable effort is at worst | |
341 | * logarithmic in the total number of packets - in fact if packets are mostly | |
342 | * received in order then we will largely do constant work per packet since the | |
343 | * newest packet will always be last. | |
344 | * | |
345 | * Of more concern is that we must acquire the lock on the heap to add a packet | |
346 | * to it. If this proves a problem in practice then the answer would be | |
347 | * (probably doubly) linked list with new packets added the end and a second | |
348 | * thread which reads packets off the list and adds them to the heap. | |
349 | * | |
350 | * We keep memory allocation (mostly) very fast by keeping pre-allocated | |
c593cf7c | 351 | * packets around; see @ref playrtp_new_packet(). |
b0fdc63d | 352 | */ |
0b75463f | 353 | static void *listen_thread(void attribute((unused)) *arg) { |
2c7c9eae | 354 | struct packet *p = 0; |
0b75463f | 355 | int n; |
2c7c9eae RK |
356 | struct rtp_header header; |
357 | uint16_t seq; | |
358 | uint32_t timestamp; | |
359 | struct iovec iov[2]; | |
e83d0967 RK |
360 | |
361 | for(;;) { | |
189e9830 | 362 | if(!p) |
c593cf7c | 363 | p = playrtp_new_packet(); |
2c7c9eae RK |
364 | iov[0].iov_base = &header; |
365 | iov[0].iov_len = sizeof header; | |
366 | iov[1].iov_base = p->samples_raw; | |
b64efe7e | 367 | iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw; |
2c7c9eae | 368 | n = readv(rtpfd, iov, 2); |
e83d0967 RK |
369 | if(n < 0) { |
370 | switch(errno) { | |
371 | case EINTR: | |
372 | continue; | |
373 | default: | |
2e9ba080 | 374 | disorder_fatal(errno, "error reading from socket"); |
e83d0967 RK |
375 | } |
376 | } | |
0b75463f | 377 | /* Ignore too-short packets */ |
345ebe66 | 378 | if((size_t)n <= sizeof (struct rtp_header)) { |
2e9ba080 | 379 | disorder_info("ignored a short packet"); |
0b75463f | 380 | continue; |
345ebe66 | 381 | } |
2c7c9eae RK |
382 | timestamp = htonl(header.timestamp); |
383 | seq = htons(header.seq); | |
09ee2f0d | 384 | /* Ignore packets in the past */ |
2c7c9eae | 385 | if(active && lt(timestamp, next_timestamp)) { |
2e9ba080 | 386 | disorder_info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32, |
2c7c9eae | 387 | timestamp, next_timestamp); |
09ee2f0d | 388 | continue; |
c0e41690 | 389 | } |
28f1495a RK |
390 | /* Ignore packets with the extension bit set. */ |
391 | if(header.vpxcc & 0x10) | |
392 | continue; | |
189e9830 | 393 | p->next = 0; |
58b5a68f | 394 | p->flags = 0; |
2c7c9eae | 395 | p->timestamp = timestamp; |
e83d0967 | 396 | /* Convert to target format */ |
58b5a68f RK |
397 | if(header.mpt & 0x80) |
398 | p->flags |= IDLE; | |
2c7c9eae | 399 | switch(header.mpt & 0x7F) { |
4fd38868 | 400 | case 10: /* L16 */ |
2c7c9eae | 401 | p->nsamples = (n - sizeof header) / sizeof(uint16_t); |
e83d0967 RK |
402 | break; |
403 | /* TODO support other RFC3551 media types (when the speaker does) */ | |
404 | default: | |
2e9ba080 | 405 | disorder_fatal(0, "unsupported RTP payload type %d", header.mpt & 0x7F); |
e83d0967 | 406 | } |
67d308e7 RK |
407 | /* See if packet is silent */ |
408 | const uint16_t *s = p->samples_raw; | |
7bdf42d0 | 409 | n = p->nsamples; |
67d308e7 RK |
410 | for(; n > 0; --n) |
411 | if(*s++) | |
412 | break; | |
413 | if(!n) | |
414 | p->flags |= SILENT; | |
345ebe66 RK |
415 | if(logfp) |
416 | fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n", | |
2c7c9eae | 417 | seq, timestamp, p->nsamples, timestamp + p->nsamples); |
0b75463f | 418 | /* Stop reading if we've reached the maximum. |
419 | * | |
420 | * This is rather unsatisfactory: it means that if packets get heavily | |
421 | * out of order then we guarantee dropouts. But for now... */ | |
345ebe66 | 422 | if(nsamples >= maxbuffer) { |
189e9830 | 423 | pthread_mutex_lock(&lock); |
4dadf1a2 | 424 | while(nsamples >= maxbuffer) { |
345ebe66 | 425 | pthread_cond_wait(&cond, &lock); |
4dadf1a2 | 426 | } |
189e9830 | 427 | pthread_mutex_unlock(&lock); |
345ebe66 | 428 | } |
189e9830 RK |
429 | /* Add the packet to the receive queue */ |
430 | pthread_mutex_lock(&receive_lock); | |
431 | *received_tail = p; | |
432 | received_tail = &p->next; | |
433 | ++nreceived; | |
434 | pthread_cond_signal(&receive_cond); | |
435 | pthread_mutex_unlock(&receive_lock); | |
58b5a68f RK |
436 | /* We'll need a new packet */ |
437 | p = 0; | |
e83d0967 RK |
438 | } |
439 | } | |
440 | ||
5626f6d2 RK |
441 | /** @brief Wait until the buffer is adequately full |
442 | * | |
443 | * Must be called with @ref lock held. | |
444 | */ | |
c593cf7c | 445 | void playrtp_fill_buffer(void) { |
0e72bf84 | 446 | /* Discard current buffer contents */ |
ad535598 RK |
447 | while(nsamples) { |
448 | //fprintf(stderr, "%8u/%u (%u) DROPPING\n", nsamples, maxbuffer, minbuffer); | |
bfd27c14 | 449 | drop_first_packet(); |
ad535598 | 450 | } |
2e9ba080 | 451 | disorder_info("Buffering..."); |
0e72bf84 RK |
452 | /* Wait until there's at least minbuffer samples available */ |
453 | while(nsamples < minbuffer) { | |
ad535598 | 454 | //fprintf(stderr, "%8u/%u (%u) FILLING\n", nsamples, maxbuffer, minbuffer); |
5626f6d2 | 455 | pthread_cond_wait(&cond, &lock); |
4dadf1a2 | 456 | } |
0e72bf84 | 457 | /* Start from whatever is earliest */ |
5626f6d2 RK |
458 | next_timestamp = pheap_first(&packets)->timestamp; |
459 | active = 1; | |
460 | } | |
461 | ||
462 | /** @brief Find next packet | |
463 | * @return Packet to play or NULL if none found | |
464 | * | |
465 | * The return packet is merely guaranteed not to be in the past: it might be | |
466 | * the first packet in the future rather than one that is actually suitable to | |
467 | * play. | |
468 | * | |
469 | * Must be called with @ref lock held. | |
470 | */ | |
c593cf7c | 471 | struct packet *playrtp_next_packet(void) { |
5626f6d2 RK |
472 | while(pheap_count(&packets)) { |
473 | struct packet *const p = pheap_first(&packets); | |
474 | if(le(p->timestamp + p->nsamples, next_timestamp)) { | |
475 | /* This packet is in the past. Drop it and try another one. */ | |
476 | drop_first_packet(); | |
477 | } else | |
478 | /* This packet is NOT in the past. (It might be in the future | |
479 | * however.) */ | |
480 | return p; | |
481 | } | |
482 | return 0; | |
483 | } | |
484 | ||
e83d0967 RK |
485 | /* display usage message and terminate */ |
486 | static void help(void) { | |
487 | xprintf("Usage:\n" | |
c897bb65 | 488 | " disorder-playrtp [OPTIONS] [[ADDRESS] PORT]\n" |
e83d0967 | 489 | "Options:\n" |
1153fd23 | 490 | " --device, -D DEVICE Output device\n" |
491 | " --min, -m FRAMES Buffer low water mark\n" | |
9086a105 | 492 | " --max, -x FRAMES Buffer maximum size\n" |
1f10f780 | 493 | " --rcvbuf, -R BYTES Socket receive buffer size\n" |
a7e9570a | 494 | " --config, -C PATH Set configuration file\n" |
146e86fb | 495 | #if HAVE_ALSA_ASOUNDLIB_H |
c593cf7c | 496 | " --alsa, -a Use ALSA to play audio\n" |
497 | #endif | |
a9f0ad12 | 498 | #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST |
c593cf7c | 499 | " --oss, -o Use OSS to play audio\n" |
500 | #endif | |
501 | #if HAVE_COREAUDIO_AUDIOHARDWARE_H | |
502 | " --core-audio, -c Use Core Audio to play audio\n" | |
503 | #endif | |
287ad384 RK |
504 | " --command, -e COMMAND Pipe audio to command.\n" |
505 | " --pause-mode, -P silence For -e: pauses send silence (default)\n" | |
506 | " --pause-mode, -P suspend For -e: pauses suspend writes\n" | |
9086a105 RK |
507 | " --help, -h Display usage message\n" |
508 | " --version, -V Display version number\n" | |
509 | ); | |
e83d0967 RK |
510 | xfclose(stdout); |
511 | exit(0); | |
512 | } | |
513 | ||
4fd38868 | 514 | static size_t playrtp_callback(void *buffer, |
7a2c7068 RK |
515 | size_t max_samples, |
516 | void attribute((unused)) *userdata) { | |
517 | size_t samples; | |
67d308e7 | 518 | int silent = 0; |
7a2c7068 RK |
519 | |
520 | pthread_mutex_lock(&lock); | |
521 | /* Get the next packet, junking any that are now in the past */ | |
522 | const struct packet *p = playrtp_next_packet(); | |
523 | if(p && contains(p, next_timestamp)) { | |
524 | /* This packet is ready to play; the desired next timestamp points | |
525 | * somewhere into it. */ | |
526 | ||
527 | /* Timestamp of end of packet */ | |
528 | const uint32_t packet_end = p->timestamp + p->nsamples; | |
529 | ||
530 | /* Offset of desired next timestamp into current packet */ | |
531 | const uint32_t offset = next_timestamp - p->timestamp; | |
532 | ||
533 | /* Pointer to audio data */ | |
534 | const uint16_t *ptr = (void *)(p->samples_raw + offset); | |
535 | ||
536 | /* Compute number of samples left in packet, limited to output buffer | |
537 | * size */ | |
538 | samples = packet_end - next_timestamp; | |
539 | if(samples > max_samples) | |
540 | samples = max_samples; | |
541 | ||
542 | /* Copy into buffer, converting to native endianness */ | |
543 | size_t i = samples; | |
544 | int16_t *bufptr = buffer; | |
545 | while(i > 0) { | |
546 | *bufptr++ = (int16_t)ntohs(*ptr++); | |
547 | --i; | |
548 | } | |
67d308e7 | 549 | silent = !!(p->flags & SILENT); |
7a2c7068 RK |
550 | } else { |
551 | /* There is no suitable packet. We introduce 0s up to the next packet, or | |
552 | * to fill the buffer if there's no next packet or that's too many. The | |
553 | * comparison with max_samples deals with the otherwise troubling overflow | |
554 | * case. */ | |
555 | samples = p ? p->timestamp - next_timestamp : max_samples; | |
556 | if(samples > max_samples) | |
557 | samples = max_samples; | |
558 | //info("infill by %zu", samples); | |
4fd38868 | 559 | memset(buffer, 0, samples * uaudio_sample_size); |
67d308e7 | 560 | silent = 1; |
7a2c7068 RK |
561 | } |
562 | /* Debug dump */ | |
563 | if(dump_buffer) { | |
564 | for(size_t i = 0; i < samples; ++i) { | |
4fd38868 | 565 | dump_buffer[dump_index++] = ((int16_t *)buffer)[i]; |
7a2c7068 RK |
566 | dump_index %= dump_size; |
567 | } | |
568 | } | |
569 | /* Advance timestamp */ | |
570 | next_timestamp += samples; | |
7edc7e42 RK |
571 | /* If we're getting behind then try to drop just silent packets |
572 | * | |
573 | * In theory this shouldn't be necessary. The server is supposed to send | |
574 | * packets at the right rate and compares the number of samples sent with the | |
575 | * time in order to ensure this. | |
576 | * | |
577 | * However, various things could throw this off: | |
578 | * | |
579 | * - the server's clock could advance at the wrong rate. This would cause it | |
580 | * to mis-estimate the right number of samples to have sent and | |
581 | * inappropriately throttle or speed up. | |
582 | * | |
583 | * - playback could happen at the wrong rate. If the playback host's sound | |
584 | * card has a slightly incorrect clock then eventually it will get out | |
585 | * of step. | |
586 | * | |
587 | * So if we play back slightly slower than the server sends for either of | |
588 | * these reasons then eventually our buffer, and the socket's buffer, will | |
589 | * fill, and the kernel will start dropping packets. The result is audible | |
590 | * and not very nice. | |
591 | * | |
592 | * Therefore if we're getting behind, we pre-emptively drop silent packets, | |
593 | * since a change in the duration of a silence is less noticeable than a | |
594 | * dropped packet from the middle of continuous music. | |
595 | * | |
596 | * (If things go wrong the other way then eventually we run out of packets to | |
597 | * play and are forced to play silence. This doesn't seem to happen in | |
598 | * practice but if it does then in the same way we can artificially extend | |
599 | * silent packets to compensate.) | |
600 | * | |
601 | * Dropped packets are always logged; use 'disorder-playrtp --monitor' to | |
602 | * track how close to target buffer occupancy we are on a once-a-minute | |
603 | * basis. | |
604 | */ | |
67d308e7 | 605 | if(nsamples > minbuffer && silent) { |
2e9ba080 RK |
606 | disorder_info("dropping %zu samples (%"PRIu32" > %"PRIu32")", |
607 | samples, nsamples, minbuffer); | |
67d308e7 RK |
608 | samples = 0; |
609 | } | |
ad535598 RK |
610 | /* Junk obsolete packets */ |
611 | playrtp_next_packet(); | |
7a2c7068 RK |
612 | pthread_mutex_unlock(&lock); |
613 | return samples; | |
614 | } | |
615 | ||
e83d0967 | 616 | int main(int argc, char **argv) { |
a99c4e9a | 617 | int n, err; |
e83d0967 RK |
618 | struct addrinfo *res; |
619 | struct stringlist sl; | |
0b75463f | 620 | char *sockname; |
0e72bf84 | 621 | int rcvbuf, target_rcvbuf = 0; |
1f10f780 | 622 | socklen_t len; |
23205f9c RK |
623 | struct ip_mreq mreq; |
624 | struct ipv6_mreq mreq6; | |
a7e9570a RK |
625 | disorder_client *c; |
626 | char *address, *port; | |
6fba990c RK |
627 | int is_multicast; |
628 | union any_sockaddr { | |
629 | struct sockaddr sa; | |
630 | struct sockaddr_in in; | |
631 | struct sockaddr_in6 in6; | |
632 | }; | |
633 | union any_sockaddr mgroup; | |
e9b635a3 | 634 | const char *dumpfile = 0; |
7a2c7068 | 635 | pthread_t ltid; |
b0619501 | 636 | int monitor = 0; |
983c3357 | 637 | static const int one = 1; |
e83d0967 | 638 | |
0b75463f | 639 | static const struct addrinfo prefs = { |
66613034 RK |
640 | .ai_flags = AI_PASSIVE, |
641 | .ai_family = PF_INET, | |
642 | .ai_socktype = SOCK_DGRAM, | |
643 | .ai_protocol = IPPROTO_UDP | |
e83d0967 RK |
644 | }; |
645 | ||
9d7a6129 RK |
646 | /* Timing information is often important to debugging playrtp, so we include |
647 | * timestamps in the logs */ | |
648 | logdate = 1; | |
e83d0967 | 649 | mem_init(); |
2e9ba080 | 650 | if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "error calling setlocale"); |
902ccab0 | 651 | backend = uaudio_apis[0]; |
b0619501 | 652 | while((n = getopt_long(argc, argv, "hVdD:m:x:L:R:aocC:re:P:M", options, 0)) >= 0) { |
e83d0967 RK |
653 | switch(n) { |
654 | case 'h': help(); | |
3fbdc96d | 655 | case 'V': version("disorder-playrtp"); |
e83d0967 | 656 | case 'd': debugging = 1; break; |
e979b844 | 657 | case 'D': uaudio_set("device", optarg); break; |
1153fd23 | 658 | case 'm': minbuffer = 2 * atol(optarg); break; |
9086a105 | 659 | case 'x': maxbuffer = 2 * atol(optarg); break; |
345ebe66 | 660 | case 'L': logfp = fopen(optarg, "w"); break; |
1f10f780 | 661 | case 'R': target_rcvbuf = atoi(optarg); break; |
146e86fb | 662 | #if HAVE_ALSA_ASOUNDLIB_H |
7a2c7068 | 663 | case 'a': backend = &uaudio_alsa; break; |
c593cf7c | 664 | #endif |
a9f0ad12 | 665 | #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST |
7a2c7068 | 666 | case 'o': backend = &uaudio_oss; break; |
c593cf7c | 667 | #endif |
668 | #if HAVE_COREAUDIO_AUDIOHARDWARE_H | |
7a2c7068 | 669 | case 'c': backend = &uaudio_coreaudio; break; |
c593cf7c | 670 | #endif |
a7e9570a | 671 | case 'C': configfile = optarg; break; |
a99c4e9a | 672 | case 's': control_socket = optarg; break; |
e9b635a3 | 673 | case 'r': dumpfile = optarg; break; |
e979b844 | 674 | case 'e': backend = &uaudio_command; uaudio_set("command", optarg); break; |
287ad384 | 675 | case 'P': uaudio_set("pause-mode", optarg); break; |
b0619501 | 676 | case 'M': monitor = 1; break; |
2e9ba080 | 677 | default: disorder_fatal(0, "invalid option"); |
e83d0967 RK |
678 | } |
679 | } | |
2e9ba080 | 680 | if(config_read(0, NULL)) disorder_fatal(0, "cannot read configuration"); |
9086a105 | 681 | if(!maxbuffer) |
0e72bf84 | 682 | maxbuffer = 2 * minbuffer; |
e83d0967 RK |
683 | argc -= optind; |
684 | argv += optind; | |
a7e9570a RK |
685 | switch(argc) { |
686 | case 0: | |
6fba990c | 687 | /* Get configuration from server */ |
a7e9570a RK |
688 | if(!(c = disorder_new(1))) exit(EXIT_FAILURE); |
689 | if(disorder_connect(c)) exit(EXIT_FAILURE); | |
690 | if(disorder_rtp_address(c, &address, &port)) exit(EXIT_FAILURE); | |
6fba990c RK |
691 | sl.n = 2; |
692 | sl.s = xcalloc(2, sizeof *sl.s); | |
693 | sl.s[0] = address; | |
694 | sl.s[1] = port; | |
a7e9570a | 695 | break; |
6fba990c | 696 | case 1: |
a7e9570a | 697 | case 2: |
6fba990c | 698 | /* Use command-line ADDRESS+PORT or just PORT */ |
a7e9570a RK |
699 | sl.n = argc; |
700 | sl.s = argv; | |
701 | break; | |
702 | default: | |
2e9ba080 | 703 | disorder_fatal(0, "usage: disorder-playrtp [OPTIONS] [[ADDRESS] PORT]"); |
a7e9570a | 704 | } |
6fba990c | 705 | /* Look up address and port */ |
0b75463f | 706 | if(!(res = get_address(&sl, &prefs, &sockname))) |
e83d0967 | 707 | exit(1); |
6fba990c | 708 | /* Create the socket */ |
e83d0967 RK |
709 | if((rtpfd = socket(res->ai_family, |
710 | res->ai_socktype, | |
711 | res->ai_protocol)) < 0) | |
2e9ba080 | 712 | disorder_fatal(errno, "error creating socket"); |
983c3357 RK |
713 | /* Allow multiple listeners */ |
714 | xsetsockopt(rtpfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); | |
715 | is_multicast = multicast(res->ai_addr); | |
716 | /* The multicast and unicast/broadcast cases are different enough that they | |
717 | * are totally split. Trying to find commonality between them causes more | |
718 | * trouble that it's worth. */ | |
719 | if(is_multicast) { | |
720 | /* Stash the multicast group address */ | |
6fba990c RK |
721 | memcpy(&mgroup, res->ai_addr, res->ai_addrlen); |
722 | switch(res->ai_addr->sa_family) { | |
723 | case AF_INET: | |
724 | mgroup.in.sin_port = 0; | |
725 | break; | |
726 | case AF_INET6: | |
727 | mgroup.in6.sin6_port = 0; | |
728 | break; | |
983c3357 | 729 | default: |
2e9ba080 RK |
730 | disorder_fatal(0, "unsupported address family %d", |
731 | (int)res->ai_addr->sa_family); | |
6fba990c | 732 | } |
983c3357 RK |
733 | /* Bind to to the multicast group address */ |
734 | if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0) | |
2e9ba080 RK |
735 | disorder_fatal(errno, "error binding socket to %s", |
736 | format_sockaddr(res->ai_addr)); | |
983c3357 | 737 | /* Add multicast group membership */ |
6fba990c | 738 | switch(mgroup.sa.sa_family) { |
23205f9c | 739 | case PF_INET: |
6fba990c | 740 | mreq.imr_multiaddr = mgroup.in.sin_addr; |
23205f9c RK |
741 | mreq.imr_interface.s_addr = 0; /* use primary interface */ |
742 | if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, | |
743 | &mreq, sizeof mreq) < 0) | |
2e9ba080 | 744 | disorder_fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP"); |
23205f9c RK |
745 | break; |
746 | case PF_INET6: | |
6fba990c | 747 | mreq6.ipv6mr_multiaddr = mgroup.in6.sin6_addr; |
23205f9c RK |
748 | memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface); |
749 | if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, | |
750 | &mreq6, sizeof mreq6) < 0) | |
2e9ba080 | 751 | disorder_fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP"); |
23205f9c RK |
752 | break; |
753 | default: | |
2e9ba080 | 754 | disorder_fatal(0, "unsupported address family %d", res->ai_family); |
23205f9c | 755 | } |
983c3357 | 756 | /* Report what we did */ |
2e9ba080 RK |
757 | disorder_info("listening on %s multicast group %s", |
758 | format_sockaddr(res->ai_addr), format_sockaddr(&mgroup.sa)); | |
983c3357 RK |
759 | } else { |
760 | /* Bind to 0/port */ | |
761 | switch(res->ai_addr->sa_family) { | |
762 | case AF_INET: { | |
763 | struct sockaddr_in *in = (struct sockaddr_in *)res->ai_addr; | |
764 | ||
765 | memset(&in->sin_addr, 0, sizeof (struct in_addr)); | |
983c3357 RK |
766 | break; |
767 | } | |
768 | case AF_INET6: { | |
769 | struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)res->ai_addr; | |
770 | ||
771 | memset(&in6->sin6_addr, 0, sizeof (struct in6_addr)); | |
772 | break; | |
773 | } | |
774 | default: | |
2e9ba080 | 775 | disorder_fatal(0, "unsupported family %d", (int)res->ai_addr->sa_family); |
983c3357 RK |
776 | } |
777 | if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0) | |
2e9ba080 RK |
778 | disorder_fatal(errno, "error binding socket to %s", |
779 | format_sockaddr(res->ai_addr)); | |
983c3357 | 780 | /* Report what we did */ |
2e9ba080 | 781 | disorder_info("listening on %s", format_sockaddr(res->ai_addr)); |
983c3357 | 782 | } |
1f10f780 RK |
783 | len = sizeof rcvbuf; |
784 | if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0) | |
2e9ba080 | 785 | disorder_fatal(errno, "error calling getsockopt SO_RCVBUF"); |
f0bae611 | 786 | if(target_rcvbuf > rcvbuf) { |
1f10f780 RK |
787 | if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, |
788 | &target_rcvbuf, sizeof target_rcvbuf) < 0) | |
2e9ba080 RK |
789 | disorder_error(errno, "error calling setsockopt SO_RCVBUF %d", |
790 | target_rcvbuf); | |
1f10f780 RK |
791 | /* We try to carry on anyway */ |
792 | else | |
2e9ba080 RK |
793 | disorder_info("changed socket receive buffer from %d to %d", |
794 | rcvbuf, target_rcvbuf); | |
1f10f780 | 795 | } else |
2e9ba080 | 796 | disorder_info("default socket receive buffer %d", rcvbuf); |
ad535598 | 797 | //info("minbuffer %u maxbuffer %u", minbuffer, maxbuffer); |
1f10f780 | 798 | if(logfp) |
2e9ba080 | 799 | disorder_info("WARNING: -L option can impact performance"); |
a99c4e9a RK |
800 | if(control_socket) { |
801 | pthread_t tid; | |
802 | ||
803 | if((err = pthread_create(&tid, 0, control_thread, 0))) | |
2e9ba080 | 804 | disorder_fatal(err, "pthread_create control_thread"); |
a99c4e9a | 805 | } |
e9b635a3 RK |
806 | if(dumpfile) { |
807 | int fd; | |
808 | unsigned char buffer[65536]; | |
809 | size_t written; | |
810 | ||
811 | if((fd = open(dumpfile, O_RDWR|O_TRUNC|O_CREAT, 0666)) < 0) | |
2e9ba080 | 812 | disorder_fatal(errno, "opening %s", dumpfile); |
e9b635a3 RK |
813 | /* Fill with 0s to a suitable size */ |
814 | memset(buffer, 0, sizeof buffer); | |
815 | for(written = 0; written < dump_size * sizeof(int16_t); | |
816 | written += sizeof buffer) { | |
817 | if(write(fd, buffer, sizeof buffer) < 0) | |
2e9ba080 | 818 | disorder_fatal(errno, "clearing %s", dumpfile); |
e9b635a3 RK |
819 | } |
820 | /* Map the buffer into memory for convenience */ | |
821 | dump_buffer = mmap(0, dump_size * sizeof(int16_t), PROT_READ|PROT_WRITE, | |
822 | MAP_SHARED, fd, 0); | |
823 | if(dump_buffer == (void *)-1) | |
2e9ba080 RK |
824 | disorder_fatal(errno, "mapping %s", dumpfile); |
825 | disorder_info("dumping to %s", dumpfile); | |
e9b635a3 | 826 | } |
4fd38868 RK |
827 | /* Set up output. Currently we only support L16 so there's no harm setting |
828 | * the format before we know what it is! */ | |
829 | uaudio_set_format(44100/*Hz*/, 2/*channels*/, | |
830 | 16/*bits/channel*/, 1/*signed*/); | |
7a2c7068 RK |
831 | backend->start(playrtp_callback, NULL); |
832 | /* We receive and convert audio data in a background thread */ | |
833 | if((err = pthread_create(<id, 0, listen_thread, 0))) | |
2e9ba080 | 834 | disorder_fatal(err, "pthread_create listen_thread"); |
7a2c7068 RK |
835 | /* We have a second thread to add received packets to the queue */ |
836 | if((err = pthread_create(<id, 0, queue_thread, 0))) | |
2e9ba080 | 837 | disorder_fatal(err, "pthread_create queue_thread"); |
7a2c7068 | 838 | pthread_mutex_lock(&lock); |
b0619501 | 839 | time_t lastlog = 0; |
7a2c7068 RK |
840 | for(;;) { |
841 | /* Wait for the buffer to fill up a bit */ | |
842 | playrtp_fill_buffer(); | |
843 | /* Start playing now */ | |
2e9ba080 | 844 | disorder_info("Playing..."); |
7a2c7068 RK |
845 | next_timestamp = pheap_first(&packets)->timestamp; |
846 | active = 1; | |
d4170ca7 | 847 | pthread_mutex_unlock(&lock); |
7a2c7068 | 848 | backend->activate(); |
d4170ca7 | 849 | pthread_mutex_lock(&lock); |
0e72bf84 RK |
850 | /* Wait until the buffer empties out |
851 | * | |
852 | * If there's a packet that we can play right now then we definitely | |
853 | * continue. | |
854 | * | |
855 | * Also if there's at least minbuffer samples we carry on regardless and | |
856 | * insert silence. The assumption is there's been a pause but more data | |
857 | * is now available. | |
858 | */ | |
7a2c7068 RK |
859 | while(nsamples >= minbuffer |
860 | || (nsamples > 0 | |
4fd38868 | 861 | && contains(pheap_first(&packets), next_timestamp))) { |
b0619501 | 862 | if(monitor) { |
4265e5d3 | 863 | time_t now = xtime(0); |
b0619501 RK |
864 | |
865 | if(now >= lastlog + 60) { | |
866 | int offset = nsamples - minbuffer; | |
867 | double offtime = (double)offset / (uaudio_rate * uaudio_channels); | |
2e9ba080 RK |
868 | disorder_info("%+d samples off (%d.%02ds, %d bytes)", |
869 | offset, | |
870 | (int)fabs(offtime) * (offtime < 0 ? -1 : 1), | |
871 | (int)(fabs(offtime) * 100) % 100, | |
872 | offset * uaudio_bits / CHAR_BIT); | |
b0619501 RK |
873 | lastlog = now; |
874 | } | |
875 | } | |
ad535598 | 876 | //fprintf(stderr, "%8u/%u (%u) PLAYING\n", nsamples, maxbuffer, minbuffer); |
7a2c7068 | 877 | pthread_cond_wait(&cond, &lock); |
4fd38868 | 878 | } |
ad535598 RK |
879 | #if 0 |
880 | if(nsamples) { | |
881 | struct packet *p = pheap_first(&packets); | |
882 | fprintf(stderr, "nsamples=%u (%u) next_timestamp=%"PRIx32", first packet is [%"PRIx32",%"PRIx32")\n", | |
883 | nsamples, minbuffer, next_timestamp,p->timestamp,p->timestamp+p->nsamples); | |
884 | } | |
885 | #endif | |
7a2c7068 | 886 | /* Stop playing for a bit until the buffer re-fills */ |
d4170ca7 | 887 | pthread_mutex_unlock(&lock); |
7a2c7068 | 888 | backend->deactivate(); |
d4170ca7 | 889 | pthread_mutex_lock(&lock); |
7a2c7068 RK |
890 | active = 0; |
891 | /* Go back round */ | |
892 | } | |
e83d0967 RK |
893 | return 0; |
894 | } | |
895 | ||
896 | /* | |
897 | Local Variables: | |
898 | c-basic-offset:2 | |
899 | comment-column:40 | |
900 | fill-column:79 | |
901 | indent-tabs-mode:nil | |
902 | End: | |
903 | */ |