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