2 * This file is part of DisOrder.
3 * Copyright (C) 2009, 2013 Richard Kettlewell
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.
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.
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/>.
18 /** @file lib/uaudio-rtp.c
19 * @brief Support for RTP network play backend */
23 #include <sys/socket.h>
26 #include <arpa/inet.h>
27 #include <netinet/in.h>
42 #include "configuration.h"
44 /** @brief Bytes to send per network packet */
45 static int rtp_max_payload;
47 /** @brief RTP payload type */
48 static int rtp_payload;
50 /** @brief RTP broadcast/multicast output socket */
51 static int rtp_fd = -1;
53 /** @brief RTP unicast output socket (IPv4) */
54 static int rtp_fd4 = -1;
56 /** @brief RTP unicast output socket (IPv6) */
57 static int rtp_fd6 = -1;
59 /** @brief RTP SSRC */
60 static uint32_t rtp_id;
62 /** @brief Base for timestamp */
63 static uint32_t rtp_base;
65 /** @brief RTP sequence number */
66 static uint16_t rtp_sequence;
68 /** @brief Network error count
70 * If too many errors occur in too short a time, we give up.
72 static int rtp_errors;
74 /** @brief RTP mode */
77 #define RTP_BROADCAST 1
78 #define RTP_MULTICAST 2
83 /** @brief A unicast client */
84 struct rtp_recipient {
85 struct rtp_recipient *next;
86 struct sockaddr_storage sa;
89 /** @brief List of unicast clients */
90 static struct rtp_recipient *rtp_recipient_list;
92 /** @brief Mutex protecting data structures */
93 static pthread_mutex_t rtp_lock = PTHREAD_MUTEX_INITIALIZER;
95 static const char *const rtp_options[] = {
97 "rtp-destination-port",
108 static void rtp_get_netconfig(const char *af,
111 struct netaddress *na) {
114 vec[0] = uaudio_get(af, NULL);
115 vec[1] = uaudio_get(addr, NULL);
116 vec[2] = uaudio_get(port, NULL);
120 if(netaddress_parse(na, 3, vec))
121 disorder_fatal(0, "invalid RTP address");
124 static void rtp_set_netconfig(const char *af,
127 const struct netaddress *na) {
128 uaudio_set(af, NULL);
129 uaudio_set(addr, NULL);
130 uaudio_set(port, NULL);
135 netaddress_format(na, &nvec, &vec);
137 uaudio_set(af, vec[0]);
141 uaudio_set(addr, vec[1]);
145 uaudio_set(port, vec[2]);
152 static size_t rtp_play(void *buffer, size_t nsamples, unsigned flags) {
153 struct rtp_header header;
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" : "");
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)
175 /* Convert samples to network byte order */
176 uint16_t *u = buffer, *const limit = u + nsamples;
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);
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. */
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",
200 flags & UAUDIO_PAUSED ? " [paused]" : "");
202 /* If we're paused don't actually end a packet, we just pretend */
203 if(flags & UAUDIO_PAUSED) {
204 uaudio_schedule_sent(nsamples);
207 /* Send stuff to explicitly registerd unicast addresses unconditionally */
208 struct rtp_recipient *r;
210 memset(&m, 0, sizeof m);
213 pthread_mutex_lock(&rtp_lock);
214 for(r = rtp_recipient_list; r; r = r->next) {
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?
222 pthread_mutex_unlock(&rtp_lock);
223 if(rtp_mode != RTP_REQUEST) {
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");
232 disorder_fatal(0, "too many audio transmission errors");
235 rtp_errors /= 2; /* gradual decay */
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);
243 static void hack_send_buffer_size(int fd, const char *what) {
244 int sndbuf, target_sndbuf = 131072;
245 socklen_t len = sizeof sndbuf;
247 if(getsockopt(fd, SOL_SOCKET, SO_SNDBUF,
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);
256 disorder_info("changed socket send buffer size on %socket from %d to %d",
257 what, sndbuf, target_sndbuf);
259 disorder_info("default socket send buffer on %s socket is %d",
263 static void rtp_open(void) {
264 struct addrinfo *dres, *sres;
265 static const int one = 1;
266 struct netaddress dst[1], src[1];
268 #ifdef IP_MTU_DISCOVER
269 const char *mtu_disc;
274 mode = uaudio_get("rtp-mode", "auto");
275 if(!strcmp(mode, "broadcast")) rtp_mode = RTP_BROADCAST;
276 else if(!strcmp(mode, "multicast")) rtp_mode = RTP_MULTICAST;
277 else if(!strcmp(mode, "unicast")) rtp_mode = RTP_UNICAST;
278 else if(!strcmp(mode, "request")) rtp_mode = RTP_REQUEST;
279 else rtp_mode = RTP_AUTO;
280 /* Get the source and destination addresses (which might be missing) */
281 rtp_get_netconfig("rtp-destination-af",
283 "rtp-destination-port",
285 rtp_get_netconfig("rtp-source-af",
290 dres = netaddress_resolve(dst, 0, IPPROTO_UDP);
296 sres = netaddress_resolve(src, 1, IPPROTO_UDP);
301 /* _AUTO inspects the destination address and acts accordingly */
302 if(rtp_mode == RTP_AUTO) {
304 rtp_mode = RTP_REQUEST;
305 else if(multicast(dres->ai_addr))
306 rtp_mode = RTP_MULTICAST;
310 if(getifaddrs(&ifs) < 0)
311 disorder_fatal(errno, "error calling getifaddrs");
313 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
314 * still a null pointer. It turns out that there's a subsequent entry
315 * for he same interface which _does_ have ifa_broadaddr though... */
316 if((ifs->ifa_flags & IFF_BROADCAST)
317 && ifs->ifa_broadaddr
318 && sockaddr_equal(ifs->ifa_broadaddr, dres->ai_addr))
323 rtp_mode = RTP_BROADCAST;
325 rtp_mode = RTP_UNICAST;
328 rtp_max_payload = atoi(uaudio_get("rtp-max-payload", "-1"));
329 if(rtp_max_payload < 0)
330 rtp_max_payload = 1500 - 8/*UDP*/ - 40/*IP*/ - 8/*conservatism*/;
331 /* Create the sockets */
332 if(rtp_mode != RTP_REQUEST) {
333 if((rtp_fd = socket(dres->ai_family,
335 dres->ai_protocol)) < 0)
336 disorder_fatal(errno, "error creating RTP transmission socket");
338 if((rtp_fd4 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
339 disorder_fatal(errno, "error creating v4 RTP transmission socket");
340 if((rtp_fd6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0)
341 disorder_fatal(errno, "error creating v6 RTP transmission socket");
342 /* Configure the socket according to the desired mode */
344 case RTP_MULTICAST: {
345 /* Enable multicast options */
346 const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
347 const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
348 switch(dres->ai_family) {
350 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
351 &ttl, sizeof ttl) < 0)
352 disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
353 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
354 &loop, sizeof loop) < 0)
355 disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
359 if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
360 &ttl, sizeof ttl) < 0)
361 disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
362 if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
363 &loop, sizeof loop) < 0)
364 disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
368 disorder_fatal(0, "unsupported address family %d", dres->ai_family);
370 disorder_info("multicasting on %s TTL=%d loop=%s",
371 format_sockaddr(dres->ai_addr), ttl, loop ? "yes" : "no");
375 disorder_info("unicasting on %s", format_sockaddr(dres->ai_addr));
378 case RTP_BROADCAST: {
379 if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
380 disorder_fatal(errno, "error setting SO_BROADCAST on broadcast socket");
381 disorder_info("broadcasting on %s",
382 format_sockaddr(dres->ai_addr));
386 disorder_info("will transmit on request");
390 /* Enlarge the socket buffers */
391 if (rtp_fd != -1) hack_send_buffer_size(rtp_fd, "master socket");
392 hack_send_buffer_size(rtp_fd4, "IPv4 on-demand socket");
393 hack_send_buffer_size(rtp_fd6, "IPv6 on-demand socket");
394 /* We might well want to set additional broadcast- or multicast-related
396 if(rtp_mode != RTP_REQUEST) {
397 if(sres && bind(rtp_fd, sres->ai_addr, sres->ai_addrlen) < 0)
398 disorder_fatal(errno, "error binding broadcast socket to %s",
399 format_sockaddr(sres->ai_addr));
400 if(connect(rtp_fd, dres->ai_addr, dres->ai_addrlen) < 0)
401 disorder_fatal(errno, "error connecting broadcast socket to %s",
402 format_sockaddr(dres->ai_addr));
404 #ifdef IP_MTU_DISCOVER
405 mtu_disc = uaudio_get("rtp-mtu-discovery", "default");
407 if(!strcmp(mtu_disc, "yes")) opt = IP_PMTUDISC_DO;
408 else if(!strcmp(mtu_disc, "no")) opt = IP_PMTUDISC_DONT;
410 if(setsockopt(rtp_fd4, IPPROTO_IP, IP_MTU_DISCOVER, &opt, sizeof opt))
411 disorder_fatal(errno, "error setting MTU discovery");
412 if(sres->ai_family == AF_INET &&
413 setsockopt(rtp_fd, IPPROTO_IP, IP_MTU_DISCOVER, &opt, sizeof opt))
414 disorder_fatal(errno, "error setting MTU discovery");
417 if(config->rtp_verbose)
418 disorder_info("RTP: prepared socket");
421 static void rtp_start(uaudio_callback *callback,
423 /* We only support L16 (but we do stereo and mono and will convert sign) */
424 if(uaudio_channels == 2
426 && uaudio_rate == 44100)
428 else if(uaudio_channels == 1
430 && uaudio_rate == 44100)
433 disorder_fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
434 uaudio_bits, uaudio_rate, uaudio_channels);
435 if(config->rtp_verbose)
436 disorder_info("RTP: %d channels %d bits %d Hz payload type %d",
437 uaudio_channels, uaudio_bits, uaudio_rate, rtp_payload);
438 /* Various fields are required to have random initial values by RFC3550. The
439 * packet contents are highly public so there's no point asking for very
440 * strong randomness. */
441 gcry_create_nonce(&rtp_id, sizeof rtp_id);
442 gcry_create_nonce(&rtp_base, sizeof rtp_base);
443 gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
444 if(config->rtp_verbose)
445 disorder_info("RTP: id %08"PRIx32" base %08"PRIx32" initial seq %08"PRIx16,
446 rtp_id, rtp_base, rtp_sequence);
448 uaudio_schedule_init();
449 if(config->rtp_verbose)
450 disorder_info("RTP: initialized schedule");
451 uaudio_thread_start(callback,
454 256 / uaudio_sample_size,
455 (rtp_max_payload - sizeof(struct rtp_header))
456 / uaudio_sample_size,
458 if(config->rtp_verbose)
459 disorder_info("RTP: created thread");
462 static void rtp_stop(void) {
463 uaudio_thread_stop();
464 if(rtp_fd >= 0) { close(rtp_fd); rtp_fd = -1; }
465 if(rtp_fd4 >= 0) { close(rtp_fd4); rtp_fd4 = -1; }
466 if(rtp_fd6 >= 0) { close(rtp_fd6); rtp_fd6 = -1; }
469 static void rtp_configure(void) {
472 uaudio_set("rtp-mode", config->rtp_mode);
473 rtp_set_netconfig("rtp-destination-af",
475 "rtp-destination-port", &config->broadcast);
476 rtp_set_netconfig("rtp-source-af",
478 "rtp-source-port", &config->broadcast_from);
479 snprintf(buffer, sizeof buffer, "%ld", config->multicast_ttl);
480 uaudio_set("multicast-ttl", buffer);
481 uaudio_set("multicast-loop", config->multicast_loop ? "yes" : "no");
482 snprintf(buffer, sizeof buffer, "%ld", config->rtp_max_payload);
483 uaudio_set("rtp-max-payload", buffer);
484 uaudio_set("rtp-mtu-discovery", config->rtp_mtu_discovery);
485 if(config->rtp_verbose)
486 disorder_info("RTP: configured");
489 /** @brief Add an RTP recipient address
490 * @param sa Pointer to recipient address
491 * @return 0 on success, -1 on error
493 int rtp_add_recipient(const struct sockaddr_storage *sa) {
494 struct rtp_recipient *r;
496 pthread_mutex_lock(&rtp_lock);
497 for(r = rtp_recipient_list;
498 r && sockaddrcmp((struct sockaddr *)sa,
499 (struct sockaddr *)&r->sa);
505 r = xmalloc(sizeof *r);
506 memcpy(&r->sa, sa, sizeof *sa);
507 r->next = rtp_recipient_list;
508 rtp_recipient_list = r;
511 pthread_mutex_unlock(&rtp_lock);
515 /** @brief Remove an RTP recipient address
516 * @param sa Pointer to recipient address
517 * @return 0 on success, -1 on error
519 int rtp_remove_recipient(const struct sockaddr_storage *sa) {
520 struct rtp_recipient *r, **rr;
522 pthread_mutex_lock(&rtp_lock);
523 for(rr = &rtp_recipient_list;
524 (r = *rr) && sockaddrcmp((struct sockaddr *)sa,
525 (struct sockaddr *)&r->sa);
533 disorder_error(0, "bogus rtp_remove_recipient");
536 pthread_mutex_unlock(&rtp_lock);
540 const struct uaudio uaudio_rtp = {
542 .options = rtp_options,
545 .activate = uaudio_thread_activate,
546 .deactivate = uaudio_thread_deactivate,
547 .configure = rtp_configure,
548 .flags = UAUDIO_API_SERVER,