chiark / gitweb /
0b5bc047135bbd4c9b498e64626c30631dc7d094
[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 "client.h"
80 #include "playrtp.h"
81
82 #define readahead linux_headers_are_borked
83
84 /** @brief RTP socket */
85 static int rtpfd;
86
87 /** @brief Log output */
88 static FILE *logfp;
89
90 /** @brief Output device */
91 const char *device;
92
93 /** @brief Minimum low watermark
94  *
95  * We'll stop playing if there's only this many samples in the buffer. */
96 unsigned minbuffer = 2 * 44100 / 10;  /* 0.2 seconds */
97
98 /** @brief Buffer high watermark
99  *
100  * We'll only start playing when this many samples are available. */
101 static unsigned readahead = 2 * 2 * 44100;
102
103 /** @brief Maximum buffer size
104  *
105  * We'll stop reading from the network if we have this many samples. */
106 static unsigned maxbuffer;
107
108 /** @brief Received packets
109  * Protected by @ref receive_lock
110  *
111  * Received packets are added to this list, and queue_thread() picks them off
112  * it and adds them to @ref packets.  Whenever a packet is added to it, @ref
113  * receive_cond is signalled.
114  */
115 struct packet *received_packets;
116
117 /** @brief Tail of @ref received_packets
118  * Protected by @ref receive_lock
119  */
120 struct packet **received_tail = &received_packets;
121
122 /** @brief Lock protecting @ref received_packets 
123  *
124  * Only listen_thread() and queue_thread() ever hold this lock.  It is vital
125  * that queue_thread() not hold it any longer than it strictly has to. */
126 pthread_mutex_t receive_lock = PTHREAD_MUTEX_INITIALIZER;
127
128 /** @brief Condition variable signalled when @ref received_packets is updated
129  *
130  * Used by listen_thread() to notify queue_thread() that it has added another
131  * packet to @ref received_packets. */
132 pthread_cond_t receive_cond = PTHREAD_COND_INITIALIZER;
133
134 /** @brief Length of @ref received_packets */
135 uint32_t nreceived;
136
137 /** @brief Binary heap of received packets */
138 struct pheap packets;
139
140 /** @brief Total number of samples available
141  *
142  * We make this volatile because we inspect it without a protecting lock,
143  * so the usual pthread_* guarantees aren't available.
144  */
145 volatile uint32_t nsamples;
146
147 /** @brief Timestamp of next packet to play.
148  *
149  * This is set to the timestamp of the last packet, plus the number of
150  * samples it contained.  Only valid if @ref active is nonzero.
151  */
152 uint32_t next_timestamp;
153
154 /** @brief True if actively playing
155  *
156  * This is true when playing and false when just buffering. */
157 int active;
158
159 /** @brief Lock protecting @ref packets */
160 pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
161
162 /** @brief Condition variable signalled whenever @ref packets is changed */
163 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
164
165 #if HAVE_ALSA_ASOUNDLIB_H
166 # define DEFAULT_BACKEND playrtp_alsa
167 #elif HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
168 # define DEFAULT_BACKEND playrtp_oss
169 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
170 # define DEFAULT_BACKEND playrtp_coreaudio
171 #else
172 # error No known backend
173 #endif
174
175 /** @brief Backend to play with */
176 static void (*backend)(void) = &DEFAULT_BACKEND;
177
178 HEAP_DEFINE(pheap, struct packet *, lt_packet);
179
180 static const struct option options[] = {
181   { "help", no_argument, 0, 'h' },
182   { "version", no_argument, 0, 'V' },
183   { "debug", no_argument, 0, 'd' },
184   { "device", required_argument, 0, 'D' },
185   { "min", required_argument, 0, 'm' },
186   { "max", required_argument, 0, 'x' },
187   { "buffer", required_argument, 0, 'b' },
188   { "rcvbuf", required_argument, 0, 'R' },
189   { "multicast", required_argument, 0, 'M' },
190 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
191   { "oss", no_argument, 0, 'o' },
192 #endif
193 #if HAVE_ALSA_ASOUNDLIB_H
194   { "alsa", no_argument, 0, 'a' },
195 #endif
196 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
197   { "core-audio", no_argument, 0, 'c' },
198 #endif
199   { "config", required_argument, 0, 'C' },
200   { 0, 0, 0, 0 }
201 };
202
203 /** @brief Drop the first packet
204  *
205  * Assumes that @ref lock is held. 
206  */
207 static void drop_first_packet(void) {
208   if(pheap_count(&packets)) {
209     struct packet *const p = pheap_remove(&packets);
210     nsamples -= p->nsamples;
211     playrtp_free_packet(p);
212     pthread_cond_broadcast(&cond);
213   }
214 }
215
216 /** @brief Background thread adding packets to heap
217  *
218  * This just transfers packets from @ref received_packets to @ref packets.  It
219  * is important that it holds @ref receive_lock for as little time as possible,
220  * in order to minimize the interval between calls to read() in
221  * listen_thread().
222  */
223 static void *queue_thread(void attribute((unused)) *arg) {
224   struct packet *p;
225
226   for(;;) {
227     /* Get the next packet */
228     pthread_mutex_lock(&receive_lock);
229     while(!received_packets)
230       pthread_cond_wait(&receive_cond, &receive_lock);
231     p = received_packets;
232     received_packets = p->next;
233     if(!received_packets)
234       received_tail = &received_packets;
235     --nreceived;
236     pthread_mutex_unlock(&receive_lock);
237     /* Add it to the heap */
238     pthread_mutex_lock(&lock);
239     pheap_insert(&packets, p);
240     nsamples += p->nsamples;
241     pthread_cond_broadcast(&cond);
242     pthread_mutex_unlock(&lock);
243   }
244 }
245
246 /** @brief Background thread collecting samples
247  *
248  * This function collects samples, perhaps converts them to the target format,
249  * and adds them to the packet list.
250  *
251  * It is crucial that the gap between successive calls to read() is as small as
252  * possible: otherwise packets will be dropped.
253  *
254  * We use a binary heap to ensure that the unavoidable effort is at worst
255  * logarithmic in the total number of packets - in fact if packets are mostly
256  * received in order then we will largely do constant work per packet since the
257  * newest packet will always be last.
258  *
259  * Of more concern is that we must acquire the lock on the heap to add a packet
260  * to it.  If this proves a problem in practice then the answer would be
261  * (probably doubly) linked list with new packets added the end and a second
262  * thread which reads packets off the list and adds them to the heap.
263  *
264  * We keep memory allocation (mostly) very fast by keeping pre-allocated
265  * packets around; see @ref playrtp_new_packet().
266  */
267 static void *listen_thread(void attribute((unused)) *arg) {
268   struct packet *p = 0;
269   int n;
270   struct rtp_header header;
271   uint16_t seq;
272   uint32_t timestamp;
273   struct iovec iov[2];
274
275   for(;;) {
276     if(!p)
277       p = playrtp_new_packet();
278     iov[0].iov_base = &header;
279     iov[0].iov_len = sizeof header;
280     iov[1].iov_base = p->samples_raw;
281     iov[1].iov_len = sizeof p->samples_raw / sizeof *p->samples_raw;
282     n = readv(rtpfd, iov, 2);
283     if(n < 0) {
284       switch(errno) {
285       case EINTR:
286         continue;
287       default:
288         fatal(errno, "error reading from socket");
289       }
290     }
291     /* Ignore too-short packets */
292     if((size_t)n <= sizeof (struct rtp_header)) {
293       info("ignored a short packet");
294       continue;
295     }
296     timestamp = htonl(header.timestamp);
297     seq = htons(header.seq);
298     /* Ignore packets in the past */
299     if(active && lt(timestamp, next_timestamp)) {
300       info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
301            timestamp, next_timestamp);
302       continue;
303     }
304     p->next = 0;
305     p->flags = 0;
306     p->timestamp = timestamp;
307     /* Convert to target format */
308     if(header.mpt & 0x80)
309       p->flags |= IDLE;
310     switch(header.mpt & 0x7F) {
311     case 10:
312       p->nsamples = (n - sizeof header) / sizeof(uint16_t);
313       break;
314       /* TODO support other RFC3551 media types (when the speaker does) */
315     default:
316       fatal(0, "unsupported RTP payload type %d",
317             header.mpt & 0x7F);
318     }
319     if(logfp)
320       fprintf(logfp, "sequence %u timestamp %"PRIx32" length %"PRIx32" end %"PRIx32"\n",
321               seq, timestamp, p->nsamples, timestamp + p->nsamples);
322     /* Stop reading if we've reached the maximum.
323      *
324      * This is rather unsatisfactory: it means that if packets get heavily
325      * out of order then we guarantee dropouts.  But for now... */
326     if(nsamples >= maxbuffer) {
327       pthread_mutex_lock(&lock);
328       while(nsamples >= maxbuffer)
329         pthread_cond_wait(&cond, &lock);
330       pthread_mutex_unlock(&lock);
331     }
332     /* Add the packet to the receive queue */
333     pthread_mutex_lock(&receive_lock);
334     *received_tail = p;
335     received_tail = &p->next;
336     ++nreceived;
337     pthread_cond_signal(&receive_cond);
338     pthread_mutex_unlock(&receive_lock);
339     /* We'll need a new packet */
340     p = 0;
341   }
342 }
343
344 /** @brief Wait until the buffer is adequately full
345  *
346  * Must be called with @ref lock held.
347  */
348 void playrtp_fill_buffer(void) {
349   while(nsamples)
350     drop_first_packet();
351   info("Buffering...");
352   while(nsamples < readahead)
353     pthread_cond_wait(&cond, &lock);
354   next_timestamp = pheap_first(&packets)->timestamp;
355   active = 1;
356 }
357
358 /** @brief Find next packet
359  * @return Packet to play or NULL if none found
360  *
361  * The return packet is merely guaranteed not to be in the past: it might be
362  * the first packet in the future rather than one that is actually suitable to
363  * play.
364  *
365  * Must be called with @ref lock held.
366  */
367 struct packet *playrtp_next_packet(void) {
368   while(pheap_count(&packets)) {
369     struct packet *const p = pheap_first(&packets);
370     if(le(p->timestamp + p->nsamples, next_timestamp)) {
371       /* This packet is in the past.  Drop it and try another one. */
372       drop_first_packet();
373     } else
374       /* This packet is NOT in the past.  (It might be in the future
375        * however.) */
376       return p;
377   }
378   return 0;
379 }
380
381 /** @brief Play an RTP stream
382  *
383  * This is the guts of the program.  It is responsible for:
384  * - starting the listening thread
385  * - opening the audio device
386  * - reading ahead to build up a buffer
387  * - arranging for audio to be played
388  * - detecting when the buffer has got too small and re-buffering
389  */
390 static void play_rtp(void) {
391   pthread_t ltid;
392
393   /* We receive and convert audio data in a background thread */
394   pthread_create(&ltid, 0, listen_thread, 0);
395   /* We have a second thread to add received packets to the queue */
396   pthread_create(&ltid, 0, queue_thread, 0);
397   /* The rest of the work is backend-specific */
398   backend();
399 }
400
401 /* display usage message and terminate */
402 static void help(void) {
403   xprintf("Usage:\n"
404           "  disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
405           "Options:\n"
406           "  --device, -D DEVICE     Output device\n"
407           "  --min, -m FRAMES        Buffer low water mark\n"
408           "  --buffer, -b FRAMES     Buffer high water mark\n"
409           "  --max, -x FRAMES        Buffer maximum size\n"
410           "  --rcvbuf, -R BYTES      Socket receive buffer size\n"
411           "  --multicast, -M GROUP   Join multicast group\n"
412           "  --config, -C PATH       Set configuration file\n"
413 #if HAVE_ALSA_ASOUNDLIB_H
414           "  --alsa, -a              Use ALSA to play audio\n"
415 #endif
416 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
417           "  --oss, -o               Use OSS to play audio\n"
418 #endif
419 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
420           "  --core-audio, -c        Use Core Audio to play audio\n"
421 #endif
422           "  --help, -h              Display usage message\n"
423           "  --version, -V           Display version number\n"
424           );
425   xfclose(stdout);
426   exit(0);
427 }
428
429 /* display version number and terminate */
430 static void version(void) {
431   xprintf("disorder-playrtp version %s\n", disorder_version_string);
432   xfclose(stdout);
433   exit(0);
434 }
435
436 int main(int argc, char **argv) {
437   int n;
438   struct addrinfo *res;
439   struct stringlist sl;
440   char *sockname;
441   int rcvbuf, target_rcvbuf = 131072;
442   socklen_t len;
443   char *multicast_group = 0;
444   struct ip_mreq mreq;
445   struct ipv6_mreq mreq6;
446   disorder_client *c;
447   char *address, *port;
448
449   static const struct addrinfo prefs = {
450     AI_PASSIVE,
451     PF_INET,
452     SOCK_DGRAM,
453     IPPROTO_UDP,
454     0,
455     0,
456     0,
457     0
458   };
459
460   mem_init();
461   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
462   while((n = getopt_long(argc, argv, "hVdD:m:b:x:L:R:M:aocC:", options, 0)) >= 0) {
463     switch(n) {
464     case 'h': help();
465     case 'V': version();
466     case 'd': debugging = 1; break;
467     case 'D': device = optarg; break;
468     case 'm': minbuffer = 2 * atol(optarg); break;
469     case 'b': readahead = 2 * atol(optarg); break;
470     case 'x': maxbuffer = 2 * atol(optarg); break;
471     case 'L': logfp = fopen(optarg, "w"); break;
472     case 'R': target_rcvbuf = atoi(optarg); break;
473     case 'M': multicast_group = optarg; break;
474 #if HAVE_ALSA_ASOUNDLIB_H
475     case 'a': backend = playrtp_alsa; break;
476 #endif
477 #if HAVE_SYS_SOUNDCARD_H || EMPEG_HOST
478     case 'o': backend = playrtp_oss; break;
479 #endif
480 #if HAVE_COREAUDIO_AUDIOHARDWARE_H      
481     case 'c': backend = playrtp_coreaudio; break;
482 #endif
483     case 'C': configfile = optarg; break;
484     default: fatal(0, "invalid option");
485     }
486   }
487   if(config_read(0)) fatal(0, "cannot read configuration");
488   if(!maxbuffer)
489     maxbuffer = 4 * readahead;
490   argc -= optind;
491   argv += optind;
492   switch(argc) {
493   case 0:
494   case 1:
495     if(!(c = disorder_new(1))) exit(EXIT_FAILURE);
496     if(disorder_connect(c)) exit(EXIT_FAILURE);
497     if(disorder_rtp_address(c, &address, &port)) exit(EXIT_FAILURE);
498     sl.n = 1;
499     sl.s = &port;
500     /* set multicast_group if address is a multicast address */
501     break;
502   case 2:
503     sl.n = argc;
504     sl.s = argv;
505     break;
506   default:
507     fatal(0, "usage: disorder-playrtp [OPTIONS] [ADDRESS [PORT]]");
508   }
509   /* Listen for inbound audio data */
510   if(!(res = get_address(&sl, &prefs, &sockname)))
511     exit(1);
512   info("listening on %s", sockname);
513   if((rtpfd = socket(res->ai_family,
514                      res->ai_socktype,
515                      res->ai_protocol)) < 0)
516     fatal(errno, "error creating socket");
517   if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
518     fatal(errno, "error binding socket to %s", sockname);
519   if(multicast_group) {
520     if((n = getaddrinfo(multicast_group, 0, &prefs, &res)))
521       fatal(0, "getaddrinfo %s: %s", multicast_group, gai_strerror(n));
522     switch(res->ai_family) {
523     case PF_INET:
524       mreq.imr_multiaddr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
525       mreq.imr_interface.s_addr = 0;      /* use primary interface */
526       if(setsockopt(rtpfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
527                     &mreq, sizeof mreq) < 0)
528         fatal(errno, "error calling setsockopt IP_ADD_MEMBERSHIP");
529       break;
530     case PF_INET6:
531       mreq6.ipv6mr_multiaddr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
532       memset(&mreq6.ipv6mr_interface, 0, sizeof mreq6.ipv6mr_interface);
533       if(setsockopt(rtpfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
534                     &mreq6, sizeof mreq6) < 0)
535         fatal(errno, "error calling setsockopt IPV6_JOIN_GROUP");
536       break;
537     default:
538       fatal(0, "unsupported address family %d", res->ai_family);
539     }
540   }
541   len = sizeof rcvbuf;
542   if(getsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) < 0)
543     fatal(errno, "error calling getsockopt SO_RCVBUF");
544   if(target_rcvbuf > rcvbuf) {
545     if(setsockopt(rtpfd, SOL_SOCKET, SO_RCVBUF,
546                   &target_rcvbuf, sizeof target_rcvbuf) < 0)
547       error(errno, "error calling setsockopt SO_RCVBUF %d", 
548             target_rcvbuf);
549       /* We try to carry on anyway */
550     else
551       info("changed socket receive buffer from %d to %d",
552            rcvbuf, target_rcvbuf);
553   } else
554     info("default socket receive buffer %d", rcvbuf);
555   if(logfp)
556     info("WARNING: -L option can impact performance");
557   play_rtp();
558   return 0;
559 }
560
561 /*
562 Local Variables:
563 c-basic-offset:2
564 comment-column:40
565 fill-column:79
566 indent-tabs-mode:nil
567 End:
568 */