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