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