2 * This file is part of DisOrder.
3 * Copyright (C) 2007-2009, 2011, 2013 Richard Kettlewell
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 3 of the License, or
8 * (at your option) any later version.
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.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /** @file clients/playrtp.c
21 * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</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.
27 * The program runs (at least) three threads:
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
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
37 * control_thread() accepts commands from Disobedience (or anything else).
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).
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.
47 * - it is safe to read uint32_t values without a lock protecting them
53 #include <sys/socket.h>
54 #include <sys/types.h>
55 #include <sys/socket.h>
61 #include <netinet/in.h>
68 #include <arpa/inet.h>
74 #include "configuration.h"
84 #include "inputline.h"
88 /** @brief Obsolete synonym */
89 #ifndef IPV6_JOIN_GROUP
90 # define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP
93 /** @brief RTP socket */
96 /** @brief Log output */
99 /** @brief Output device */
101 /** @brief Buffer low watermark in samples */
102 unsigned minbuffer
= 4 * (2 * 44100) / 10; /* 0.4 seconds */
104 /** @brief Maximum buffer size in samples
106 * We'll stop reading from the network if we have this many samples.
108 static unsigned maxbuffer
;
110 /** @brief Received packets
111 * Protected by @ref receive_lock
113 * Received packets are added to this list, and queue_thread() picks them off
114 * it and adds them to @ref packets. Whenever a packet is added to it, @ref
115 * receive_cond is signalled.
117 struct packet
*received_packets
;
119 /** @brief Tail of @ref received_packets
120 * Protected by @ref receive_lock
122 struct packet
**received_tail
= &received_packets
;
124 /** @brief Lock protecting @ref received_packets
126 * Only listen_thread() and queue_thread() ever hold this lock. It is vital
127 * that queue_thread() not hold it any longer than it strictly has to. */
128 pthread_mutex_t receive_lock
= PTHREAD_MUTEX_INITIALIZER
;
130 /** @brief Condition variable signalled when @ref received_packets is updated
132 * Used by listen_thread() to notify queue_thread() that it has added another
133 * packet to @ref received_packets. */
134 pthread_cond_t receive_cond
= PTHREAD_COND_INITIALIZER
;
136 /** @brief Length of @ref received_packets */
139 /** @brief Binary heap of received packets */
140 struct pheap packets
;
142 /** @brief Total number of samples available
144 * We make this volatile because we inspect it without a protecting lock,
145 * so the usual pthread_* guarantees aren't available.
147 volatile uint32_t nsamples
;
149 /** @brief Timestamp of next packet to play.
151 * This is set to the timestamp of the last packet, plus the number of
152 * samples it contained. Only valid if @ref active is nonzero.
154 uint32_t next_timestamp
;
156 /** @brief True if actively playing
158 * This is true when playing and false when just buffering. */
161 /** @brief Lock protecting @ref packets */
162 pthread_mutex_t lock
= PTHREAD_MUTEX_INITIALIZER
;
164 /** @brief Condition variable signalled whenever @ref packets is changed */
165 pthread_cond_t cond
= PTHREAD_COND_INITIALIZER
;
167 /** @brief Backend to play with */
168 static const struct uaudio
*backend
;
170 HEAP_DEFINE(pheap
, struct packet
*, lt_packet
);
172 /** @brief Control socket or NULL */
173 const char *control_socket
;
175 /** @brief Buffer for debugging dump
177 * The debug dump is enabled by the @c --dump option. It records the last 20s
178 * of audio to the specified file (which will be about 3.5Mbytes). The file is
179 * written as as ring buffer, so the start point will progress through it.
181 * Use clients/dump2wav to convert this to a WAV file, which can then be loaded
182 * into (e.g.) Audacity for further inspection.
184 * All three backends (ALSA, OSS, Core Audio) now support this option.
186 * The idea is to allow the user a few seconds to react to an audible artefact.
188 int16_t *dump_buffer
;
190 /** @brief Current index within debugging dump */
193 /** @brief Size of debugging dump in samples */
194 size_t dump_size
= 44100/*Hz*/ * 2/*channels*/ * 20/*seconds*/;
196 static const struct option options
[] = {
197 { "help", no_argument
, 0, 'h' },
198 { "version", no_argument
, 0, 'V' },
199 { "debug", no_argument
, 0, 'd' },
200 { "device", required_argument
, 0, 'D' },
201 { "min", required_argument
, 0, 'm' },
202 { "max", required_argument
, 0, 'x' },
203 { "rcvbuf", required_argument
, 0, 'R' },
204 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
205 { "oss", no_argument
, 0, 'o' },
207 #if HAVE_ALSA_ASOUNDLIB_H
208 { "alsa", no_argument
, 0, 'a' },
210 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
211 { "core-audio", no_argument
, 0, 'c' },
213 { "api", required_argument
, 0, 'A' },
214 { "dump", required_argument
, 0, 'r' },
215 { "command", required_argument
, 0, 'e' },
216 { "pause-mode", required_argument
, 0, 'P' },
217 { "socket", required_argument
, 0, 's' },
218 { "config", required_argument
, 0, 'C' },
219 { "monitor", no_argument
, 0, 'M' },
223 /** @brief Control thread
225 * This thread is responsible for accepting control commands from Disobedience
226 * (or other controllers) over an AF_UNIX stream socket with a path specified
227 * by the @c --socket option. The protocol uses simple string commands and
230 * - @c stop will shut the player down
231 * - @c query will send back the reply @c running
232 * - anything else is ignored
234 * Commands and response strings terminated by shutting down the connection or
235 * by a newline. No attempt is made to multiplex multiple clients so it is
236 * important that the command be sent as soon as the connection is made - it is
237 * assumed that both parties to the protocol are entirely cooperating with one
240 static void *control_thread(void attribute((unused
)) *arg
) {
241 struct sockaddr_un sa
;
248 assert(control_socket
);
249 unlink(control_socket
);
250 memset(&sa
, 0, sizeof sa
);
251 sa
.sun_family
= AF_UNIX
;
252 strcpy(sa
.sun_path
, control_socket
);
253 sfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
254 if(bind(sfd
, (const struct sockaddr
*)&sa
, sizeof sa
) < 0)
255 disorder_fatal(errno
, "error binding to %s", control_socket
);
256 if(listen(sfd
, 128) < 0)
257 disorder_fatal(errno
, "error calling listen on %s", control_socket
);
258 disorder_info("listening on %s", control_socket
);
261 cfd
= accept(sfd
, (struct sockaddr
*)&sa
, &salen
);
268 disorder_fatal(errno
, "error calling accept on %s", control_socket
);
271 if(!(fp
= fdopen(cfd
, "r+"))) {
272 disorder_error(errno
, "error calling fdopen for %s connection", control_socket
);
276 if(!inputline(control_socket
, fp
, &line
, '\n')) {
277 if(!strcmp(line
, "stop")) {
278 disorder_info("stopped via %s", control_socket
);
279 exit(0); /* terminate immediately */
280 } else if(!strcmp(line
, "query"))
281 fprintf(fp
, "running");
282 else if(!strcmp(line
, "getvol")) {
283 if(backend
->get_volume
) backend
->get_volume(&vl
, &vr
);
285 fprintf(fp
, "%d %d\n", vl
, vr
);
286 } else if(!strncmp(line
, "setvol ", 7)) {
287 if(!backend
->set_volume
)
289 else if(sscanf(line
+ 7, "%d %d", &vl
, &vr
) == 2)
290 backend
->set_volume(&vl
, &vr
);
292 backend
->get_volume(&vl
, &vr
);
293 fprintf(fp
, "%d %d\n", vl
, vr
);
298 disorder_error(errno
, "error closing %s connection", control_socket
);
302 /** @brief Drop the first packet
304 * Assumes that @ref lock is held.
306 static void drop_first_packet(void) {
307 if(pheap_count(&packets
)) {
308 struct packet
*const p
= pheap_remove(&packets
);
309 nsamples
-= p
->nsamples
;
310 playrtp_free_packet(p
);
311 pthread_cond_broadcast(&cond
);
315 /** @brief Background thread adding packets to heap
317 * This just transfers packets from @ref received_packets to @ref packets. It
318 * is important that it holds @ref receive_lock for as little time as possible,
319 * in order to minimize the interval between calls to read() in
322 static void *queue_thread(void attribute((unused
)) *arg
) {
326 /* Get the next packet */
327 pthread_mutex_lock(&receive_lock
);
328 while(!received_packets
) {
329 pthread_cond_wait(&receive_cond
, &receive_lock
);
331 p
= received_packets
;
332 received_packets
= p
->next
;
333 if(!received_packets
)
334 received_tail
= &received_packets
;
336 pthread_mutex_unlock(&receive_lock
);
337 /* Add it to the heap */
338 pthread_mutex_lock(&lock
);
339 pheap_insert(&packets
, p
);
340 nsamples
+= p
->nsamples
;
341 pthread_cond_broadcast(&cond
);
342 pthread_mutex_unlock(&lock
);
344 #if HAVE_STUPID_GCC44
349 /** @brief Background thread collecting samples
351 * This function collects samples, perhaps converts them to the target format,
352 * and adds them to the packet list.
354 * It is crucial that the gap between successive calls to read() is as small as
355 * possible: otherwise packets will be dropped.
357 * We use a binary heap to ensure that the unavoidable effort is at worst
358 * logarithmic in the total number of packets - in fact if packets are mostly
359 * received in order then we will largely do constant work per packet since the
360 * newest packet will always be last.
362 * Of more concern is that we must acquire the lock on the heap to add a packet
363 * to it. If this proves a problem in practice then the answer would be
364 * (probably doubly) linked list with new packets added the end and a second
365 * thread which reads packets off the list and adds them to the heap.
367 * We keep memory allocation (mostly) very fast by keeping pre-allocated
368 * packets around; see @ref playrtp_new_packet().
370 static void *listen_thread(void attribute((unused
)) *arg
) {
371 struct packet
*p
= 0;
373 struct rtp_header header
;
380 p
= playrtp_new_packet();
381 iov
[0].iov_base
= &header
;
382 iov
[0].iov_len
= sizeof header
;
383 iov
[1].iov_base
= p
->samples_raw
;
384 iov
[1].iov_len
= sizeof p
->samples_raw
/ sizeof *p
->samples_raw
;
385 n
= readv(rtpfd
, iov
, 2);
391 disorder_fatal(errno
, "error reading from socket");
394 /* Ignore too-short packets */
395 if((size_t)n
<= sizeof (struct rtp_header
)) {
396 disorder_info("ignored a short packet");
399 timestamp
= htonl(header
.timestamp
);
400 seq
= htons(header
.seq
);
401 /* Ignore packets in the past */
402 if(active
&& lt(timestamp
, next_timestamp
)) {
403 disorder_info("dropping old packet, timestamp=%"PRIx32
" < %"PRIx32
,
404 timestamp
, next_timestamp
);
407 /* Ignore packets with the extension bit set. */
408 if(header
.vpxcc
& 0x10)
412 p
->timestamp
= timestamp
;
413 /* Convert to target format */
414 if(header
.mpt
& 0x80)
416 switch(header
.mpt
& 0x7F) {
418 p
->nsamples
= (n
- sizeof header
) / sizeof(uint16_t);
420 /* TODO support other RFC3551 media types (when the speaker does) */
422 disorder_fatal(0, "unsupported RTP payload type %d", header
.mpt
& 0x7F);
424 /* See if packet is silent */
425 const uint16_t *s
= p
->samples_raw
;
433 fprintf(logfp
, "sequence %u timestamp %"PRIx32
" length %"PRIx32
" end %"PRIx32
"\n",
434 seq
, timestamp
, p
->nsamples
, timestamp
+ p
->nsamples
);
435 /* Stop reading if we've reached the maximum.
437 * This is rather unsatisfactory: it means that if packets get heavily
438 * out of order then we guarantee dropouts. But for now... */
439 if(nsamples
>= maxbuffer
) {
440 pthread_mutex_lock(&lock
);
441 while(nsamples
>= maxbuffer
) {
442 pthread_cond_wait(&cond
, &lock
);
444 pthread_mutex_unlock(&lock
);
446 /* Add the packet to the receive queue */
447 pthread_mutex_lock(&receive_lock
);
449 received_tail
= &p
->next
;
451 pthread_cond_signal(&receive_cond
);
452 pthread_mutex_unlock(&receive_lock
);
453 /* We'll need a new packet */
458 /** @brief Wait until the buffer is adequately full
460 * Must be called with @ref lock held.
462 void playrtp_fill_buffer(void) {
463 /* Discard current buffer contents */
465 //fprintf(stderr, "%8u/%u (%u) DROPPING\n", nsamples, maxbuffer, minbuffer);
468 disorder_info("Buffering...");
469 /* Wait until there's at least minbuffer samples available */
470 while(nsamples
< minbuffer
) {
471 //fprintf(stderr, "%8u/%u (%u) FILLING\n", nsamples, maxbuffer, minbuffer);
472 pthread_cond_wait(&cond
, &lock
);
474 /* Start from whatever is earliest */
475 next_timestamp
= pheap_first(&packets
)->timestamp
;
479 /** @brief Find next packet
480 * @return Packet to play or NULL if none found
482 * The return packet is merely guaranteed not to be in the past: it might be
483 * the first packet in the future rather than one that is actually suitable to
486 * Must be called with @ref lock held.
488 struct packet
*playrtp_next_packet(void) {
489 while(pheap_count(&packets
)) {
490 struct packet
*const p
= pheap_first(&packets
);
491 if(le(p
->timestamp
+ p
->nsamples
, next_timestamp
)) {
492 /* This packet is in the past. Drop it and try another one. */
495 /* This packet is NOT in the past. (It might be in the future
502 /* display usage message and terminate */
503 static void help(void) {
505 " disorder-playrtp [OPTIONS] [[ADDRESS] PORT]\n"
507 " --device, -D DEVICE Output device\n"
508 " --min, -m FRAMES Buffer low water mark\n"
509 " --max, -x FRAMES Buffer maximum size\n"
510 " --rcvbuf, -R BYTES Socket receive buffer size\n"
511 " --config, -C PATH Set configuration file\n"
512 " --api, -A API Select audio API. Possibilities:\n"
515 for(int n
= 0; uaudio_apis
[n
]; ++n
) {
516 if(uaudio_apis
[n
]->flags
& UAUDIO_API_CLIENT
) {
521 xprintf("%s", uaudio_apis
[n
]->name
);
525 " --command, -e COMMAND Pipe audio to command.\n"
526 " --pause-mode, -P silence For -e: pauses send silence (default)\n"
527 " --pause-mode, -P suspend For -e: pauses suspend writes\n"
528 " --help, -h Display usage message\n"
529 " --version, -V Display version number\n"
535 static size_t playrtp_callback(void *buffer
,
537 void attribute((unused
)) *userdata
) {
541 pthread_mutex_lock(&lock
);
542 /* Get the next packet, junking any that are now in the past */
543 const struct packet
*p
= playrtp_next_packet();
544 if(p
&& contains(p
, next_timestamp
)) {
545 /* This packet is ready to play; the desired next timestamp points
546 * somewhere into it. */
548 /* Timestamp of end of packet */
549 const uint32_t packet_end
= p
->timestamp
+ p
->nsamples
;
551 /* Offset of desired next timestamp into current packet */
552 const uint32_t offset
= next_timestamp
- p
->timestamp
;
554 /* Pointer to audio data */
555 const uint16_t *ptr
= (void *)(p
->samples_raw
+ offset
);
557 /* Compute number of samples left in packet, limited to output buffer
559 samples
= packet_end
- next_timestamp
;
560 if(samples
> max_samples
)
561 samples
= max_samples
;
563 /* Copy into buffer, converting to native endianness */
565 int16_t *bufptr
= buffer
;
567 *bufptr
++ = (int16_t)ntohs(*ptr
++);
570 silent
= !!(p
->flags
& SILENT
);
572 /* There is no suitable packet. We introduce 0s up to the next packet, or
573 * to fill the buffer if there's no next packet or that's too many. The
574 * comparison with max_samples deals with the otherwise troubling overflow
576 samples
= p ? p
->timestamp
- next_timestamp
: max_samples
;
577 if(samples
> max_samples
)
578 samples
= max_samples
;
579 //info("infill by %zu", samples);
580 memset(buffer
, 0, samples
* uaudio_sample_size
);
585 for(size_t i
= 0; i
< samples
; ++i
) {
586 dump_buffer
[dump_index
++] = ((int16_t *)buffer
)[i
];
587 dump_index
%= dump_size
;
590 /* Advance timestamp */
591 next_timestamp
+= samples
;
592 /* If we're getting behind then try to drop just silent packets
594 * In theory this shouldn't be necessary. The server is supposed to send
595 * packets at the right rate and compares the number of samples sent with the
596 * time in order to ensure this.
598 * However, various things could throw this off:
600 * - the server's clock could advance at the wrong rate. This would cause it
601 * to mis-estimate the right number of samples to have sent and
602 * inappropriately throttle or speed up.
604 * - playback could happen at the wrong rate. If the playback host's sound
605 * card has a slightly incorrect clock then eventually it will get out
608 * So if we play back slightly slower than the server sends for either of
609 * these reasons then eventually our buffer, and the socket's buffer, will
610 * fill, and the kernel will start dropping packets. The result is audible
613 * Therefore if we're getting behind, we pre-emptively drop silent packets,
614 * since a change in the duration of a silence is less noticeable than a
615 * dropped packet from the middle of continuous music.
617 * (If things go wrong the other way then eventually we run out of packets to
618 * play and are forced to play silence. This doesn't seem to happen in
619 * practice but if it does then in the same way we can artificially extend
620 * silent packets to compensate.)
622 * Dropped packets are always logged; use 'disorder-playrtp --monitor' to
623 * track how close to target buffer occupancy we are on a once-a-minute
626 if(nsamples
> minbuffer
&& silent
) {
627 disorder_info("dropping %zu samples (%"PRIu32
" > %"PRIu32
")",
628 samples
, nsamples
, minbuffer
);
631 /* Junk obsolete packets */
632 playrtp_next_packet();
633 pthread_mutex_unlock(&lock
);
637 static int compare_family(const struct ifaddrs
*a
,
638 const struct ifaddrs
*b
,
640 int afamily
= a
->ifa_addr
->sa_family
;
641 int bfamily
= b
->ifa_addr
->sa_family
;
642 if(afamily
!= bfamily
) {
643 /* Preferred family wins */
644 if(afamily
== family
) return 1;
645 if(bfamily
== family
) return -1;
646 /* Either there's no preference or it doesn't help. Prefer IPv4 */
647 if(afamily
== AF_INET
) return 1;
648 if(bfamily
== AF_INET
) return -1;
649 /* Failing that prefer IPv6 */
650 if(afamily
== AF_INET6
) return 1;
651 if(bfamily
== AF_INET6
) return -1;
656 static int compare_flags(const struct ifaddrs
*a
,
657 const struct ifaddrs
*b
) {
658 unsigned aflags
= a
->ifa_flags
, bflags
= b
->ifa_flags
;
659 /* Up interfaces are better than down ones */
660 unsigned aup
= aflags
& IFF_UP
, bup
= bflags
& IFF_UP
;
662 return aup
> bup ?
1 : -1;
664 /* Static addresses are better than dynamic */
665 unsigned adynamic
= aflags
& IFF_DYNAMIC
, bdynamic
= bflags
& IFF_DYNAMIC
;
666 if(adynamic
!= bdynamic
)
667 return adynamic
< bdynamic ?
1 : -1;
669 unsigned aloopback
= aflags
& IFF_LOOPBACK
, bloopback
= bflags
& IFF_LOOPBACK
;
670 /* Static addresses are better than dynamic */
671 if(aloopback
!= bloopback
)
672 return aloopback
< bloopback ?
1 : -1;
676 static int compare_interfaces(const struct ifaddrs
*a
,
677 const struct ifaddrs
*b
,
680 if((c
= compare_family(a
, b
, family
))) return c
;
681 return compare_flags(a
, b
);
684 int main(int argc
, char **argv
) {
686 struct addrinfo
*res
;
687 struct stringlist sl
;
689 int rcvbuf
, target_rcvbuf
= 0;
692 struct ipv6_mreq mreq6
;
693 disorder_client
*c
= NULL
;
694 char *address
, *port
;
698 struct sockaddr_in in
;
699 struct sockaddr_in6 in6
;
701 union any_sockaddr mgroup
;
702 const char *dumpfile
= 0;
705 static const int one
= 1;
707 static const struct addrinfo prefs
= {
708 .ai_flags
= AI_PASSIVE
,
709 .ai_family
= PF_INET
,
710 .ai_socktype
= SOCK_DGRAM
,
711 .ai_protocol
= IPPROTO_UDP
714 /* Timing information is often important to debugging playrtp, so we include
715 * timestamps in the logs */
718 if(!setlocale(LC_CTYPE
, "")) disorder_fatal(errno
, "error calling setlocale");
719 while((n
= getopt_long(argc
, argv
, "hVdD:m:x:L:R:aocC:re:P:MA:", options
, 0)) >= 0) {
722 case 'V': version("disorder-playrtp");
723 case 'd': debugging
= 1; break;
724 case 'D': uaudio_set("device", optarg
); break;
725 case 'm': minbuffer
= 2 * atol(optarg
); break;
726 case 'x': maxbuffer
= 2 * atol(optarg
); break;
727 case 'L': logfp
= fopen(optarg
, "w"); break;
728 case 'R': target_rcvbuf
= atoi(optarg
); break;
729 #if HAVE_ALSA_ASOUNDLIB_H
731 disorder_error(0, "deprecated option; use --api alsa instead");
732 backend
= &uaudio_alsa
; break;
734 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
736 disorder_error(0, "deprecated option; use --api oss instead");
737 backend
= &uaudio_oss
;
740 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
742 disorder_error(0, "deprecated option; use --api coreaudio instead");
743 backend
= &uaudio_coreaudio
;
746 case 'A': backend
= uaudio_find(optarg
); break;
747 case 'C': configfile
= optarg
; break;
748 case 's': control_socket
= optarg
; break;
749 case 'r': dumpfile
= optarg
; break;
750 case 'e': backend
= &uaudio_command
; uaudio_set("command", optarg
); break;
751 case 'P': uaudio_set("pause-mode", optarg
); break;
752 case 'M': monitor
= 1; break;
753 default: disorder_fatal(0, "invalid option");
756 if(config_read(0, NULL
)) disorder_fatal(0, "cannot read configuration");
758 backend
= uaudio_default(uaudio_apis
, UAUDIO_API_CLIENT
);
760 disorder_fatal(0, "no default uaudio API found");
761 disorder_info("default audio API %s", backend
->name
);
763 if(backend
== &uaudio_rtp
) {
764 /* This means that you have NO local sound output. This can happen if you
765 * use a non-Apple GCC on a Mac (because it doesn't know how to compile
766 * CoreAudio/AudioHardware.h). */
767 disorder_fatal(0, "cannot play RTP through RTP");
770 maxbuffer
= 2 * minbuffer
;
775 /* Get configuration from server */
776 if(!(c
= disorder_new(1))) exit(EXIT_FAILURE
);
777 if(disorder_connect(c
)) exit(EXIT_FAILURE
);
778 if(disorder_rtp_address(c
, &address
, &port
)) exit(EXIT_FAILURE
);
780 sl
.s
= xcalloc(2, sizeof *sl
.s
);
786 /* Use command-line ADDRESS+PORT or just PORT */
791 disorder_fatal(0, "usage: disorder-playrtp [OPTIONS] [[ADDRESS] PORT]");
793 disorder_info("version "VERSION
" process ID %lu",
794 (unsigned long)getpid());
795 struct sockaddr
*addr
;
797 if(!strcmp(sl
.s
[0], "-")) {
798 /* Pick address family to match known-working connectivity to the server */
799 int family
= disorder_client_af(c
);
800 /* Get a list of interfaces */
801 struct ifaddrs
*ifa
, *bestifa
= NULL
;
802 if(getifaddrs(&ifa
) < 0)
803 disorder_fatal(errno
, "error calling getifaddrs");
804 /* Try to pick a good one */
805 for(; ifa
; ifa
= ifa
->ifa_next
) {
807 || compare_interfaces(ifa
, bestifa
, family
) > 0)
811 disorder_fatal(0, "failed to select a network interface");
812 family
= bestifa
->ifa_addr
->sa_family
;
813 if((rtpfd
= socket(family
,
816 disorder_fatal(errno
, "error creating socket (family %d)", family
);
817 /* Bind the address */
818 if(bind(rtpfd
, bestifa
->ifa_addr
,
820 ?
sizeof (struct sockaddr_in
) : sizeof (struct sockaddr_in6
)) < 0)
821 disorder_fatal(errno
, "error binding socket");
822 static struct sockaddr_storage bound_address
;
823 addr
= (struct sockaddr
*)&bound_address
;
824 addr_len
= sizeof bound_address
;
825 if(getsockname(rtpfd
, addr
, &addr_len
) < 0)
826 disorder_fatal(errno
, "error getting socket address");
827 /* Convert to string */
828 char addrname
[128], portname
[32];
829 if(getnameinfo(addr
, addr_len
,
830 addrname
, sizeof addrname
,
831 portname
, sizeof portname
,
832 NI_NUMERICHOST
|NI_NUMERICSERV
) < 0)
833 disorder_fatal(errno
, "getnameinfo");
834 /* Ask for audio data */
835 if(disorder_rtp_request(c
, addrname
, portname
)) exit(EXIT_FAILURE
);
836 /* Report what we did */
837 disorder_info("listening on %s", format_sockaddr(addr
));
839 /* Look up address and port */
840 if(!(res
= get_address(&sl
, &prefs
, &sockname
)))
843 addr_len
= res
->ai_addrlen
;
844 /* Create the socket */
845 if((rtpfd
= socket(res
->ai_family
,
847 res
->ai_protocol
)) < 0)
848 disorder_fatal(errno
, "error creating socket");
849 /* Allow multiple listeners */
850 xsetsockopt(rtpfd
, SOL_SOCKET
, SO_REUSEADDR
, &one
, sizeof one
);
851 is_multicast
= multicast(addr
);
852 /* The multicast and unicast/broadcast cases are different enough that they
853 * are totally split. Trying to find commonality between them causes more
854 * trouble that it's worth. */
856 /* Stash the multicast group address */
857 memcpy(&mgroup
, addr
, addr_len
);
858 switch(res
->ai_addr
->sa_family
) {
860 mgroup
.in
.sin_port
= 0;
863 mgroup
.in6
.sin6_port
= 0;
866 disorder_fatal(0, "unsupported address family %d",
867 (int)addr
->sa_family
);
869 /* Bind to to the multicast group address */
870 if(bind(rtpfd
, addr
, addr_len
) < 0)
871 disorder_fatal(errno
, "error binding socket to %s",
872 format_sockaddr(addr
));
873 /* Add multicast group membership */
874 switch(mgroup
.sa
.sa_family
) {
876 mreq
.imr_multiaddr
= mgroup
.in
.sin_addr
;
877 mreq
.imr_interface
.s_addr
= 0; /* use primary interface */
878 if(setsockopt(rtpfd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
879 &mreq
, sizeof mreq
) < 0)
880 disorder_fatal(errno
, "error calling setsockopt IP_ADD_MEMBERSHIP");
883 mreq6
.ipv6mr_multiaddr
= mgroup
.in6
.sin6_addr
;
884 memset(&mreq6
.ipv6mr_interface
, 0, sizeof mreq6
.ipv6mr_interface
);
885 if(setsockopt(rtpfd
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
,
886 &mreq6
, sizeof mreq6
) < 0)
887 disorder_fatal(errno
, "error calling setsockopt IPV6_JOIN_GROUP");
890 disorder_fatal(0, "unsupported address family %d", res
->ai_family
);
892 /* Report what we did */
893 disorder_info("listening on %s multicast group %s",
894 format_sockaddr(addr
), format_sockaddr(&mgroup
.sa
));
897 switch(addr
->sa_family
) {
899 struct sockaddr_in
*in
= (struct sockaddr_in
*)addr
;
901 memset(&in
->sin_addr
, 0, sizeof (struct in_addr
));
905 struct sockaddr_in6
*in6
= (struct sockaddr_in6
*)addr
;
907 memset(&in6
->sin6_addr
, 0, sizeof (struct in6_addr
));
911 disorder_fatal(0, "unsupported family %d", (int)addr
->sa_family
);
913 if(bind(rtpfd
, addr
, addr_len
) < 0)
914 disorder_fatal(errno
, "error binding socket to %s",
915 format_sockaddr(addr
));
916 /* Report what we did */
917 disorder_info("listening on %s", format_sockaddr(addr
));
921 if(getsockopt(rtpfd
, SOL_SOCKET
, SO_RCVBUF
, &rcvbuf
, &len
) < 0)
922 disorder_fatal(errno
, "error calling getsockopt SO_RCVBUF");
923 if(target_rcvbuf
> rcvbuf
) {
924 if(setsockopt(rtpfd
, SOL_SOCKET
, SO_RCVBUF
,
925 &target_rcvbuf
, sizeof target_rcvbuf
) < 0)
926 disorder_error(errno
, "error calling setsockopt SO_RCVBUF %d",
928 /* We try to carry on anyway */
930 disorder_info("changed socket receive buffer from %d to %d",
931 rcvbuf
, target_rcvbuf
);
933 disorder_info("default socket receive buffer %d", rcvbuf
);
934 //info("minbuffer %u maxbuffer %u", minbuffer, maxbuffer);
936 disorder_info("WARNING: -L option can impact performance");
940 if((err
= pthread_create(&tid
, 0, control_thread
, 0)))
941 disorder_fatal(err
, "pthread_create control_thread");
945 unsigned char buffer
[65536];
948 if((fd
= open(dumpfile
, O_RDWR
|O_TRUNC
|O_CREAT
, 0666)) < 0)
949 disorder_fatal(errno
, "opening %s", dumpfile
);
950 /* Fill with 0s to a suitable size */
951 memset(buffer
, 0, sizeof buffer
);
952 for(written
= 0; written
< dump_size
* sizeof(int16_t);
953 written
+= sizeof buffer
) {
954 if(write(fd
, buffer
, sizeof buffer
) < 0)
955 disorder_fatal(errno
, "clearing %s", dumpfile
);
957 /* Map the buffer into memory for convenience */
958 dump_buffer
= mmap(0, dump_size
* sizeof(int16_t), PROT_READ
|PROT_WRITE
,
960 if(dump_buffer
== (void *)-1)
961 disorder_fatal(errno
, "mapping %s", dumpfile
);
962 disorder_info("dumping to %s", dumpfile
);
964 /* Set up output. Currently we only support L16 so there's no harm setting
965 * the format before we know what it is! */
966 uaudio_set_format(44100/*Hz*/, 2/*channels*/,
967 16/*bits/channel*/, 1/*signed*/);
968 uaudio_set("application", "disorder-playrtp");
969 backend
->configure();
970 backend
->start(playrtp_callback
, NULL
);
971 if(backend
->open_mixer
) backend
->open_mixer();
972 /* We receive and convert audio data in a background thread */
973 if((err
= pthread_create(<id
, 0, listen_thread
, 0)))
974 disorder_fatal(err
, "pthread_create listen_thread");
975 /* We have a second thread to add received packets to the queue */
976 if((err
= pthread_create(<id
, 0, queue_thread
, 0)))
977 disorder_fatal(err
, "pthread_create queue_thread");
978 pthread_mutex_lock(&lock
);
981 /* Wait for the buffer to fill up a bit */
982 playrtp_fill_buffer();
983 /* Start playing now */
984 disorder_info("Playing...");
985 next_timestamp
= pheap_first(&packets
)->timestamp
;
987 pthread_mutex_unlock(&lock
);
989 pthread_mutex_lock(&lock
);
990 /* Wait until the buffer empties out
992 * If there's a packet that we can play right now then we definitely
995 * Also if there's at least minbuffer samples we carry on regardless and
996 * insert silence. The assumption is there's been a pause but more data
999 while(nsamples
>= minbuffer
1001 && contains(pheap_first(&packets
), next_timestamp
))) {
1003 time_t now
= xtime(0);
1005 if(now
>= lastlog
+ 60) {
1006 int offset
= nsamples
- minbuffer
;
1007 double offtime
= (double)offset
/ (uaudio_rate
* uaudio_channels
);
1008 disorder_info("%+d samples off (%d.%02ds, %d bytes)",
1010 (int)fabs(offtime
) * (offtime
< 0 ?
-1 : 1),
1011 (int)(fabs(offtime
) * 100) % 100,
1012 offset
* uaudio_bits
/ CHAR_BIT
);
1016 //fprintf(stderr, "%8u/%u (%u) PLAYING\n", nsamples, maxbuffer, minbuffer);
1017 pthread_cond_wait(&cond
, &lock
);
1021 struct packet
*p
= pheap_first(&packets
);
1022 fprintf(stderr
, "nsamples=%u (%u) next_timestamp=%"PRIx32
", first packet is [%"PRIx32
",%"PRIx32
")\n",
1023 nsamples
, minbuffer
, next_timestamp
,p
->timestamp
,p
->timestamp
+p
->nsamples
);
1026 /* Stop playing for a bit until the buffer re-fills */
1027 pthread_mutex_unlock(&lock
);
1028 backend
->deactivate();
1029 pthread_mutex_lock(&lock
);
1041 indent-tabs-mode:nil