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 */
60 /** @brief RTP output socket (IPv6) */
63 /** @brief RTP SSRC */
64 static uint32_t rtp_id;
66 /** @brief Base for timestamp */
67 static uint32_t rtp_base;
69 /** @brief RTP sequence number */
70 static uint16_t rtp_sequence;
72 /** @brief Network error count
74 * If too many errors occur in too short a time, we give up.
76 static int rtp_errors;
78 /** @brief Set while paused */
79 static volatile int rtp_paused;
81 /** @brief RTP mode */
84 #define RTP_BROADCAST 1
85 #define RTP_MULTICAST 2
90 /** @brief A unicast client */
91 struct rtp_recipient {
92 struct rtp_recipient *next;
93 struct sockaddr_storage sa;
96 /** @brief List of unicast clients */
97 static struct rtp_recipient *rtp_recipient_list;
99 /** @brief Mutex protecting data structures */
100 static pthread_mutex_t rtp_lock = PTHREAD_MUTEX_INITIALIZER;
102 static const char *const rtp_options[] = {
104 "rtp-destination-port",
113 static void rtp_get_netconfig(const char *af,
116 struct netaddress *na) {
119 vec[0] = uaudio_get(af, NULL);
120 vec[1] = uaudio_get(addr, NULL);
121 vec[2] = uaudio_get(port, NULL);
125 if(netaddress_parse(na, 3, vec))
126 disorder_fatal(0, "invalid RTP address");
129 static void rtp_set_netconfig(const char *af,
132 const struct netaddress *na) {
133 uaudio_set(af, NULL);
134 uaudio_set(addr, NULL);
135 uaudio_set(port, NULL);
140 netaddress_format(na, &nvec, &vec);
142 uaudio_set(af, vec[0]);
146 uaudio_set(addr, vec[1]);
150 uaudio_set(port, vec[2]);
157 static size_t rtp_play(void *buffer, size_t nsamples, unsigned flags) {
158 struct rtp_header header;
162 if(flags & (UAUDIO_PAUSE|UAUDIO_RESUME))
163 fprintf(stderr, "rtp_play %zu samples%s%s%s%s\n", nsamples,
164 flags & UAUDIO_PAUSE ? " UAUDIO_PAUSE" : "",
165 flags & UAUDIO_RESUME ? " UAUDIO_RESUME" : "",
166 flags & UAUDIO_PLAYING ? " UAUDIO_PLAYING" : "",
167 flags & UAUDIO_PAUSED ? " UAUDIO_PAUSED" : "");
170 /* We do as much work as possible before checking what time it is */
171 /* Fill out header */
172 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
173 header.seq = htons(rtp_sequence++);
174 header.ssrc = rtp_id;
175 header.mpt = rtp_payload;
176 /* If we've come out of a pause, set the marker bit */
177 if(flags & UAUDIO_RESUME)
180 /* Convert samples to network byte order */
181 uint16_t *u = buffer, *const limit = u + nsamples;
187 vec[0].iov_base = (void *)&header;
188 vec[0].iov_len = sizeof header;
189 vec[1].iov_base = buffer;
190 vec[1].iov_len = nsamples * uaudio_sample_size;
191 const uint32_t timestamp = uaudio_schedule_sync();
192 header.timestamp = htonl(rtp_base + (uint32_t)timestamp);
194 /* We send ~120 packets a second with current arrangements. So if we log
195 * once every 8192 packets we log about once a minute. */
197 if(!(ntohs(header.seq) & 8191)
198 && config->rtp_verbose)
199 disorder_info("RTP: seq %04"PRIx16" %08"PRIx32"+%08"PRIx32"=%08"PRIx32" ns %zu%s",
205 flags & UAUDIO_PAUSED ? " [paused]" : "");
207 /* If we're paused don't actually end a packet, we just pretend */
208 if(flags & UAUDIO_PAUSED) {
209 uaudio_schedule_sent(nsamples);
212 if(rtp_mode == RTP_REQUEST) {
213 struct rtp_recipient *r;
215 memset(&m, 0, sizeof m);
218 pthread_mutex_lock(&rtp_lock);
219 for(r = rtp_recipient_list; r; r = r->next) {
221 m.msg_namelen = r->sa.ss_family == AF_INET ?
222 sizeof(struct sockaddr_in) : sizeof (struct sockaddr_in6);
223 sendmsg(r->sa.ss_family == AF_INET ? rtp_fd : rtp_fd6,
224 &m, MSG_DONTWAIT|MSG_NOSIGNAL);
225 // TODO similar error handling to other case?
227 pthread_mutex_unlock(&rtp_lock);
231 written_bytes = writev(rtp_fd, vec, 2);
232 } while(written_bytes < 0 && errno == EINTR);
233 if(written_bytes < 0) {
234 disorder_error(errno, "error transmitting audio data");
237 disorder_fatal(0, "too many audio transmission errors");
240 rtp_errors /= 2; /* gradual decay */
242 /* TODO what can we sensibly do about short writes here? Really that's just
243 * an error and we ought to be using smaller packets. */
244 uaudio_schedule_sent(nsamples);
248 static void rtp_open(void) {
249 struct addrinfo *dres, *sres;
250 static const int one = 1;
251 int sndbuf, target_sndbuf = 131072;
253 struct netaddress dst[1], src[1];
257 mode = uaudio_get("rtp-mode", "auto");
258 if(!strcmp(mode, "broadcast")) rtp_mode = RTP_BROADCAST;
259 else if(!strcmp(mode, "multicast")) rtp_mode = RTP_MULTICAST;
260 else if(!strcmp(mode, "unicast")) rtp_mode = RTP_UNICAST;
261 else if(!strcmp(mode, "request")) rtp_mode = RTP_REQUEST;
262 else rtp_mode = RTP_AUTO;
263 /* Get the source and destination addresses (which might be missing) */
264 rtp_get_netconfig("rtp-destination-af",
266 "rtp-destination-port",
268 rtp_get_netconfig("rtp-source-af",
273 dres = netaddress_resolve(dst, 0, IPPROTO_UDP);
279 sres = netaddress_resolve(src, 1, IPPROTO_UDP);
284 /* _AUTO inspects the destination address and acts accordingly */
285 if(rtp_mode == RTP_AUTO) {
287 rtp_mode = RTP_REQUEST;
288 else if(multicast(dres->ai_addr))
289 rtp_mode = RTP_MULTICAST;
293 if(getifaddrs(&ifs) < 0)
294 disorder_fatal(errno, "error calling getifaddrs");
296 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
297 * still a null pointer. It turns out that there's a subsequent entry
298 * for he same interface which _does_ have ifa_broadaddr though... */
299 if((ifs->ifa_flags & IFF_BROADCAST)
300 && ifs->ifa_broadaddr
301 && sockaddr_equal(ifs->ifa_broadaddr, dres->ai_addr))
306 rtp_mode = RTP_BROADCAST;
308 rtp_mode = RTP_UNICAST;
311 /* Create the socket */
312 if(rtp_mode != RTP_REQUEST) {
313 if((rtp_fd = socket(dres->ai_family,
315 dres->ai_protocol)) < 0)
316 disorder_fatal(errno, "error creating RTP transmission socket");
317 } else { /* request mode slightly different */
318 if((rtp_fd = socket(AF_INET,
321 disorder_fatal(errno, "error creating v4 RTP transmission socket");
322 if((rtp_fd6 = socket(AF_INET6,
325 disorder_fatal(errno, "error creating v6 RTP transmission socket");
327 /* Configure the socket according to the desired mode */
329 case RTP_MULTICAST: {
330 /* Enable multicast options */
331 const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
332 const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
333 switch(dres->ai_family) {
335 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
336 &ttl, sizeof ttl) < 0)
337 disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
338 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
339 &loop, sizeof loop) < 0)
340 disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
344 if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
345 &ttl, sizeof ttl) < 0)
346 disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
347 if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
348 &loop, sizeof loop) < 0)
349 disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
353 disorder_fatal(0, "unsupported address family %d", dres->ai_family);
355 disorder_info("multicasting on %s TTL=%d loop=%s",
356 format_sockaddr(dres->ai_addr), ttl, loop ? "yes" : "no");
360 disorder_info("unicasting on %s", format_sockaddr(dres->ai_addr));
363 case RTP_BROADCAST: {
364 if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
365 disorder_fatal(errno, "error setting SO_BROADCAST on broadcast socket");
366 disorder_info("broadcasting on %s",
367 format_sockaddr(dres->ai_addr));
371 disorder_info("will transmit on request");
375 /* Enlarge the socket buffer */
377 if(getsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
379 disorder_fatal(errno, "error getting SO_SNDBUF");
380 if(target_sndbuf > sndbuf) {
381 if(setsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
382 &target_sndbuf, sizeof target_sndbuf) < 0)
383 disorder_error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
385 disorder_info("changed socket send buffer size from %d to %d",
386 sndbuf, target_sndbuf);
388 disorder_info("default socket send buffer is %d", sndbuf);
389 /* We might well want to set additional broadcast- or multicast-related
391 if(rtp_mode != RTP_REQUEST) {
392 if(sres && bind(rtp_fd, sres->ai_addr, sres->ai_addrlen) < 0)
393 disorder_fatal(errno, "error binding broadcast socket to %s",
394 format_sockaddr(sres->ai_addr));
395 if(connect(rtp_fd, dres->ai_addr, dres->ai_addrlen) < 0)
396 disorder_fatal(errno, "error connecting broadcast socket to %s",
397 format_sockaddr(dres->ai_addr));
399 if(config->rtp_verbose)
400 disorder_info("RTP: prepared socket");
403 static void rtp_start(uaudio_callback *callback,
405 /* We only support L16 (but we do stereo and mono and will convert sign) */
406 if(uaudio_channels == 2
408 && uaudio_rate == 44100)
410 else if(uaudio_channels == 1
412 && uaudio_rate == 44100)
415 disorder_fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
416 uaudio_bits, uaudio_rate, uaudio_channels);
417 if(config->rtp_verbose)
418 disorder_info("RTP: %d channels %d bits %d Hz payload type %d",
419 uaudio_channels, uaudio_bits, uaudio_rate, rtp_payload);
420 /* Various fields are required to have random initial values by RFC3550. The
421 * packet contents are highly public so there's no point asking for very
422 * strong randomness. */
423 gcry_create_nonce(&rtp_id, sizeof rtp_id);
424 gcry_create_nonce(&rtp_base, sizeof rtp_base);
425 gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
426 if(config->rtp_verbose)
427 disorder_info("RTP: id %08"PRIx32" base %08"PRIx32" initial seq %08"PRIx16,
428 rtp_id, rtp_base, rtp_sequence);
430 uaudio_schedule_init();
431 if(config->rtp_verbose)
432 disorder_info("RTP: initialized schedule");
433 uaudio_thread_start(callback,
436 256 / uaudio_sample_size,
437 (NETWORK_BYTES - sizeof(struct rtp_header))
438 / uaudio_sample_size,
440 if(config->rtp_verbose)
441 disorder_info("RTP: created thread");
444 static void rtp_stop(void) {
445 uaudio_thread_stop();
454 static void rtp_configure(void) {
457 uaudio_set("rtp-mode", config->rtp_mode);
458 rtp_set_netconfig("rtp-destination-af",
460 "rtp-destination-port", &config->broadcast);
461 rtp_set_netconfig("rtp-source-af",
463 "rtp-source-port", &config->broadcast_from);
464 snprintf(buffer, sizeof buffer, "%ld", config->multicast_ttl);
465 uaudio_set("multicast-ttl", buffer);
466 uaudio_set("multicast-loop", config->multicast_loop ? "yes" : "no");
467 if(config->rtp_verbose)
468 disorder_info("RTP: configured");
471 /** @brief Add an RTP recipient address
472 * @param sa Pointer to recipient address
473 * @return 0 on success, -1 on error
475 int rtp_add_recipient(const struct sockaddr_storage *sa) {
476 struct rtp_recipient *r;
478 pthread_mutex_lock(&rtp_lock);
479 for(r = rtp_recipient_list;
480 r && sockaddrcmp((struct sockaddr *)sa,
481 (struct sockaddr *)&r->sa);
487 r = xmalloc(sizeof *r);
488 memcpy(&r->sa, sa, sizeof *sa);
489 r->next = rtp_recipient_list;
490 rtp_recipient_list = r;
493 pthread_mutex_unlock(&rtp_lock);
497 /** @brief Remove an RTP recipient address
498 * @param sa Pointer to recipient address
499 * @return 0 on success, -1 on error
501 int rtp_remove_recipient(const struct sockaddr_storage *sa) {
502 struct rtp_recipient *r, **rr;
504 pthread_mutex_lock(&rtp_lock);
505 for(rr = &rtp_recipient_list;
506 (r = *rr) && sockaddrcmp((struct sockaddr *)sa,
507 (struct sockaddr *)&r->sa);
515 disorder_error(0, "bogus rtp_remove_recipient");
518 pthread_mutex_unlock(&rtp_lock);
522 const struct uaudio uaudio_rtp = {
524 .options = rtp_options,
527 .activate = uaudio_thread_activate,
528 .deactivate = uaudio_thread_deactivate,
529 .configure = rtp_configure,
530 .flags = UAUDIO_API_SERVER,