chiark / gitweb /
1be801f53153bdf93054c7c7cb08cf79f632c6f9
[disorder] / clients / playrtp.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2007 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20 /** @file clients/playrtp.c
21  * @brief RTP player
22  *
23  * This player supports Linux (<a href="http://www.alsa-project.org/">ALSA</a>)
24  * and Apple Mac (<a
25  * href="http://developer.apple.com/audio/coreaudio.html">Core Audio</a>)
26  * systems.  There is no support for Microsoft Windows yet, and that will in
27  * fact probably an entirely separate program.
28  *
29  * The program runs (at least) three threads.  listen_thread() is responsible
30  * for reading RTP packets off the wire and adding them to the linked list @ref
31  * received_packets, assuming they are basically sound.  queue_thread() takes
32  * packets off this linked list and adds them to @ref packets (an operation
33  * which might be much slower due to contention for @ref lock).
34  *
35  * The main thread is responsible for actually playing audio.  In ALSA this
36  * means it waits until ALSA says it's ready for more audio which it then
37  * plays.  See @ref clients/playrtp-alsa.c.
38  *
39  * In Core Audio the main thread is only responsible for starting and stopping
40  * play: the system does the actual playback in its own private thread, and
41  * calls adioproc() to fetch the audio data.  See @ref
42  * clients/playrtp-coreaudio.c.
43  *
44  * Sometimes it happens that there is no audio available to play.  This may
45  * because the server went away, or a packet was dropped, or the server
46  * deliberately did not send any sound because it encountered a silence.
47  *
48  * Assumptions:
49  * - it is safe to read uint32_t values without a lock protecting them
50  */
51
52 #include <config.h>
53 #include "types.h"
54
55 #include <getopt.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <sys/socket.h>
59 #include <sys/types.h>
60 #include <sys/socket.h>
61 #include <netdb.h>
62 #include <pthread.h>
63 #include <locale.h>
64 #include <sys/uio.h>
65 #include <string.h>
66 #include <assert.h>
67 #include <errno.h>
68
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 "playrtp.h"
80
81 #define readahead linux_headers_are_borked
82
83 /** @brief RTP socket */
84 static int rtpfd;
85
86 /** @brief Log output */
87 static FILE *logfp;
88
89 /** @brief Output device */
90 const char *device;
91
92 /** @brief Minimum low watermark
93  *
94  * We'll stop playing if there's only this many samples in the buffer. */
95 unsigned minbuffer = 2 * 44100 / 10;  /* 0.2 seconds */
96
97 /** @brief Buffer high watermark
98  *
99  * We'll only start playing when this many samples are available. */
100 static unsigned readahead = 2 * 2 * 44100;
101
102 /** @brief Maximum buffer size
103  *
104  * We'll stop reading from the network if we have this many samples. */
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 #if API_ALSA
165 # define DEFAULT_BACKEND playrtp_alsa
166 #elif HAVE_SYS_SOUNDCARD_H
167 # define DEFAULT_BACKEND playrtp_oss
168 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
169 # define DEFAULT_BACKEND playrtp_coreaudio
170 #else
171 # error No known backend
172 #endif
173
174 /** @brief Backend to play with */
175 static void (*backend)(void) = &DEFAULT_BACKEND;
176
177 HEAP_DEFINE(pheap, struct packet *, lt_packet);
178
179 static const struct option options[] = {
180   { "help", no_argument, 0, 'h' },
181   { "version", no_argument, 0, 'V' },
182   { "debug", no_argument, 0, 'd' },
183   { "device", required_argument, 0, 'D' },
184   { "min", required_argument, 0, 'm' },
185   { "max", required_argument, 0, 'x' },
186   { "buffer", required_argument, 0, 'b' },
187   { "rcvbuf", required_argument, 0, 'R' },
188   { "multicast", required_argument, 0, 'M' },
189 #if HAVE_SYS_SOUNDCARD_H
190   { "oss", no_argument, 0, 'o' },
191 #endif
192 #if API_ALSA
193   { "alsa", no_argument, 0, 'a' },
194 #endif
195 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
196   { "core-audio", no_argument, 0, 'c' },
197 #endif
198   { 0, 0, 0, 0 }
199 };
200
201 /** @brief Drop the first packet
202  *
203  * Assumes that @ref lock is held. 
204  */
205 static void drop_first_packet(void) {
206   if(pheap_count(&packets)) {
207     struct packet *const p = pheap_remove(&packets);
208     nsamples -= p->nsamples;
209     playrtp_free_packet(p);
210     pthread_cond_broadcast(&cond);
211   }
212 }
213
214 /** @brief Background thread adding packets to heap
215  *
216  * This just transfers packets from @ref received_packets to @ref packets.  It
217  * is important that it holds @ref receive_lock for as little time as possible,
218  * in order to minimize the interval between calls to read() in
219  * listen_thread().
220  */
221 static void *queue_thread(void attribute((unused)) *arg) {
222   struct packet *p;
223
224   for(;;) {
225     /* Get the next packet */
226     pthread_mutex_lock(&receive_lock);
227     while(!received_packets)
228       pthread_cond_wait(&receive_cond, &receive_lock);
229     p = received_packets;
230     received_packets = p->next;
231     if(!received_packets)
232       received_tail = &received_packets;
233     --nreceived;
234     pthread_mutex_unlock(&receive_lock);
235     /* Add it to the heap */
236     pthread_mutex_lock(&lock);
237     pheap_insert(&packets, p);
238     nsamples += p->nsamples;
239     pthread_cond_broadcast(&cond);
240     pthread_mutex_unlock(&lock);
241   }
242 }
243
244 /** @brief Background thread collecting samples
245  *
246  * This function collects samples, perhaps converts them to the target format,
247  * and adds them to the packet list.
248  *
249  * It is crucial that the gap between successive calls to read() is as small as
250  * possible: otherwise packets will be dropped.
251  *
252  * We use a binary heap to ensure that the unavoidable effort is at worst
253  * logarithmic in the total number of packets - in fact if packets are mostly
254  * received in order then we will largely do constant work per packet since the
255  * newest packet will always be last.
256  *
257  * Of more concern is that we must acquire the lock on the heap to add a packet
258  * to it.  If this proves a problem in practice then the answer would be
259  * (probably doubly) linked list with new packets added the end and a second
260  * thread which reads packets off the list and adds them to the heap.
261  *
262  * We keep memory allocation (mostly) very fast by keeping pre-allocated
263  * packets around; see @ref playrtp_new_packet().
264  */
265 static void *listen_thread(void attribute((unused)) *arg) {
266   struct packet *p = 0;
267   int n;
268   struct rtp_header header;
269   uint16_t seq;
270   uint32_t timestamp;
271   struct iovec iov[2];
272
273   for(;;) {
274     if(!p)
275       p = playrtp_new_packet();
276     iov[0].iov_base = &header;
277     iov[0].iov_len = sizeof header;
278     iov[1].iov_base = p->samples_raw;
279     iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
280     n = readv(rtpfd, iov, 2);
281     if(n < 0) {
282       switch(errno) {
283       case EINTR:
284         continue;
285       default:
286         fatal(errno, "error reading from socket");
287       }
288     }
289     /* Ignore too-short packets */
290     if((size_t)n <= sizeof (struct rtp_header)) {
291       info("ignored a short packet");
292       continue;
293     }
294     timestamp = htonl(header.timestamp);
295     seq = htons(header.seq);
296     /* Ignore packets in the past */
297     if(active && lt(timestamp, next_timestamp)) {
298       info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
299            timestamp, next_timestamp);
300       continue;
301     }
302     p->next = 0;
303     p->flags = 0;
304     p->timestamp = timestamp;
305     /* Convert to target format */
306     if(header.mpt & 0x80)
307       p->flags |= IDLE;
308     switch(header.mpt & 0x7F) {
309     case 10:
310       p->nsamples = (n - sizeof header) / sizeof(uint16_t);
311       break;
312       /* TODO support other RFC3551 media types (when the speaker does) */
313     default:
314       fatal(0, "unsupported RTP payload type %d",
315             header.mpt & 0x7F);
316     }
317     if(logfp)
318       fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
319               seq, timestamp, p->nsamples, timestamp + p->nsamples);
320     /* Stop reading if we've reached the maximum.
321      *
322      * This is rather unsatisfactory: it means that if packets get heavily
323      * out of order then we guarantee dropouts.  But for now... */
324     if(nsamples >= maxbuffer) {
325       pthread_mutex_lock(&lock);
326       while(nsamples >= maxbuffer)
327         pthread_cond_wait(&cond, &lock);
328       pthread_mutex_unlock(&lock);
329     }
330     /* Add the packet to the receive queue */
331     pthread_mutex_lock(&receive_lock);
332     *received_tail = p;
333     received_tail = &p->next;
334     ++nreceived;
335     pthread_cond_signal(&receive_cond);
336     pthread_mutex_unlock(&receive_lock);
337     /* We'll need a new packet */
338     p = 0;
339   }
340 }
341
342 /** @brief Wait until the buffer is adequately full
343  *
344  * Must be called with @ref lock held.
345  */
346 void playrtp_fill_buffer(void) {
347   while(nsamples)
348     drop_first_packet();
349   info("Buffering...");
350   while(nsamples < readahead)
351     pthread_cond_wait(&cond, &lock);
352   next_timestamp = pheap_first(&packets)->timestamp;
353   active = 1;
354 }
355
356 /** @brief Find next packet
357  * @return Packet to play or NULL if none found
358  *
359  * The return packet is merely guaranteed not to be in the past: it might be
360  * the first packet in the future rather than one that is actually suitable to
361  * play.
362  *
363  * Must be called with @ref lock held.
364  */
365 struct packet *playrtp_next_packet(void) {
366   while(pheap_count(&packets)) {
367     struct packet *const p = pheap_first(&packets);
368     if(le(p->timestamp + p->nsamples, next_timestamp)) {
369       /* This packet is in the past.  Drop it and try another one. */
370       drop_first_packet();
371     } else
372       /* This packet is NOT in the past.  (It might be in the future
373        * however.) */
374       return p;
375   }
376   return 0;
377 }
378
379 /** @brief Play an RTP stream
380  *
381  * This is the guts of the program.  It is responsible for:
382  * - starting the listening thread
383  * - opening the audio device
384  * - reading ahead to build up a buffer
385  * - arranging for audio to be played
386  * - detecting when the buffer has got too small and re-buffering
387  */
388 static void play_rtp(void) {
389   pthread_t ltid;
390
391   /* We receive and convert audio data in a background thread */
392   pthread_create(&ltid, 0, listen_thread, 0);
393   /* We have a second thread to add received packets to the queue */
394   pthread_create(&ltid, 0, queue_thread, 0);
395   /* The rest of the work is backend-specific */
396   backend();
397 }
398
399 /* display usage message and terminate */
400 static void help(void) {
401   xprintf("Usage:\n"
402           "  disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
403           "Options:\n"
404           "  --device, -D DEVICE     Output device\n"
405           "  --min, -m FRAMES        Buffer low water mark\n"
406           "  --buffer, -b FRAMES     Buffer high water mark\n"
407           "  --max, -x FRAMES        Buffer maximum size\n"
408           "  --rcvbuf, -R BYTES      Socket receive buffer size\n"
409           "  --multicast, -M GROUP   Join multicast group\n"
410 #if API_ALSA
411           "  --alsa, -a              Use ALSA to play audio\n"
412 #endif
413 #if HAVE_SYS_SOUNDCARD_H
414           "  --oss, -o               Use OSS to play audio\n"
415 #endif
416 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
417           "  --core-audio, -c        Use Core Audio to play audio\n"
418 #endif
419           "  --help, -h              Display usage message\n"
420           "  --version, -V           Display version number\n"
421           );
422   xfclose(stdout);
423   exit(0);
424 }
425
426 /* display version number and terminate */
427 static void version(void) {
428   xprintf("disorder-playrtp version %s\n", disorder_version_string);
429   xfclose(stdout);
430   exit(0);
431 }
432
433 int main(int argc, char **argv) {
434   int n;
435   struct addrinfo *res;
436   struct stringlist sl;
437   char *sockname;
438   int rcvbuf, target_rcvbuf = 131072;
439   socklen_t len;
440   char *multicast_group = 0;
441   struct ip_mreq mreq;
442   struct ipv6_mreq mreq6;
443
444   static const struct addrinfo prefs = {
445     AI_PASSIVE,
446     PF_INET,
447     SOCK_DGRAM,
448     IPPROTO_UDP,
449     0,
450     0,
451     0,
452     0
453   };
454
455   mem_init();
456   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
457   while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:R:M:aoc", options, 0)) >= 0) {
458     switch(n) {
459     case 'h': help();
460     case 'V': version();
461     case 'd': debugging = 1; break;
462     case 'D': device = optarg; break;
463     case 'm': minbuffer = 2 * atol(optarg); break;
464     case 'b': readahead = 2 * atol(optarg); break;
465     case 'x': maxbuffer = 2 * atol(optarg); break;
466     case 'L': logfp = fopen(optarg, "w"); break;
467     case 'R': target_rcvbuf = atoi(optarg); break;
468     case 'M': multicast_group = optarg; break;
469 #if API_ALSA
470     case 'a': backend = playrtp_alsa; break;
471 #endif
472 #if 0
473 #if HAVE_SYS_SOUNDCARD_H      
474     case 'o': backend = playrtp_oss; break;
475 #endif
476 #if HAVE_COREAUDIO_AUDIOHARDWARE_H      
477     case 'c': backend = playrtp_coreaudio; break;
478 #endif
479 #endif
480     default: fatal(0, "invalid option");
481     }
482   }
483   if(!maxbuffer)
484     maxbuffer = 4 * readahead;
485   argc -= optind;
486   argv += optind;
487   if(argc < 1 || argc > 2)
488     fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
489   sl.n = argc;
490   sl.s = argv;
491   /* Listen for inbound audio data */
492   if(!(res = get_address(&sl, &prefs, &sockname)))
493     exit(1);
494   if((rtpfd = socket(res->ai_family,
495                      res->ai_socktype,
496                      res->ai_protocol)) < 0)
497     fatal(errno, "error creating socket");
498   if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
499     fatal(errno, "error binding socket to %s", sockname);
500   if(multicast_group) {
501     if((n = getaddrinfo(multicast_group, 0, &prefs, &res)))
502       fatal(0, "getaddrinfo %s: %s", multicast_group, gai_strerror(n));
503     switch(res->ai_family) {
504     case PF_INET:
505       mreq.imr_multiaddr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
506       mreq.imr_interface.s_addr = 0;      /* use primary interface */
507       if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
508                     &mreq, sizeof mreq) < 0)
509         fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP");
510       break;
511     case PF_INET6:
512       mreq6.ipv6mr_multiaddr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
513       memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface);
514       if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
515                     &mreq6, sizeof mreq6) < 0)
516         fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP");
517       break;
518     default:
519       fatal(0, "unsupported address family %d", res->ai_family);
520     }
521   }
522   len = sizeof rcvbuf;
523   if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
524     fatal(errno, "error calling getsockopt SO_RCVBUF");
525   if(target_rcvbuf > rcvbuf) {
526     if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
527                   &target_rcvbuf, sizeof target_rcvbuf) < 0)
528       error(errno, "error calling setsockopt SO_RCVBUF %d", 
529             target_rcvbuf);
530       /* We try to carry on anyway */
531     else
532       info("changed socket receive buffer from %d to %d",
533            rcvbuf, target_rcvbuf);
534   } else
535     info("default socket receive buffer %d", rcvbuf);
536   if(logfp)
537     info("WARNING: -L option can impact performance");
538   play_rtp();
539   return 0;
540 }
541
542 /*
543 Local Variables:
544 c-basic-offset:2
545 comment-column:40
546 fill-column:79
547 indent-tabs-mode:nil
548 End:
549 */