chiark / gitweb /
Merge branch 'master' of git.distorted.org.uk:~mdw/publish/public-git/disorder
[disorder] / clients / playrtp.c
CommitLineData
e83d0967
RK
1/*
2 * This file is part of DisOrder.
06385470 3 * Copyright (C) 2007-2009, 2011, 2013 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>
cca034e5
RK
68#include <arpa/inet.h>
69#include <ifaddrs.h>
70#include <net/if.h>
e83d0967
RK
71
72#include "log.h"
73#include "mem.h"
74#include "configuration.h"
75#include "addr.h"
76#include "syscalls.h"
14b5913c 77#include "printf.h"
e83d0967 78#include "rtp.h"
0b75463f 79#include "defs.h"
28bacdc0
RK
80#include "vector.h"
81#include "heap.h"
189e9830 82#include "timeval.h"
a7e9570a 83#include "client.h"
8e3fe3d8 84#include "playrtp.h"
a99c4e9a 85#include "inputline.h"
3fbdc96d 86#include "version.h"
7a2c7068 87#include "uaudio.h"
e83d0967 88
e3426f7b
RK
89/** @brief Obsolete synonym */
90#ifndef IPV6_JOIN_GROUP
91# define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP
92#endif
93
0b75463f 94/** @brief RTP socket */
e83d0967
RK
95static int rtpfd;
96
345ebe66
RK
97/** @brief Log output */
98static FILE *logfp;
99
0b75463f 100/** @brief Output device */
0b75463f 101
ad535598 102/** @brief Buffer low watermark in samples */
14b5913c 103unsigned minbuffer;
0b75463f 104
ad535598 105/** @brief Maximum buffer size in samples
9086a105 106 *
ad535598
RK
107 * We'll stop reading from the network if we have this many samples.
108 */
9086a105
RK
109static unsigned maxbuffer;
110
189e9830
RK
111/** @brief Received packets
112 * Protected by @ref receive_lock
113 *
114 * Received packets are added to this list, and queue_thread() picks them off
115 * it and adds them to @ref packets. Whenever a packet is added to it, @ref
116 * receive_cond is signalled.
117 */
8e3fe3d8 118struct packet *received_packets;
189e9830
RK
119
120/** @brief Tail of @ref received_packets
121 * Protected by @ref receive_lock
122 */
8e3fe3d8 123struct packet **received_tail = &received_packets;
189e9830
RK
124
125/** @brief Lock protecting @ref received_packets
126 *
127 * Only listen_thread() and queue_thread() ever hold this lock. It is vital
128 * that queue_thread() not hold it any longer than it strictly has to. */
8e3fe3d8 129pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER;
189e9830
RK
130
131/** @brief Condition variable signalled when @ref received_packets is updated
132 *
133 * Used by listen_thread() to notify queue_thread() that it has added another
134 * packet to @ref received_packets. */
8e3fe3d8 135pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER;
189e9830
RK
136
137/** @brief Length of @ref received_packets */
8e3fe3d8 138uint32_t nreceived;
28bacdc0
RK
139
140/** @brief Binary heap of received packets */
8e3fe3d8 141struct pheap packets;
28bacdc0 142
189e9830
RK
143/** @brief Total number of samples available
144 *
145 * We make this volatile because we inspect it without a protecting lock,
146 * so the usual pthread_* guarantees aren't available.
147 */
8e3fe3d8 148volatile uint32_t nsamples;
0b75463f 149
150/** @brief Timestamp of next packet to play.
151 *
152 * This is set to the timestamp of the last packet, plus the number of
09ee2f0d 153 * samples it contained. Only valid if @ref active is nonzero.
0b75463f 154 */
8e3fe3d8 155uint32_t next_timestamp;
e83d0967 156
09ee2f0d 157/** @brief True if actively playing
158 *
159 * This is true when playing and false when just buffering. */
8e3fe3d8 160int active;
09ee2f0d 161
189e9830 162/** @brief Lock protecting @ref packets */
8e3fe3d8 163pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
189e9830
RK
164
165/** @brief Condition variable signalled whenever @ref packets is changed */
8e3fe3d8 166pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
2c7c9eae 167
c593cf7c 168/** @brief Backend to play with */
7a2c7068 169static const struct uaudio *backend;
c593cf7c 170
8e3fe3d8 171HEAP_DEFINE(pheap, struct packet *, lt_packet);
e83d0967 172
a99c4e9a
RK
173/** @brief Control socket or NULL */
174const char *control_socket;
175
b28bddbb
RK
176/** @brief Buffer for debugging dump
177 *
178 * The debug dump is enabled by the @c --dump option. It records the last 20s
179 * of audio to the specified file (which will be about 3.5Mbytes). The file is
180 * written as as ring buffer, so the start point will progress through it.
181 *
182 * Use clients/dump2wav to convert this to a WAV file, which can then be loaded
183 * into (e.g.) Audacity for further inspection.
184 *
185 * All three backends (ALSA, OSS, Core Audio) now support this option.
186 *
187 * The idea is to allow the user a few seconds to react to an audible artefact.
188 */
e9b635a3 189int16_t *dump_buffer;
b28bddbb
RK
190
191/** @brief Current index within debugging dump */
e9b635a3 192size_t dump_index;
b28bddbb
RK
193
194/** @brief Size of debugging dump in samples */
195size_t dump_size = 44100/*Hz*/ * 2/*channels*/ * 20/*seconds*/;
e9b635a3 196
e83d0967
RK
197static const struct option options[] = {
198 { "help", no_argument, 0, 'h' },
199 { "version", no_argument, 0, 'V' },
200 { "debug", no_argument, 0, 'd' },
0b75463f 201 { "device", required_argument, 0, 'D' },
1153fd23 202 { "min", required_argument, 0, 'm' },
9086a105 203 { "max", required_argument, 0, 'x' },
1f10f780 204 { "rcvbuf", required_argument, 0, 'R' },
a9f0ad12 205#if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
c593cf7c 206 { "oss", no_argument, 0, 'o' },
207#endif
146e86fb 208#if HAVE_ALSA_ASOUNDLIB_H
c593cf7c 209 { "alsa", no_argument, 0, 'a' },
210#endif
211#if HAVE_COREAUDIO_AUDIOHARDWARE_H
212 { "core-audio", no_argument, 0, 'c' },
213#endif
ba32e50c 214 { "api", required_argument, 0, 'A' },
e9b635a3 215 { "dump", required_argument, 0, 'r' },
e979b844 216 { "command", required_argument, 0, 'e' },
287ad384 217 { "pause-mode", required_argument, 0, 'P' },
a99c4e9a 218 { "socket", required_argument, 0, 's' },
a7e9570a 219 { "config", required_argument, 0, 'C' },
af52ec84 220 { "user-config", required_argument, 0, 'u' },
b0619501 221 { "monitor", no_argument, 0, 'M' },
e83d0967
RK
222 { 0, 0, 0, 0 }
223};
224
a99c4e9a
RK
225/** @brief Control thread
226 *
227 * This thread is responsible for accepting control commands from Disobedience
228 * (or other controllers) over an AF_UNIX stream socket with a path specified
229 * by the @c --socket option. The protocol uses simple string commands and
230 * replies:
231 *
232 * - @c stop will shut the player down
233 * - @c query will send back the reply @c running
234 * - anything else is ignored
235 *
236 * Commands and response strings terminated by shutting down the connection or
237 * by a newline. No attempt is made to multiplex multiple clients so it is
238 * important that the command be sent as soon as the connection is made - it is
239 * assumed that both parties to the protocol are entirely cooperating with one
240 * another.
241 */
242static void *control_thread(void attribute((unused)) *arg) {
243 struct sockaddr_un sa;
244 int sfd, cfd;
245 char *line;
246 socklen_t salen;
247 FILE *fp;
af21fb6b 248 int vl, vr;
a99c4e9a
RK
249
250 assert(control_socket);
251 unlink(control_socket);
252 memset(&sa, 0, sizeof sa);
253 sa.sun_family = AF_UNIX;
254 strcpy(sa.sun_path, control_socket);
255 sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
256 if(bind(sfd, (const struct sockaddr *)&sa, sizeof sa) < 0)
2e9ba080 257 disorder_fatal(errno, "error binding to %s", control_socket);
a99c4e9a 258 if(listen(sfd, 128) < 0)
2e9ba080
RK
259 disorder_fatal(errno, "error calling listen on %s", control_socket);
260 disorder_info("listening on %s", control_socket);
a99c4e9a
RK
261 for(;;) {
262 salen = sizeof sa;
263 cfd = accept(sfd, (struct sockaddr *)&sa, &salen);
264 if(cfd < 0) {
265 switch(errno) {
266 case EINTR:
267 case EAGAIN:
268 break;
269 default:
2e9ba080 270 disorder_fatal(errno, "error calling accept on %s", control_socket);
a99c4e9a
RK
271 }
272 }
273 if(!(fp = fdopen(cfd, "r+"))) {
2e9ba080 274 disorder_error(errno, "error calling fdopen for %s connection", control_socket);
a99c4e9a
RK
275 close(cfd);
276 continue;
277 }
278 if(!inputline(control_socket, fp, &line, '\n')) {
279 if(!strcmp(line, "stop")) {
2e9ba080 280 disorder_info("stopped via %s", control_socket);
a99c4e9a 281 exit(0); /* terminate immediately */
af21fb6b 282 } else if(!strcmp(line, "query"))
a99c4e9a 283 fprintf(fp, "running");
af21fb6b
MW
284 else if(!strcmp(line, "getvol")) {
285 if(backend->get_volume) backend->get_volume(&vl, &vr);
286 else vl = vr = 0;
287 fprintf(fp, "%d %d\n", vl, vr);
288 } else if(!strncmp(line, "setvol ", 7)) {
289 if(!backend->set_volume)
290 vl = vr = 0;
291 else if(sscanf(line + 7, "%d %d", &vl, &vr) == 2)
292 backend->set_volume(&vl, &vr);
293 else
294 backend->get_volume(&vl, &vr);
295 fprintf(fp, "%d %d\n", vl, vr);
296 }
a99c4e9a
RK
297 xfree(line);
298 }
299 if(fclose(fp) < 0)
2e9ba080 300 disorder_error(errno, "error closing %s connection", control_socket);
a99c4e9a
RK
301 }
302}
303
28bacdc0
RK
304/** @brief Drop the first packet
305 *
306 * Assumes that @ref lock is held.
307 */
308static void drop_first_packet(void) {
309 if(pheap_count(&packets)) {
310 struct packet *const p = pheap_remove(&packets);
311 nsamples -= p->nsamples;
c593cf7c 312 playrtp_free_packet(p);
2c7c9eae 313 pthread_cond_broadcast(&cond);
2c7c9eae 314 }
9086a105
RK
315}
316
189e9830
RK
317/** @brief Background thread adding packets to heap
318 *
319 * This just transfers packets from @ref received_packets to @ref packets. It
320 * is important that it holds @ref receive_lock for as little time as possible,
321 * in order to minimize the interval between calls to read() in
322 * listen_thread().
323 */
324static void *queue_thread(void attribute((unused)) *arg) {
325 struct packet *p;
326
327 for(;;) {
328 /* Get the next packet */
329 pthread_mutex_lock(&receive_lock);
4dadf1a2 330 while(!received_packets) {
189e9830 331 pthread_cond_wait(&receive_cond, &receive_lock);
4dadf1a2 332 }
189e9830
RK
333 p = received_packets;
334 received_packets = p->next;
335 if(!received_packets)
336 received_tail = &received_packets;
337 --nreceived;
338 pthread_mutex_unlock(&receive_lock);
339 /* Add it to the heap */
340 pthread_mutex_lock(&lock);
341 pheap_insert(&packets, p);
342 nsamples += p->nsamples;
343 pthread_cond_broadcast(&cond);
344 pthread_mutex_unlock(&lock);
345 }
c6a70f38
RK
346#if HAVE_STUPID_GCC44
347 return NULL;
348#endif
189e9830
RK
349}
350
09ee2f0d 351/** @brief Background thread collecting samples
0b75463f 352 *
353 * This function collects samples, perhaps converts them to the target format,
b0fdc63d 354 * and adds them to the packet list.
355 *
356 * It is crucial that the gap between successive calls to read() is as small as
357 * possible: otherwise packets will be dropped.
358 *
359 * We use a binary heap to ensure that the unavoidable effort is at worst
360 * logarithmic in the total number of packets - in fact if packets are mostly
361 * received in order then we will largely do constant work per packet since the
362 * newest packet will always be last.
363 *
364 * Of more concern is that we must acquire the lock on the heap to add a packet
365 * to it. If this proves a problem in practice then the answer would be
366 * (probably doubly) linked list with new packets added the end and a second
367 * thread which reads packets off the list and adds them to the heap.
368 *
369 * We keep memory allocation (mostly) very fast by keeping pre-allocated
c593cf7c 370 * packets around; see @ref playrtp_new_packet().
b0fdc63d 371 */
0b75463f 372static void *listen_thread(void attribute((unused)) *arg) {
2c7c9eae 373 struct packet *p = 0;
0b75463f 374 int n;
2c7c9eae
RK
375 struct rtp_header header;
376 uint16_t seq;
377 uint32_t timestamp;
378 struct iovec iov[2];
e83d0967
RK
379
380 for(;;) {
189e9830 381 if(!p)
c593cf7c 382 p = playrtp_new_packet();
2c7c9eae
RK
383 iov[0].iov_base = &header;
384 iov[0].iov_len = sizeof header;
385 iov[1].iov_base = p->samples_raw;
b64efe7e 386 iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
2c7c9eae 387 n = readv(rtpfd, iov, 2);
e83d0967
RK
388 if(n < 0) {
389 switch(errno) {
390 case EINTR:
391 continue;
392 default:
2e9ba080 393 disorder_fatal(errno, "error reading from socket");
e83d0967
RK
394 }
395 }
0b75463f 396 /* Ignore too-short packets */
345ebe66 397 if((size_t)n <= sizeof (struct rtp_header)) {
2e9ba080 398 disorder_info("ignored a short packet");
0b75463f 399 continue;
345ebe66 400 }
2c7c9eae
RK
401 timestamp = htonl(header.timestamp);
402 seq = htons(header.seq);
09ee2f0d 403 /* Ignore packets in the past */
2c7c9eae 404 if(active && lt(timestamp, next_timestamp)) {
2e9ba080 405 disorder_info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
2c7c9eae 406 timestamp, next_timestamp);
09ee2f0d 407 continue;
c0e41690 408 }
28f1495a
RK
409 /* Ignore packets with the extension bit set. */
410 if(header.vpxcc & 0x10)
411 continue;
189e9830 412 p->next = 0;
58b5a68f 413 p->flags = 0;
2c7c9eae 414 p->timestamp = timestamp;
e83d0967 415 /* Convert to target format */
58b5a68f
RK
416 if(header.mpt & 0x80)
417 p->flags |= IDLE;
2c7c9eae 418 switch(header.mpt & 0x7F) {
4fd38868 419 case 10: /* L16 */
2c7c9eae 420 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
e83d0967
RK
421 break;
422 /* TODO support other RFC3551 media types (when the speaker does) */
423 default:
2e9ba080 424 disorder_fatal(0, "unsupported RTP payload type %d", header.mpt & 0x7F);
e83d0967 425 }
67d308e7
RK
426 /* See if packet is silent */
427 const uint16_t *s = p->samples_raw;
7bdf42d0 428 n = p->nsamples;
67d308e7
RK
429 for(; n > 0; --n)
430 if(*s++)
431 break;
432 if(!n)
433 p->flags |= SILENT;
345ebe66
RK
434 if(logfp)
435 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
2c7c9eae 436 seq, timestamp, p->nsamples, timestamp + p->nsamples);
0b75463f 437 /* Stop reading if we've reached the maximum.
438 *
439 * This is rather unsatisfactory: it means that if packets get heavily
440 * out of order then we guarantee dropouts. But for now... */
345ebe66 441 if(nsamples >= maxbuffer) {
189e9830 442 pthread_mutex_lock(&lock);
4dadf1a2 443 while(nsamples >= maxbuffer) {
345ebe66 444 pthread_cond_wait(&cond, &lock);
4dadf1a2 445 }
189e9830 446 pthread_mutex_unlock(&lock);
345ebe66 447 }
189e9830
RK
448 /* Add the packet to the receive queue */
449 pthread_mutex_lock(&receive_lock);
450 *received_tail = p;
451 received_tail = &p->next;
452 ++nreceived;
453 pthread_cond_signal(&receive_cond);
454 pthread_mutex_unlock(&receive_lock);
58b5a68f
RK
455 /* We'll need a new packet */
456 p = 0;
e83d0967
RK
457 }
458}
459
5626f6d2
RK
460/** @brief Wait until the buffer is adequately full
461 *
462 * Must be called with @ref lock held.
463 */
c593cf7c 464void playrtp_fill_buffer(void) {
0e72bf84 465 /* Discard current buffer contents */
ad535598
RK
466 while(nsamples) {
467 //fprintf(stderr, "%8u/%u (%u) DROPPING\n", nsamples, maxbuffer, minbuffer);
bfd27c14 468 drop_first_packet();
ad535598 469 }
2e9ba080 470 disorder_info("Buffering...");
0e72bf84
RK
471 /* Wait until there's at least minbuffer samples available */
472 while(nsamples < minbuffer) {
ad535598 473 //fprintf(stderr, "%8u/%u (%u) FILLING\n", nsamples, maxbuffer, minbuffer);
5626f6d2 474 pthread_cond_wait(&cond, &lock);
4dadf1a2 475 }
0e72bf84 476 /* Start from whatever is earliest */
5626f6d2
RK
477 next_timestamp = pheap_first(&packets)->timestamp;
478 active = 1;
479}
480
481/** @brief Find next packet
482 * @return Packet to play or NULL if none found
483 *
484 * The return packet is merely guaranteed not to be in the past: it might be
485 * the first packet in the future rather than one that is actually suitable to
486 * play.
487 *
488 * Must be called with @ref lock held.
489 */
c593cf7c 490struct packet *playrtp_next_packet(void) {
5626f6d2
RK
491 while(pheap_count(&packets)) {
492 struct packet *const p = pheap_first(&packets);
493 if(le(p->timestamp + p->nsamples, next_timestamp)) {
494 /* This packet is in the past. Drop it and try another one. */
495 drop_first_packet();
496 } else
497 /* This packet is NOT in the past. (It might be in the future
498 * however.) */
499 return p;
500 }
501 return 0;
502}
503
e83d0967 504/* display usage message and terminate */
16bf32dc 505static void attribute((noreturn)) help(void) {
e83d0967 506 xprintf("Usage:\n"
c897bb65 507 " disorder-playrtp [OPTIONS] [[ADDRESS] PORT]\n"
e83d0967 508 "Options:\n"
1153fd23 509 " --device, -D DEVICE Output device\n"
510 " --min, -m FRAMES Buffer low water mark\n"
9086a105 511 " --max, -x FRAMES Buffer maximum size\n"
1f10f780 512 " --rcvbuf, -R BYTES Socket receive buffer size\n"
af52ec84
MW
513 " --config, -C PATH Set system configuration file\n"
514 " --user-config, -u PATH Set user configuration file\n"
ba32e50c
RK
515 " --api, -A API Select audio API. Possibilities:\n"
516 " ");
517 int first = 1;
518 for(int n = 0; uaudio_apis[n]; ++n) {
519 if(uaudio_apis[n]->flags & UAUDIO_API_CLIENT) {
520 if(first)
521 first = 0;
522 else
523 xprintf(", ");
524 xprintf("%s", uaudio_apis[n]->name);
525 }
526 }
527 xprintf("\n"
287ad384
RK
528 " --command, -e COMMAND Pipe audio to command.\n"
529 " --pause-mode, -P silence For -e: pauses send silence (default)\n"
530 " --pause-mode, -P suspend For -e: pauses suspend writes\n"
9086a105
RK
531 " --help, -h Display usage message\n"
532 " --version, -V Display version number\n"
533 );
e83d0967
RK
534 xfclose(stdout);
535 exit(0);
536}
537
4fd38868 538static size_t playrtp_callback(void *buffer,
7a2c7068
RK
539 size_t max_samples,
540 void attribute((unused)) *userdata) {
541 size_t samples;
67d308e7 542 int silent = 0;
7a2c7068
RK
543
544 pthread_mutex_lock(&lock);
545 /* Get the next packet, junking any that are now in the past */
546 const struct packet *p = playrtp_next_packet();
547 if(p && contains(p, next_timestamp)) {
548 /* This packet is ready to play; the desired next timestamp points
549 * somewhere into it. */
550
551 /* Timestamp of end of packet */
552 const uint32_t packet_end = p->timestamp + p->nsamples;
553
554 /* Offset of desired next timestamp into current packet */
555 const uint32_t offset = next_timestamp - p->timestamp;
556
557 /* Pointer to audio data */
558 const uint16_t *ptr = (void *)(p->samples_raw + offset);
559
560 /* Compute number of samples left in packet, limited to output buffer
561 * size */
562 samples = packet_end - next_timestamp;
563 if(samples > max_samples)
564 samples = max_samples;
565
566 /* Copy into buffer, converting to native endianness */
567 size_t i = samples;
568 int16_t *bufptr = buffer;
569 while(i > 0) {
570 *bufptr++ = (int16_t)ntohs(*ptr++);
571 --i;
572 }
67d308e7 573 silent = !!(p->flags & SILENT);
7a2c7068
RK
574 } else {
575 /* There is no suitable packet. We introduce 0s up to the next packet, or
576 * to fill the buffer if there's no next packet or that's too many. The
577 * comparison with max_samples deals with the otherwise troubling overflow
578 * case. */
579 samples = p ? p->timestamp - next_timestamp : max_samples;
580 if(samples > max_samples)
581 samples = max_samples;
582 //info("infill by %zu", samples);
4fd38868 583 memset(buffer, 0, samples * uaudio_sample_size);
67d308e7 584 silent = 1;
7a2c7068
RK
585 }
586 /* Debug dump */
587 if(dump_buffer) {
588 for(size_t i = 0; i < samples; ++i) {
4fd38868 589 dump_buffer[dump_index++] = ((int16_t *)buffer)[i];
7a2c7068
RK
590 dump_index %= dump_size;
591 }
592 }
593 /* Advance timestamp */
594 next_timestamp += samples;
7edc7e42
RK
595 /* If we're getting behind then try to drop just silent packets
596 *
597 * In theory this shouldn't be necessary. The server is supposed to send
598 * packets at the right rate and compares the number of samples sent with the
599 * time in order to ensure this.
600 *
601 * However, various things could throw this off:
602 *
603 * - the server's clock could advance at the wrong rate. This would cause it
604 * to mis-estimate the right number of samples to have sent and
605 * inappropriately throttle or speed up.
606 *
607 * - playback could happen at the wrong rate. If the playback host's sound
608 * card has a slightly incorrect clock then eventually it will get out
609 * of step.
610 *
611 * So if we play back slightly slower than the server sends for either of
612 * these reasons then eventually our buffer, and the socket's buffer, will
613 * fill, and the kernel will start dropping packets. The result is audible
614 * and not very nice.
615 *
616 * Therefore if we're getting behind, we pre-emptively drop silent packets,
617 * since a change in the duration of a silence is less noticeable than a
618 * dropped packet from the middle of continuous music.
619 *
620 * (If things go wrong the other way then eventually we run out of packets to
621 * play and are forced to play silence. This doesn't seem to happen in
622 * practice but if it does then in the same way we can artificially extend
623 * silent packets to compensate.)
624 *
625 * Dropped packets are always logged; use 'disorder-playrtp --monitor' to
626 * track how close to target buffer occupancy we are on a once-a-minute
627 * basis.
628 */
67d308e7 629 if(nsamples > minbuffer && silent) {
2e9ba080
RK
630 disorder_info("dropping %zu samples (%"PRIu32" > %"PRIu32")",
631 samples, nsamples, minbuffer);
67d308e7
RK
632 samples = 0;
633 }
ad535598
RK
634 /* Junk obsolete packets */
635 playrtp_next_packet();
7a2c7068
RK
636 pthread_mutex_unlock(&lock);
637 return samples;
638}
639
e83d0967 640int main(int argc, char **argv) {
a99c4e9a 641 int n, err;
e83d0967
RK
642 struct addrinfo *res;
643 struct stringlist sl;
0b75463f 644 char *sockname;
14b5913c 645 int rcvbuf, target_rcvbuf = -1;
1f10f780 646 socklen_t len;
23205f9c
RK
647 struct ip_mreq mreq;
648 struct ipv6_mreq mreq6;
cca034e5 649 disorder_client *c = NULL;
a7e9570a 650 char *address, *port;
6fba990c
RK
651 int is_multicast;
652 union any_sockaddr {
653 struct sockaddr sa;
654 struct sockaddr_in in;
655 struct sockaddr_in6 in6;
656 };
657 union any_sockaddr mgroup;
e9b635a3 658 const char *dumpfile = 0;
7a2c7068 659 pthread_t ltid;
b0619501 660 int monitor = 0;
983c3357 661 static const int one = 1;
e83d0967 662
c5fbc6c7 663 struct addrinfo prefs = {
66613034
RK
664 .ai_flags = AI_PASSIVE,
665 .ai_family = PF_INET,
666 .ai_socktype = SOCK_DGRAM,
667 .ai_protocol = IPPROTO_UDP
e83d0967
RK
668 };
669
9d7a6129
RK
670 /* Timing information is often important to debugging playrtp, so we include
671 * timestamps in the logs */
672 logdate = 1;
e83d0967 673 mem_init();
2e9ba080 674 if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "error calling setlocale");
af52ec84 675 while((n = getopt_long(argc, argv, "hVdD:m:x:L:R:aocC:u:re:P:MA:", options, 0)) >= 0) {
e83d0967
RK
676 switch(n) {
677 case 'h': help();
3fbdc96d 678 case 'V': version("disorder-playrtp");
e83d0967 679 case 'd': debugging = 1; break;
e979b844 680 case 'D': uaudio_set("device", optarg); break;
1153fd23 681 case 'm': minbuffer = 2 * atol(optarg); break;
9086a105 682 case 'x': maxbuffer = 2 * atol(optarg); break;
345ebe66 683 case 'L': logfp = fopen(optarg, "w"); break;
1f10f780 684 case 'R': target_rcvbuf = atoi(optarg); break;
146e86fb 685#if HAVE_ALSA_ASOUNDLIB_H
ba32e50c
RK
686 case 'a':
687 disorder_error(0, "deprecated option; use --api alsa instead");
688 backend = &uaudio_alsa; break;
c593cf7c 689#endif
a9f0ad12 690#if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
ba32e50c
RK
691 case 'o':
692 disorder_error(0, "deprecated option; use --api oss instead");
693 backend = &uaudio_oss;
694 break;
c593cf7c 695#endif
696#if HAVE_COREAUDIO_AUDIOHARDWARE_H
ba32e50c
RK
697 case 'c':
698 disorder_error(0, "deprecated option; use --api coreaudio instead");
699 backend = &uaudio_coreaudio;
700 break;
c593cf7c 701#endif
ba32e50c 702 case 'A': backend = uaudio_find(optarg); break;
a7e9570a 703 case 'C': configfile = optarg; break;
af52ec84 704 case 'u': userconfigfile = optarg; break;
a99c4e9a 705 case 's': control_socket = optarg; break;
e9b635a3 706 case 'r': dumpfile = optarg; break;
e979b844 707 case 'e': backend = &uaudio_command; uaudio_set("command", optarg); break;
287ad384 708 case 'P': uaudio_set("pause-mode", optarg); break;
b0619501 709 case 'M': monitor = 1; break;
2e9ba080 710 default: disorder_fatal(0, "invalid option");
e83d0967
RK
711 }
712 }
2e9ba080 713 if(config_read(0, NULL)) disorder_fatal(0, "cannot read configuration");
163ed8a5 714 /* Choose a sensible default audio backend */
06385470
RK
715 if(!backend) {
716 backend = uaudio_default(uaudio_apis, UAUDIO_API_CLIENT);
717 if(!backend)
718 disorder_fatal(0, "no default uaudio API found");
719 disorder_info("default audio API %s", backend->name);
720 }
30a82196
RK
721 if(backend == &uaudio_rtp) {
722 /* This means that you have NO local sound output. This can happen if you
723 * use a non-Apple GCC on a Mac (because it doesn't know how to compile
724 * CoreAudio/AudioHardware.h). */
725 disorder_fatal(0, "cannot play RTP through RTP");
726 }
14b5913c
MW
727 /* Set buffering parameters if not overridden */
728 if(!minbuffer) {
729 minbuffer = config->rtp_minbuffer;
730 if(!minbuffer) minbuffer = (2*44100)*4/10;
731 }
732 if(!maxbuffer) {
733 maxbuffer = config->rtp_maxbuffer;
734 if(!maxbuffer) maxbuffer = 2 * minbuffer;
735 }
736 if(target_rcvbuf < 0) target_rcvbuf = config->rtp_rcvbuf;
e83d0967
RK
737 argc -= optind;
738 argv += optind;
a7e9570a
RK
739 switch(argc) {
740 case 0:
14b5913c
MW
741 sl.s = xcalloc(3, sizeof *sl.s);
742 if(config->rtp_always_request) {
743 sl.s[0] = sl.s[1] = (/*unconst*/ char *)"-";
744 sl.n = 2;
745 } else {
746 /* Get configuration from server */
747 if(!(c = disorder_new(1))) exit(EXIT_FAILURE);
748 if(disorder_connect(c)) exit(EXIT_FAILURE);
749 if(disorder_rtp_address(c, &address, &port)) exit(EXIT_FAILURE);
750 sl.s[0] = address;
751 sl.s[1] = port;
752 sl.n = 2;
753 }
754 /* If we're requesting a new stream then apply the local network address
755 * overrides.
756 */
757 if(!strcmp(sl.s[0], "-")) {
758 if(config->rtp_request_address.port)
759 byte_xasprintf(&sl.s[1], "%d", config->rtp_request_address.port);
760 if(config->rtp_request_address.address) {
761 sl.s[2] = sl.s[1];
762 sl.s[1] = config->rtp_request_address.address;
763 sl.n = 3;
764 }
765 }
a7e9570a 766 break;
169f1a6f 767 case 1: case 2: case 3:
6fba990c 768 /* Use command-line ADDRESS+PORT or just PORT */
a7e9570a
RK
769 sl.n = argc;
770 sl.s = argv;
771 break;
772 default:
2e9ba080 773 disorder_fatal(0, "usage: disorder-playrtp [OPTIONS] [[ADDRESS] PORT]");
a7e9570a 774 }
7077d53f
RK
775 disorder_info("version "VERSION" process ID %lu",
776 (unsigned long)getpid());
cca034e5
RK
777 struct sockaddr *addr;
778 socklen_t addr_len;
779 if(!strcmp(sl.s[0], "-")) {
169f1a6f
MW
780 /* Syntax: - [[ADDRESS] PORT]. Here, the PORT may be `-' to get the local
781 * kernel to choose. The ADDRESS may be omitted or `-' to pick something
782 * suitable. */
783 const char *node, *svc;
784 struct sockaddr *sa = 0;
785 switch (sl.n) {
786#define NULLDASH(s) (strcmp((s), "-") ? (s) : 0)
787 case 1: node = 0; svc = 0; break;
788 case 2: node = 0; svc = NULLDASH(sl.s[1]); break;
789 case 3: node = NULLDASH(sl.s[1]); svc = NULLDASH(sl.s[2]); break;
790 default: disorder_fatal(0, "too many listening-address compoennts");
791#undef NULLDASH
792 }
d7255a30
MW
793 /* We'll need a connection to request the incoming stream, so open one if
794 * we don't have one already */
795 if(!c) {
796 if(!(c = disorder_new(1))) exit(EXIT_FAILURE);
797 if(disorder_connect(c)) exit(EXIT_FAILURE);
798 }
32d209ee
MW
799 /* If no address was given, we need to pick one. But we already have a
800 * connection to the server, so we can probably use the address from that.
801 */
802 struct sockaddr_storage ss;
169f1a6f 803 if(!node) {
32d209ee
MW
804 addr_len = sizeof ss;
805 if(disorder_client_sockname(c, (struct sockaddr *)&ss, &addr_len))
806 exit(EXIT_FAILURE);
807 if(ss.ss_family != AF_INET && ss.ss_family != AF_INET6) {
808 /* We're using a Unix-domain socket, so use a loopback address. I'm
809 * cowardly using IPv4 here. */
810 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
811 sin->sin_family = AF_INET;
812 sin->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
169f1a6f 813 }
32d209ee 814 sa = (struct sockaddr *)&ss;
169f1a6f
MW
815 prefs.ai_family = sa->sa_family;
816 }
817 /* If we have an address or port to resolve then do that now */
818 if (node || svc) {
819 struct addrinfo *ai;
820 char errbuf[1024];
821 int rc;
822 if((rc = getaddrinfo(node, svc, &prefs, &ai)))
823 disorder_fatal(0, "failed to resolve address `%s' and service `%s': %s",
824 node ? node : "-", svc ? svc : "-",
825 format_error(ec_getaddrinfo, rc,
826 errbuf, sizeof(errbuf)));
827 if(!sa)
828 sa = ai->ai_addr;
829 else {
830 assert(sa->sa_family == ai->ai_addr->sa_family);
831 switch(sa->sa_family) {
832 case AF_INET:
833 ((struct sockaddr_in *)sa)->sin_port =
834 ((struct sockaddr_in *)ai->ai_addr)->sin_port;
835 break;
836 case AF_INET6:
837 ((struct sockaddr_in6 *)sa)->sin6_port =
838 ((struct sockaddr_in6 *)ai->ai_addr)->sin6_port;
839 break;
840 default:
841 assert(!"unexpected address family");
842 }
843 }
23205f9c 844 }
169f1a6f
MW
845 if((rtpfd = socket(sa->sa_family, SOCK_DGRAM, IPPROTO_UDP)) < 0)
846 disorder_fatal(errno, "error creating socket (family %d)",
847 sa->sa_family);
cca034e5 848 /* Bind the address */
169f1a6f
MW
849 if(bind(rtpfd, sa,
850 sa->sa_family == AF_INET
cca034e5
RK
851 ? sizeof (struct sockaddr_in) : sizeof (struct sockaddr_in6)) < 0)
852 disorder_fatal(errno, "error binding socket");
853 static struct sockaddr_storage bound_address;
854 addr = (struct sockaddr *)&bound_address;
855 addr_len = sizeof bound_address;
856 if(getsockname(rtpfd, addr, &addr_len) < 0)
857 disorder_fatal(errno, "error getting socket address");
858 /* Convert to string */
859 char addrname[128], portname[32];
860 if(getnameinfo(addr, addr_len,
861 addrname, sizeof addrname,
862 portname, sizeof portname,
863 NI_NUMERICHOST|NI_NUMERICSERV) < 0)
864 disorder_fatal(errno, "getnameinfo");
865 /* Ask for audio data */
866 if(disorder_rtp_request(c, addrname, portname)) exit(EXIT_FAILURE);
983c3357 867 /* Report what we did */
7675ceab
MW
868 disorder_info("listening on %s (stream requested)",
869 format_sockaddr(addr));
983c3357 870 } else {
169f1a6f 871 if(sl.n > 2) disorder_fatal(0, "too many address components");
cca034e5
RK
872 /* Look up address and port */
873 if(!(res = get_address(&sl, &prefs, &sockname)))
874 exit(1);
875 addr = res->ai_addr;
876 addr_len = res->ai_addrlen;
877 /* Create the socket */
878 if((rtpfd = socket(res->ai_family,
879 res->ai_socktype,
880 res->ai_protocol)) < 0)
881 disorder_fatal(errno, "error creating socket");
882 /* Allow multiple listeners */
883 xsetsockopt(rtpfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
884 is_multicast = multicast(addr);
885 /* The multicast and unicast/broadcast cases are different enough that they
886 * are totally split. Trying to find commonality between them causes more
887 * trouble that it's worth. */
888 if(is_multicast) {
889 /* Stash the multicast group address */
890 memcpy(&mgroup, addr, addr_len);
891 switch(res->ai_addr->sa_family) {
892 case AF_INET:
893 mgroup.in.sin_port = 0;
894 break;
895 case AF_INET6:
896 mgroup.in6.sin6_port = 0;
897 break;
898 default:
899 disorder_fatal(0, "unsupported address family %d",
900 (int)addr->sa_family);
901 }
902 /* Bind to to the multicast group address */
903 if(bind(rtpfd, addr, addr_len) < 0)
904 disorder_fatal(errno, "error binding socket to %s",
905 format_sockaddr(addr));
906 /* Add multicast group membership */
907 switch(mgroup.sa.sa_family) {
908 case PF_INET:
909 mreq.imr_multiaddr = mgroup.in.sin_addr;
910 mreq.imr_interface.s_addr = 0; /* use primary interface */
911 if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
912 &mreq, sizeof mreq) < 0)
913 disorder_fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP");
914 break;
915 case PF_INET6:
916 mreq6.ipv6mr_multiaddr = mgroup.in6.sin6_addr;
917 memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface);
918 if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
919 &mreq6, sizeof mreq6) < 0)
920 disorder_fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP");
921 break;
922 default:
923 disorder_fatal(0, "unsupported address family %d", res->ai_family);
924 }
925 /* Report what we did */
926 disorder_info("listening on %s multicast group %s",
927 format_sockaddr(addr), format_sockaddr(&mgroup.sa));
928 } else {
929 /* Bind to 0/port */
930 switch(addr->sa_family) {
931 case AF_INET: {
932 struct sockaddr_in *in = (struct sockaddr_in *)addr;
983c3357 933
cca034e5
RK
934 memset(&in->sin_addr, 0, sizeof (struct in_addr));
935 break;
936 }
937 case AF_INET6: {
938 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)addr;
983c3357 939
cca034e5
RK
940 memset(&in6->sin6_addr, 0, sizeof (struct in6_addr));
941 break;
942 }
943 default:
944 disorder_fatal(0, "unsupported family %d", (int)addr->sa_family);
945 }
946 if(bind(rtpfd, addr, addr_len) < 0)
947 disorder_fatal(errno, "error binding socket to %s",
948 format_sockaddr(addr));
949 /* Report what we did */
950 disorder_info("listening on %s", format_sockaddr(addr));
983c3357 951 }
983c3357 952 }
1f10f780
RK
953 len = sizeof rcvbuf;
954 if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
2e9ba080 955 disorder_fatal(errno, "error calling getsockopt SO_RCVBUF");
f0bae611 956 if(target_rcvbuf > rcvbuf) {
1f10f780
RK
957 if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
958 &target_rcvbuf, sizeof target_rcvbuf) < 0)
2e9ba080
RK
959 disorder_error(errno, "error calling setsockopt SO_RCVBUF %d",
960 target_rcvbuf);
1f10f780
RK
961 /* We try to carry on anyway */
962 else
2e9ba080
RK
963 disorder_info("changed socket receive buffer from %d to %d",
964 rcvbuf, target_rcvbuf);
1f10f780 965 } else
2e9ba080 966 disorder_info("default socket receive buffer %d", rcvbuf);
ad535598 967 //info("minbuffer %u maxbuffer %u", minbuffer, maxbuffer);
1f10f780 968 if(logfp)
2e9ba080 969 disorder_info("WARNING: -L option can impact performance");
a99c4e9a
RK
970 if(control_socket) {
971 pthread_t tid;
972
973 if((err = pthread_create(&tid, 0, control_thread, 0)))
2e9ba080 974 disorder_fatal(err, "pthread_create control_thread");
a99c4e9a 975 }
e9b635a3
RK
976 if(dumpfile) {
977 int fd;
978 unsigned char buffer[65536];
979 size_t written;
980
981 if((fd = open(dumpfile, O_RDWR|O_TRUNC|O_CREAT, 0666)) < 0)
2e9ba080 982 disorder_fatal(errno, "opening %s", dumpfile);
e9b635a3
RK
983 /* Fill with 0s to a suitable size */
984 memset(buffer, 0, sizeof buffer);
985 for(written = 0; written < dump_size * sizeof(int16_t);
986 written += sizeof buffer) {
987 if(write(fd, buffer, sizeof buffer) < 0)
2e9ba080 988 disorder_fatal(errno, "clearing %s", dumpfile);
e9b635a3
RK
989 }
990 /* Map the buffer into memory for convenience */
991 dump_buffer = mmap(0, dump_size * sizeof(int16_t), PROT_READ|PROT_WRITE,
992 MAP_SHARED, fd, 0);
993 if(dump_buffer == (void *)-1)
2e9ba080
RK
994 disorder_fatal(errno, "mapping %s", dumpfile);
995 disorder_info("dumping to %s", dumpfile);
e9b635a3 996 }
4fd38868
RK
997 /* Set up output. Currently we only support L16 so there's no harm setting
998 * the format before we know what it is! */
999 uaudio_set_format(44100/*Hz*/, 2/*channels*/,
1000 16/*bits/channel*/, 1/*signed*/);
de0ef46e 1001 uaudio_set("application", "disorder-playrtp");
3b9aa3e5 1002 backend->configure();
7a2c7068 1003 backend->start(playrtp_callback, NULL);
af21fb6b 1004 if(backend->open_mixer) backend->open_mixer();
7a2c7068
RK
1005 /* We receive and convert audio data in a background thread */
1006 if((err = pthread_create(&ltid, 0, listen_thread, 0)))
2e9ba080 1007 disorder_fatal(err, "pthread_create listen_thread");
7a2c7068
RK
1008 /* We have a second thread to add received packets to the queue */
1009 if((err = pthread_create(&ltid, 0, queue_thread, 0)))
2e9ba080 1010 disorder_fatal(err, "pthread_create queue_thread");
7a2c7068 1011 pthread_mutex_lock(&lock);
b0619501 1012 time_t lastlog = 0;
7a2c7068
RK
1013 for(;;) {
1014 /* Wait for the buffer to fill up a bit */
1015 playrtp_fill_buffer();
1016 /* Start playing now */
2e9ba080 1017 disorder_info("Playing...");
7a2c7068
RK
1018 next_timestamp = pheap_first(&packets)->timestamp;
1019 active = 1;
d4170ca7 1020 pthread_mutex_unlock(&lock);
7a2c7068 1021 backend->activate();
d4170ca7 1022 pthread_mutex_lock(&lock);
0e72bf84
RK
1023 /* Wait until the buffer empties out
1024 *
1025 * If there's a packet that we can play right now then we definitely
1026 * continue.
1027 *
1028 * Also if there's at least minbuffer samples we carry on regardless and
1029 * insert silence. The assumption is there's been a pause but more data
1030 * is now available.
1031 */
7a2c7068
RK
1032 while(nsamples >= minbuffer
1033 || (nsamples > 0
4fd38868 1034 && contains(pheap_first(&packets), next_timestamp))) {
b0619501 1035 if(monitor) {
4265e5d3 1036 time_t now = xtime(0);
b0619501
RK
1037
1038 if(now >= lastlog + 60) {
1039 int offset = nsamples - minbuffer;
1040 double offtime = (double)offset / (uaudio_rate * uaudio_channels);
2e9ba080
RK
1041 disorder_info("%+d samples off (%d.%02ds, %d bytes)",
1042 offset,
1043 (int)fabs(offtime) * (offtime < 0 ? -1 : 1),
1044 (int)(fabs(offtime) * 100) % 100,
1045 offset * uaudio_bits / CHAR_BIT);
b0619501
RK
1046 lastlog = now;
1047 }
1048 }
ad535598 1049 //fprintf(stderr, "%8u/%u (%u) PLAYING\n", nsamples, maxbuffer, minbuffer);
7a2c7068 1050 pthread_cond_wait(&cond, &lock);
4fd38868 1051 }
ad535598
RK
1052#if 0
1053 if(nsamples) {
1054 struct packet *p = pheap_first(&packets);
1055 fprintf(stderr, "nsamples=%u (%u) next_timestamp=%"PRIx32", first packet is [%"PRIx32",%"PRIx32")\n",
1056 nsamples, minbuffer, next_timestamp,p->timestamp,p->timestamp+p->nsamples);
1057 }
1058#endif
7a2c7068 1059 /* Stop playing for a bit until the buffer re-fills */
d4170ca7 1060 pthread_mutex_unlock(&lock);
7a2c7068 1061 backend->deactivate();
d4170ca7 1062 pthread_mutex_lock(&lock);
7a2c7068
RK
1063 active = 0;
1064 /* Go back round */
1065 }
e83d0967
RK
1066 return 0;
1067}
1068
1069/*
1070Local Variables:
1071c-basic-offset:2
1072comment-column:40
1073fill-column:79
1074indent-tabs-mode:nil
1075End:
1076*/