2 * This file is part of DisOrder.
3 * Copyright (C) 2007-2009 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>
71 #include "configuration.h"
81 #include "inputline.h"
85 /** @brief Obsolete synonym */
86 #ifndef IPV6_JOIN_GROUP
87 # define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP
90 /** @brief RTP socket */
93 /** @brief Log output */
96 /** @brief Output device */
98 /** @brief Buffer low watermark in samples */
99 unsigned minbuffer = 4 * (2 * 44100) / 10; /* 0.4 seconds */
101 /** @brief Maximum buffer size in samples
103 * We'll stop reading from the network if we have this many samples.
105 static unsigned maxbuffer;
107 /** @brief Received packets
108 * Protected by @ref receive_lock
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.
114 struct packet *received_packets;
116 /** @brief Tail of @ref received_packets
117 * Protected by @ref receive_lock
119 struct packet **received_tail = &received_packets;
121 /** @brief Lock protecting @ref received_packets
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. */
125 pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER;
127 /** @brief Condition variable signalled when @ref received_packets is updated
129 * Used by listen_thread() to notify queue_thread() that it has added another
130 * packet to @ref received_packets. */
131 pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER;
133 /** @brief Length of @ref received_packets */
136 /** @brief Binary heap of received packets */
137 struct pheap packets;
139 /** @brief Total number of samples available
141 * We make this volatile because we inspect it without a protecting lock,
142 * so the usual pthread_* guarantees aren't available.
144 volatile uint32_t nsamples;
146 /** @brief Timestamp of next packet to play.
148 * This is set to the timestamp of the last packet, plus the number of
149 * samples it contained. Only valid if @ref active is nonzero.
151 uint32_t next_timestamp;
153 /** @brief True if actively playing
155 * This is true when playing and false when just buffering. */
158 /** @brief Lock protecting @ref packets */
159 pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
161 /** @brief Condition variable signalled whenever @ref packets is changed */
162 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
164 /** @brief Backend to play with */
165 static const struct uaudio *backend;
167 HEAP_DEFINE(pheap, struct packet *, lt_packet);
169 /** @brief Control socket or NULL */
170 const char *control_socket;
172 /** @brief Buffer for debugging dump
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.
178 * Use clients/dump2wav to convert this to a WAV file, which can then be loaded
179 * into (e.g.) Audacity for further inspection.
181 * All three backends (ALSA, OSS, Core Audio) now support this option.
183 * The idea is to allow the user a few seconds to react to an audible artefact.
185 int16_t *dump_buffer;
187 /** @brief Current index within debugging dump */
190 /** @brief Size of debugging dump in samples */
191 size_t dump_size = 44100/*Hz*/ * 2/*channels*/ * 20/*seconds*/;
193 static const struct option options[] = {
194 { "help", no_argument, 0, 'h' },
195 { "version", no_argument, 0, 'V' },
196 { "debug", no_argument, 0, 'd' },
197 { "device", required_argument, 0, 'D' },
198 { "min", required_argument, 0, 'm' },
199 { "max", required_argument, 0, 'x' },
200 { "rcvbuf", required_argument, 0, 'R' },
201 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
202 { "oss", no_argument, 0, 'o' },
204 #if HAVE_ALSA_ASOUNDLIB_H
205 { "alsa", no_argument, 0, 'a' },
207 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
208 { "core-audio", no_argument, 0, 'c' },
210 { "dump", required_argument, 0, 'r' },
211 { "command", required_argument, 0, 'e' },
212 { "pause-mode", required_argument, 0, 'P' },
213 { "socket", required_argument, 0, 's' },
214 { "config", required_argument, 0, 'C' },
215 { "monitor", no_argument, 0, 'M' },
219 /** @brief Control thread
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
226 * - @c stop will shut the player down
227 * - @c query will send back the reply @c running
228 * - anything else is ignored
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
236 static void *control_thread(void attribute((unused)) *arg) {
237 struct sockaddr_un sa;
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)
250 fatal(errno, "error binding to %s", control_socket);
251 if(listen(sfd, 128) < 0)
252 fatal(errno, "error calling listen on %s", control_socket);
253 info("listening on %s", control_socket);
256 cfd = accept(sfd, (struct sockaddr *)&sa, &salen);
263 fatal(errno, "error calling accept on %s", control_socket);
266 if(!(fp = fdopen(cfd, "r+"))) {
267 error(errno, "error calling fdopen for %s connection", control_socket);
271 if(!inputline(control_socket, fp, &line, '\n')) {
272 if(!strcmp(line, "stop")) {
273 info("stopped via %s", control_socket);
274 exit(0); /* terminate immediately */
276 if(!strcmp(line, "query"))
277 fprintf(fp, "running");
281 error(errno, "error closing %s connection", control_socket);
285 /** @brief Drop the first packet
287 * Assumes that @ref lock is held.
289 static void drop_first_packet(void) {
290 if(pheap_count(&packets)) {
291 struct packet *const p = pheap_remove(&packets);
292 nsamples -= p->nsamples;
293 playrtp_free_packet(p);
294 pthread_cond_broadcast(&cond);
298 /** @brief Background thread adding packets to heap
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
305 static void *queue_thread(void attribute((unused)) *arg) {
309 /* Get the next packet */
310 pthread_mutex_lock(&receive_lock);
311 while(!received_packets) {
312 pthread_cond_wait(&receive_cond, &receive_lock);
314 p = received_packets;
315 received_packets = p->next;
316 if(!received_packets)
317 received_tail = &received_packets;
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);
327 #if HAVE_STUPID_GCC44
332 /** @brief Background thread collecting samples
334 * This function collects samples, perhaps converts them to the target format,
335 * and adds them to the packet list.
337 * It is crucial that the gap between successive calls to read() is as small as
338 * possible: otherwise packets will be dropped.
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.
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.
350 * We keep memory allocation (mostly) very fast by keeping pre-allocated
351 * packets around; see @ref playrtp_new_packet().
353 static void *listen_thread(void attribute((unused)) *arg) {
354 struct packet *p = 0;
356 struct rtp_header header;
363 p = playrtp_new_packet();
364 iov[0].iov_base = &header;
365 iov[0].iov_len = sizeof header;
366 iov[1].iov_base = p->samples_raw;
367 iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
368 n = readv(rtpfd, iov, 2);
374 fatal(errno, "error reading from socket");
377 /* Ignore too-short packets */
378 if((size_t)n <= sizeof (struct rtp_header)) {
379 info("ignored a short packet");
382 timestamp = htonl(header.timestamp);
383 seq = htons(header.seq);
384 /* Ignore packets in the past */
385 if(active && lt(timestamp, next_timestamp)) {
386 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
387 timestamp, next_timestamp);
390 /* Ignore packets with the extension bit set. */
391 if(header.vpxcc & 0x10)
395 p->timestamp = timestamp;
396 /* Convert to target format */
397 if(header.mpt & 0x80)
399 switch(header.mpt & 0x7F) {
401 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
403 /* TODO support other RFC3551 media types (when the speaker does) */
405 fatal(0, "unsupported RTP payload type %d",
408 /* See if packet is silent */
409 const uint16_t *s = p->samples_raw;
417 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
418 seq, timestamp, p->nsamples, timestamp + p->nsamples);
419 /* Stop reading if we've reached the maximum.
421 * This is rather unsatisfactory: it means that if packets get heavily
422 * out of order then we guarantee dropouts. But for now... */
423 if(nsamples >= maxbuffer) {
424 pthread_mutex_lock(&lock);
425 while(nsamples >= maxbuffer) {
426 pthread_cond_wait(&cond, &lock);
428 pthread_mutex_unlock(&lock);
430 /* Add the packet to the receive queue */
431 pthread_mutex_lock(&receive_lock);
433 received_tail = &p->next;
435 pthread_cond_signal(&receive_cond);
436 pthread_mutex_unlock(&receive_lock);
437 /* We'll need a new packet */
442 /** @brief Wait until the buffer is adequately full
444 * Must be called with @ref lock held.
446 void playrtp_fill_buffer(void) {
447 /* Discard current buffer contents */
449 //fprintf(stderr, "%8u/%u (%u) DROPPING\n", nsamples, maxbuffer, minbuffer);
452 info("Buffering...");
453 /* Wait until there's at least minbuffer samples available */
454 while(nsamples < minbuffer) {
455 //fprintf(stderr, "%8u/%u (%u) FILLING\n", nsamples, maxbuffer, minbuffer);
456 pthread_cond_wait(&cond, &lock);
458 /* Start from whatever is earliest */
459 next_timestamp = pheap_first(&packets)->timestamp;
463 /** @brief Find next packet
464 * @return Packet to play or NULL if none found
466 * The return packet is merely guaranteed not to be in the past: it might be
467 * the first packet in the future rather than one that is actually suitable to
470 * Must be called with @ref lock held.
472 struct packet *playrtp_next_packet(void) {
473 while(pheap_count(&packets)) {
474 struct packet *const p = pheap_first(&packets);
475 if(le(p->timestamp + p->nsamples, next_timestamp)) {
476 /* This packet is in the past. Drop it and try another one. */
479 /* This packet is NOT in the past. (It might be in the future
486 /* display usage message and terminate */
487 static void help(void) {
489 " disorder-playrtp [OPTIONS] [[ADDRESS] PORT]\n"
491 " --device, -D DEVICE Output device\n"
492 " --min, -m FRAMES Buffer low water mark\n"
493 " --max, -x FRAMES Buffer maximum size\n"
494 " --rcvbuf, -R BYTES Socket receive buffer size\n"
495 " --config, -C PATH Set configuration file\n"
496 #if HAVE_ALSA_ASOUNDLIB_H
497 " --alsa, -a Use ALSA to play audio\n"
499 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
500 " --oss, -o Use OSS to play audio\n"
502 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
503 " --core-audio, -c Use Core Audio to play audio\n"
505 " --command, -e COMMAND Pipe audio to command.\n"
506 " --pause-mode, -P silence For -e: pauses send silence (default)\n"
507 " --pause-mode, -P suspend For -e: pauses suspend writes\n"
508 " --help, -h Display usage message\n"
509 " --version, -V Display version number\n"
515 static size_t playrtp_callback(void *buffer,
517 void attribute((unused)) *userdata) {
521 pthread_mutex_lock(&lock);
522 /* Get the next packet, junking any that are now in the past */
523 const struct packet *p = playrtp_next_packet();
524 if(p && contains(p, next_timestamp)) {
525 /* This packet is ready to play; the desired next timestamp points
526 * somewhere into it. */
528 /* Timestamp of end of packet */
529 const uint32_t packet_end = p->timestamp + p->nsamples;
531 /* Offset of desired next timestamp into current packet */
532 const uint32_t offset = next_timestamp - p->timestamp;
534 /* Pointer to audio data */
535 const uint16_t *ptr = (void *)(p->samples_raw + offset);
537 /* Compute number of samples left in packet, limited to output buffer
539 samples = packet_end - next_timestamp;
540 if(samples > max_samples)
541 samples = max_samples;
543 /* Copy into buffer, converting to native endianness */
545 int16_t *bufptr = buffer;
547 *bufptr++ = (int16_t)ntohs(*ptr++);
550 silent = !!(p->flags & SILENT);
552 /* There is no suitable packet. We introduce 0s up to the next packet, or
553 * to fill the buffer if there's no next packet or that's too many. The
554 * comparison with max_samples deals with the otherwise troubling overflow
556 samples = p ? p->timestamp - next_timestamp : max_samples;
557 if(samples > max_samples)
558 samples = max_samples;
559 //info("infill by %zu", samples);
560 memset(buffer, 0, samples * uaudio_sample_size);
565 for(size_t i = 0; i < samples; ++i) {
566 dump_buffer[dump_index++] = ((int16_t *)buffer)[i];
567 dump_index %= dump_size;
570 /* Advance timestamp */
571 next_timestamp += samples;
572 /* If we're getting behind then try to drop just silent packets
574 * In theory this shouldn't be necessary. The server is supposed to send
575 * packets at the right rate and compares the number of samples sent with the
576 * time in order to ensure this.
578 * However, various things could throw this off:
580 * - the server's clock could advance at the wrong rate. This would cause it
581 * to mis-estimate the right number of samples to have sent and
582 * inappropriately throttle or speed up.
584 * - playback could happen at the wrong rate. If the playback host's sound
585 * card has a slightly incorrect clock then eventually it will get out
588 * So if we play back slightly slower than the server sends for either of
589 * these reasons then eventually our buffer, and the socket's buffer, will
590 * fill, and the kernel will start dropping packets. The result is audible
593 * Therefore if we're getting behind, we pre-emptively drop silent packets,
594 * since a change in the duration of a silence is less noticeable than a
595 * dropped packet from the middle of continuous music.
597 * (If things go wrong the other way then eventually we run out of packets to
598 * play and are forced to play silence. This doesn't seem to happen in
599 * practice but if it does then in the same way we can artificially extend
600 * silent packets to compensate.)
602 * Dropped packets are always logged; use 'disorder-playrtp --monitor' to
603 * track how close to target buffer occupancy we are on a once-a-minute
606 if(nsamples > minbuffer && silent) {
607 info("dropping %zu samples (%"PRIu32" > %"PRIu32")",
608 samples, nsamples, minbuffer);
611 /* Junk obsolete packets */
612 playrtp_next_packet();
613 pthread_mutex_unlock(&lock);
617 int main(int argc, char **argv) {
619 struct addrinfo *res;
620 struct stringlist sl;
622 int rcvbuf, target_rcvbuf = 0;
625 struct ipv6_mreq mreq6;
627 char *address, *port;
631 struct sockaddr_in in;
632 struct sockaddr_in6 in6;
634 union any_sockaddr mgroup;
635 const char *dumpfile = 0;
638 static const int one = 1;
640 static const struct addrinfo prefs = {
641 .ai_flags = AI_PASSIVE,
642 .ai_family = PF_INET,
643 .ai_socktype = SOCK_DGRAM,
644 .ai_protocol = IPPROTO_UDP
647 /* Timing information is often important to debugging playrtp, so we include
648 * timestamps in the logs */
651 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
652 backend = uaudio_apis[0];
653 while((n = getopt_long(argc, argv, "hVdD:m:x:L:R:aocC:re:P:M", options, 0)) >= 0) {
656 case 'V': version("disorder-playrtp");
657 case 'd': debugging = 1; break;
658 case 'D': uaudio_set("device", optarg); break;
659 case 'm': minbuffer = 2 * atol(optarg); break;
660 case 'x': maxbuffer = 2 * atol(optarg); break;
661 case 'L': logfp = fopen(optarg, "w"); break;
662 case 'R': target_rcvbuf = atoi(optarg); break;
663 #if HAVE_ALSA_ASOUNDLIB_H
664 case 'a': backend = &uaudio_alsa; break;
666 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
667 case 'o': backend = &uaudio_oss; break;
669 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
670 case 'c': backend = &uaudio_coreaudio; break;
672 case 'C': configfile = optarg; break;
673 case 's': control_socket = optarg; break;
674 case 'r': dumpfile = optarg; break;
675 case 'e': backend = &uaudio_command; uaudio_set("command", optarg); break;
676 case 'P': uaudio_set("pause-mode", optarg); break;
677 case 'M': monitor = 1; break;
678 default: fatal(0, "invalid option");
681 if(config_read(0, NULL)) fatal(0, "cannot read configuration");
683 maxbuffer = 2 * minbuffer;
688 /* Get configuration from server */
689 if(!(c = disorder_new(1))) exit(EXIT_FAILURE);
690 if(disorder_connect(c)) exit(EXIT_FAILURE);
691 if(disorder_rtp_address(c, &address, &port)) exit(EXIT_FAILURE);
693 sl.s = xcalloc(2, sizeof *sl.s);
699 /* Use command-line ADDRESS+PORT or just PORT */
704 fatal(0, "usage: disorder-playrtp [OPTIONS] [[ADDRESS] PORT]");
706 /* Look up address and port */
707 if(!(res = get_address(&sl, &prefs, &sockname)))
709 /* Create the socket */
710 if((rtpfd = socket(res->ai_family,
712 res->ai_protocol)) < 0)
713 fatal(errno, "error creating socket");
714 /* Allow multiple listeners */
715 xsetsockopt(rtpfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
716 is_multicast = multicast(res->ai_addr);
717 /* The multicast and unicast/broadcast cases are different enough that they
718 * are totally split. Trying to find commonality between them causes more
719 * trouble that it's worth. */
721 /* Stash the multicast group address */
722 memcpy(&mgroup, res->ai_addr, res->ai_addrlen);
723 switch(res->ai_addr->sa_family) {
725 mgroup.in.sin_port = 0;
728 mgroup.in6.sin6_port = 0;
731 fatal(0, "unsupported family %d", (int)res->ai_addr->sa_family);
733 /* Bind to to the multicast group address */
734 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
735 fatal(errno, "error binding socket to %s", format_sockaddr(res->ai_addr));
736 /* Add multicast group membership */
737 switch(mgroup.sa.sa_family) {
739 mreq.imr_multiaddr = mgroup.in.sin_addr;
740 mreq.imr_interface.s_addr = 0; /* use primary interface */
741 if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
742 &mreq, sizeof mreq) < 0)
743 fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP");
746 mreq6.ipv6mr_multiaddr = mgroup.in6.sin6_addr;
747 memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface);
748 if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
749 &mreq6, sizeof mreq6) < 0)
750 fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP");
753 fatal(0, "unsupported address family %d", res->ai_family);
755 /* Report what we did */
756 info("listening on %s multicast group %s",
757 format_sockaddr(res->ai_addr), format_sockaddr(&mgroup.sa));
760 switch(res->ai_addr->sa_family) {
762 struct sockaddr_in *in = (struct sockaddr_in *)res->ai_addr;
764 memset(&in->sin_addr, 0, sizeof (struct in_addr));
768 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)res->ai_addr;
770 memset(&in6->sin6_addr, 0, sizeof (struct in6_addr));
774 fatal(0, "unsupported family %d", (int)res->ai_addr->sa_family);
776 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
777 fatal(errno, "error binding socket to %s", format_sockaddr(res->ai_addr));
778 /* Report what we did */
779 info("listening on %s", format_sockaddr(res->ai_addr));
782 if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
783 fatal(errno, "error calling getsockopt SO_RCVBUF");
784 if(target_rcvbuf > rcvbuf) {
785 if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
786 &target_rcvbuf, sizeof target_rcvbuf) < 0)
787 error(errno, "error calling setsockopt SO_RCVBUF %d",
789 /* We try to carry on anyway */
791 info("changed socket receive buffer from %d to %d",
792 rcvbuf, target_rcvbuf);
794 info("default socket receive buffer %d", rcvbuf);
795 //info("minbuffer %u maxbuffer %u", minbuffer, maxbuffer);
797 info("WARNING: -L option can impact performance");
801 if((err = pthread_create(&tid, 0, control_thread, 0)))
802 fatal(err, "pthread_create control_thread");
806 unsigned char buffer[65536];
809 if((fd = open(dumpfile, O_RDWR|O_TRUNC|O_CREAT, 0666)) < 0)
810 fatal(errno, "opening %s", dumpfile);
811 /* Fill with 0s to a suitable size */
812 memset(buffer, 0, sizeof buffer);
813 for(written = 0; written < dump_size * sizeof(int16_t);
814 written += sizeof buffer) {
815 if(write(fd, buffer, sizeof buffer) < 0)
816 fatal(errno, "clearing %s", dumpfile);
818 /* Map the buffer into memory for convenience */
819 dump_buffer = mmap(0, dump_size * sizeof(int16_t), PROT_READ|PROT_WRITE,
821 if(dump_buffer == (void *)-1)
822 fatal(errno, "mapping %s", dumpfile);
823 info("dumping to %s", dumpfile);
825 /* Set up output. Currently we only support L16 so there's no harm setting
826 * the format before we know what it is! */
827 uaudio_set_format(44100/*Hz*/, 2/*channels*/,
828 16/*bits/channel*/, 1/*signed*/);
829 backend->start(playrtp_callback, NULL);
830 /* We receive and convert audio data in a background thread */
831 if((err = pthread_create(<id, 0, listen_thread, 0)))
832 fatal(err, "pthread_create listen_thread");
833 /* We have a second thread to add received packets to the queue */
834 if((err = pthread_create(<id, 0, queue_thread, 0)))
835 fatal(err, "pthread_create queue_thread");
836 pthread_mutex_lock(&lock);
839 /* Wait for the buffer to fill up a bit */
840 playrtp_fill_buffer();
841 /* Start playing now */
843 next_timestamp = pheap_first(&packets)->timestamp;
845 pthread_mutex_unlock(&lock);
847 pthread_mutex_lock(&lock);
848 /* Wait until the buffer empties out
850 * If there's a packet that we can play right now then we definitely
853 * Also if there's at least minbuffer samples we carry on regardless and
854 * insert silence. The assumption is there's been a pause but more data
857 while(nsamples >= minbuffer
859 && contains(pheap_first(&packets), next_timestamp))) {
861 time_t now = xtime(0);
863 if(now >= lastlog + 60) {
864 int offset = nsamples - minbuffer;
865 double offtime = (double)offset / (uaudio_rate * uaudio_channels);
866 info("%+d samples off (%d.%02ds, %d bytes)",
868 (int)fabs(offtime) * (offtime < 0 ? -1 : 1),
869 (int)(fabs(offtime) * 100) % 100,
870 offset * uaudio_bits / CHAR_BIT);
874 //fprintf(stderr, "%8u/%u (%u) PLAYING\n", nsamples, maxbuffer, minbuffer);
875 pthread_cond_wait(&cond, &lock);
879 struct packet *p = pheap_first(&packets);
880 fprintf(stderr, "nsamples=%u (%u) next_timestamp=%"PRIx32", first packet is [%"PRIx32",%"PRIx32")\n",
881 nsamples, minbuffer, next_timestamp,p->timestamp,p->timestamp+p->nsamples);
884 /* Stop playing for a bit until the buffer re-fills */
885 pthread_mutex_unlock(&lock);
886 backend->deactivate();
887 pthread_mutex_lock(&lock);