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