2 * This file is part of DisOrder.
3 * Copyright (C) 2007 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 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 /** @file clients/playrtp.c
23 * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</a>)
25 * href="http://developer.apple.com/audio/coreaudio.html">Core Audio</a>)
26 * systems. There is no support for Microsoft Windows yet, and that will in
27 * fact probably an entirely separate program.
29 * The program runs (at least) three threads. listen_thread() is responsible
30 * for reading RTP packets off the wire and adding them to the linked list @ref
31 * received_packets, assuming they are basically sound. queue_thread() takes
32 * packets off this linked list and adds them to @ref packets (an operation
33 * which might be much slower due to contention for @ref lock).
35 * The main thread is responsible for actually playing audio. In ALSA this
36 * means it waits until ALSA says it's ready for more audio which it then
37 * plays. See @ref clients/playrtp-alsa.c.
39 * In Core Audio the main thread is only responsible for starting and stopping
40 * play: the system does the actual playback in its own private thread, and
41 * calls adioproc() to fetch the audio data. See @ref
42 * clients/playrtp-coreaudio.c.
44 * Sometimes it happens that there is no audio available to play. This may
45 * because the server went away, or a packet was dropped, or the server
46 * deliberately did not send any sound because it encountered a silence.
49 * - it is safe to read uint32_t values without a lock protecting them
58 #include <sys/socket.h>
59 #include <sys/types.h>
60 #include <sys/socket.h>
68 #include <netinet/in.h>
73 #include "configuration.h"
84 #define readahead linux_headers_are_borked
86 /** @brief Obsolete synonym */
87 #ifndef IPV6_JOIN_GROUP
88 # define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP
91 /** @brief RTP socket */
94 /** @brief Log output */
97 /** @brief Output device */
100 /** @brief Minimum low watermark
102 * We'll stop playing if there's only this many samples in the buffer. */
103 unsigned minbuffer = 2 * 44100 / 10; /* 0.2 seconds */
105 /** @brief Buffer high watermark
107 * We'll only start playing when this many samples are available. */
108 static unsigned readahead = 2 * 2 * 44100;
110 /** @brief Maximum buffer size
112 * We'll stop reading from the network if we have this many samples. */
113 static unsigned maxbuffer;
115 /** @brief Received packets
116 * Protected by @ref receive_lock
118 * Received packets are added to this list, and queue_thread() picks them off
119 * it and adds them to @ref packets. Whenever a packet is added to it, @ref
120 * receive_cond is signalled.
122 struct packet *received_packets;
124 /** @brief Tail of @ref received_packets
125 * Protected by @ref receive_lock
127 struct packet **received_tail = &received_packets;
129 /** @brief Lock protecting @ref received_packets
131 * Only listen_thread() and queue_thread() ever hold this lock. It is vital
132 * that queue_thread() not hold it any longer than it strictly has to. */
133 pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER;
135 /** @brief Condition variable signalled when @ref received_packets is updated
137 * Used by listen_thread() to notify queue_thread() that it has added another
138 * packet to @ref received_packets. */
139 pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER;
141 /** @brief Length of @ref received_packets */
144 /** @brief Binary heap of received packets */
145 struct pheap packets;
147 /** @brief Total number of samples available
149 * We make this volatile because we inspect it without a protecting lock,
150 * so the usual pthread_* guarantees aren't available.
152 volatile uint32_t nsamples;
154 /** @brief Timestamp of next packet to play.
156 * This is set to the timestamp of the last packet, plus the number of
157 * samples it contained. Only valid if @ref active is nonzero.
159 uint32_t next_timestamp;
161 /** @brief True if actively playing
163 * This is true when playing and false when just buffering. */
166 /** @brief Lock protecting @ref packets */
167 pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
169 /** @brief Condition variable signalled whenever @ref packets is changed */
170 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
172 #if HAVE_ALSA_ASOUNDLIB_H
173 # define DEFAULT_BACKEND playrtp_alsa
174 #elif HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
175 # define DEFAULT_BACKEND playrtp_oss
176 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
177 # define DEFAULT_BACKEND playrtp_coreaudio
179 # error No known backend
182 /** @brief Backend to play with */
183 static void (*backend)(void) = &DEFAULT_BACKEND;
185 HEAP_DEFINE(pheap, struct packet *, lt_packet);
187 static const struct option options[] = {
188 { "help", no_argument, 0, 'h' },
189 { "version", no_argument, 0, 'V' },
190 { "debug", no_argument, 0, 'd' },
191 { "device", required_argument, 0, 'D' },
192 { "min", required_argument, 0, 'm' },
193 { "max", required_argument, 0, 'x' },
194 { "buffer", required_argument, 0, 'b' },
195 { "rcvbuf", required_argument, 0, 'R' },
196 { "multicast", required_argument, 0, 'M' },
197 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
198 { "oss", no_argument, 0, 'o' },
200 #if HAVE_ALSA_ASOUNDLIB_H
201 { "alsa", no_argument, 0, 'a' },
203 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
204 { "core-audio", no_argument, 0, 'c' },
206 { "config", required_argument, 0, 'C' },
210 /** @brief Drop the first packet
212 * Assumes that @ref lock is held.
214 static void drop_first_packet(void) {
215 if(pheap_count(&packets)) {
216 struct packet *const p = pheap_remove(&packets);
217 nsamples -= p->nsamples;
218 playrtp_free_packet(p);
219 pthread_cond_broadcast(&cond);
223 /** @brief Background thread adding packets to heap
225 * This just transfers packets from @ref received_packets to @ref packets. It
226 * is important that it holds @ref receive_lock for as little time as possible,
227 * in order to minimize the interval between calls to read() in
230 static void *queue_thread(void attribute((unused)) *arg) {
234 /* Get the next packet */
235 pthread_mutex_lock(&receive_lock);
236 while(!received_packets)
237 pthread_cond_wait(&receive_cond, &receive_lock);
238 p = received_packets;
239 received_packets = p->next;
240 if(!received_packets)
241 received_tail = &received_packets;
243 pthread_mutex_unlock(&receive_lock);
244 /* Add it to the heap */
245 pthread_mutex_lock(&lock);
246 pheap_insert(&packets, p);
247 nsamples += p->nsamples;
248 pthread_cond_broadcast(&cond);
249 pthread_mutex_unlock(&lock);
253 /** @brief Background thread collecting samples
255 * This function collects samples, perhaps converts them to the target format,
256 * and adds them to the packet list.
258 * It is crucial that the gap between successive calls to read() is as small as
259 * possible: otherwise packets will be dropped.
261 * We use a binary heap to ensure that the unavoidable effort is at worst
262 * logarithmic in the total number of packets - in fact if packets are mostly
263 * received in order then we will largely do constant work per packet since the
264 * newest packet will always be last.
266 * Of more concern is that we must acquire the lock on the heap to add a packet
267 * to it. If this proves a problem in practice then the answer would be
268 * (probably doubly) linked list with new packets added the end and a second
269 * thread which reads packets off the list and adds them to the heap.
271 * We keep memory allocation (mostly) very fast by keeping pre-allocated
272 * packets around; see @ref playrtp_new_packet().
274 static void *listen_thread(void attribute((unused)) *arg) {
275 struct packet *p = 0;
277 struct rtp_header header;
284 p = playrtp_new_packet();
285 iov[0].iov_base = &header;
286 iov[0].iov_len = sizeof header;
287 iov[1].iov_base = p->samples_raw;
288 iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
289 n = readv(rtpfd, iov, 2);
295 fatal(errno, "error reading from socket");
298 /* Ignore too-short packets */
299 if((size_t)n <= sizeof (struct rtp_header)) {
300 info("ignored a short packet");
303 timestamp = htonl(header.timestamp);
304 seq = htons(header.seq);
305 /* Ignore packets in the past */
306 if(active && lt(timestamp, next_timestamp)) {
307 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
308 timestamp, next_timestamp);
313 p->timestamp = timestamp;
314 /* Convert to target format */
315 if(header.mpt & 0x80)
317 switch(header.mpt & 0x7F) {
319 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
321 /* TODO support other RFC3551 media types (when the speaker does) */
323 fatal(0, "unsupported RTP payload type %d",
327 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
328 seq, timestamp, p->nsamples, timestamp + p->nsamples);
329 /* Stop reading if we've reached the maximum.
331 * This is rather unsatisfactory: it means that if packets get heavily
332 * out of order then we guarantee dropouts. But for now... */
333 if(nsamples >= maxbuffer) {
334 pthread_mutex_lock(&lock);
335 while(nsamples >= maxbuffer)
336 pthread_cond_wait(&cond, &lock);
337 pthread_mutex_unlock(&lock);
339 /* Add the packet to the receive queue */
340 pthread_mutex_lock(&receive_lock);
342 received_tail = &p->next;
344 pthread_cond_signal(&receive_cond);
345 pthread_mutex_unlock(&receive_lock);
346 /* We'll need a new packet */
351 /** @brief Wait until the buffer is adequately full
353 * Must be called with @ref lock held.
355 void playrtp_fill_buffer(void) {
358 info("Buffering...");
359 while(nsamples < readahead)
360 pthread_cond_wait(&cond, &lock);
361 next_timestamp = pheap_first(&packets)->timestamp;
365 /** @brief Find next packet
366 * @return Packet to play or NULL if none found
368 * The return packet is merely guaranteed not to be in the past: it might be
369 * the first packet in the future rather than one that is actually suitable to
372 * Must be called with @ref lock held.
374 struct packet *playrtp_next_packet(void) {
375 while(pheap_count(&packets)) {
376 struct packet *const p = pheap_first(&packets);
377 if(le(p->timestamp + p->nsamples, next_timestamp)) {
378 /* This packet is in the past. Drop it and try another one. */
381 /* This packet is NOT in the past. (It might be in the future
388 /** @brief Play an RTP stream
390 * This is the guts of the program. It is responsible for:
391 * - starting the listening thread
392 * - opening the audio device
393 * - reading ahead to build up a buffer
394 * - arranging for audio to be played
395 * - detecting when the buffer has got too small and re-buffering
397 static void play_rtp(void) {
400 /* We receive and convert audio data in a background thread */
401 pthread_create(<id, 0, listen_thread, 0);
402 /* We have a second thread to add received packets to the queue */
403 pthread_create(<id, 0, queue_thread, 0);
404 /* The rest of the work is backend-specific */
408 /* display usage message and terminate */
409 static void help(void) {
411 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
413 " --device, -D DEVICE Output device\n"
414 " --min, -m FRAMES Buffer low water mark\n"
415 " --buffer, -b FRAMES Buffer high water mark\n"
416 " --max, -x FRAMES Buffer maximum size\n"
417 " --rcvbuf, -R BYTES Socket receive buffer size\n"
418 " --multicast, -M GROUP Join multicast group\n"
419 " --config, -C PATH Set configuration file\n"
420 #if HAVE_ALSA_ASOUNDLIB_H
421 " --alsa, -a Use ALSA to play audio\n"
423 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
424 " --oss, -o Use OSS to play audio\n"
426 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
427 " --core-audio, -c Use Core Audio to play audio\n"
429 " --help, -h Display usage message\n"
430 " --version, -V Display version number\n"
436 /* display version number and terminate */
437 static void version(void) {
438 xprintf("disorder-playrtp version %s\n", disorder_version_string);
443 int main(int argc, char **argv) {
445 struct addrinfo *res;
446 struct stringlist sl;
448 int rcvbuf, target_rcvbuf = 131072;
450 char *multicast_group = 0;
452 struct ipv6_mreq mreq6;
454 char *address, *port;
456 static const struct addrinfo prefs = {
468 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
469 while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:R:M:aocC:", options, 0)) >= 0) {
473 case 'd': debugging = 1; break;
474 case 'D': device = optarg; break;
475 case 'm': minbuffer = 2 * atol(optarg); break;
476 case 'b': readahead = 2 * atol(optarg); break;
477 case 'x': maxbuffer = 2 * atol(optarg); break;
478 case 'L': logfp = fopen(optarg, "w"); break;
479 case 'R': target_rcvbuf = atoi(optarg); break;
480 case 'M': multicast_group = optarg; break;
481 #if HAVE_ALSA_ASOUNDLIB_H
482 case 'a': backend = playrtp_alsa; break;
484 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
485 case 'o': backend = playrtp_oss; break;
487 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
488 case 'c': backend = playrtp_coreaudio; break;
490 case 'C': configfile = optarg; break;
491 default: fatal(0, "invalid option");
494 if(config_read(0)) fatal(0, "cannot read configuration");
496 maxbuffer = 4 * readahead;
502 if(!(c = disorder_new(1))) exit(EXIT_FAILURE);
503 if(disorder_connect(c)) exit(EXIT_FAILURE);
504 if(disorder_rtp_address(c, &address, &port)) exit(EXIT_FAILURE);
507 /* set multicast_group if address is a multicast address */
514 fatal(0, "usage: disorder-playrtp [OPTIONS] [ADDRESS [PORT]]");
516 /* Listen for inbound audio data */
517 if(!(res = get_address(&sl, &prefs, &sockname)))
519 info("listening on %s", sockname);
520 if((rtpfd = socket(res->ai_family,
522 res->ai_protocol)) < 0)
523 fatal(errno, "error creating socket");
524 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
525 fatal(errno, "error binding socket to %s", sockname);
526 if(multicast_group) {
527 if((n = getaddrinfo(multicast_group, 0, &prefs, &res)))
528 fatal(0, "getaddrinfo %s: %s", multicast_group, gai_strerror(n));
529 switch(res->ai_family) {
531 mreq.imr_multiaddr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
532 mreq.imr_interface.s_addr = 0; /* use primary interface */
533 if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
534 &mreq, sizeof mreq) < 0)
535 fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP");
538 mreq6.ipv6mr_multiaddr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
539 memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface);
540 if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
541 &mreq6, sizeof mreq6) < 0)
542 fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP");
545 fatal(0, "unsupported address family %d", res->ai_family);
549 if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
550 fatal(errno, "error calling getsockopt SO_RCVBUF");
551 if(target_rcvbuf > rcvbuf) {
552 if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
553 &target_rcvbuf, sizeof target_rcvbuf) < 0)
554 error(errno, "error calling setsockopt SO_RCVBUF %d",
556 /* We try to carry on anyway */
558 info("changed socket receive buffer from %d to %d",
559 rcvbuf, target_rcvbuf);
561 info("default socket receive buffer %d", rcvbuf);
563 info("WARNING: -L option can impact performance");