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