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