chiark / gitweb /
Larger silent interval for pauses; spinning in sub-millisecond
[disorder] / clients / playrtp.c
CommitLineData
e83d0967
RK
1/*
2 * This file is part of DisOrder.
5aff007d 3 * Copyright (C) 2007, 2008 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>
e83d0967
RK
67
68#include "log.h"
69#include "mem.h"
70#include "configuration.h"
71#include "addr.h"
72#include "syscalls.h"
73#include "rtp.h"
0b75463f 74#include "defs.h"
28bacdc0
RK
75#include "vector.h"
76#include "heap.h"
189e9830 77#include "timeval.h"
a7e9570a 78#include "client.h"
8e3fe3d8 79#include "playrtp.h"
a99c4e9a 80#include "inputline.h"
3fbdc96d 81#include "version.h"
7a2c7068 82#include "uaudio.h"
e83d0967 83
e3426f7b
RK
84/** @brief Obsolete synonym */
85#ifndef IPV6_JOIN_GROUP
86# define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP
87#endif
88
0b75463f 89/** @brief RTP socket */
e83d0967
RK
90static int rtpfd;
91
345ebe66
RK
92/** @brief Log output */
93static FILE *logfp;
94
0b75463f 95/** @brief Output device */
0b75463f 96
9086a105 97/** @brief Minimum low watermark
0b75463f 98 *
99 * We'll stop playing if there's only this many samples in the buffer. */
c593cf7c 100unsigned minbuffer = 2 * 44100 / 10; /* 0.2 seconds */
0b75463f 101
9086a105
RK
102/** @brief Maximum buffer size
103 *
104 * We'll stop reading from the network if we have this many samples. */
105static unsigned maxbuffer;
106
189e9830
RK
107/** @brief Received packets
108 * Protected by @ref receive_lock
109 *
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.
113 */
8e3fe3d8 114struct packet *received_packets;
189e9830
RK
115
116/** @brief Tail of @ref received_packets
117 * Protected by @ref receive_lock
118 */
8e3fe3d8 119struct packet **received_tail = &received_packets;
189e9830
RK
120
121/** @brief Lock protecting @ref received_packets
122 *
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. */
8e3fe3d8 125pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER;
189e9830
RK
126
127/** @brief Condition variable signalled when @ref received_packets is updated
128 *
129 * Used by listen_thread() to notify queue_thread() that it has added another
130 * packet to @ref received_packets. */
8e3fe3d8 131pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER;
189e9830
RK
132
133/** @brief Length of @ref received_packets */
8e3fe3d8 134uint32_t nreceived;
28bacdc0
RK
135
136/** @brief Binary heap of received packets */
8e3fe3d8 137struct pheap packets;
28bacdc0 138
189e9830
RK
139/** @brief Total number of samples available
140 *
141 * We make this volatile because we inspect it without a protecting lock,
142 * so the usual pthread_* guarantees aren't available.
143 */
8e3fe3d8 144volatile uint32_t nsamples;
0b75463f 145
146/** @brief Timestamp of next packet to play.
147 *
148 * This is set to the timestamp of the last packet, plus the number of
09ee2f0d 149 * samples it contained. Only valid if @ref active is nonzero.
0b75463f 150 */
8e3fe3d8 151uint32_t next_timestamp;
e83d0967 152
09ee2f0d 153/** @brief True if actively playing
154 *
155 * This is true when playing and false when just buffering. */
8e3fe3d8 156int active;
09ee2f0d 157
189e9830 158/** @brief Lock protecting @ref packets */
8e3fe3d8 159pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
189e9830
RK
160
161/** @brief Condition variable signalled whenever @ref packets is changed */
8e3fe3d8 162pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
2c7c9eae 163
c593cf7c 164/** @brief Backend to play with */
7a2c7068 165static const struct uaudio *backend;
c593cf7c 166
8e3fe3d8 167HEAP_DEFINE(pheap, struct packet *, lt_packet);
e83d0967 168
a99c4e9a
RK
169/** @brief Control socket or NULL */
170const char *control_socket;
171
b28bddbb
RK
172/** @brief Buffer for debugging dump
173 *
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.
177 *
178 * Use clients/dump2wav to convert this to a WAV file, which can then be loaded
179 * into (e.g.) Audacity for further inspection.
180 *
181 * All three backends (ALSA, OSS, Core Audio) now support this option.
182 *
183 * The idea is to allow the user a few seconds to react to an audible artefact.
184 */
e9b635a3 185int16_t *dump_buffer;
b28bddbb
RK
186
187/** @brief Current index within debugging dump */
e9b635a3 188size_t dump_index;
b28bddbb
RK
189
190/** @brief Size of debugging dump in samples */
191size_t dump_size = 44100/*Hz*/ * 2/*channels*/ * 20/*seconds*/;
e9b635a3 192
e83d0967
RK
193static const struct option options[] = {
194 { "help", no_argument, 0, 'h' },
195 { "version", no_argument, 0, 'V' },
196 { "debug", no_argument, 0, 'd' },
0b75463f 197 { "device", required_argument, 0, 'D' },
1153fd23 198 { "min", required_argument, 0, 'm' },
9086a105 199 { "max", required_argument, 0, 'x' },
1f10f780 200 { "rcvbuf", required_argument, 0, 'R' },
a9f0ad12 201#if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
c593cf7c 202 { "oss", no_argument, 0, 'o' },
203#endif
146e86fb 204#if HAVE_ALSA_ASOUNDLIB_H
c593cf7c 205 { "alsa", no_argument, 0, 'a' },
206#endif
207#if HAVE_COREAUDIO_AUDIOHARDWARE_H
208 { "core-audio", no_argument, 0, 'c' },
209#endif
e9b635a3 210 { "dump", required_argument, 0, 'r' },
e979b844 211 { "command", required_argument, 0, 'e' },
287ad384 212 { "pause-mode", required_argument, 0, 'P' },
a99c4e9a 213 { "socket", required_argument, 0, 's' },
a7e9570a 214 { "config", required_argument, 0, 'C' },
e83d0967
RK
215 { 0, 0, 0, 0 }
216};
217
a99c4e9a
RK
218/** @brief Control thread
219 *
220 * This thread is responsible for accepting control commands from Disobedience
221 * (or other controllers) over an AF_UNIX stream socket with a path specified
222 * by the @c --socket option. The protocol uses simple string commands and
223 * replies:
224 *
225 * - @c stop will shut the player down
226 * - @c query will send back the reply @c running
227 * - anything else is ignored
228 *
229 * Commands and response strings terminated by shutting down the connection or
230 * by a newline. No attempt is made to multiplex multiple clients so it is
231 * important that the command be sent as soon as the connection is made - it is
232 * assumed that both parties to the protocol are entirely cooperating with one
233 * another.
234 */
235static void *control_thread(void attribute((unused)) *arg) {
236 struct sockaddr_un sa;
237 int sfd, cfd;
238 char *line;
239 socklen_t salen;
240 FILE *fp;
241
242 assert(control_socket);
243 unlink(control_socket);
244 memset(&sa, 0, sizeof sa);
245 sa.sun_family = AF_UNIX;
246 strcpy(sa.sun_path, control_socket);
247 sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
248 if(bind(sfd, (const struct sockaddr *)&sa, sizeof sa) < 0)
249 fatal(errno, "error binding to %s", control_socket);
250 if(listen(sfd, 128) < 0)
251 fatal(errno, "error calling listen on %s", control_socket);
252 info("listening on %s", control_socket);
253 for(;;) {
254 salen = sizeof sa;
255 cfd = accept(sfd, (struct sockaddr *)&sa, &salen);
256 if(cfd < 0) {
257 switch(errno) {
258 case EINTR:
259 case EAGAIN:
260 break;
261 default:
262 fatal(errno, "error calling accept on %s", control_socket);
263 }
264 }
265 if(!(fp = fdopen(cfd, "r+"))) {
266 error(errno, "error calling fdopen for %s connection", control_socket);
267 close(cfd);
268 continue;
269 }
270 if(!inputline(control_socket, fp, &line, '\n')) {
271 if(!strcmp(line, "stop")) {
272 info("stopped via %s", control_socket);
273 exit(0); /* terminate immediately */
274 }
275 if(!strcmp(line, "query"))
276 fprintf(fp, "running");
277 xfree(line);
278 }
279 if(fclose(fp) < 0)
280 error(errno, "error closing %s connection", control_socket);
281 }
282}
283
28bacdc0
RK
284/** @brief Drop the first packet
285 *
286 * Assumes that @ref lock is held.
287 */
288static void drop_first_packet(void) {
289 if(pheap_count(&packets)) {
290 struct packet *const p = pheap_remove(&packets);
291 nsamples -= p->nsamples;
c593cf7c 292 playrtp_free_packet(p);
2c7c9eae 293 pthread_cond_broadcast(&cond);
2c7c9eae 294 }
9086a105
RK
295}
296
189e9830
RK
297/** @brief Background thread adding packets to heap
298 *
299 * This just transfers packets from @ref received_packets to @ref packets. It
300 * is important that it holds @ref receive_lock for as little time as possible,
301 * in order to minimize the interval between calls to read() in
302 * listen_thread().
303 */
304static void *queue_thread(void attribute((unused)) *arg) {
305 struct packet *p;
306
307 for(;;) {
308 /* Get the next packet */
309 pthread_mutex_lock(&receive_lock);
4dadf1a2 310 while(!received_packets) {
189e9830 311 pthread_cond_wait(&receive_cond, &receive_lock);
4dadf1a2 312 }
189e9830
RK
313 p = received_packets;
314 received_packets = p->next;
315 if(!received_packets)
316 received_tail = &received_packets;
317 --nreceived;
318 pthread_mutex_unlock(&receive_lock);
319 /* Add it to the heap */
320 pthread_mutex_lock(&lock);
321 pheap_insert(&packets, p);
322 nsamples += p->nsamples;
323 pthread_cond_broadcast(&cond);
324 pthread_mutex_unlock(&lock);
325 }
326}
327
09ee2f0d 328/** @brief Background thread collecting samples
0b75463f 329 *
330 * This function collects samples, perhaps converts them to the target format,
b0fdc63d 331 * and adds them to the packet list.
332 *
333 * It is crucial that the gap between successive calls to read() is as small as
334 * possible: otherwise packets will be dropped.
335 *
336 * We use a binary heap to ensure that the unavoidable effort is at worst
337 * logarithmic in the total number of packets - in fact if packets are mostly
338 * received in order then we will largely do constant work per packet since the
339 * newest packet will always be last.
340 *
341 * Of more concern is that we must acquire the lock on the heap to add a packet
342 * to it. If this proves a problem in practice then the answer would be
343 * (probably doubly) linked list with new packets added the end and a second
344 * thread which reads packets off the list and adds them to the heap.
345 *
346 * We keep memory allocation (mostly) very fast by keeping pre-allocated
c593cf7c 347 * packets around; see @ref playrtp_new_packet().
b0fdc63d 348 */
0b75463f 349static void *listen_thread(void attribute((unused)) *arg) {
2c7c9eae 350 struct packet *p = 0;
0b75463f 351 int n;
2c7c9eae
RK
352 struct rtp_header header;
353 uint16_t seq;
354 uint32_t timestamp;
355 struct iovec iov[2];
e83d0967
RK
356
357 for(;;) {
189e9830 358 if(!p)
c593cf7c 359 p = playrtp_new_packet();
2c7c9eae
RK
360 iov[0].iov_base = &header;
361 iov[0].iov_len = sizeof header;
362 iov[1].iov_base = p->samples_raw;
b64efe7e 363 iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
2c7c9eae 364 n = readv(rtpfd, iov, 2);
e83d0967
RK
365 if(n < 0) {
366 switch(errno) {
367 case EINTR:
368 continue;
369 default:
370 fatal(errno, "error reading from socket");
371 }
372 }
0b75463f 373 /* Ignore too-short packets */
345ebe66
RK
374 if((size_t)n <= sizeof (struct rtp_header)) {
375 info("ignored a short packet");
0b75463f 376 continue;
345ebe66 377 }
2c7c9eae
RK
378 timestamp = htonl(header.timestamp);
379 seq = htons(header.seq);
09ee2f0d 380 /* Ignore packets in the past */
2c7c9eae 381 if(active && lt(timestamp, next_timestamp)) {
c0e41690 382 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
2c7c9eae 383 timestamp, next_timestamp);
09ee2f0d 384 continue;
c0e41690 385 }
28f1495a
RK
386 /* Ignore packets with the extension bit set. */
387 if(header.vpxcc & 0x10)
388 continue;
189e9830 389 p->next = 0;
58b5a68f 390 p->flags = 0;
2c7c9eae 391 p->timestamp = timestamp;
e83d0967 392 /* Convert to target format */
58b5a68f
RK
393 if(header.mpt & 0x80)
394 p->flags |= IDLE;
2c7c9eae 395 switch(header.mpt & 0x7F) {
4fd38868 396 case 10: /* L16 */
2c7c9eae 397 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
e83d0967
RK
398 break;
399 /* TODO support other RFC3551 media types (when the speaker does) */
400 default:
0b75463f 401 fatal(0, "unsupported RTP payload type %d",
2c7c9eae 402 header.mpt & 0x7F);
e83d0967 403 }
345ebe66
RK
404 if(logfp)
405 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
2c7c9eae 406 seq, timestamp, p->nsamples, timestamp + p->nsamples);
0b75463f 407 /* Stop reading if we've reached the maximum.
408 *
409 * This is rather unsatisfactory: it means that if packets get heavily
410 * out of order then we guarantee dropouts. But for now... */
345ebe66 411 if(nsamples >= maxbuffer) {
189e9830 412 pthread_mutex_lock(&lock);
4dadf1a2 413 while(nsamples >= maxbuffer) {
345ebe66 414 pthread_cond_wait(&cond, &lock);
4dadf1a2 415 }
189e9830 416 pthread_mutex_unlock(&lock);
345ebe66 417 }
189e9830
RK
418 /* Add the packet to the receive queue */
419 pthread_mutex_lock(&receive_lock);
420 *received_tail = p;
421 received_tail = &p->next;
422 ++nreceived;
423 pthread_cond_signal(&receive_cond);
424 pthread_mutex_unlock(&receive_lock);
58b5a68f
RK
425 /* We'll need a new packet */
426 p = 0;
e83d0967
RK
427 }
428}
429
5626f6d2
RK
430/** @brief Wait until the buffer is adequately full
431 *
432 * Must be called with @ref lock held.
433 */
c593cf7c 434void playrtp_fill_buffer(void) {
0e72bf84 435 /* Discard current buffer contents */
bfd27c14
RK
436 while(nsamples)
437 drop_first_packet();
5626f6d2 438 info("Buffering...");
0e72bf84
RK
439 /* Wait until there's at least minbuffer samples available */
440 while(nsamples < minbuffer) {
5626f6d2 441 pthread_cond_wait(&cond, &lock);
4dadf1a2 442 }
0e72bf84 443 /* Start from whatever is earliest */
5626f6d2
RK
444 next_timestamp = pheap_first(&packets)->timestamp;
445 active = 1;
446}
447
448/** @brief Find next packet
449 * @return Packet to play or NULL if none found
450 *
451 * The return packet is merely guaranteed not to be in the past: it might be
452 * the first packet in the future rather than one that is actually suitable to
453 * play.
454 *
455 * Must be called with @ref lock held.
456 */
c593cf7c 457struct packet *playrtp_next_packet(void) {
5626f6d2
RK
458 while(pheap_count(&packets)) {
459 struct packet *const p = pheap_first(&packets);
460 if(le(p->timestamp + p->nsamples, next_timestamp)) {
461 /* This packet is in the past. Drop it and try another one. */
462 drop_first_packet();
463 } else
464 /* This packet is NOT in the past. (It might be in the future
465 * however.) */
466 return p;
467 }
468 return 0;
469}
470
e83d0967
RK
471/* display usage message and terminate */
472static void help(void) {
473 xprintf("Usage:\n"
c897bb65 474 " disorder-playrtp [OPTIONS] [[ADDRESS] PORT]\n"
e83d0967 475 "Options:\n"
1153fd23 476 " --device, -D DEVICE Output device\n"
477 " --min, -m FRAMES Buffer low water mark\n"
9086a105 478 " --max, -x FRAMES Buffer maximum size\n"
1f10f780 479 " --rcvbuf, -R BYTES Socket receive buffer size\n"
a7e9570a 480 " --config, -C PATH Set configuration file\n"
146e86fb 481#if HAVE_ALSA_ASOUNDLIB_H
c593cf7c 482 " --alsa, -a Use ALSA to play audio\n"
483#endif
a9f0ad12 484#if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
c593cf7c 485 " --oss, -o Use OSS to play audio\n"
486#endif
487#if HAVE_COREAUDIO_AUDIOHARDWARE_H
488 " --core-audio, -c Use Core Audio to play audio\n"
489#endif
287ad384
RK
490 " --command, -e COMMAND Pipe audio to command.\n"
491 " --pause-mode, -P silence For -e: pauses send silence (default)\n"
492 " --pause-mode, -P suspend For -e: pauses suspend writes\n"
9086a105
RK
493 " --help, -h Display usage message\n"
494 " --version, -V Display version number\n"
495 );
e83d0967
RK
496 xfclose(stdout);
497 exit(0);
498}
499
4fd38868 500static size_t playrtp_callback(void *buffer,
7a2c7068
RK
501 size_t max_samples,
502 void attribute((unused)) *userdata) {
503 size_t samples;
504
505 pthread_mutex_lock(&lock);
506 /* Get the next packet, junking any that are now in the past */
507 const struct packet *p = playrtp_next_packet();
508 if(p && contains(p, next_timestamp)) {
509 /* This packet is ready to play; the desired next timestamp points
510 * somewhere into it. */
511
512 /* Timestamp of end of packet */
513 const uint32_t packet_end = p->timestamp + p->nsamples;
514
515 /* Offset of desired next timestamp into current packet */
516 const uint32_t offset = next_timestamp - p->timestamp;
517
518 /* Pointer to audio data */
519 const uint16_t *ptr = (void *)(p->samples_raw + offset);
520
521 /* Compute number of samples left in packet, limited to output buffer
522 * size */
523 samples = packet_end - next_timestamp;
524 if(samples > max_samples)
525 samples = max_samples;
526
527 /* Copy into buffer, converting to native endianness */
528 size_t i = samples;
529 int16_t *bufptr = buffer;
530 while(i > 0) {
531 *bufptr++ = (int16_t)ntohs(*ptr++);
532 --i;
533 }
534 /* We don't junk the packet here; a subsequent call to
535 * playrtp_next_packet() will dispose of it (if it's actually done with). */
536 } else {
537 /* There is no suitable packet. We introduce 0s up to the next packet, or
538 * to fill the buffer if there's no next packet or that's too many. The
539 * comparison with max_samples deals with the otherwise troubling overflow
540 * case. */
541 samples = p ? p->timestamp - next_timestamp : max_samples;
542 if(samples > max_samples)
543 samples = max_samples;
544 //info("infill by %zu", samples);
4fd38868 545 memset(buffer, 0, samples * uaudio_sample_size);
7a2c7068
RK
546 }
547 /* Debug dump */
548 if(dump_buffer) {
549 for(size_t i = 0; i < samples; ++i) {
4fd38868 550 dump_buffer[dump_index++] = ((int16_t *)buffer)[i];
7a2c7068
RK
551 dump_index %= dump_size;
552 }
553 }
554 /* Advance timestamp */
555 next_timestamp += samples;
556 pthread_mutex_unlock(&lock);
557 return samples;
558}
559
e83d0967 560int main(int argc, char **argv) {
a99c4e9a 561 int n, err;
e83d0967
RK
562 struct addrinfo *res;
563 struct stringlist sl;
0b75463f 564 char *sockname;
0e72bf84 565 int rcvbuf, target_rcvbuf = 0;
1f10f780 566 socklen_t len;
23205f9c
RK
567 struct ip_mreq mreq;
568 struct ipv6_mreq mreq6;
a7e9570a
RK
569 disorder_client *c;
570 char *address, *port;
6fba990c
RK
571 int is_multicast;
572 union any_sockaddr {
573 struct sockaddr sa;
574 struct sockaddr_in in;
575 struct sockaddr_in6 in6;
576 };
577 union any_sockaddr mgroup;
e9b635a3 578 const char *dumpfile = 0;
7a2c7068 579 pthread_t ltid;
983c3357 580 static const int one = 1;
e83d0967 581
0b75463f 582 static const struct addrinfo prefs = {
66613034
RK
583 .ai_flags = AI_PASSIVE,
584 .ai_family = PF_INET,
585 .ai_socktype = SOCK_DGRAM,
586 .ai_protocol = IPPROTO_UDP
e83d0967
RK
587 };
588
9d7a6129
RK
589 /* Timing information is often important to debugging playrtp, so we include
590 * timestamps in the logs */
591 logdate = 1;
e83d0967
RK
592 mem_init();
593 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
902ccab0 594 backend = uaudio_apis[0];
0e72bf84 595 while((n = getopt_long(argc, argv, "hVdD:m:x:L:R:M:aocC:re:P:", options, 0)) >= 0) {
e83d0967
RK
596 switch(n) {
597 case 'h': help();
3fbdc96d 598 case 'V': version("disorder-playrtp");
e83d0967 599 case 'd': debugging = 1; break;
e979b844 600 case 'D': uaudio_set("device", optarg); break;
1153fd23 601 case 'm': minbuffer = 2 * atol(optarg); break;
9086a105 602 case 'x': maxbuffer = 2 * atol(optarg); break;
345ebe66 603 case 'L': logfp = fopen(optarg, "w"); break;
1f10f780 604 case 'R': target_rcvbuf = atoi(optarg); break;
146e86fb 605#if HAVE_ALSA_ASOUNDLIB_H
7a2c7068 606 case 'a': backend = &uaudio_alsa; break;
c593cf7c 607#endif
a9f0ad12 608#if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
7a2c7068 609 case 'o': backend = &uaudio_oss; break;
c593cf7c 610#endif
611#if HAVE_COREAUDIO_AUDIOHARDWARE_H
7a2c7068 612 case 'c': backend = &uaudio_coreaudio; break;
c593cf7c 613#endif
a7e9570a 614 case 'C': configfile = optarg; break;
a99c4e9a 615 case 's': control_socket = optarg; break;
e9b635a3 616 case 'r': dumpfile = optarg; break;
e979b844 617 case 'e': backend = &uaudio_command; uaudio_set("command", optarg); break;
287ad384 618 case 'P': uaudio_set("pause-mode", optarg); break;
e83d0967
RK
619 default: fatal(0, "invalid option");
620 }
621 }
a7e9570a 622 if(config_read(0)) fatal(0, "cannot read configuration");
9086a105 623 if(!maxbuffer)
0e72bf84 624 maxbuffer = 2 * minbuffer;
e83d0967
RK
625 argc -= optind;
626 argv += optind;
a7e9570a
RK
627 switch(argc) {
628 case 0:
6fba990c 629 /* Get configuration from server */
a7e9570a
RK
630 if(!(c = disorder_new(1))) exit(EXIT_FAILURE);
631 if(disorder_connect(c)) exit(EXIT_FAILURE);
632 if(disorder_rtp_address(c, &address, &port)) exit(EXIT_FAILURE);
6fba990c
RK
633 sl.n = 2;
634 sl.s = xcalloc(2, sizeof *sl.s);
635 sl.s[0] = address;
636 sl.s[1] = port;
a7e9570a 637 break;
6fba990c 638 case 1:
a7e9570a 639 case 2:
6fba990c 640 /* Use command-line ADDRESS+PORT or just PORT */
a7e9570a
RK
641 sl.n = argc;
642 sl.s = argv;
643 break;
644 default:
6fba990c 645 fatal(0, "usage: disorder-playrtp [OPTIONS] [[ADDRESS] PORT]");
a7e9570a 646 }
6fba990c 647 /* Look up address and port */
0b75463f 648 if(!(res = get_address(&sl, &prefs, &sockname)))
e83d0967 649 exit(1);
6fba990c 650 /* Create the socket */
e83d0967
RK
651 if((rtpfd = socket(res->ai_family,
652 res->ai_socktype,
653 res->ai_protocol)) < 0)
654 fatal(errno, "error creating socket");
983c3357
RK
655 /* Allow multiple listeners */
656 xsetsockopt(rtpfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
657 is_multicast = multicast(res->ai_addr);
658 /* The multicast and unicast/broadcast cases are different enough that they
659 * are totally split. Trying to find commonality between them causes more
660 * trouble that it's worth. */
661 if(is_multicast) {
662 /* Stash the multicast group address */
6fba990c
RK
663 memcpy(&mgroup, res->ai_addr, res->ai_addrlen);
664 switch(res->ai_addr->sa_family) {
665 case AF_INET:
666 mgroup.in.sin_port = 0;
667 break;
668 case AF_INET6:
669 mgroup.in6.sin6_port = 0;
670 break;
983c3357
RK
671 default:
672 fatal(0, "unsupported family %d", (int)res->ai_addr->sa_family);
6fba990c 673 }
983c3357
RK
674 /* Bind to to the multicast group address */
675 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
676 fatal(errno, "error binding socket to %s", format_sockaddr(res->ai_addr));
677 /* Add multicast group membership */
6fba990c 678 switch(mgroup.sa.sa_family) {
23205f9c 679 case PF_INET:
6fba990c 680 mreq.imr_multiaddr = mgroup.in.sin_addr;
23205f9c
RK
681 mreq.imr_interface.s_addr = 0; /* use primary interface */
682 if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
683 &mreq, sizeof mreq) < 0)
684 fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP");
685 break;
686 case PF_INET6:
6fba990c 687 mreq6.ipv6mr_multiaddr = mgroup.in6.sin6_addr;
23205f9c
RK
688 memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface);
689 if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
690 &mreq6, sizeof mreq6) < 0)
691 fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP");
692 break;
693 default:
694 fatal(0, "unsupported address family %d", res->ai_family);
695 }
983c3357 696 /* Report what we did */
6fba990c
RK
697 info("listening on %s multicast group %s",
698 format_sockaddr(res->ai_addr), format_sockaddr(&mgroup.sa));
983c3357
RK
699 } else {
700 /* Bind to 0/port */
701 switch(res->ai_addr->sa_family) {
702 case AF_INET: {
703 struct sockaddr_in *in = (struct sockaddr_in *)res->ai_addr;
704
705 memset(&in->sin_addr, 0, sizeof (struct in_addr));
706 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
707 fatal(errno, "error binding socket to 0.0.0.0 port %d",
708 ntohs(in->sin_port));
709 break;
710 }
711 case AF_INET6: {
712 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)res->ai_addr;
713
714 memset(&in6->sin6_addr, 0, sizeof (struct in6_addr));
715 break;
716 }
717 default:
718 fatal(0, "unsupported family %d", (int)res->ai_addr->sa_family);
719 }
720 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
721 fatal(errno, "error binding socket to %s", format_sockaddr(res->ai_addr));
722 /* Report what we did */
6fba990c 723 info("listening on %s", format_sockaddr(res->ai_addr));
983c3357 724 }
1f10f780
RK
725 len = sizeof rcvbuf;
726 if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
727 fatal(errno, "error calling getsockopt SO_RCVBUF");
f0bae611 728 if(target_rcvbuf > rcvbuf) {
1f10f780
RK
729 if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
730 &target_rcvbuf, sizeof target_rcvbuf) < 0)
731 error(errno, "error calling setsockopt SO_RCVBUF %d",
732 target_rcvbuf);
733 /* We try to carry on anyway */
734 else
735 info("changed socket receive buffer from %d to %d",
736 rcvbuf, target_rcvbuf);
737 } else
738 info("default socket receive buffer %d", rcvbuf);
739 if(logfp)
740 info("WARNING: -L option can impact performance");
a99c4e9a
RK
741 if(control_socket) {
742 pthread_t tid;
743
744 if((err = pthread_create(&tid, 0, control_thread, 0)))
745 fatal(err, "pthread_create control_thread");
746 }
e9b635a3
RK
747 if(dumpfile) {
748 int fd;
749 unsigned char buffer[65536];
750 size_t written;
751
752 if((fd = open(dumpfile, O_RDWR|O_TRUNC|O_CREAT, 0666)) < 0)
753 fatal(errno, "opening %s", dumpfile);
754 /* Fill with 0s to a suitable size */
755 memset(buffer, 0, sizeof buffer);
756 for(written = 0; written < dump_size * sizeof(int16_t);
757 written += sizeof buffer) {
758 if(write(fd, buffer, sizeof buffer) < 0)
759 fatal(errno, "clearing %s", dumpfile);
760 }
761 /* Map the buffer into memory for convenience */
762 dump_buffer = mmap(0, dump_size * sizeof(int16_t), PROT_READ|PROT_WRITE,
763 MAP_SHARED, fd, 0);
764 if(dump_buffer == (void *)-1)
765 fatal(errno, "mapping %s", dumpfile);
766 info("dumping to %s", dumpfile);
767 }
4fd38868
RK
768 /* Set up output. Currently we only support L16 so there's no harm setting
769 * the format before we know what it is! */
770 uaudio_set_format(44100/*Hz*/, 2/*channels*/,
771 16/*bits/channel*/, 1/*signed*/);
7a2c7068
RK
772 backend->start(playrtp_callback, NULL);
773 /* We receive and convert audio data in a background thread */
774 if((err = pthread_create(&ltid, 0, listen_thread, 0)))
775 fatal(err, "pthread_create listen_thread");
776 /* We have a second thread to add received packets to the queue */
777 if((err = pthread_create(&ltid, 0, queue_thread, 0)))
778 fatal(err, "pthread_create queue_thread");
779 pthread_mutex_lock(&lock);
780 for(;;) {
781 /* Wait for the buffer to fill up a bit */
782 playrtp_fill_buffer();
783 /* Start playing now */
784 info("Playing...");
785 next_timestamp = pheap_first(&packets)->timestamp;
786 active = 1;
d4170ca7 787 pthread_mutex_unlock(&lock);
7a2c7068 788 backend->activate();
d4170ca7 789 pthread_mutex_lock(&lock);
0e72bf84
RK
790 /* Wait until the buffer empties out
791 *
792 * If there's a packet that we can play right now then we definitely
793 * continue.
794 *
795 * Also if there's at least minbuffer samples we carry on regardless and
796 * insert silence. The assumption is there's been a pause but more data
797 * is now available.
798 */
7a2c7068
RK
799 while(nsamples >= minbuffer
800 || (nsamples > 0
4fd38868 801 && contains(pheap_first(&packets), next_timestamp))) {
7a2c7068 802 pthread_cond_wait(&cond, &lock);
4fd38868 803 }
7a2c7068 804 /* Stop playing for a bit until the buffer re-fills */
d4170ca7 805 pthread_mutex_unlock(&lock);
7a2c7068 806 backend->deactivate();
d4170ca7 807 pthread_mutex_lock(&lock);
7a2c7068
RK
808 active = 0;
809 /* Go back round */
810 }
e83d0967
RK
811 return 0;
812}
813
814/*
815Local Variables:
816c-basic-offset:2
817comment-column:40
818fill-column:79
819indent-tabs-mode:nil
820End:
821*/