chiark / gitweb /
configure.ac: Link `-lgc' when searching for `GC_mumble' functions.
[disorder] / lib / uaudio-rtp.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2009, 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 lib/uaudio-rtp.c
19  * @brief Support for RTP network play backend */
20 #include "common.h"
21
22 #include <errno.h>
23 #include <sys/socket.h>
24 #include <ifaddrs.h>
25 #include <net/if.h>
26 #include <arpa/inet.h>
27 #include <netinet/in.h>
28 #include <gcrypt.h>
29 #include <unistd.h>
30 #include <time.h>
31 #include <sys/uio.h>
32 #include <pthread.h>
33
34 #include "uaudio.h"
35 #include "mem.h"
36 #include "log.h"
37 #include "syscalls.h"
38 #include "rtp.h"
39 #include "addr.h"
40 #include "ifreq.h"
41 #include "timeval.h"
42 #include "configuration.h"
43
44 /** @brief Bytes to send per network packet
45  *
46  * This is the maximum number of bytes we pass to write(2); to determine actual
47  * packet sizes, add a UDP header and an IP header (and a link layer header if
48  * it's the link layer size you care about).
49  *
50  * Don't make this too big or arithmetic will start to overflow.
51  */
52 #define NETWORK_BYTES (1500-8/*UDP*/-40/*IP*/-8/*conservatism*/)
53
54 /** @brief RTP payload type */
55 static int rtp_payload;
56
57 /** @brief RTP output socket */
58 static int rtp_fd;
59
60 /** @brief RTP output socket (IPv6) */
61 static int rtp_fd6;
62
63 /** @brief RTP SSRC */
64 static uint32_t rtp_id;
65
66 /** @brief Base for timestamp */
67 static uint32_t rtp_base;
68
69 /** @brief RTP sequence number */
70 static uint16_t rtp_sequence;
71
72 /** @brief Network error count
73  *
74  * If too many errors occur in too short a time, we give up.
75  */
76 static int rtp_errors;
77
78 /** @brief RTP mode */
79 static int rtp_mode;
80
81 #define RTP_BROADCAST 1
82 #define RTP_MULTICAST 2
83 #define RTP_UNICAST 3
84 #define RTP_REQUEST 4
85 #define RTP_AUTO 5
86
87 /** @brief A unicast client */
88 struct rtp_recipient {
89   struct rtp_recipient *next;
90   struct sockaddr_storage sa;
91 };
92
93 /** @brief List of unicast clients */
94 static struct rtp_recipient *rtp_recipient_list;
95
96 /** @brief Mutex protecting data structures */
97 static pthread_mutex_t rtp_lock = PTHREAD_MUTEX_INITIALIZER;
98
99 static const char *const rtp_options[] = {
100   "rtp-destination",
101   "rtp-destination-port",
102   "rtp-source",
103   "rtp-source-port",
104   "multicast-ttl",
105   "multicast-loop",
106   "rtp-mode",
107   NULL
108 };
109
110 static void rtp_get_netconfig(const char *af,
111                               const char *addr,
112                               const char *port,
113                               struct netaddress *na) {
114   char *vec[3];
115   
116   vec[0] = uaudio_get(af, NULL);
117   vec[1] = uaudio_get(addr, NULL);
118   vec[2] = uaudio_get(port, NULL);
119   if(!*vec)
120     na->af = -1;
121   else
122     if(netaddress_parse(na, 3, vec))
123       disorder_fatal(0, "invalid RTP address");
124 }
125
126 static void rtp_set_netconfig(const char *af,
127                               const char *addr,
128                               const char *port,
129                               const struct netaddress *na) {
130   uaudio_set(af, NULL);
131   uaudio_set(addr, NULL);
132   uaudio_set(port, NULL);
133   if(na->af != -1) {
134     int nvec;
135     char **vec;
136
137     netaddress_format(na, &nvec, &vec);
138     if(nvec > 0) {
139       uaudio_set(af, vec[0]);
140       xfree(vec[0]);
141     }
142     if(nvec > 1) {
143       uaudio_set(addr, vec[1]);
144       xfree(vec[1]);
145     }
146     if(nvec > 2) {
147       uaudio_set(port, vec[2]);
148       xfree(vec[2]);
149     }
150     xfree(vec);
151   }
152 }
153
154 static size_t rtp_play(void *buffer, size_t nsamples, unsigned flags) {
155   struct rtp_header header;
156   struct iovec vec[2];
157
158 #if 0
159   if(flags & (UAUDIO_PAUSE|UAUDIO_RESUME))
160     fprintf(stderr, "rtp_play %zu samples%s%s%s%s\n", nsamples,
161             flags & UAUDIO_PAUSE ? " UAUDIO_PAUSE" : "",
162             flags & UAUDIO_RESUME ? " UAUDIO_RESUME" : "",
163             flags & UAUDIO_PLAYING ? " UAUDIO_PLAYING" : "",
164             flags & UAUDIO_PAUSED ? " UAUDIO_PAUSED" : "");
165 #endif
166           
167   /* We do as much work as possible before checking what time it is */
168   /* Fill out header */
169   header.vpxcc = 2 << 6;              /* V=2, P=0, X=0, CC=0 */
170   header.seq = htons(rtp_sequence++);
171   header.ssrc = rtp_id;
172   header.mpt = rtp_payload;
173   /* If we've come out of a pause, set the marker bit */
174   if(flags & UAUDIO_RESUME)
175     header.mpt |= 0x80;
176 #if !WORDS_BIGENDIAN
177   /* Convert samples to network byte order */
178   uint16_t *u = buffer, *const limit = u + nsamples;
179   while(u < limit) {
180     *u = htons(*u);
181     ++u;
182   }
183 #endif
184   vec[0].iov_base = (void *)&header;
185   vec[0].iov_len = sizeof header;
186   vec[1].iov_base = buffer;
187   vec[1].iov_len = nsamples * uaudio_sample_size;
188   const uint32_t timestamp = uaudio_schedule_sync();
189   header.timestamp = htonl(rtp_base + (uint32_t)timestamp);
190
191   /* We send ~120 packets a second with current arrangements.  So if we log
192    * once every 8192 packets we log about once a minute. */
193
194   if(!(ntohs(header.seq) & 8191)
195      && config->rtp_verbose)
196     disorder_info("RTP: seq %04"PRIx16" %08"PRIx32"+%08"PRIx32"=%08"PRIx32" ns %zu%s",
197                   ntohs(header.seq),
198                   rtp_base,
199                   timestamp,
200                   header.timestamp,
201                   nsamples,
202                   flags & UAUDIO_PAUSED ? " [paused]" : "");
203
204   /* If we're paused don't actually end a packet, we just pretend */
205   if(flags & UAUDIO_PAUSED) {
206     uaudio_schedule_sent(nsamples);
207     return nsamples;
208   }
209   if(rtp_mode == RTP_REQUEST) {
210     struct rtp_recipient *r;
211     struct msghdr m;
212     memset(&m, 0, sizeof m);
213     m.msg_iov = vec;
214     m.msg_iovlen = 2;
215     pthread_mutex_lock(&rtp_lock);
216     for(r = rtp_recipient_list; r; r = r->next) {
217       m.msg_name = &r->sa;
218       m.msg_namelen = r->sa.ss_family == AF_INET ? 
219         sizeof(struct sockaddr_in) : sizeof (struct sockaddr_in6);
220       sendmsg(r->sa.ss_family == AF_INET ? rtp_fd : rtp_fd6,
221               &m, MSG_DONTWAIT|MSG_NOSIGNAL);
222       // TODO similar error handling to other case?
223     }
224     pthread_mutex_unlock(&rtp_lock);
225   } else {
226     int written_bytes;
227     do {
228       written_bytes = writev(rtp_fd, vec, 2);
229     } while(written_bytes < 0 && errno == EINTR);
230     if(written_bytes < 0) {
231       disorder_error(errno, "error transmitting audio data");
232       ++rtp_errors;
233       if(rtp_errors == 10)
234         disorder_fatal(0, "too many audio transmission errors");
235       return 0;
236     } else
237       rtp_errors /= 2;                    /* gradual decay */
238   }
239   /* TODO what can we sensibly do about short writes here?  Really that's just
240    * an error and we ought to be using smaller packets. */
241   uaudio_schedule_sent(nsamples);
242   return nsamples;
243 }
244
245 static void rtp_open(void) {
246   struct addrinfo *dres, *sres;
247   static const int one = 1;
248   int sndbuf, target_sndbuf = 131072;
249   socklen_t len;
250   struct netaddress dst[1], src[1];
251   const char *mode;
252   
253   /* Get the mode */
254   mode = uaudio_get("rtp-mode", "auto");
255   if(!strcmp(mode, "broadcast")) rtp_mode = RTP_BROADCAST;
256   else if(!strcmp(mode, "multicast")) rtp_mode = RTP_MULTICAST;
257   else if(!strcmp(mode, "unicast")) rtp_mode = RTP_UNICAST;
258   else if(!strcmp(mode, "request")) rtp_mode = RTP_REQUEST;
259   else rtp_mode = RTP_AUTO;
260   /* Get the source and destination addresses (which might be missing) */
261   rtp_get_netconfig("rtp-destination-af",
262                     "rtp-destination",
263                     "rtp-destination-port",
264                     dst);
265   rtp_get_netconfig("rtp-source-af",
266                     "rtp-source",
267                     "rtp-source-port",
268                     src);
269   if(dst->af != -1) {
270     dres = netaddress_resolve(dst, 0, IPPROTO_UDP);
271     if(!dres)
272       exit(-1);
273   } else
274     dres = 0;
275   if(src->af != -1) {
276     sres = netaddress_resolve(src, 1, IPPROTO_UDP);
277     if(!sres)
278       exit(-1);
279   } else
280     sres = 0;
281   /* _AUTO inspects the destination address and acts accordingly */
282   if(rtp_mode == RTP_AUTO) {
283     if(!dres)
284       rtp_mode = RTP_REQUEST;
285     else if(multicast(dres->ai_addr))
286       rtp_mode = RTP_MULTICAST;
287     else {
288       struct ifaddrs *ifs;
289
290       if(getifaddrs(&ifs) < 0)
291         disorder_fatal(errno, "error calling getifaddrs");
292       while(ifs) {
293         /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
294          * still a null pointer.  It turns out that there's a subsequent entry
295          * for he same interface which _does_ have ifa_broadaddr though... */
296         if((ifs->ifa_flags & IFF_BROADCAST)
297            && ifs->ifa_broadaddr
298            && sockaddr_equal(ifs->ifa_broadaddr, dres->ai_addr))
299           break;
300         ifs = ifs->ifa_next;
301       }
302       if(ifs) 
303         rtp_mode = RTP_BROADCAST;
304       else
305         rtp_mode = RTP_UNICAST;
306     }
307   }
308   /* Create the socket */
309   if(rtp_mode != RTP_REQUEST) {
310     if((rtp_fd = socket(dres->ai_family,
311                         dres->ai_socktype,
312                         dres->ai_protocol)) < 0)
313       disorder_fatal(errno, "error creating RTP transmission socket");
314   } else {                              /* request mode slightly different */
315     if((rtp_fd = socket(AF_INET,
316                         SOCK_DGRAM,
317                         IPPROTO_UDP)) < 0)
318       disorder_fatal(errno, "error creating v4 RTP transmission socket");
319     if((rtp_fd6 = socket(AF_INET6,
320                          SOCK_DGRAM,
321                          IPPROTO_UDP)) < 0)
322       disorder_fatal(errno, "error creating v6 RTP transmission socket");
323   }
324   /* Configure the socket according to the desired mode */
325   switch(rtp_mode) {
326   case RTP_MULTICAST: {
327     /* Enable multicast options */
328     const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
329     const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
330     switch(dres->ai_family) {
331     case PF_INET: {
332       if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
333                     &ttl, sizeof ttl) < 0)
334         disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
335       if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
336                     &loop, sizeof loop) < 0)
337         disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
338       break;
339     }
340     case PF_INET6: {
341       if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
342                     &ttl, sizeof ttl) < 0)
343         disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
344       if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
345                     &loop, sizeof loop) < 0)
346         disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
347       break;
348     }
349     default:
350       disorder_fatal(0, "unsupported address family %d", dres->ai_family);
351     }
352     disorder_info("multicasting on %s TTL=%d loop=%s", 
353                   format_sockaddr(dres->ai_addr), ttl, loop ? "yes" : "no");
354     break;
355   }
356   case RTP_UNICAST: {
357     disorder_info("unicasting on %s", format_sockaddr(dres->ai_addr));
358     break;
359   }
360   case RTP_BROADCAST: {
361     if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
362       disorder_fatal(errno, "error setting SO_BROADCAST on broadcast socket");
363     disorder_info("broadcasting on %s", 
364                   format_sockaddr(dres->ai_addr));
365     break;
366   }
367   case RTP_REQUEST: {
368     disorder_info("will transmit on request");
369     break;
370   }
371   }
372   /* Enlarge the socket buffer */
373   len = sizeof sndbuf;
374   if(getsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
375                 &sndbuf, &len) < 0)
376     disorder_fatal(errno, "error getting SO_SNDBUF");
377   if(target_sndbuf > sndbuf) {
378     if(setsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
379                   &target_sndbuf, sizeof target_sndbuf) < 0)
380       disorder_error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
381     else
382       disorder_info("changed socket send buffer size from %d to %d",
383                     sndbuf, target_sndbuf);
384   } else
385     disorder_info("default socket send buffer is %d", sndbuf);
386   /* We might well want to set additional broadcast- or multicast-related
387    * options here */
388   if(rtp_mode != RTP_REQUEST) {
389     if(sres && bind(rtp_fd, sres->ai_addr, sres->ai_addrlen) < 0)
390       disorder_fatal(errno, "error binding broadcast socket to %s", 
391                      format_sockaddr(sres->ai_addr));
392     if(connect(rtp_fd, dres->ai_addr, dres->ai_addrlen) < 0)
393       disorder_fatal(errno, "error connecting broadcast socket to %s", 
394                      format_sockaddr(dres->ai_addr));
395   }
396   if(config->rtp_verbose)
397     disorder_info("RTP: prepared socket");
398 }
399
400 static void rtp_start(uaudio_callback *callback,
401                       void *userdata) {
402   /* We only support L16 (but we do stereo and mono and will convert sign) */
403   if(uaudio_channels == 2
404      && uaudio_bits == 16
405      && uaudio_rate == 44100)
406     rtp_payload = 10;
407   else if(uaudio_channels == 1
408      && uaudio_bits == 16
409      && uaudio_rate == 44100)
410     rtp_payload = 11;
411   else
412     disorder_fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
413                    uaudio_bits, uaudio_rate, uaudio_channels); 
414   if(config->rtp_verbose)
415     disorder_info("RTP: %d channels %d bits %d Hz payload type %d",
416                   uaudio_channels, uaudio_bits, uaudio_rate, rtp_payload);
417   /* Various fields are required to have random initial values by RFC3550.  The
418    * packet contents are highly public so there's no point asking for very
419    * strong randomness. */
420   gcry_create_nonce(&rtp_id, sizeof rtp_id);
421   gcry_create_nonce(&rtp_base, sizeof rtp_base);
422   gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
423   if(config->rtp_verbose)
424     disorder_info("RTP: id %08"PRIx32" base %08"PRIx32" initial seq %08"PRIx16,
425                   rtp_id, rtp_base, rtp_sequence);
426   rtp_open();
427   uaudio_schedule_init();
428   if(config->rtp_verbose)
429     disorder_info("RTP: initialized schedule");
430   uaudio_thread_start(callback,
431                       userdata,
432                       rtp_play,
433                       256 / uaudio_sample_size,
434                       (NETWORK_BYTES - sizeof(struct rtp_header))
435                       / uaudio_sample_size,
436                       0);
437   if(config->rtp_verbose)
438     disorder_info("RTP: created thread");
439 }
440
441 static void rtp_stop(void) {
442   uaudio_thread_stop();
443   close(rtp_fd);
444   rtp_fd = -1;
445   if(rtp_fd6 >= 0) {
446     close(rtp_fd6);
447     rtp_fd6 = -1;
448   }
449 }
450
451 static void rtp_configure(void) {
452   char buffer[64];
453
454   uaudio_set("rtp-mode", config->rtp_mode);
455   rtp_set_netconfig("rtp-destination-af",
456                     "rtp-destination",
457                     "rtp-destination-port", &config->broadcast);
458   rtp_set_netconfig("rtp-source-af",
459                     "rtp-source",
460                     "rtp-source-port", &config->broadcast_from);
461   snprintf(buffer, sizeof buffer, "%ld", config->multicast_ttl);
462   uaudio_set("multicast-ttl", buffer);
463   uaudio_set("multicast-loop", config->multicast_loop ? "yes" : "no");
464   if(config->rtp_verbose)
465     disorder_info("RTP: configured");
466 }
467
468 /** @brief Add an RTP recipient address
469  * @param sa Pointer to recipient address
470  * @return 0 on success, -1 on error
471  */
472 int rtp_add_recipient(const struct sockaddr_storage *sa) {
473   struct rtp_recipient *r;
474   int rc;
475   pthread_mutex_lock(&rtp_lock);
476   for(r = rtp_recipient_list;
477       r && sockaddrcmp((struct sockaddr *)sa,
478                        (struct sockaddr *)&r->sa);
479       r = r->next)
480     ;
481   if(r)
482     rc = -1;
483   else {
484     r = xmalloc(sizeof *r);
485     memcpy(&r->sa, sa, sizeof *sa);
486     r->next = rtp_recipient_list;
487     rtp_recipient_list = r;
488     rc = 0;
489   }
490   pthread_mutex_unlock(&rtp_lock);
491   return rc;
492 }
493
494 /** @brief Remove an RTP recipient address
495  * @param sa Pointer to recipient address
496  * @return 0 on success, -1 on error
497  */
498 int rtp_remove_recipient(const struct sockaddr_storage *sa) {
499   struct rtp_recipient *r, **rr;
500   int rc;
501   pthread_mutex_lock(&rtp_lock);
502   for(rr = &rtp_recipient_list;
503       (r = *rr) && sockaddrcmp((struct sockaddr *)sa,
504                                (struct sockaddr *)&r->sa);
505       rr = &r->next)
506     ;
507   if(r) {
508     *rr = r->next;
509     xfree(r);
510     rc = 0;
511   } else {
512     disorder_error(0, "bogus rtp_remove_recipient");
513     rc = -1;
514   }
515   pthread_mutex_unlock(&rtp_lock);
516   return rc;
517 }
518
519 const struct uaudio uaudio_rtp = {
520   .name = "rtp",
521   .options = rtp_options,
522   .start = rtp_start,
523   .stop = rtp_stop,
524   .activate = uaudio_thread_activate,
525   .deactivate = uaudio_thread_deactivate,
526   .configure = rtp_configure,
527   .flags = UAUDIO_API_SERVER,
528 };
529
530 /*
531 Local Variables:
532 c-basic-offset:2
533 comment-column:40
534 fill-column:79
535 indent-tabs-mode:nil
536 End:
537 */