lib/uaudio-rtp.c: Factor out setting the send-buffer size on a socket.
[disorder] / lib / uaudio-rtp.c
CommitLineData
7a2c7068
RK
1/*
2 * This file is part of DisOrder.
80fb0bd9 3 * Copyright (C) 2009, 2013 Richard Kettlewell
7a2c7068
RK
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 */
e8c185c3 18/** @file lib/uaudio-rtp.c
7a2c7068
RK
19 * @brief Support for RTP network play backend */
20#include "common.h"
21
dfa51bb7 22#include <errno.h>
60e5bc86 23#include <sys/socket.h>
dfa51bb7
RK
24#include <ifaddrs.h>
25#include <net/if.h>
adeb58a0
RK
26#include <arpa/inet.h>
27#include <netinet/in.h>
dfa51bb7
RK
28#include <gcrypt.h>
29#include <unistd.h>
30#include <time.h>
60e5bc86 31#include <sys/uio.h>
80fb0bd9 32#include <pthread.h>
7a2c7068
RK
33
34#include "uaudio.h"
35#include "mem.h"
36#include "log.h"
37#include "syscalls.h"
dfa51bb7
RK
38#include "rtp.h"
39#include "addr.h"
40#include "ifreq.h"
41#include "timeval.h"
ba70caca 42#include "configuration.h"
dfa51bb7
RK
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 */
55static int rtp_payload;
56
57/** @brief RTP output socket */
58static int rtp_fd;
59
80fb0bd9
RK
60/** @brief RTP output socket (IPv6) */
61static int rtp_fd6;
62
dfa51bb7
RK
63/** @brief RTP SSRC */
64static uint32_t rtp_id;
65
b1f6ca8c
RK
66/** @brief Base for timestamp */
67static uint32_t rtp_base;
68
dfa51bb7
RK
69/** @brief RTP sequence number */
70static uint16_t rtp_sequence;
71
dfa51bb7
RK
72/** @brief Network error count
73 *
74 * If too many errors occur in too short a time, we give up.
75 */
76static int rtp_errors;
77
80fb0bd9
RK
78/** @brief RTP mode */
79static 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 */
88struct rtp_recipient {
89 struct rtp_recipient *next;
90 struct sockaddr_storage sa;
91};
92
93/** @brief List of unicast clients */
94static struct rtp_recipient *rtp_recipient_list;
95
96/** @brief Mutex protecting data structures */
97static pthread_mutex_t rtp_lock = PTHREAD_MUTEX_INITIALIZER;
98
7a2c7068 99static const char *const rtp_options[] = {
dfa51bb7
RK
100 "rtp-destination",
101 "rtp-destination-port",
102 "rtp-source",
103 "rtp-source-port",
104 "multicast-ttl",
105 "multicast-loop",
80fb0bd9 106 "rtp-mode",
7a2c7068
RK
107 NULL
108};
109
76e72f65
RK
110static 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))
2e9ba080 123 disorder_fatal(0, "invalid RTP address");
76e72f65
RK
124}
125
126static 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
b1f6ca8c 154static size_t rtp_play(void *buffer, size_t nsamples, unsigned flags) {
dfa51bb7
RK
155 struct rtp_header header;
156 struct iovec vec[2];
b1f6ca8c
RK
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
dfa51bb7
RK
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;
b1f6ca8c
RK
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;
dfa51bb7
RK
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;
b1f6ca8c
RK
188 const uint32_t timestamp = uaudio_schedule_sync();
189 header.timestamp = htonl(rtp_base + (uint32_t)timestamp);
87864f77
RK
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
b1f6ca8c
RK
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 }
80fb0bd9
RK
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 }
b1f6ca8c
RK
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;
dfa51bb7
RK
243}
244
d5172201
MW
245static void hack_send_buffer_size(int fd, const char *what) {
246 int sndbuf, target_sndbuf = 131072;
247 socklen_t len = sizeof sndbuf;
248
249 if(getsockopt(fd, SOL_SOCKET, SO_SNDBUF,
250 &sndbuf, &len) < 0)
251 disorder_fatal(errno, "error getting SO_SNDBUF on %s socket", what);
252 if(target_sndbuf > sndbuf) {
253 if(setsockopt(fd, SOL_SOCKET, SO_SNDBUF,
254 &target_sndbuf, sizeof target_sndbuf) < 0)
255 disorder_error(errno, "error setting SO_SNDBUF on %s socket to %d",
256 what, target_sndbuf);
257 else
258 disorder_info("changed socket send buffer size on %socket from %d to %d",
259 what, sndbuf, target_sndbuf);
260 } else
261 disorder_info("default socket send buffer on %s socket is %d",
262 what, sndbuf);
263}
264
dfa51bb7 265static void rtp_open(void) {
80fb0bd9 266 struct addrinfo *dres, *sres;
dfa51bb7 267 static const int one = 1;
76e72f65 268 struct netaddress dst[1], src[1];
80fb0bd9 269 const char *mode;
dfa51bb7 270
80fb0bd9
RK
271 /* Get the mode */
272 mode = uaudio_get("rtp-mode", "auto");
273 if(!strcmp(mode, "broadcast")) rtp_mode = RTP_BROADCAST;
274 else if(!strcmp(mode, "multicast")) rtp_mode = RTP_MULTICAST;
275 else if(!strcmp(mode, "unicast")) rtp_mode = RTP_UNICAST;
276 else if(!strcmp(mode, "request")) rtp_mode = RTP_REQUEST;
277 else rtp_mode = RTP_AUTO;
278 /* Get the source and destination addresses (which might be missing) */
76e72f65
RK
279 rtp_get_netconfig("rtp-destination-af",
280 "rtp-destination",
281 "rtp-destination-port",
282 dst);
283 rtp_get_netconfig("rtp-source-af",
284 "rtp-source",
285 "rtp-source-port",
286 src);
80fb0bd9
RK
287 if(dst->af != -1) {
288 dres = netaddress_resolve(dst, 0, IPPROTO_UDP);
289 if(!dres)
290 exit(-1);
291 } else
292 dres = 0;
76e72f65
RK
293 if(src->af != -1) {
294 sres = netaddress_resolve(src, 1, IPPROTO_UDP);
295 if(!sres)
296 exit(-1);
dfa51bb7
RK
297 } else
298 sres = 0;
80fb0bd9
RK
299 /* _AUTO inspects the destination address and acts accordingly */
300 if(rtp_mode == RTP_AUTO) {
301 if(!dres)
302 rtp_mode = RTP_REQUEST;
303 else if(multicast(dres->ai_addr))
304 rtp_mode = RTP_MULTICAST;
305 else {
306 struct ifaddrs *ifs;
307
308 if(getifaddrs(&ifs) < 0)
309 disorder_fatal(errno, "error calling getifaddrs");
310 while(ifs) {
311 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
312 * still a null pointer. It turns out that there's a subsequent entry
313 * for he same interface which _does_ have ifa_broadaddr though... */
314 if((ifs->ifa_flags & IFF_BROADCAST)
315 && ifs->ifa_broadaddr
316 && sockaddr_equal(ifs->ifa_broadaddr, dres->ai_addr))
317 break;
318 ifs = ifs->ifa_next;
319 }
320 if(ifs)
321 rtp_mode = RTP_BROADCAST;
322 else
323 rtp_mode = RTP_UNICAST;
324 }
325 }
dfa51bb7 326 /* Create the socket */
80fb0bd9
RK
327 if(rtp_mode != RTP_REQUEST) {
328 if((rtp_fd = socket(dres->ai_family,
329 dres->ai_socktype,
330 dres->ai_protocol)) < 0)
331 disorder_fatal(errno, "error creating RTP transmission socket");
332 } else { /* request mode slightly different */
333 if((rtp_fd = socket(AF_INET,
334 SOCK_DGRAM,
335 IPPROTO_UDP)) < 0)
336 disorder_fatal(errno, "error creating v4 RTP transmission socket");
337 if((rtp_fd6 = socket(AF_INET6,
338 SOCK_DGRAM,
339 IPPROTO_UDP)) < 0)
340 disorder_fatal(errno, "error creating v6 RTP transmission socket");
341 }
342 /* Configure the socket according to the desired mode */
343 switch(rtp_mode) {
344 case RTP_MULTICAST: {
dfa51bb7 345 /* Enable multicast options */
b50cfb8a
RK
346 const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
347 const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
80fb0bd9 348 switch(dres->ai_family) {
dfa51bb7
RK
349 case PF_INET: {
350 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
351 &ttl, sizeof ttl) < 0)
2e9ba080 352 disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
dfa51bb7
RK
353 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
354 &loop, sizeof loop) < 0)
2e9ba080 355 disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
356 break;
357 }
358 case PF_INET6: {
359 if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
360 &ttl, sizeof ttl) < 0)
2e9ba080 361 disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
dfa51bb7
RK
362 if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
363 &loop, sizeof loop) < 0)
2e9ba080 364 disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
365 break;
366 }
367 default:
80fb0bd9 368 disorder_fatal(0, "unsupported address family %d", dres->ai_family);
dfa51bb7 369 }
2e9ba080 370 disorder_info("multicasting on %s TTL=%d loop=%s",
80fb0bd9
RK
371 format_sockaddr(dres->ai_addr), ttl, loop ? "yes" : "no");
372 break;
373 }
374 case RTP_UNICAST: {
375 disorder_info("unicasting on %s", format_sockaddr(dres->ai_addr));
376 break;
377 }
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));
383 break;
384 }
385 case RTP_REQUEST: {
386 disorder_info("will transmit on request");
387 break;
388 }
dfa51bb7 389 }
d5172201
MW
390 /* Enlarge the socket buffers */
391 hack_send_buffer_size(rtp_fd, "master socket");
dfa51bb7
RK
392 /* We might well want to set additional broadcast- or multicast-related
393 * options here */
80fb0bd9
RK
394 if(rtp_mode != RTP_REQUEST) {
395 if(sres && bind(rtp_fd, sres->ai_addr, sres->ai_addrlen) < 0)
396 disorder_fatal(errno, "error binding broadcast socket to %s",
397 format_sockaddr(sres->ai_addr));
398 if(connect(rtp_fd, dres->ai_addr, dres->ai_addrlen) < 0)
399 disorder_fatal(errno, "error connecting broadcast socket to %s",
400 format_sockaddr(dres->ai_addr));
401 }
87864f77
RK
402 if(config->rtp_verbose)
403 disorder_info("RTP: prepared socket");
dfa51bb7
RK
404}
405
7a2c7068
RK
406static void rtp_start(uaudio_callback *callback,
407 void *userdata) {
dfa51bb7
RK
408 /* We only support L16 (but we do stereo and mono and will convert sign) */
409 if(uaudio_channels == 2
410 && uaudio_bits == 16
411 && uaudio_rate == 44100)
412 rtp_payload = 10;
413 else if(uaudio_channels == 1
414 && uaudio_bits == 16
415 && uaudio_rate == 44100)
416 rtp_payload = 11;
417 else
2e9ba080
RK
418 disorder_fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
419 uaudio_bits, uaudio_rate, uaudio_channels);
87864f77
RK
420 if(config->rtp_verbose)
421 disorder_info("RTP: %d channels %d bits %d Hz payload type %d",
422 uaudio_channels, uaudio_bits, uaudio_rate, rtp_payload);
ec57f6c9
RK
423 /* Various fields are required to have random initial values by RFC3550. The
424 * packet contents are highly public so there's no point asking for very
425 * strong randomness. */
426 gcry_create_nonce(&rtp_id, sizeof rtp_id);
b1f6ca8c 427 gcry_create_nonce(&rtp_base, sizeof rtp_base);
ec57f6c9 428 gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
87864f77
RK
429 if(config->rtp_verbose)
430 disorder_info("RTP: id %08"PRIx32" base %08"PRIx32" initial seq %08"PRIx16,
431 rtp_id, rtp_base, rtp_sequence);
dfa51bb7 432 rtp_open();
ec57f6c9 433 uaudio_schedule_init();
87864f77
RK
434 if(config->rtp_verbose)
435 disorder_info("RTP: initialized schedule");
dfa51bb7
RK
436 uaudio_thread_start(callback,
437 userdata,
438 rtp_play,
439 256 / uaudio_sample_size,
440 (NETWORK_BYTES - sizeof(struct rtp_header))
63761c19
RK
441 / uaudio_sample_size,
442 0);
87864f77
RK
443 if(config->rtp_verbose)
444 disorder_info("RTP: created thread");
7a2c7068
RK
445}
446
447static void rtp_stop(void) {
dfa51bb7
RK
448 uaudio_thread_stop();
449 close(rtp_fd);
450 rtp_fd = -1;
80fb0bd9
RK
451 if(rtp_fd6 >= 0) {
452 close(rtp_fd6);
453 rtp_fd6 = -1;
454 }
7a2c7068
RK
455}
456
ba70caca
RK
457static void rtp_configure(void) {
458 char buffer[64];
459
b0116b5c 460 uaudio_set("rtp-mode", config->rtp_mode);
76e72f65
RK
461 rtp_set_netconfig("rtp-destination-af",
462 "rtp-destination",
463 "rtp-destination-port", &config->broadcast);
464 rtp_set_netconfig("rtp-source-af",
465 "rtp-source",
466 "rtp-source-port", &config->broadcast_from);
ba70caca
RK
467 snprintf(buffer, sizeof buffer, "%ld", config->multicast_ttl);
468 uaudio_set("multicast-ttl", buffer);
469 uaudio_set("multicast-loop", config->multicast_loop ? "yes" : "no");
87864f77
RK
470 if(config->rtp_verbose)
471 disorder_info("RTP: configured");
ba70caca
RK
472}
473
80fb0bd9
RK
474/** @brief Add an RTP recipient address
475 * @param sa Pointer to recipient address
476 * @return 0 on success, -1 on error
477 */
478int rtp_add_recipient(const struct sockaddr_storage *sa) {
479 struct rtp_recipient *r;
480 int rc;
481 pthread_mutex_lock(&rtp_lock);
482 for(r = rtp_recipient_list;
483 r && sockaddrcmp((struct sockaddr *)sa,
484 (struct sockaddr *)&r->sa);
485 r = r->next)
486 ;
487 if(r)
488 rc = -1;
489 else {
490 r = xmalloc(sizeof *r);
c0dadbae 491 memcpy(&r->sa, sa, sizeof *sa);
80fb0bd9
RK
492 r->next = rtp_recipient_list;
493 rtp_recipient_list = r;
494 rc = 0;
495 }
496 pthread_mutex_unlock(&rtp_lock);
497 return rc;
498}
499
500/** @brief Remove an RTP recipient address
501 * @param sa Pointer to recipient address
502 * @return 0 on success, -1 on error
503 */
504int rtp_remove_recipient(const struct sockaddr_storage *sa) {
505 struct rtp_recipient *r, **rr;
506 int rc;
507 pthread_mutex_lock(&rtp_lock);
508 for(rr = &rtp_recipient_list;
509 (r = *rr) && sockaddrcmp((struct sockaddr *)sa,
510 (struct sockaddr *)&r->sa);
511 rr = &r->next)
512 ;
513 if(r) {
514 *rr = r->next;
515 xfree(r);
516 rc = 0;
517 } else {
518 disorder_error(0, "bogus rtp_remove_recipient");
519 rc = -1;
520 }
521 pthread_mutex_unlock(&rtp_lock);
522 return rc;
523}
524
7a2c7068
RK
525const struct uaudio uaudio_rtp = {
526 .name = "rtp",
527 .options = rtp_options,
528 .start = rtp_start,
529 .stop = rtp_stop,
b1f6ca8c
RK
530 .activate = uaudio_thread_activate,
531 .deactivate = uaudio_thread_deactivate,
ba70caca 532 .configure = rtp_configure,
06385470 533 .flags = UAUDIO_API_SERVER,
7a2c7068
RK
534};
535
536/*
537Local Variables:
538c-basic-offset:2
539comment-column:40
540fill-column:79
541indent-tabs-mode:nil
542End:
543*/