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