chiark / gitweb /
Correct playlist read sense
[disorder] / clients / playrtp.c
CommitLineData
e83d0967
RK
1/*
2 * This file is part of DisOrder.
5aff007d 3 * Copyright (C) 2007, 2008 Richard Kettlewell
e83d0967
RK
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 * USA
19 */
28bacdc0
RK
20/** @file clients/playrtp.c
21 * @brief RTP player
22 *
b0fdc63d 23 * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</a>)
24 * and Apple Mac (<a
25 * href="http://developer.apple.com/audio/coreaudio.html">Core Audio</a>)
26 * systems. There is no support for Microsoft Windows yet, and that will in
27 * fact probably an entirely separate program.
28 *
189e9830
RK
29 * The program runs (at least) three threads. listen_thread() is responsible
30 * for reading RTP packets off the wire and adding them to the linked list @ref
31 * received_packets, assuming they are basically sound. queue_thread() takes
32 * packets off this linked list and adds them to @ref packets (an operation
33 * which might be much slower due to contention for @ref lock).
b0fdc63d 34 *
35 * The main thread is responsible for actually playing audio. In ALSA this
36 * means it waits until ALSA says it's ready for more audio which it then
c593cf7c 37 * plays. See @ref clients/playrtp-alsa.c.
b0fdc63d 38 *
8e3fe3d8 39 * In Core Audio the main thread is only responsible for starting and stopping
b0fdc63d 40 * play: the system does the actual playback in its own private thread, and
c593cf7c 41 * calls adioproc() to fetch the audio data. See @ref
42 * clients/playrtp-coreaudio.c.
b0fdc63d 43 *
44 * Sometimes it happens that there is no audio available to play. This may
45 * because the server went away, or a packet was dropped, or the server
46 * deliberately did not send any sound because it encountered a silence.
189e9830
RK
47 *
48 * Assumptions:
49 * - it is safe to read uint32_t values without a lock protecting them
28bacdc0 50 */
e83d0967 51
05b75f8d 52#include "common.h"
e83d0967
RK
53
54#include <getopt.h>
e83d0967
RK
55#include <sys/socket.h>
56#include <sys/types.h>
57#include <sys/socket.h>
58#include <netdb.h>
59#include <pthread.h>
0b75463f 60#include <locale.h>
2c7c9eae 61#include <sys/uio.h>
c593cf7c 62#include <errno.h>
e3426f7b 63#include <netinet/in.h>
2d2effe2 64#include <sys/time.h>
a99c4e9a 65#include <sys/un.h>
9fbe0996 66#include <unistd.h>
e9b635a3
RK
67#include <sys/mman.h>
68#include <fcntl.h>
e83d0967
RK
69
70#include "log.h"
71#include "mem.h"
72#include "configuration.h"
73#include "addr.h"
74#include "syscalls.h"
75#include "rtp.h"
0b75463f 76#include "defs.h"
28bacdc0
RK
77#include "vector.h"
78#include "heap.h"
189e9830 79#include "timeval.h"
a7e9570a 80#include "client.h"
8e3fe3d8 81#include "playrtp.h"
a99c4e9a 82#include "inputline.h"
3fbdc96d 83#include "version.h"
e83d0967 84
1153fd23 85#define readahead linux_headers_are_borked
86
e3426f7b
RK
87/** @brief Obsolete synonym */
88#ifndef IPV6_JOIN_GROUP
89# define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP
90#endif
91
0b75463f 92/** @brief RTP socket */
e83d0967
RK
93static int rtpfd;
94
345ebe66
RK
95/** @brief Log output */
96static FILE *logfp;
97
0b75463f 98/** @brief Output device */
8e3fe3d8 99const char *device;
0b75463f 100
9086a105 101/** @brief Minimum low watermark
0b75463f 102 *
103 * We'll stop playing if there's only this many samples in the buffer. */
c593cf7c 104unsigned minbuffer = 2 * 44100 / 10; /* 0.2 seconds */
0b75463f 105
9086a105 106/** @brief Buffer high watermark
1153fd23 107 *
108 * We'll only start playing when this many samples are available. */
8d0c14d7 109static unsigned readahead = 2 * 2 * 44100;
0b75463f 110
9086a105
RK
111/** @brief Maximum buffer size
112 *
113 * We'll stop reading from the network if we have this many samples. */
114static unsigned maxbuffer;
115
189e9830
RK
116/** @brief Received packets
117 * Protected by @ref receive_lock
118 *
119 * Received packets are added to this list, and queue_thread() picks them off
120 * it and adds them to @ref packets. Whenever a packet is added to it, @ref
121 * receive_cond is signalled.
122 */
8e3fe3d8 123struct packet *received_packets;
189e9830
RK
124
125/** @brief Tail of @ref received_packets
126 * Protected by @ref receive_lock
127 */
8e3fe3d8 128struct packet **received_tail = &received_packets;
189e9830
RK
129
130/** @brief Lock protecting @ref received_packets
131 *
132 * Only listen_thread() and queue_thread() ever hold this lock. It is vital
133 * that queue_thread() not hold it any longer than it strictly has to. */
8e3fe3d8 134pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER;
189e9830
RK
135
136/** @brief Condition variable signalled when @ref received_packets is updated
137 *
138 * Used by listen_thread() to notify queue_thread() that it has added another
139 * packet to @ref received_packets. */
8e3fe3d8 140pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER;
189e9830
RK
141
142/** @brief Length of @ref received_packets */
8e3fe3d8 143uint32_t nreceived;
28bacdc0
RK
144
145/** @brief Binary heap of received packets */
8e3fe3d8 146struct pheap packets;
28bacdc0 147
189e9830
RK
148/** @brief Total number of samples available
149 *
150 * We make this volatile because we inspect it without a protecting lock,
151 * so the usual pthread_* guarantees aren't available.
152 */
8e3fe3d8 153volatile uint32_t nsamples;
0b75463f 154
155/** @brief Timestamp of next packet to play.
156 *
157 * This is set to the timestamp of the last packet, plus the number of
09ee2f0d 158 * samples it contained. Only valid if @ref active is nonzero.
0b75463f 159 */
8e3fe3d8 160uint32_t next_timestamp;
e83d0967 161
09ee2f0d 162/** @brief True if actively playing
163 *
164 * This is true when playing and false when just buffering. */
8e3fe3d8 165int active;
09ee2f0d 166
189e9830 167/** @brief Lock protecting @ref packets */
8e3fe3d8 168pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
189e9830
RK
169
170/** @brief Condition variable signalled whenever @ref packets is changed */
8e3fe3d8 171pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
2c7c9eae 172
3c499fe7
RK
173#if DEFAULT_BACKEND == BACKEND_ALSA
174# define DEFAULT_PLAYRTP_BACKEND playrtp_alsa
175#elif DEFAULT_BACKEND == BACKEND_OSS
176# define DEFAULT_PLAYRTP_BACKEND playrtp_oss
177#elif DEFAULT_BACKEND == BACKEND_COREAUDIO
178# define DEFAULT_PLAYRTP_BACKEND playrtp_coreaudio
c593cf7c 179#endif
180
181/** @brief Backend to play with */
3c499fe7 182static void (*backend)(void) = DEFAULT_PLAYRTP_BACKEND;
c593cf7c 183
8e3fe3d8 184HEAP_DEFINE(pheap, struct packet *, lt_packet);
e83d0967 185
a99c4e9a
RK
186/** @brief Control socket or NULL */
187const char *control_socket;
188
b28bddbb
RK
189/** @brief Buffer for debugging dump
190 *
191 * The debug dump is enabled by the @c --dump option. It records the last 20s
192 * of audio to the specified file (which will be about 3.5Mbytes). The file is
193 * written as as ring buffer, so the start point will progress through it.
194 *
195 * Use clients/dump2wav to convert this to a WAV file, which can then be loaded
196 * into (e.g.) Audacity for further inspection.
197 *
198 * All three backends (ALSA, OSS, Core Audio) now support this option.
199 *
200 * The idea is to allow the user a few seconds to react to an audible artefact.
201 */
e9b635a3 202int16_t *dump_buffer;
b28bddbb
RK
203
204/** @brief Current index within debugging dump */
e9b635a3 205size_t dump_index;
b28bddbb
RK
206
207/** @brief Size of debugging dump in samples */
208size_t dump_size = 44100/*Hz*/ * 2/*channels*/ * 20/*seconds*/;
e9b635a3 209
e83d0967
RK
210static const struct option options[] = {
211 { "help", no_argument, 0, 'h' },
212 { "version", no_argument, 0, 'V' },
213 { "debug", no_argument, 0, 'd' },
0b75463f 214 { "device", required_argument, 0, 'D' },
1153fd23 215 { "min", required_argument, 0, 'm' },
9086a105 216 { "max", required_argument, 0, 'x' },
1153fd23 217 { "buffer", required_argument, 0, 'b' },
1f10f780 218 { "rcvbuf", required_argument, 0, 'R' },
a9f0ad12 219#if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
c593cf7c 220 { "oss", no_argument, 0, 'o' },
221#endif
146e86fb 222#if HAVE_ALSA_ASOUNDLIB_H
c593cf7c 223 { "alsa", no_argument, 0, 'a' },
224#endif
225#if HAVE_COREAUDIO_AUDIOHARDWARE_H
226 { "core-audio", no_argument, 0, 'c' },
227#endif
e9b635a3 228 { "dump", required_argument, 0, 'r' },
a99c4e9a 229 { "socket", required_argument, 0, 's' },
a7e9570a 230 { "config", required_argument, 0, 'C' },
e83d0967
RK
231 { 0, 0, 0, 0 }
232};
233
a99c4e9a
RK
234/** @brief Control thread
235 *
236 * This thread is responsible for accepting control commands from Disobedience
237 * (or other controllers) over an AF_UNIX stream socket with a path specified
238 * by the @c --socket option. The protocol uses simple string commands and
239 * replies:
240 *
241 * - @c stop will shut the player down
242 * - @c query will send back the reply @c running
243 * - anything else is ignored
244 *
245 * Commands and response strings terminated by shutting down the connection or
246 * by a newline. No attempt is made to multiplex multiple clients so it is
247 * important that the command be sent as soon as the connection is made - it is
248 * assumed that both parties to the protocol are entirely cooperating with one
249 * another.
250 */
251static void *control_thread(void attribute((unused)) *arg) {
252 struct sockaddr_un sa;
253 int sfd, cfd;
254 char *line;
255 socklen_t salen;
256 FILE *fp;
257
258 assert(control_socket);
259 unlink(control_socket);
260 memset(&sa, 0, sizeof sa);
261 sa.sun_family = AF_UNIX;
262 strcpy(sa.sun_path, control_socket);
263 sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
264 if(bind(sfd, (const struct sockaddr *)&sa, sizeof sa) < 0)
265 fatal(errno, "error binding to %s", control_socket);
266 if(listen(sfd, 128) < 0)
267 fatal(errno, "error calling listen on %s", control_socket);
268 info("listening on %s", control_socket);
269 for(;;) {
270 salen = sizeof sa;
271 cfd = accept(sfd, (struct sockaddr *)&sa, &salen);
272 if(cfd < 0) {
273 switch(errno) {
274 case EINTR:
275 case EAGAIN:
276 break;
277 default:
278 fatal(errno, "error calling accept on %s", control_socket);
279 }
280 }
281 if(!(fp = fdopen(cfd, "r+"))) {
282 error(errno, "error calling fdopen for %s connection", control_socket);
283 close(cfd);
284 continue;
285 }
286 if(!inputline(control_socket, fp, &line, '\n')) {
287 if(!strcmp(line, "stop")) {
288 info("stopped via %s", control_socket);
289 exit(0); /* terminate immediately */
290 }
291 if(!strcmp(line, "query"))
292 fprintf(fp, "running");
293 xfree(line);
294 }
295 if(fclose(fp) < 0)
296 error(errno, "error closing %s connection", control_socket);
297 }
298}
299
28bacdc0
RK
300/** @brief Drop the first packet
301 *
302 * Assumes that @ref lock is held.
303 */
304static void drop_first_packet(void) {
305 if(pheap_count(&packets)) {
306 struct packet *const p = pheap_remove(&packets);
307 nsamples -= p->nsamples;
c593cf7c 308 playrtp_free_packet(p);
2c7c9eae 309 pthread_cond_broadcast(&cond);
2c7c9eae 310 }
9086a105
RK
311}
312
189e9830
RK
313/** @brief Background thread adding packets to heap
314 *
315 * This just transfers packets from @ref received_packets to @ref packets. It
316 * is important that it holds @ref receive_lock for as little time as possible,
317 * in order to minimize the interval between calls to read() in
318 * listen_thread().
319 */
320static void *queue_thread(void attribute((unused)) *arg) {
321 struct packet *p;
322
323 for(;;) {
324 /* Get the next packet */
325 pthread_mutex_lock(&receive_lock);
4dadf1a2 326 while(!received_packets) {
189e9830 327 pthread_cond_wait(&receive_cond, &receive_lock);
4dadf1a2 328 }
189e9830
RK
329 p = received_packets;
330 received_packets = p->next;
331 if(!received_packets)
332 received_tail = &received_packets;
333 --nreceived;
334 pthread_mutex_unlock(&receive_lock);
335 /* Add it to the heap */
336 pthread_mutex_lock(&lock);
337 pheap_insert(&packets, p);
338 nsamples += p->nsamples;
339 pthread_cond_broadcast(&cond);
340 pthread_mutex_unlock(&lock);
341 }
342}
343
09ee2f0d 344/** @brief Background thread collecting samples
0b75463f 345 *
346 * This function collects samples, perhaps converts them to the target format,
b0fdc63d 347 * and adds them to the packet list.
348 *
349 * It is crucial that the gap between successive calls to read() is as small as
350 * possible: otherwise packets will be dropped.
351 *
352 * We use a binary heap to ensure that the unavoidable effort is at worst
353 * logarithmic in the total number of packets - in fact if packets are mostly
354 * received in order then we will largely do constant work per packet since the
355 * newest packet will always be last.
356 *
357 * Of more concern is that we must acquire the lock on the heap to add a packet
358 * to it. If this proves a problem in practice then the answer would be
359 * (probably doubly) linked list with new packets added the end and a second
360 * thread which reads packets off the list and adds them to the heap.
361 *
362 * We keep memory allocation (mostly) very fast by keeping pre-allocated
c593cf7c 363 * packets around; see @ref playrtp_new_packet().
b0fdc63d 364 */
0b75463f 365static void *listen_thread(void attribute((unused)) *arg) {
2c7c9eae 366 struct packet *p = 0;
0b75463f 367 int n;
2c7c9eae
RK
368 struct rtp_header header;
369 uint16_t seq;
370 uint32_t timestamp;
371 struct iovec iov[2];
e83d0967
RK
372
373 for(;;) {
189e9830 374 if(!p)
c593cf7c 375 p = playrtp_new_packet();
2c7c9eae
RK
376 iov[0].iov_base = &header;
377 iov[0].iov_len = sizeof header;
378 iov[1].iov_base = p->samples_raw;
b64efe7e 379 iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
2c7c9eae 380 n = readv(rtpfd, iov, 2);
e83d0967
RK
381 if(n < 0) {
382 switch(errno) {
383 case EINTR:
384 continue;
385 default:
386 fatal(errno, "error reading from socket");
387 }
388 }
0b75463f 389 /* Ignore too-short packets */
345ebe66
RK
390 if((size_t)n <= sizeof (struct rtp_header)) {
391 info("ignored a short packet");
0b75463f 392 continue;
345ebe66 393 }
2c7c9eae
RK
394 timestamp = htonl(header.timestamp);
395 seq = htons(header.seq);
09ee2f0d 396 /* Ignore packets in the past */
2c7c9eae 397 if(active && lt(timestamp, next_timestamp)) {
c0e41690 398 info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
2c7c9eae 399 timestamp, next_timestamp);
09ee2f0d 400 continue;
c0e41690 401 }
189e9830 402 p->next = 0;
58b5a68f 403 p->flags = 0;
2c7c9eae 404 p->timestamp = timestamp;
e83d0967 405 /* Convert to target format */
58b5a68f
RK
406 if(header.mpt & 0x80)
407 p->flags |= IDLE;
2c7c9eae 408 switch(header.mpt & 0x7F) {
e83d0967 409 case 10:
2c7c9eae 410 p->nsamples = (n - sizeof header) / sizeof(uint16_t);
e83d0967
RK
411 break;
412 /* TODO support other RFC3551 media types (when the speaker does) */
413 default:
0b75463f 414 fatal(0, "unsupported RTP payload type %d",
2c7c9eae 415 header.mpt & 0x7F);
e83d0967 416 }
345ebe66
RK
417 if(logfp)
418 fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
2c7c9eae 419 seq, timestamp, p->nsamples, timestamp + p->nsamples);
0b75463f 420 /* Stop reading if we've reached the maximum.
421 *
422 * This is rather unsatisfactory: it means that if packets get heavily
423 * out of order then we guarantee dropouts. But for now... */
345ebe66 424 if(nsamples >= maxbuffer) {
189e9830 425 pthread_mutex_lock(&lock);
4dadf1a2 426 while(nsamples >= maxbuffer) {
345ebe66 427 pthread_cond_wait(&cond, &lock);
4dadf1a2 428 }
189e9830 429 pthread_mutex_unlock(&lock);
345ebe66 430 }
189e9830
RK
431 /* Add the packet to the receive queue */
432 pthread_mutex_lock(&receive_lock);
433 *received_tail = p;
434 received_tail = &p->next;
435 ++nreceived;
436 pthread_cond_signal(&receive_cond);
437 pthread_mutex_unlock(&receive_lock);
58b5a68f
RK
438 /* We'll need a new packet */
439 p = 0;
e83d0967
RK
440 }
441}
442
5626f6d2
RK
443/** @brief Wait until the buffer is adequately full
444 *
445 * Must be called with @ref lock held.
446 */
c593cf7c 447void playrtp_fill_buffer(void) {
bfd27c14
RK
448 while(nsamples)
449 drop_first_packet();
5626f6d2 450 info("Buffering...");
4dadf1a2 451 while(nsamples < readahead) {
5626f6d2 452 pthread_cond_wait(&cond, &lock);
4dadf1a2 453 }
5626f6d2
RK
454 next_timestamp = pheap_first(&packets)->timestamp;
455 active = 1;
456}
457
458/** @brief Find next packet
459 * @return Packet to play or NULL if none found
460 *
461 * The return packet is merely guaranteed not to be in the past: it might be
462 * the first packet in the future rather than one that is actually suitable to
463 * play.
464 *
465 * Must be called with @ref lock held.
466 */
c593cf7c 467struct packet *playrtp_next_packet(void) {
5626f6d2
RK
468 while(pheap_count(&packets)) {
469 struct packet *const p = pheap_first(&packets);
470 if(le(p->timestamp + p->nsamples, next_timestamp)) {
471 /* This packet is in the past. Drop it and try another one. */
472 drop_first_packet();
473 } else
474 /* This packet is NOT in the past. (It might be in the future
475 * however.) */
476 return p;
477 }
478 return 0;
479}
480
09ee2f0d 481/** @brief Play an RTP stream
482 *
483 * This is the guts of the program. It is responsible for:
484 * - starting the listening thread
485 * - opening the audio device
486 * - reading ahead to build up a buffer
487 * - arranging for audio to be played
488 * - detecting when the buffer has got too small and re-buffering
489 */
0b75463f 490static void play_rtp(void) {
491 pthread_t ltid;
a99c4e9a 492 int err;
e83d0967
RK
493
494 /* We receive and convert audio data in a background thread */
a99c4e9a
RK
495 if((err = pthread_create(&ltid, 0, listen_thread, 0)))
496 fatal(err, "pthread_create listen_thread");
189e9830 497 /* We have a second thread to add received packets to the queue */
a99c4e9a
RK
498 if((err = pthread_create(&ltid, 0, queue_thread, 0)))
499 fatal(err, "pthread_create queue_thread");
c593cf7c 500 /* The rest of the work is backend-specific */
501 backend();
e83d0967
RK
502}
503
504/* display usage message and terminate */
505static void help(void) {
506 xprintf("Usage:\n"
507 " disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
508 "Options:\n"
1153fd23 509 " --device, -D DEVICE Output device\n"
510 " --min, -m FRAMES Buffer low water mark\n"
9086a105
RK
511 " --buffer, -b FRAMES Buffer high water mark\n"
512 " --max, -x FRAMES Buffer maximum size\n"
1f10f780 513 " --rcvbuf, -R BYTES Socket receive buffer size\n"
a7e9570a 514 " --config, -C PATH Set configuration file\n"
146e86fb 515#if HAVE_ALSA_ASOUNDLIB_H
c593cf7c 516 " --alsa, -a Use ALSA to play audio\n"
517#endif
a9f0ad12 518#if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
c593cf7c 519 " --oss, -o Use OSS to play audio\n"
520#endif
521#if HAVE_COREAUDIO_AUDIOHARDWARE_H
522 " --core-audio, -c Use Core Audio to play audio\n"
523#endif
9086a105
RK
524 " --help, -h Display usage message\n"
525 " --version, -V Display version number\n"
526 );
e83d0967
RK
527 xfclose(stdout);
528 exit(0);
529}
530
e83d0967 531int main(int argc, char **argv) {
a99c4e9a 532 int n, err;
e83d0967
RK
533 struct addrinfo *res;
534 struct stringlist sl;
0b75463f 535 char *sockname;
1f10f780
RK
536 int rcvbuf, target_rcvbuf = 131072;
537 socklen_t len;
23205f9c
RK
538 struct ip_mreq mreq;
539 struct ipv6_mreq mreq6;
a7e9570a
RK
540 disorder_client *c;
541 char *address, *port;
6fba990c
RK
542 int is_multicast;
543 union any_sockaddr {
544 struct sockaddr sa;
545 struct sockaddr_in in;
546 struct sockaddr_in6 in6;
547 };
548 union any_sockaddr mgroup;
e9b635a3 549 const char *dumpfile = 0;
e83d0967 550
0b75463f 551 static const struct addrinfo prefs = {
66613034
RK
552 .ai_flags = AI_PASSIVE,
553 .ai_family = PF_INET,
554 .ai_socktype = SOCK_DGRAM,
555 .ai_protocol = IPPROTO_UDP
e83d0967
RK
556 };
557
558 mem_init();
559 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
e9b635a3 560 while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:R:M:aocC:r", options, 0)) >= 0) {
e83d0967
RK
561 switch(n) {
562 case 'h': help();
3fbdc96d 563 case 'V': version("disorder-playrtp");
e83d0967 564 case 'd': debugging = 1; break;
0b75463f 565 case 'D': device = optarg; break;
1153fd23 566 case 'm': minbuffer = 2 * atol(optarg); break;
567 case 'b': readahead = 2 * atol(optarg); break;
9086a105 568 case 'x': maxbuffer = 2 * atol(optarg); break;
345ebe66 569 case 'L': logfp = fopen(optarg, "w"); break;
1f10f780 570 case 'R': target_rcvbuf = atoi(optarg); break;
146e86fb 571#if HAVE_ALSA_ASOUNDLIB_H
c593cf7c 572 case 'a': backend = playrtp_alsa; break;
573#endif
a9f0ad12 574#if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
c593cf7c 575 case 'o': backend = playrtp_oss; break;
576#endif
577#if HAVE_COREAUDIO_AUDIOHARDWARE_H
578 case 'c': backend = playrtp_coreaudio; break;
c593cf7c 579#endif
a7e9570a 580 case 'C': configfile = optarg; break;
a99c4e9a 581 case 's': control_socket = optarg; break;
e9b635a3 582 case 'r': dumpfile = optarg; break;
e83d0967
RK
583 default: fatal(0, "invalid option");
584 }
585 }
a7e9570a 586 if(config_read(0)) fatal(0, "cannot read configuration");
9086a105
RK
587 if(!maxbuffer)
588 maxbuffer = 4 * readahead;
e83d0967
RK
589 argc -= optind;
590 argv += optind;
a7e9570a
RK
591 switch(argc) {
592 case 0:
6fba990c 593 /* Get configuration from server */
a7e9570a
RK
594 if(!(c = disorder_new(1))) exit(EXIT_FAILURE);
595 if(disorder_connect(c)) exit(EXIT_FAILURE);
596 if(disorder_rtp_address(c, &address, &port)) exit(EXIT_FAILURE);
6fba990c
RK
597 sl.n = 2;
598 sl.s = xcalloc(2, sizeof *sl.s);
599 sl.s[0] = address;
600 sl.s[1] = port;
a7e9570a 601 break;
6fba990c 602 case 1:
a7e9570a 603 case 2:
6fba990c 604 /* Use command-line ADDRESS+PORT or just PORT */
a7e9570a
RK
605 sl.n = argc;
606 sl.s = argv;
607 break;
608 default:
6fba990c 609 fatal(0, "usage: disorder-playrtp [OPTIONS] [[ADDRESS] PORT]");
a7e9570a 610 }
6fba990c 611 /* Look up address and port */
0b75463f 612 if(!(res = get_address(&sl, &prefs, &sockname)))
e83d0967 613 exit(1);
6fba990c 614 /* Create the socket */
e83d0967
RK
615 if((rtpfd = socket(res->ai_family,
616 res->ai_socktype,
617 res->ai_protocol)) < 0)
618 fatal(errno, "error creating socket");
6fba990c
RK
619 /* Stash the multicast group address */
620 if((is_multicast = multicast(res->ai_addr))) {
621 memcpy(&mgroup, res->ai_addr, res->ai_addrlen);
622 switch(res->ai_addr->sa_family) {
623 case AF_INET:
624 mgroup.in.sin_port = 0;
625 break;
626 case AF_INET6:
627 mgroup.in6.sin6_port = 0;
628 break;
629 }
630 }
631 /* Bind to 0/port */
632 switch(res->ai_addr->sa_family) {
633 case AF_INET:
634 memset(&((struct sockaddr_in *)res->ai_addr)->sin_addr, 0,
635 sizeof (struct in_addr));
636 break;
637 case AF_INET6:
638 memset(&((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 0,
639 sizeof (struct in6_addr));
640 break;
641 default:
642 fatal(0, "unsupported family %d", (int)res->ai_addr->sa_family);
643 }
e83d0967
RK
644 if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
645 fatal(errno, "error binding socket to %s", sockname);
6fba990c
RK
646 if(is_multicast) {
647 switch(mgroup.sa.sa_family) {
23205f9c 648 case PF_INET:
6fba990c 649 mreq.imr_multiaddr = mgroup.in.sin_addr;
23205f9c
RK
650 mreq.imr_interface.s_addr = 0; /* use primary interface */
651 if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
652 &mreq, sizeof mreq) < 0)
653 fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP");
654 break;
655 case PF_INET6:
6fba990c 656 mreq6.ipv6mr_multiaddr = mgroup.in6.sin6_addr;
23205f9c
RK
657 memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface);
658 if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
659 &mreq6, sizeof mreq6) < 0)
660 fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP");
661 break;
662 default:
663 fatal(0, "unsupported address family %d", res->ai_family);
664 }
6fba990c
RK
665 info("listening on %s multicast group %s",
666 format_sockaddr(res->ai_addr), format_sockaddr(&mgroup.sa));
667 } else
668 info("listening on %s", format_sockaddr(res->ai_addr));
1f10f780
RK
669 len = sizeof rcvbuf;
670 if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
671 fatal(errno, "error calling getsockopt SO_RCVBUF");
f0bae611 672 if(target_rcvbuf > rcvbuf) {
1f10f780
RK
673 if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
674 &target_rcvbuf, sizeof target_rcvbuf) < 0)
675 error(errno, "error calling setsockopt SO_RCVBUF %d",
676 target_rcvbuf);
677 /* We try to carry on anyway */
678 else
679 info("changed socket receive buffer from %d to %d",
680 rcvbuf, target_rcvbuf);
681 } else
682 info("default socket receive buffer %d", rcvbuf);
683 if(logfp)
684 info("WARNING: -L option can impact performance");
a99c4e9a
RK
685 if(control_socket) {
686 pthread_t tid;
687
688 if((err = pthread_create(&tid, 0, control_thread, 0)))
689 fatal(err, "pthread_create control_thread");
690 }
e9b635a3
RK
691 if(dumpfile) {
692 int fd;
693 unsigned char buffer[65536];
694 size_t written;
695
696 if((fd = open(dumpfile, O_RDWR|O_TRUNC|O_CREAT, 0666)) < 0)
697 fatal(errno, "opening %s", dumpfile);
698 /* Fill with 0s to a suitable size */
699 memset(buffer, 0, sizeof buffer);
700 for(written = 0; written < dump_size * sizeof(int16_t);
701 written += sizeof buffer) {
702 if(write(fd, buffer, sizeof buffer) < 0)
703 fatal(errno, "clearing %s", dumpfile);
704 }
705 /* Map the buffer into memory for convenience */
706 dump_buffer = mmap(0, dump_size * sizeof(int16_t), PROT_READ|PROT_WRITE,
707 MAP_SHARED, fd, 0);
708 if(dump_buffer == (void *)-1)
709 fatal(errno, "mapping %s", dumpfile);
710 info("dumping to %s", dumpfile);
711 }
e83d0967
RK
712 play_rtp();
713 return 0;
714}
715
716/*
717Local Variables:
718c-basic-offset:2
719comment-column:40
720fill-column:79
721indent-tabs-mode:nil
722End:
723*/