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
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).
50 * Don't make this too big or arithmetic will start to overflow.
52 #define NETWORK_BYTES (1500-8/*UDP*/-40/*IP*/-8/*conservatism*/)
54 /** @brief RTP payload type */
55 static int rtp_payload;
57 /** @brief RTP output socket */
58 static int rtp_fd = -1;
60 /** @brief RTP output socket (IPv6) */
62 /** @brief RTP unicast output socket (IPv6) */
63 static int rtp_fd6 = -1;
65 /** @brief RTP SSRC */
66 static uint32_t rtp_id;
68 /** @brief Base for timestamp */
69 static uint32_t rtp_base;
71 /** @brief RTP sequence number */
72 static uint16_t rtp_sequence;
74 /** @brief Network error count
76 * If too many errors occur in too short a time, we give up.
78 static int rtp_errors;
80 /** @brief RTP mode */
83 #define RTP_BROADCAST 1
84 #define RTP_MULTICAST 2
89 /** @brief A unicast client */
90 struct rtp_recipient {
91 struct rtp_recipient *next;
92 struct sockaddr_storage sa;
95 /** @brief List of unicast clients */
96 static struct rtp_recipient *rtp_recipient_list;
98 /** @brief Mutex protecting data structures */
99 static pthread_mutex_t rtp_lock = PTHREAD_MUTEX_INITIALIZER;
101 static const char *const rtp_options[] = {
103 "rtp-destination-port",
112 static void rtp_get_netconfig(const char *af,
115 struct netaddress *na) {
118 vec[0] = uaudio_get(af, NULL);
119 vec[1] = uaudio_get(addr, NULL);
120 vec[2] = uaudio_get(port, NULL);
124 if(netaddress_parse(na, 3, vec))
125 disorder_fatal(0, "invalid RTP address");
128 static void rtp_set_netconfig(const char *af,
131 const struct netaddress *na) {
132 uaudio_set(af, NULL);
133 uaudio_set(addr, NULL);
134 uaudio_set(port, NULL);
139 netaddress_format(na, &nvec, &vec);
141 uaudio_set(af, vec[0]);
145 uaudio_set(addr, vec[1]);
149 uaudio_set(port, vec[2]);
156 static size_t rtp_play(void *buffer, size_t nsamples, unsigned flags) {
157 struct rtp_header header;
161 if(flags & (UAUDIO_PAUSE|UAUDIO_RESUME))
162 fprintf(stderr, "rtp_play %zu samples%s%s%s%s\n", nsamples,
163 flags & UAUDIO_PAUSE ? " UAUDIO_PAUSE" : "",
164 flags & UAUDIO_RESUME ? " UAUDIO_RESUME" : "",
165 flags & UAUDIO_PLAYING ? " UAUDIO_PLAYING" : "",
166 flags & UAUDIO_PAUSED ? " UAUDIO_PAUSED" : "");
169 /* We do as much work as possible before checking what time it is */
170 /* Fill out header */
171 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
172 header.seq = htons(rtp_sequence++);
173 header.ssrc = rtp_id;
174 header.mpt = rtp_payload;
175 /* If we've come out of a pause, set the marker bit */
176 if(flags & UAUDIO_RESUME)
179 /* Convert samples to network byte order */
180 uint16_t *u = buffer, *const limit = u + nsamples;
186 vec[0].iov_base = (void *)&header;
187 vec[0].iov_len = sizeof header;
188 vec[1].iov_base = buffer;
189 vec[1].iov_len = nsamples * uaudio_sample_size;
190 const uint32_t timestamp = uaudio_schedule_sync();
191 header.timestamp = htonl(rtp_base + (uint32_t)timestamp);
193 /* We send ~120 packets a second with current arrangements. So if we log
194 * once every 8192 packets we log about once a minute. */
196 if(!(ntohs(header.seq) & 8191)
197 && config->rtp_verbose)
198 disorder_info("RTP: seq %04"PRIx16" %08"PRIx32"+%08"PRIx32"=%08"PRIx32" ns %zu%s",
204 flags & UAUDIO_PAUSED ? " [paused]" : "");
206 /* If we're paused don't actually end a packet, we just pretend */
207 if(flags & UAUDIO_PAUSED) {
208 uaudio_schedule_sent(nsamples);
211 if(rtp_mode == RTP_REQUEST) {
212 struct rtp_recipient *r;
214 memset(&m, 0, sizeof m);
217 pthread_mutex_lock(&rtp_lock);
218 for(r = rtp_recipient_list; r; r = r->next) {
220 m.msg_namelen = r->sa.ss_family == AF_INET ?
221 sizeof(struct sockaddr_in) : sizeof (struct sockaddr_in6);
222 sendmsg(r->sa.ss_family == AF_INET ? rtp_fd : rtp_fd6,
223 &m, MSG_DONTWAIT|MSG_NOSIGNAL);
224 // TODO similar error handling to other case?
226 pthread_mutex_unlock(&rtp_lock);
230 written_bytes = writev(rtp_fd, vec, 2);
231 } while(written_bytes < 0 && errno == EINTR);
232 if(written_bytes < 0) {
233 disorder_error(errno, "error transmitting audio data");
236 disorder_fatal(0, "too many audio transmission errors");
239 rtp_errors /= 2; /* gradual decay */
241 /* TODO what can we sensibly do about short writes here? Really that's just
242 * an error and we ought to be using smaller packets. */
243 uaudio_schedule_sent(nsamples);
247 static void hack_send_buffer_size(int fd, const char *what) {
248 int sndbuf, target_sndbuf = 131072;
249 socklen_t len = sizeof sndbuf;
251 if(getsockopt(fd, SOL_SOCKET, SO_SNDBUF,
253 disorder_fatal(errno, "error getting SO_SNDBUF on %s socket", what);
254 if(target_sndbuf > sndbuf) {
255 if(setsockopt(fd, SOL_SOCKET, SO_SNDBUF,
256 &target_sndbuf, sizeof target_sndbuf) < 0)
257 disorder_error(errno, "error setting SO_SNDBUF on %s socket to %d",
258 what, target_sndbuf);
260 disorder_info("changed socket send buffer size on %socket from %d to %d",
261 what, sndbuf, target_sndbuf);
263 disorder_info("default socket send buffer on %s socket is %d",
267 static void rtp_open(void) {
268 struct addrinfo *dres, *sres;
269 static const int one = 1;
270 struct netaddress dst[1], src[1];
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 /* Create the socket */
329 if(rtp_mode != RTP_REQUEST) {
330 if((rtp_fd = socket(dres->ai_family,
332 dres->ai_protocol)) < 0)
333 disorder_fatal(errno, "error creating RTP transmission socket");
334 } else { /* request mode slightly different */
335 if((rtp_fd = socket(AF_INET,
338 disorder_fatal(errno, "error creating v4 RTP transmission socket");
339 if((rtp_fd6 = socket(AF_INET6,
342 disorder_fatal(errno, "error creating v6 RTP transmission socket");
344 /* Configure the socket according to the desired mode */
346 case RTP_MULTICAST: {
347 /* Enable multicast options */
348 const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
349 const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
350 switch(dres->ai_family) {
352 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
353 &ttl, sizeof ttl) < 0)
354 disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
355 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
356 &loop, sizeof loop) < 0)
357 disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
361 if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
362 &ttl, sizeof ttl) < 0)
363 disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
364 if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
365 &loop, sizeof loop) < 0)
366 disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
370 disorder_fatal(0, "unsupported address family %d", dres->ai_family);
372 disorder_info("multicasting on %s TTL=%d loop=%s",
373 format_sockaddr(dres->ai_addr), ttl, loop ? "yes" : "no");
377 disorder_info("unicasting on %s", format_sockaddr(dres->ai_addr));
380 case RTP_BROADCAST: {
381 if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
382 disorder_fatal(errno, "error setting SO_BROADCAST on broadcast socket");
383 disorder_info("broadcasting on %s",
384 format_sockaddr(dres->ai_addr));
388 disorder_info("will transmit on request");
392 /* Enlarge the socket buffers */
393 hack_send_buffer_size(rtp_fd, "master 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 if(config->rtp_verbose)
405 disorder_info("RTP: prepared socket");
408 static void rtp_start(uaudio_callback *callback,
410 /* We only support L16 (but we do stereo and mono and will convert sign) */
411 if(uaudio_channels == 2
413 && uaudio_rate == 44100)
415 else if(uaudio_channels == 1
417 && uaudio_rate == 44100)
420 disorder_fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
421 uaudio_bits, uaudio_rate, uaudio_channels);
422 if(config->rtp_verbose)
423 disorder_info("RTP: %d channels %d bits %d Hz payload type %d",
424 uaudio_channels, uaudio_bits, uaudio_rate, rtp_payload);
425 /* Various fields are required to have random initial values by RFC3550. The
426 * packet contents are highly public so there's no point asking for very
427 * strong randomness. */
428 gcry_create_nonce(&rtp_id, sizeof rtp_id);
429 gcry_create_nonce(&rtp_base, sizeof rtp_base);
430 gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
431 if(config->rtp_verbose)
432 disorder_info("RTP: id %08"PRIx32" base %08"PRIx32" initial seq %08"PRIx16,
433 rtp_id, rtp_base, rtp_sequence);
435 uaudio_schedule_init();
436 if(config->rtp_verbose)
437 disorder_info("RTP: initialized schedule");
438 uaudio_thread_start(callback,
441 256 / uaudio_sample_size,
442 (NETWORK_BYTES - sizeof(struct rtp_header))
443 / uaudio_sample_size,
445 if(config->rtp_verbose)
446 disorder_info("RTP: created thread");
449 static void rtp_stop(void) {
450 uaudio_thread_stop();
451 close(rtp_fd); rtp_fd = -1;
452 if(rtp_fd6 >= 0) { close(rtp_fd6); rtp_fd6 = -1; }
455 static void rtp_configure(void) {
458 uaudio_set("rtp-mode", config->rtp_mode);
459 rtp_set_netconfig("rtp-destination-af",
461 "rtp-destination-port", &config->broadcast);
462 rtp_set_netconfig("rtp-source-af",
464 "rtp-source-port", &config->broadcast_from);
465 snprintf(buffer, sizeof buffer, "%ld", config->multicast_ttl);
466 uaudio_set("multicast-ttl", buffer);
467 uaudio_set("multicast-loop", config->multicast_loop ? "yes" : "no");
468 if(config->rtp_verbose)
469 disorder_info("RTP: configured");
472 /** @brief Add an RTP recipient address
473 * @param sa Pointer to recipient address
474 * @return 0 on success, -1 on error
476 int rtp_add_recipient(const struct sockaddr_storage *sa) {
477 struct rtp_recipient *r;
479 pthread_mutex_lock(&rtp_lock);
480 for(r = rtp_recipient_list;
481 r && sockaddrcmp((struct sockaddr *)sa,
482 (struct sockaddr *)&r->sa);
488 r = xmalloc(sizeof *r);
489 memcpy(&r->sa, sa, sizeof *sa);
490 r->next = rtp_recipient_list;
491 rtp_recipient_list = r;
494 pthread_mutex_unlock(&rtp_lock);
498 /** @brief Remove an RTP recipient address
499 * @param sa Pointer to recipient address
500 * @return 0 on success, -1 on error
502 int rtp_remove_recipient(const struct sockaddr_storage *sa) {
503 struct rtp_recipient *r, **rr;
505 pthread_mutex_lock(&rtp_lock);
506 for(rr = &rtp_recipient_list;
507 (r = *rr) && sockaddrcmp((struct sockaddr *)sa,
508 (struct sockaddr *)&r->sa);
516 disorder_error(0, "bogus rtp_remove_recipient");
519 pthread_mutex_unlock(&rtp_lock);
523 const struct uaudio uaudio_rtp = {
525 .options = rtp_options,
528 .activate = uaudio_thread_activate,
529 .deactivate = uaudio_thread_deactivate,
530 .configure = rtp_configure,
531 .flags = UAUDIO_API_SERVER,