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