chiark / gitweb /
uaudio: pulseaudio support
[disorder] / clients / playrtp.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2007-2009, 2011, 2013 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   { "api", required_argument, 0, 'A' },
211   { "dump", required_argument, 0, 'r' },
212   { "command", required_argument, 0, 'e' },
213   { "pause-mode", required_argument, 0, 'P' },
214   { "socket", required_argument, 0, 's' },
215   { "config", required_argument, 0, 'C' },
216   { "monitor", no_argument, 0, 'M' },
217   { 0, 0, 0, 0 }
218 };
219
220 /** @brief Control thread
221  *
222  * This thread is responsible for accepting control commands from Disobedience
223  * (or other controllers) over an AF_UNIX stream socket with a path specified
224  * by the @c --socket option.  The protocol uses simple string commands and
225  * replies:
226  *
227  * - @c stop will shut the player down
228  * - @c query will send back the reply @c running
229  * - anything else is ignored
230  *
231  * Commands and response strings terminated by shutting down the connection or
232  * by a newline.  No attempt is made to multiplex multiple clients so it is
233  * important that the command be sent as soon as the connection is made - it is
234  * assumed that both parties to the protocol are entirely cooperating with one
235  * another.
236  */
237 static void *control_thread(void attribute((unused)) *arg) {
238   struct sockaddr_un sa;
239   int sfd, cfd;
240   char *line;
241   socklen_t salen;
242   FILE *fp;
243
244   assert(control_socket);
245   unlink(control_socket);
246   memset(&sa, 0, sizeof sa);
247   sa.sun_family = AF_UNIX;
248   strcpy(sa.sun_path, control_socket);
249   sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
250   if(bind(sfd, (const struct sockaddr *)&sa, sizeof sa) < 0)
251     disorder_fatal(errno, "error binding to %s", control_socket);
252   if(listen(sfd, 128) < 0)
253     disorder_fatal(errno, "error calling listen on %s", control_socket);
254   disorder_info("listening on %s", control_socket);
255   for(;;) {
256     salen = sizeof sa;
257     cfd = accept(sfd, (struct sockaddr *)&sa, &salen);
258     if(cfd < 0) {
259       switch(errno) {
260       case EINTR:
261       case EAGAIN:
262         break;
263       default:
264         disorder_fatal(errno, "error calling accept on %s", control_socket);
265       }
266     }
267     if(!(fp = fdopen(cfd, "r+"))) {
268       disorder_error(errno, "error calling fdopen for %s connection", control_socket);
269       close(cfd);
270       continue;
271     }
272     if(!inputline(control_socket, fp, &line, '\n')) {
273       if(!strcmp(line, "stop")) {
274         disorder_info("stopped via %s", control_socket);
275         exit(0);                          /* terminate immediately */
276       }
277       if(!strcmp(line, "query"))
278         fprintf(fp, "running");
279       xfree(line);
280     }
281     if(fclose(fp) < 0)
282       disorder_error(errno, "error closing %s connection", control_socket);
283   }
284 }
285
286 /** @brief Drop the first packet
287  *
288  * Assumes that @ref lock is held. 
289  */
290 static void drop_first_packet(void) {
291   if(pheap_count(&packets)) {
292     struct packet *const p = pheap_remove(&packets);
293     nsamples -= p->nsamples;
294     playrtp_free_packet(p);
295     pthread_cond_broadcast(&cond);
296   }
297 }
298
299 /** @brief Background thread adding packets to heap
300  *
301  * This just transfers packets from @ref received_packets to @ref packets.  It
302  * is important that it holds @ref receive_lock for as little time as possible,
303  * in order to minimize the interval between calls to read() in
304  * listen_thread().
305  */
306 static void *queue_thread(void attribute((unused)) *arg) {
307   struct packet *p;
308
309   for(;;) {
310     /* Get the next packet */
311     pthread_mutex_lock(&receive_lock);
312     while(!received_packets) {
313       pthread_cond_wait(&receive_cond, &receive_lock);
314     }
315     p = received_packets;
316     received_packets = p->next;
317     if(!received_packets)
318       received_tail = &received_packets;
319     --nreceived;
320     pthread_mutex_unlock(&receive_lock);
321     /* Add it to the heap */
322     pthread_mutex_lock(&lock);
323     pheap_insert(&packets, p);
324     nsamples += p->nsamples;
325     pthread_cond_broadcast(&cond);
326     pthread_mutex_unlock(&lock);
327   }
328 #if HAVE_STUPID_GCC44
329   return NULL;
330 #endif
331 }
332
333 /** @brief Background thread collecting samples
334  *
335  * This function collects samples, perhaps converts them to the target format,
336  * and adds them to the packet list.
337  *
338  * It is crucial that the gap between successive calls to read() is as small as
339  * possible: otherwise packets will be dropped.
340  *
341  * We use a binary heap to ensure that the unavoidable effort is at worst
342  * logarithmic in the total number of packets - in fact if packets are mostly
343  * received in order then we will largely do constant work per packet since the
344  * newest packet will always be last.
345  *
346  * Of more concern is that we must acquire the lock on the heap to add a packet
347  * to it.  If this proves a problem in practice then the answer would be
348  * (probably doubly) linked list with new packets added the end and a second
349  * thread which reads packets off the list and adds them to the heap.
350  *
351  * We keep memory allocation (mostly) very fast by keeping pre-allocated
352  * packets around; see @ref playrtp_new_packet().
353  */
354 static void *listen_thread(void attribute((unused)) *arg) {
355   struct packet *p = 0;
356   int n;
357   struct rtp_header header;
358   uint16_t seq;
359   uint32_t timestamp;
360   struct iovec iov[2];
361
362   for(;;) {
363     if(!p)
364       p = playrtp_new_packet();
365     iov[0].iov_base = &header;
366     iov[0].iov_len = sizeof header;
367     iov[1].iov_base = p->samples_raw;
368     iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
369     n = readv(rtpfd, iov, 2);
370     if(n < 0) {
371       switch(errno) {
372       case EINTR:
373         continue;
374       default:
375         disorder_fatal(errno, "error reading from socket");
376       }
377     }
378     /* Ignore too-short packets */
379     if((size_t)n <= sizeof (struct rtp_header)) {
380       disorder_info("ignored a short packet");
381       continue;
382     }
383     timestamp = htonl(header.timestamp);
384     seq = htons(header.seq);
385     /* Ignore packets in the past */
386     if(active && lt(timestamp, next_timestamp)) {
387       disorder_info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
388            timestamp, next_timestamp);
389       continue;
390     }
391     /* Ignore packets with the extension bit set. */
392     if(header.vpxcc & 0x10)
393       continue;
394     p->next = 0;
395     p->flags = 0;
396     p->timestamp = timestamp;
397     /* Convert to target format */
398     if(header.mpt & 0x80)
399       p->flags |= IDLE;
400     switch(header.mpt & 0x7F) {
401     case 10:                            /* L16 */
402       p->nsamples = (n - sizeof header) / sizeof(uint16_t);
403       break;
404       /* TODO support other RFC3551 media types (when the speaker does) */
405     default:
406       disorder_fatal(0, "unsupported RTP payload type %d", header.mpt & 0x7F);
407     }
408     /* See if packet is silent */
409     const uint16_t *s = p->samples_raw;
410     n = p->nsamples;
411     for(; n > 0; --n)
412       if(*s++)
413         break;
414     if(!n)
415       p->flags |= SILENT;
416     if(logfp)
417       fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
418               seq, timestamp, p->nsamples, timestamp + p->nsamples);
419     /* Stop reading if we've reached the maximum.
420      *
421      * This is rather unsatisfactory: it means that if packets get heavily
422      * out of order then we guarantee dropouts.  But for now... */
423     if(nsamples >= maxbuffer) {
424       pthread_mutex_lock(&lock);
425       while(nsamples >= maxbuffer) {
426         pthread_cond_wait(&cond, &lock);
427       }
428       pthread_mutex_unlock(&lock);
429     }
430     /* Add the packet to the receive queue */
431     pthread_mutex_lock(&receive_lock);
432     *received_tail = p;
433     received_tail = &p->next;
434     ++nreceived;
435     pthread_cond_signal(&receive_cond);
436     pthread_mutex_unlock(&receive_lock);
437     /* We'll need a new packet */
438     p = 0;
439   }
440 }
441
442 /** @brief Wait until the buffer is adequately full
443  *
444  * Must be called with @ref lock held.
445  */
446 void playrtp_fill_buffer(void) {
447   /* Discard current buffer contents */
448   while(nsamples) {
449     //fprintf(stderr, "%8u/%u (%u) DROPPING\n", nsamples, maxbuffer, minbuffer);
450     drop_first_packet();
451   }
452   disorder_info("Buffering...");
453   /* Wait until there's at least minbuffer samples available */
454   while(nsamples < minbuffer) {
455     //fprintf(stderr, "%8u/%u (%u) FILLING\n", nsamples, maxbuffer, minbuffer);
456     pthread_cond_wait(&cond, &lock);
457   }
458   /* Start from whatever is earliest */
459   next_timestamp = pheap_first(&packets)->timestamp;
460   active = 1;
461 }
462
463 /** @brief Find next packet
464  * @return Packet to play or NULL if none found
465  *
466  * The return packet is merely guaranteed not to be in the past: it might be
467  * the first packet in the future rather than one that is actually suitable to
468  * play.
469  *
470  * Must be called with @ref lock held.
471  */
472 struct packet *playrtp_next_packet(void) {
473   while(pheap_count(&packets)) {
474     struct packet *const p = pheap_first(&packets);
475     if(le(p->timestamp + p->nsamples, next_timestamp)) {
476       /* This packet is in the past.  Drop it and try another one. */
477       drop_first_packet();
478     } else
479       /* This packet is NOT in the past.  (It might be in the future
480        * however.) */
481       return p;
482   }
483   return 0;
484 }
485
486 /* display usage message and terminate */
487 static void help(void) {
488   xprintf("Usage:\n"
489           "  disorder-playrtp [OPTIONS] [[ADDRESS] PORT]\n"
490           "Options:\n"
491           "  --device, -D DEVICE     Output device\n"
492           "  --min, -m FRAMES        Buffer low water mark\n"
493           "  --max, -x FRAMES        Buffer maximum size\n"
494           "  --rcvbuf, -R BYTES      Socket receive buffer size\n"
495           "  --config, -C PATH       Set configuration file\n"
496           "  --api, -A API           Select audio API.  Possibilities:\n"
497           "                            ");
498   int first = 1;
499   for(int n = 0; uaudio_apis[n]; ++n) {
500     if(uaudio_apis[n]->flags & UAUDIO_API_CLIENT) {
501       if(first)
502         first = 0;
503       else
504         xprintf(", ");
505       xprintf("%s", uaudio_apis[n]->name);
506     }
507   }
508   xprintf("\n"
509           "  --command, -e COMMAND   Pipe audio to command.\n"
510           "  --pause-mode, -P silence  For -e: pauses send silence (default)\n"
511           "  --pause-mode, -P suspend  For -e: pauses suspend writes\n"
512           "  --help, -h              Display usage message\n"
513           "  --version, -V           Display version number\n"
514           );
515   xfclose(stdout);
516   exit(0);
517 }
518
519 static size_t playrtp_callback(void *buffer,
520                                size_t max_samples,
521                                void attribute((unused)) *userdata) {
522   size_t samples;
523   int silent = 0;
524
525   pthread_mutex_lock(&lock);
526   /* Get the next packet, junking any that are now in the past */
527   const struct packet *p = playrtp_next_packet();
528   if(p && contains(p, next_timestamp)) {
529     /* This packet is ready to play; the desired next timestamp points
530      * somewhere into it. */
531
532     /* Timestamp of end of packet */
533     const uint32_t packet_end = p->timestamp + p->nsamples;
534
535     /* Offset of desired next timestamp into current packet */
536     const uint32_t offset = next_timestamp - p->timestamp;
537
538     /* Pointer to audio data */
539     const uint16_t *ptr = (void *)(p->samples_raw + offset);
540
541     /* Compute number of samples left in packet, limited to output buffer
542      * size */
543     samples = packet_end - next_timestamp;
544     if(samples > max_samples)
545       samples = max_samples;
546
547     /* Copy into buffer, converting to native endianness */
548     size_t i = samples;
549     int16_t *bufptr = buffer;
550     while(i > 0) {
551       *bufptr++ = (int16_t)ntohs(*ptr++);
552       --i;
553     }
554     silent = !!(p->flags & SILENT);
555   } else {
556     /* There is no suitable packet.  We introduce 0s up to the next packet, or
557      * to fill the buffer if there's no next packet or that's too many.  The
558      * comparison with max_samples deals with the otherwise troubling overflow
559      * case. */
560     samples = p ? p->timestamp - next_timestamp : max_samples;
561     if(samples > max_samples)
562       samples = max_samples;
563     //info("infill by %zu", samples);
564     memset(buffer, 0, samples * uaudio_sample_size);
565     silent = 1;
566   }
567   /* Debug dump */
568   if(dump_buffer) {
569     for(size_t i = 0; i < samples; ++i) {
570       dump_buffer[dump_index++] = ((int16_t *)buffer)[i];
571       dump_index %= dump_size;
572     }
573   }
574   /* Advance timestamp */
575   next_timestamp += samples;
576   /* If we're getting behind then try to drop just silent packets
577    *
578    * In theory this shouldn't be necessary.  The server is supposed to send
579    * packets at the right rate and compares the number of samples sent with the
580    * time in order to ensure this.
581    *
582    * However, various things could throw this off:
583    *
584    * - the server's clock could advance at the wrong rate.  This would cause it
585    *   to mis-estimate the right number of samples to have sent and
586    *   inappropriately throttle or speed up.
587    *
588    * - playback could happen at the wrong rate.  If the playback host's sound
589    *   card has a slightly incorrect clock then eventually it will get out
590    *   of step.
591    *
592    * So if we play back slightly slower than the server sends for either of
593    * these reasons then eventually our buffer, and the socket's buffer, will
594    * fill, and the kernel will start dropping packets.  The result is audible
595    * and not very nice.
596    *
597    * Therefore if we're getting behind, we pre-emptively drop silent packets,
598    * since a change in the duration of a silence is less noticeable than a
599    * dropped packet from the middle of continuous music.
600    *
601    * (If things go wrong the other way then eventually we run out of packets to
602    * play and are forced to play silence.  This doesn't seem to happen in
603    * practice but if it does then in the same way we can artificially extend
604    * silent packets to compensate.)
605    *
606    * Dropped packets are always logged; use 'disorder-playrtp --monitor' to
607    * track how close to target buffer occupancy we are on a once-a-minute
608    * basis.
609    */
610   if(nsamples > minbuffer && silent) {
611     disorder_info("dropping %zu samples (%"PRIu32" > %"PRIu32")",
612                   samples, nsamples, minbuffer);
613     samples = 0;
614   }
615   /* Junk obsolete packets */
616   playrtp_next_packet();
617   pthread_mutex_unlock(&lock);
618   return samples;
619 }
620
621 int main(int argc, char **argv) {
622   int n, err;
623   struct addrinfo *res;
624   struct stringlist sl;
625   char *sockname;
626   int rcvbuf, target_rcvbuf = 0;
627   socklen_t len;
628   struct ip_mreq mreq;
629   struct ipv6_mreq mreq6;
630   disorder_client *c;
631   char *address, *port;
632   int is_multicast;
633   union any_sockaddr {
634     struct sockaddr sa;
635     struct sockaddr_in in;
636     struct sockaddr_in6 in6;
637   };
638   union any_sockaddr mgroup;
639   const char *dumpfile = 0;
640   pthread_t ltid;
641   int monitor = 0;
642   static const int one = 1;
643
644   static const struct addrinfo prefs = {
645     .ai_flags = AI_PASSIVE,
646     .ai_family = PF_INET,
647     .ai_socktype = SOCK_DGRAM,
648     .ai_protocol = IPPROTO_UDP
649   };
650
651   /* Timing information is often important to debugging playrtp, so we include
652    * timestamps in the logs */
653   logdate = 1;
654   mem_init();
655   if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "error calling setlocale");
656   while((n = getopt_long(argc, argv, "hVdD:m:x:L:R:aocC:re:P:MA:", options, 0)) >= 0) {
657     switch(n) {
658     case 'h': help();
659     case 'V': version("disorder-playrtp");
660     case 'd': debugging = 1; break;
661     case 'D': uaudio_set("device", optarg); break;
662     case 'm': minbuffer = 2 * atol(optarg); break;
663     case 'x': maxbuffer = 2 * atol(optarg); break;
664     case 'L': logfp = fopen(optarg, "w"); break;
665     case 'R': target_rcvbuf = atoi(optarg); break;
666 #if HAVE_ALSA_ASOUNDLIB_H
667     case 'a':
668       disorder_error(0, "deprecated option; use --api alsa instead");
669       backend = &uaudio_alsa; break;
670 #endif
671 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
672     case 'o':
673       disorder_error(0, "deprecated option; use --api oss instead");
674       backend = &uaudio_oss; 
675       break;
676 #endif
677 #if HAVE_COREAUDIO_AUDIOHARDWARE_H      
678     case 'c':
679       disorder_error(0, "deprecated option; use --api coreaudio instead");
680       backend = &uaudio_coreaudio;
681       break;
682 #endif
683     case 'A': backend = uaudio_find(optarg); break;
684     case 'C': configfile = optarg; break;
685     case 's': control_socket = optarg; break;
686     case 'r': dumpfile = optarg; break;
687     case 'e': backend = &uaudio_command; uaudio_set("command", optarg); break;
688     case 'P': uaudio_set("pause-mode", optarg); break;
689     case 'M': monitor = 1; break;
690     default: disorder_fatal(0, "invalid option");
691     }
692   }
693   if(config_read(0, NULL)) disorder_fatal(0, "cannot read configuration");
694   if(!backend) {
695     backend = uaudio_default(uaudio_apis, UAUDIO_API_CLIENT);
696     if(!backend)
697       disorder_fatal(0, "no default uaudio API found");
698     disorder_info("default audio API %s", backend->name);
699   }
700   if(backend == &uaudio_rtp) {
701     /* This means that you have NO local sound output.  This can happen if you
702      * use a non-Apple GCC on a Mac (because it doesn't know how to compile
703      * CoreAudio/AudioHardware.h). */
704     disorder_fatal(0, "cannot play RTP through RTP");
705   }
706   if(!maxbuffer)
707     maxbuffer = 2 * minbuffer;
708   argc -= optind;
709   argv += optind;
710   switch(argc) {
711   case 0:
712     /* Get configuration from server */
713     if(!(c = disorder_new(1))) exit(EXIT_FAILURE);
714     if(disorder_connect(c)) exit(EXIT_FAILURE);
715     if(disorder_rtp_address(c, &address, &port)) exit(EXIT_FAILURE);
716     sl.n = 2;
717     sl.s = xcalloc(2, sizeof *sl.s);
718     sl.s[0] = address;
719     sl.s[1] = port;
720     break;
721   case 1:
722   case 2:
723     /* Use command-line ADDRESS+PORT or just PORT */
724     sl.n = argc;
725     sl.s = argv;
726     break;
727   default:
728     disorder_fatal(0, "usage: disorder-playrtp [OPTIONS] [[ADDRESS] PORT]");
729   }
730   disorder_info("version "VERSION" process ID %lu",
731                 (unsigned long)getpid());
732   /* Look up address and port */
733   if(!(res = get_address(&sl, &prefs, &sockname)))
734     exit(1);
735   /* Create the socket */
736   if((rtpfd = socket(res->ai_family,
737                      res->ai_socktype,
738                      res->ai_protocol)) < 0)
739     disorder_fatal(errno, "error creating socket");
740   /* Allow multiple listeners */
741   xsetsockopt(rtpfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
742   is_multicast = multicast(res->ai_addr);
743   /* The multicast and unicast/broadcast cases are different enough that they
744    * are totally split.  Trying to find commonality between them causes more
745    * trouble that it's worth. */
746   if(is_multicast) {
747     /* Stash the multicast group address */
748     memcpy(&mgroup, res->ai_addr, res->ai_addrlen);
749     switch(res->ai_addr->sa_family) {
750     case AF_INET:
751       mgroup.in.sin_port = 0;
752       break;
753     case AF_INET6:
754       mgroup.in6.sin6_port = 0;
755       break;
756     default:
757       disorder_fatal(0, "unsupported address family %d",
758                      (int)res->ai_addr->sa_family);
759     }
760     /* Bind to to the multicast group address */
761     if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
762       disorder_fatal(errno, "error binding socket to %s",
763                      format_sockaddr(res->ai_addr));
764     /* Add multicast group membership */
765     switch(mgroup.sa.sa_family) {
766     case PF_INET:
767       mreq.imr_multiaddr = mgroup.in.sin_addr;
768       mreq.imr_interface.s_addr = 0;      /* use primary interface */
769       if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
770                     &mreq, sizeof mreq) < 0)
771         disorder_fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP");
772       break;
773     case PF_INET6:
774       mreq6.ipv6mr_multiaddr = mgroup.in6.sin6_addr;
775       memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface);
776       if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
777                     &mreq6, sizeof mreq6) < 0)
778         disorder_fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP");
779       break;
780     default:
781       disorder_fatal(0, "unsupported address family %d", res->ai_family);
782     }
783     /* Report what we did */
784     disorder_info("listening on %s multicast group %s",
785                   format_sockaddr(res->ai_addr), format_sockaddr(&mgroup.sa));
786   } else {
787     /* Bind to 0/port */
788     switch(res->ai_addr->sa_family) {
789     case AF_INET: {
790       struct sockaddr_in *in = (struct sockaddr_in *)res->ai_addr;
791       
792       memset(&in->sin_addr, 0, sizeof (struct in_addr));
793       break;
794     }
795     case AF_INET6: {
796       struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)res->ai_addr;
797       
798       memset(&in6->sin6_addr, 0, sizeof (struct in6_addr));
799       break;
800     }
801     default:
802       disorder_fatal(0, "unsupported family %d", (int)res->ai_addr->sa_family);
803     }
804     if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
805       disorder_fatal(errno, "error binding socket to %s",
806                      format_sockaddr(res->ai_addr));
807     /* Report what we did */
808     disorder_info("listening on %s", format_sockaddr(res->ai_addr));
809   }
810   len = sizeof rcvbuf;
811   if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
812     disorder_fatal(errno, "error calling getsockopt SO_RCVBUF");
813   if(target_rcvbuf > rcvbuf) {
814     if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
815                   &target_rcvbuf, sizeof target_rcvbuf) < 0)
816       disorder_error(errno, "error calling setsockopt SO_RCVBUF %d", 
817                      target_rcvbuf);
818       /* We try to carry on anyway */
819     else
820       disorder_info("changed socket receive buffer from %d to %d",
821                     rcvbuf, target_rcvbuf);
822   } else
823     disorder_info("default socket receive buffer %d", rcvbuf);
824   //info("minbuffer %u maxbuffer %u", minbuffer, maxbuffer);
825   if(logfp)
826     disorder_info("WARNING: -L option can impact performance");
827   if(control_socket) {
828     pthread_t tid;
829
830     if((err = pthread_create(&tid, 0, control_thread, 0)))
831       disorder_fatal(err, "pthread_create control_thread");
832   }
833   if(dumpfile) {
834     int fd;
835     unsigned char buffer[65536];
836     size_t written;
837
838     if((fd = open(dumpfile, O_RDWR|O_TRUNC|O_CREAT, 0666)) < 0)
839       disorder_fatal(errno, "opening %s", dumpfile);
840     /* Fill with 0s to a suitable size */
841     memset(buffer, 0, sizeof buffer);
842     for(written = 0; written < dump_size * sizeof(int16_t);
843         written += sizeof buffer) {
844       if(write(fd, buffer, sizeof buffer) < 0)
845         disorder_fatal(errno, "clearing %s", dumpfile);
846     }
847     /* Map the buffer into memory for convenience */
848     dump_buffer = mmap(0, dump_size * sizeof(int16_t), PROT_READ|PROT_WRITE,
849                        MAP_SHARED, fd, 0);
850     if(dump_buffer == (void *)-1)
851       disorder_fatal(errno, "mapping %s", dumpfile);
852     disorder_info("dumping to %s", dumpfile);
853   }
854   /* Set up output.  Currently we only support L16 so there's no harm setting
855    * the format before we know what it is! */
856   uaudio_set_format(44100/*Hz*/, 2/*channels*/,
857                     16/*bits/channel*/, 1/*signed*/);
858   uaudio_set("application", "disorder-playrtp");
859   backend->start(playrtp_callback, NULL);
860   /* We receive and convert audio data in a background thread */
861   if((err = pthread_create(&ltid, 0, listen_thread, 0)))
862     disorder_fatal(err, "pthread_create listen_thread");
863   /* We have a second thread to add received packets to the queue */
864   if((err = pthread_create(&ltid, 0, queue_thread, 0)))
865     disorder_fatal(err, "pthread_create queue_thread");
866   pthread_mutex_lock(&lock);
867   time_t lastlog = 0;
868   for(;;) {
869     /* Wait for the buffer to fill up a bit */
870     playrtp_fill_buffer();
871     /* Start playing now */
872     disorder_info("Playing...");
873     next_timestamp = pheap_first(&packets)->timestamp;
874     active = 1;
875     pthread_mutex_unlock(&lock);
876     backend->activate();
877     pthread_mutex_lock(&lock);
878     /* Wait until the buffer empties out
879      *
880      * If there's a packet that we can play right now then we definitely
881      * continue.
882      *
883      * Also if there's at least minbuffer samples we carry on regardless and
884      * insert silence.  The assumption is there's been a pause but more data
885      * is now available.
886      */
887     while(nsamples >= minbuffer
888           || (nsamples > 0
889               && contains(pheap_first(&packets), next_timestamp))) {
890       if(monitor) {
891         time_t now = xtime(0);
892
893         if(now >= lastlog + 60) {
894           int offset = nsamples - minbuffer;
895           double offtime = (double)offset / (uaudio_rate * uaudio_channels);
896           disorder_info("%+d samples off (%d.%02ds, %d bytes)",
897                         offset,
898                         (int)fabs(offtime) * (offtime < 0 ? -1 : 1),
899                         (int)(fabs(offtime) * 100) % 100,
900                         offset * uaudio_bits / CHAR_BIT);
901           lastlog = now;
902         }
903       }
904       //fprintf(stderr, "%8u/%u (%u) PLAYING\n", nsamples, maxbuffer, minbuffer);
905       pthread_cond_wait(&cond, &lock);
906     }
907 #if 0
908     if(nsamples) {
909       struct packet *p = pheap_first(&packets);
910       fprintf(stderr, "nsamples=%u (%u) next_timestamp=%"PRIx32", first packet is [%"PRIx32",%"PRIx32")\n",
911               nsamples, minbuffer, next_timestamp,p->timestamp,p->timestamp+p->nsamples);
912     }
913 #endif
914     /* Stop playing for a bit until the buffer re-fills */
915     pthread_mutex_unlock(&lock);
916     backend->deactivate();
917     pthread_mutex_lock(&lock);
918     active = 0;
919     /* Go back round */
920   }
921   return 0;
922 }
923
924 /*
925 Local Variables:
926 c-basic-offset:2
927 comment-column:40
928 fill-column:79
929 indent-tabs-mode:nil
930 End:
931 */