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