chiark / gitweb /
lib/configuration.c: Factor out common validation code.
[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
245static void rtp_open(void) {
80fb0bd9 246 struct addrinfo *dres, *sres;
dfa51bb7
RK
247 static const int one = 1;
248 int sndbuf, target_sndbuf = 131072;
249 socklen_t len;
76e72f65 250 struct netaddress dst[1], src[1];
80fb0bd9 251 const char *mode;
dfa51bb7 252
80fb0bd9
RK
253 /* Get the mode */
254 mode = uaudio_get("rtp-mode", "auto");
255 if(!strcmp(mode, "broadcast")) rtp_mode = RTP_BROADCAST;
256 else if(!strcmp(mode, "multicast")) rtp_mode = RTP_MULTICAST;
257 else if(!strcmp(mode, "unicast")) rtp_mode = RTP_UNICAST;
258 else if(!strcmp(mode, "request")) rtp_mode = RTP_REQUEST;
259 else rtp_mode = RTP_AUTO;
260 /* Get the source and destination addresses (which might be missing) */
76e72f65
RK
261 rtp_get_netconfig("rtp-destination-af",
262 "rtp-destination",
263 "rtp-destination-port",
264 dst);
265 rtp_get_netconfig("rtp-source-af",
266 "rtp-source",
267 "rtp-source-port",
268 src);
80fb0bd9
RK
269 if(dst->af != -1) {
270 dres = netaddress_resolve(dst, 0, IPPROTO_UDP);
271 if(!dres)
272 exit(-1);
273 } else
274 dres = 0;
76e72f65
RK
275 if(src->af != -1) {
276 sres = netaddress_resolve(src, 1, IPPROTO_UDP);
277 if(!sres)
278 exit(-1);
dfa51bb7
RK
279 } else
280 sres = 0;
80fb0bd9
RK
281 /* _AUTO inspects the destination address and acts accordingly */
282 if(rtp_mode == RTP_AUTO) {
283 if(!dres)
284 rtp_mode = RTP_REQUEST;
285 else if(multicast(dres->ai_addr))
286 rtp_mode = RTP_MULTICAST;
287 else {
288 struct ifaddrs *ifs;
289
290 if(getifaddrs(&ifs) < 0)
291 disorder_fatal(errno, "error calling getifaddrs");
292 while(ifs) {
293 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
294 * still a null pointer. It turns out that there's a subsequent entry
295 * for he same interface which _does_ have ifa_broadaddr though... */
296 if((ifs->ifa_flags & IFF_BROADCAST)
297 && ifs->ifa_broadaddr
298 && sockaddr_equal(ifs->ifa_broadaddr, dres->ai_addr))
299 break;
300 ifs = ifs->ifa_next;
301 }
302 if(ifs)
303 rtp_mode = RTP_BROADCAST;
304 else
305 rtp_mode = RTP_UNICAST;
306 }
307 }
dfa51bb7 308 /* Create the socket */
80fb0bd9
RK
309 if(rtp_mode != RTP_REQUEST) {
310 if((rtp_fd = socket(dres->ai_family,
311 dres->ai_socktype,
312 dres->ai_protocol)) < 0)
313 disorder_fatal(errno, "error creating RTP transmission socket");
314 } else { /* request mode slightly different */
315 if((rtp_fd = socket(AF_INET,
316 SOCK_DGRAM,
317 IPPROTO_UDP)) < 0)
318 disorder_fatal(errno, "error creating v4 RTP transmission socket");
319 if((rtp_fd6 = socket(AF_INET6,
320 SOCK_DGRAM,
321 IPPROTO_UDP)) < 0)
322 disorder_fatal(errno, "error creating v6 RTP transmission socket");
323 }
324 /* Configure the socket according to the desired mode */
325 switch(rtp_mode) {
326 case RTP_MULTICAST: {
dfa51bb7 327 /* Enable multicast options */
b50cfb8a
RK
328 const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
329 const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
80fb0bd9 330 switch(dres->ai_family) {
dfa51bb7
RK
331 case PF_INET: {
332 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
333 &ttl, sizeof ttl) < 0)
2e9ba080 334 disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
dfa51bb7
RK
335 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
336 &loop, sizeof loop) < 0)
2e9ba080 337 disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
338 break;
339 }
340 case PF_INET6: {
341 if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
342 &ttl, sizeof ttl) < 0)
2e9ba080 343 disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
dfa51bb7
RK
344 if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
345 &loop, sizeof loop) < 0)
2e9ba080 346 disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
347 break;
348 }
349 default:
80fb0bd9 350 disorder_fatal(0, "unsupported address family %d", dres->ai_family);
dfa51bb7 351 }
2e9ba080 352 disorder_info("multicasting on %s TTL=%d loop=%s",
80fb0bd9
RK
353 format_sockaddr(dres->ai_addr), ttl, loop ? "yes" : "no");
354 break;
355 }
356 case RTP_UNICAST: {
357 disorder_info("unicasting on %s", format_sockaddr(dres->ai_addr));
358 break;
359 }
360 case RTP_BROADCAST: {
361 if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
362 disorder_fatal(errno, "error setting SO_BROADCAST on broadcast socket");
363 disorder_info("broadcasting on %s",
364 format_sockaddr(dres->ai_addr));
365 break;
366 }
367 case RTP_REQUEST: {
368 disorder_info("will transmit on request");
369 break;
370 }
dfa51bb7
RK
371 }
372 /* Enlarge the socket buffer */
373 len = sizeof sndbuf;
374 if(getsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
375 &sndbuf, &len) < 0)
2e9ba080 376 disorder_fatal(errno, "error getting SO_SNDBUF");
dfa51bb7
RK
377 if(target_sndbuf > sndbuf) {
378 if(setsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
379 &target_sndbuf, sizeof target_sndbuf) < 0)
2e9ba080 380 disorder_error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
dfa51bb7 381 else
2e9ba080 382 disorder_info("changed socket send buffer size from %d to %d",
80fb0bd9 383 sndbuf, target_sndbuf);
dfa51bb7 384 } else
2e9ba080 385 disorder_info("default socket send buffer is %d", sndbuf);
dfa51bb7
RK
386 /* We might well want to set additional broadcast- or multicast-related
387 * options here */
80fb0bd9
RK
388 if(rtp_mode != RTP_REQUEST) {
389 if(sres && bind(rtp_fd, sres->ai_addr, sres->ai_addrlen) < 0)
390 disorder_fatal(errno, "error binding broadcast socket to %s",
391 format_sockaddr(sres->ai_addr));
392 if(connect(rtp_fd, dres->ai_addr, dres->ai_addrlen) < 0)
393 disorder_fatal(errno, "error connecting broadcast socket to %s",
394 format_sockaddr(dres->ai_addr));
395 }
87864f77
RK
396 if(config->rtp_verbose)
397 disorder_info("RTP: prepared socket");
dfa51bb7
RK
398}
399
7a2c7068
RK
400static void rtp_start(uaudio_callback *callback,
401 void *userdata) {
dfa51bb7
RK
402 /* We only support L16 (but we do stereo and mono and will convert sign) */
403 if(uaudio_channels == 2
404 && uaudio_bits == 16
405 && uaudio_rate == 44100)
406 rtp_payload = 10;
407 else if(uaudio_channels == 1
408 && uaudio_bits == 16
409 && uaudio_rate == 44100)
410 rtp_payload = 11;
411 else
2e9ba080
RK
412 disorder_fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
413 uaudio_bits, uaudio_rate, uaudio_channels);
87864f77
RK
414 if(config->rtp_verbose)
415 disorder_info("RTP: %d channels %d bits %d Hz payload type %d",
416 uaudio_channels, uaudio_bits, uaudio_rate, rtp_payload);
ec57f6c9
RK
417 /* Various fields are required to have random initial values by RFC3550. The
418 * packet contents are highly public so there's no point asking for very
419 * strong randomness. */
420 gcry_create_nonce(&rtp_id, sizeof rtp_id);
b1f6ca8c 421 gcry_create_nonce(&rtp_base, sizeof rtp_base);
ec57f6c9 422 gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
87864f77
RK
423 if(config->rtp_verbose)
424 disorder_info("RTP: id %08"PRIx32" base %08"PRIx32" initial seq %08"PRIx16,
425 rtp_id, rtp_base, rtp_sequence);
dfa51bb7 426 rtp_open();
ec57f6c9 427 uaudio_schedule_init();
87864f77
RK
428 if(config->rtp_verbose)
429 disorder_info("RTP: initialized schedule");
dfa51bb7
RK
430 uaudio_thread_start(callback,
431 userdata,
432 rtp_play,
433 256 / uaudio_sample_size,
434 (NETWORK_BYTES - sizeof(struct rtp_header))
63761c19
RK
435 / uaudio_sample_size,
436 0);
87864f77
RK
437 if(config->rtp_verbose)
438 disorder_info("RTP: created thread");
7a2c7068
RK
439}
440
441static void rtp_stop(void) {
dfa51bb7
RK
442 uaudio_thread_stop();
443 close(rtp_fd);
444 rtp_fd = -1;
80fb0bd9
RK
445 if(rtp_fd6 >= 0) {
446 close(rtp_fd6);
447 rtp_fd6 = -1;
448 }
7a2c7068
RK
449}
450
ba70caca
RK
451static void rtp_configure(void) {
452 char buffer[64];
453
b0116b5c 454 uaudio_set("rtp-mode", config->rtp_mode);
76e72f65
RK
455 rtp_set_netconfig("rtp-destination-af",
456 "rtp-destination",
457 "rtp-destination-port", &config->broadcast);
458 rtp_set_netconfig("rtp-source-af",
459 "rtp-source",
460 "rtp-source-port", &config->broadcast_from);
ba70caca
RK
461 snprintf(buffer, sizeof buffer, "%ld", config->multicast_ttl);
462 uaudio_set("multicast-ttl", buffer);
463 uaudio_set("multicast-loop", config->multicast_loop ? "yes" : "no");
87864f77
RK
464 if(config->rtp_verbose)
465 disorder_info("RTP: configured");
ba70caca
RK
466}
467
80fb0bd9
RK
468/** @brief Add an RTP recipient address
469 * @param sa Pointer to recipient address
470 * @return 0 on success, -1 on error
471 */
472int rtp_add_recipient(const struct sockaddr_storage *sa) {
473 struct rtp_recipient *r;
474 int rc;
475 pthread_mutex_lock(&rtp_lock);
476 for(r = rtp_recipient_list;
477 r && sockaddrcmp((struct sockaddr *)sa,
478 (struct sockaddr *)&r->sa);
479 r = r->next)
480 ;
481 if(r)
482 rc = -1;
483 else {
484 r = xmalloc(sizeof *r);
c0dadbae 485 memcpy(&r->sa, sa, sizeof *sa);
80fb0bd9
RK
486 r->next = rtp_recipient_list;
487 rtp_recipient_list = r;
488 rc = 0;
489 }
490 pthread_mutex_unlock(&rtp_lock);
491 return rc;
492}
493
494/** @brief Remove an RTP recipient address
495 * @param sa Pointer to recipient address
496 * @return 0 on success, -1 on error
497 */
498int rtp_remove_recipient(const struct sockaddr_storage *sa) {
499 struct rtp_recipient *r, **rr;
500 int rc;
501 pthread_mutex_lock(&rtp_lock);
502 for(rr = &rtp_recipient_list;
503 (r = *rr) && sockaddrcmp((struct sockaddr *)sa,
504 (struct sockaddr *)&r->sa);
505 rr = &r->next)
506 ;
507 if(r) {
508 *rr = r->next;
509 xfree(r);
510 rc = 0;
511 } else {
512 disorder_error(0, "bogus rtp_remove_recipient");
513 rc = -1;
514 }
515 pthread_mutex_unlock(&rtp_lock);
516 return rc;
517}
518
7a2c7068
RK
519const struct uaudio uaudio_rtp = {
520 .name = "rtp",
521 .options = rtp_options,
522 .start = rtp_start,
523 .stop = rtp_stop,
b1f6ca8c
RK
524 .activate = uaudio_thread_activate,
525 .deactivate = uaudio_thread_deactivate,
ba70caca 526 .configure = rtp_configure,
06385470 527 .flags = UAUDIO_API_SERVER,
7a2c7068
RK
528};
529
530/*
531Local Variables:
532c-basic-offset:2
533comment-column:40
534fill-column:79
535indent-tabs-mode:nil
536End:
537*/