chiark / gitweb /
lib/uaudio-rtp.c: Always allow clients to request unicast RTP streams.
[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
ac52c873 57/** @brief RTP broadcast/multicast output socket */
4285d0cf 58static int rtp_fd = -1;
dfa51bb7 59
ac52c873
MW
60/** @brief RTP unicast output socket (IPv4) */
61static int rtp_fd4 = -1;
62
4285d0cf
MW
63/** @brief RTP unicast output socket (IPv6) */
64static int rtp_fd6 = -1;
80fb0bd9 65
dfa51bb7
RK
66/** @brief RTP SSRC */
67static uint32_t rtp_id;
68
b1f6ca8c
RK
69/** @brief Base for timestamp */
70static uint32_t rtp_base;
71
dfa51bb7
RK
72/** @brief RTP sequence number */
73static uint16_t rtp_sequence;
74
dfa51bb7
RK
75/** @brief Network error count
76 *
77 * If too many errors occur in too short a time, we give up.
78 */
79static int rtp_errors;
80
80fb0bd9
RK
81/** @brief RTP mode */
82static int rtp_mode;
83
84#define RTP_BROADCAST 1
85#define RTP_MULTICAST 2
86#define RTP_UNICAST 3
87#define RTP_REQUEST 4
88#define RTP_AUTO 5
89
90/** @brief A unicast client */
91struct rtp_recipient {
92 struct rtp_recipient *next;
93 struct sockaddr_storage sa;
94};
95
96/** @brief List of unicast clients */
97static struct rtp_recipient *rtp_recipient_list;
98
99/** @brief Mutex protecting data structures */
100static pthread_mutex_t rtp_lock = PTHREAD_MUTEX_INITIALIZER;
101
7a2c7068 102static const char *const rtp_options[] = {
dfa51bb7
RK
103 "rtp-destination",
104 "rtp-destination-port",
105 "rtp-source",
106 "rtp-source-port",
107 "multicast-ttl",
108 "multicast-loop",
80fb0bd9 109 "rtp-mode",
7a2c7068
RK
110 NULL
111};
112
76e72f65
RK
113static void rtp_get_netconfig(const char *af,
114 const char *addr,
115 const char *port,
116 struct netaddress *na) {
117 char *vec[3];
118
119 vec[0] = uaudio_get(af, NULL);
120 vec[1] = uaudio_get(addr, NULL);
121 vec[2] = uaudio_get(port, NULL);
122 if(!*vec)
123 na->af = -1;
124 else
125 if(netaddress_parse(na, 3, vec))
2e9ba080 126 disorder_fatal(0, "invalid RTP address");
76e72f65
RK
127}
128
129static void rtp_set_netconfig(const char *af,
130 const char *addr,
131 const char *port,
132 const struct netaddress *na) {
133 uaudio_set(af, NULL);
134 uaudio_set(addr, NULL);
135 uaudio_set(port, NULL);
136 if(na->af != -1) {
137 int nvec;
138 char **vec;
139
140 netaddress_format(na, &nvec, &vec);
141 if(nvec > 0) {
142 uaudio_set(af, vec[0]);
143 xfree(vec[0]);
144 }
145 if(nvec > 1) {
146 uaudio_set(addr, vec[1]);
147 xfree(vec[1]);
148 }
149 if(nvec > 2) {
150 uaudio_set(port, vec[2]);
151 xfree(vec[2]);
152 }
153 xfree(vec);
154 }
155}
156
b1f6ca8c 157static size_t rtp_play(void *buffer, size_t nsamples, unsigned flags) {
dfa51bb7
RK
158 struct rtp_header header;
159 struct iovec vec[2];
b1f6ca8c
RK
160
161#if 0
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" : "");
168#endif
169
dfa51bb7
RK
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;
b1f6ca8c
RK
175 header.mpt = rtp_payload;
176 /* If we've come out of a pause, set the marker bit */
177 if(flags & UAUDIO_RESUME)
178 header.mpt |= 0x80;
dfa51bb7
RK
179#if !WORDS_BIGENDIAN
180 /* Convert samples to network byte order */
181 uint16_t *u = buffer, *const limit = u + nsamples;
182 while(u < limit) {
183 *u = htons(*u);
184 ++u;
185 }
186#endif
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;
b1f6ca8c
RK
191 const uint32_t timestamp = uaudio_schedule_sync();
192 header.timestamp = htonl(rtp_base + (uint32_t)timestamp);
87864f77
RK
193
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. */
196
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",
200 ntohs(header.seq),
201 rtp_base,
202 timestamp,
203 header.timestamp,
204 nsamples,
205 flags & UAUDIO_PAUSED ? " [paused]" : "");
206
b1f6ca8c
RK
207 /* If we're paused don't actually end a packet, we just pretend */
208 if(flags & UAUDIO_PAUSED) {
209 uaudio_schedule_sent(nsamples);
210 return nsamples;
211 }
43e7474d
MW
212 /* Send stuff to explicitly registerd unicast addresses unconditionally */
213 struct rtp_recipient *r;
214 struct msghdr m;
215 memset(&m, 0, sizeof m);
216 m.msg_iov = vec;
217 m.msg_iovlen = 2;
218 pthread_mutex_lock(&rtp_lock);
219 for(r = rtp_recipient_list; r; r = r->next) {
220 m.msg_name = &r->sa;
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_fd4 : rtp_fd6,
224 &m, MSG_DONTWAIT|MSG_NOSIGNAL);
225 // TODO similar error handling to other case?
226 }
227 pthread_mutex_unlock(&rtp_lock);
228 if(rtp_mode != RTP_REQUEST) {
80fb0bd9
RK
229 int written_bytes;
230 do {
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");
235 ++rtp_errors;
236 if(rtp_errors == 10)
237 disorder_fatal(0, "too many audio transmission errors");
238 return 0;
239 } else
240 rtp_errors /= 2; /* gradual decay */
241 }
b1f6ca8c
RK
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);
245 return nsamples;
dfa51bb7
RK
246}
247
d5172201
MW
248static void hack_send_buffer_size(int fd, const char *what) {
249 int sndbuf, target_sndbuf = 131072;
250 socklen_t len = sizeof sndbuf;
251
252 if(getsockopt(fd, SOL_SOCKET, SO_SNDBUF,
253 &sndbuf, &len) < 0)
254 disorder_fatal(errno, "error getting SO_SNDBUF on %s socket", what);
255 if(target_sndbuf > sndbuf) {
256 if(setsockopt(fd, SOL_SOCKET, SO_SNDBUF,
257 &target_sndbuf, sizeof target_sndbuf) < 0)
258 disorder_error(errno, "error setting SO_SNDBUF on %s socket to %d",
259 what, target_sndbuf);
260 else
261 disorder_info("changed socket send buffer size on %socket from %d to %d",
262 what, sndbuf, target_sndbuf);
263 } else
264 disorder_info("default socket send buffer on %s socket is %d",
265 what, sndbuf);
266}
267
dfa51bb7 268static void rtp_open(void) {
80fb0bd9 269 struct addrinfo *dres, *sres;
dfa51bb7 270 static const int one = 1;
76e72f65 271 struct netaddress dst[1], src[1];
80fb0bd9 272 const char *mode;
dfa51bb7 273
80fb0bd9
RK
274 /* Get the mode */
275 mode = uaudio_get("rtp-mode", "auto");
276 if(!strcmp(mode, "broadcast")) rtp_mode = RTP_BROADCAST;
277 else if(!strcmp(mode, "multicast")) rtp_mode = RTP_MULTICAST;
278 else if(!strcmp(mode, "unicast")) rtp_mode = RTP_UNICAST;
279 else if(!strcmp(mode, "request")) rtp_mode = RTP_REQUEST;
280 else rtp_mode = RTP_AUTO;
281 /* Get the source and destination addresses (which might be missing) */
76e72f65
RK
282 rtp_get_netconfig("rtp-destination-af",
283 "rtp-destination",
284 "rtp-destination-port",
285 dst);
286 rtp_get_netconfig("rtp-source-af",
287 "rtp-source",
288 "rtp-source-port",
289 src);
80fb0bd9
RK
290 if(dst->af != -1) {
291 dres = netaddress_resolve(dst, 0, IPPROTO_UDP);
292 if(!dres)
293 exit(-1);
294 } else
295 dres = 0;
76e72f65
RK
296 if(src->af != -1) {
297 sres = netaddress_resolve(src, 1, IPPROTO_UDP);
298 if(!sres)
299 exit(-1);
dfa51bb7
RK
300 } else
301 sres = 0;
80fb0bd9
RK
302 /* _AUTO inspects the destination address and acts accordingly */
303 if(rtp_mode == RTP_AUTO) {
304 if(!dres)
305 rtp_mode = RTP_REQUEST;
306 else if(multicast(dres->ai_addr))
307 rtp_mode = RTP_MULTICAST;
308 else {
309 struct ifaddrs *ifs;
310
311 if(getifaddrs(&ifs) < 0)
312 disorder_fatal(errno, "error calling getifaddrs");
313 while(ifs) {
314 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
315 * still a null pointer. It turns out that there's a subsequent entry
316 * for he same interface which _does_ have ifa_broadaddr though... */
317 if((ifs->ifa_flags & IFF_BROADCAST)
318 && ifs->ifa_broadaddr
319 && sockaddr_equal(ifs->ifa_broadaddr, dres->ai_addr))
320 break;
321 ifs = ifs->ifa_next;
322 }
323 if(ifs)
324 rtp_mode = RTP_BROADCAST;
325 else
326 rtp_mode = RTP_UNICAST;
327 }
328 }
ac52c873 329 /* Create the sockets */
80fb0bd9
RK
330 if(rtp_mode != RTP_REQUEST) {
331 if((rtp_fd = socket(dres->ai_family,
332 dres->ai_socktype,
333 dres->ai_protocol)) < 0)
334 disorder_fatal(errno, "error creating RTP transmission socket");
80fb0bd9 335 }
ac52c873
MW
336 if((rtp_fd4 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
337 disorder_fatal(errno, "error creating v4 RTP transmission socket");
338 if((rtp_fd6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0)
339 disorder_fatal(errno, "error creating v6 RTP transmission socket");
80fb0bd9
RK
340 /* Configure the socket according to the desired mode */
341 switch(rtp_mode) {
342 case RTP_MULTICAST: {
dfa51bb7 343 /* Enable multicast options */
b50cfb8a
RK
344 const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
345 const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
80fb0bd9 346 switch(dres->ai_family) {
dfa51bb7
RK
347 case PF_INET: {
348 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
349 &ttl, sizeof ttl) < 0)
2e9ba080 350 disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
dfa51bb7
RK
351 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
352 &loop, sizeof loop) < 0)
2e9ba080 353 disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
354 break;
355 }
356 case PF_INET6: {
357 if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
358 &ttl, sizeof ttl) < 0)
2e9ba080 359 disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
dfa51bb7
RK
360 if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
361 &loop, sizeof loop) < 0)
2e9ba080 362 disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
363 break;
364 }
365 default:
80fb0bd9 366 disorder_fatal(0, "unsupported address family %d", dres->ai_family);
dfa51bb7 367 }
2e9ba080 368 disorder_info("multicasting on %s TTL=%d loop=%s",
80fb0bd9
RK
369 format_sockaddr(dres->ai_addr), ttl, loop ? "yes" : "no");
370 break;
371 }
372 case RTP_UNICAST: {
373 disorder_info("unicasting on %s", format_sockaddr(dres->ai_addr));
374 break;
375 }
376 case RTP_BROADCAST: {
377 if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
378 disorder_fatal(errno, "error setting SO_BROADCAST on broadcast socket");
379 disorder_info("broadcasting on %s",
380 format_sockaddr(dres->ai_addr));
381 break;
382 }
383 case RTP_REQUEST: {
384 disorder_info("will transmit on request");
385 break;
386 }
dfa51bb7 387 }
d5172201 388 /* Enlarge the socket buffers */
ac52c873
MW
389 if (rtp_fd != -1) hack_send_buffer_size(rtp_fd, "master socket");
390 hack_send_buffer_size(rtp_fd4, "IPv4 on-demand socket");
dc24572f 391 hack_send_buffer_size(rtp_fd6, "IPv6 on-demand 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 448 uaudio_thread_stop();
ac52c873
MW
449 if(rtp_fd >= 0) { close(rtp_fd); rtp_fd = -1; }
450 if(rtp_fd4 >= 0) { close(rtp_fd4); rtp_fd4 = -1; }
2301e915 451 if(rtp_fd6 >= 0) { close(rtp_fd6); rtp_fd6 = -1; }
7a2c7068
RK
452}
453
ba70caca
RK
454static void rtp_configure(void) {
455 char buffer[64];
456
b0116b5c 457 uaudio_set("rtp-mode", config->rtp_mode);
76e72f65
RK
458 rtp_set_netconfig("rtp-destination-af",
459 "rtp-destination",
460 "rtp-destination-port", &config->broadcast);
461 rtp_set_netconfig("rtp-source-af",
462 "rtp-source",
463 "rtp-source-port", &config->broadcast_from);
ba70caca
RK
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");
87864f77
RK
467 if(config->rtp_verbose)
468 disorder_info("RTP: configured");
ba70caca
RK
469}
470
80fb0bd9
RK
471/** @brief Add an RTP recipient address
472 * @param sa Pointer to recipient address
473 * @return 0 on success, -1 on error
474 */
475int rtp_add_recipient(const struct sockaddr_storage *sa) {
476 struct rtp_recipient *r;
477 int rc;
478 pthread_mutex_lock(&rtp_lock);
479 for(r = rtp_recipient_list;
480 r && sockaddrcmp((struct sockaddr *)sa,
481 (struct sockaddr *)&r->sa);
482 r = r->next)
483 ;
484 if(r)
485 rc = -1;
486 else {
487 r = xmalloc(sizeof *r);
c0dadbae 488 memcpy(&r->sa, sa, sizeof *sa);
80fb0bd9
RK
489 r->next = rtp_recipient_list;
490 rtp_recipient_list = r;
491 rc = 0;
492 }
493 pthread_mutex_unlock(&rtp_lock);
494 return rc;
495}
496
497/** @brief Remove an RTP recipient address
498 * @param sa Pointer to recipient address
499 * @return 0 on success, -1 on error
500 */
501int rtp_remove_recipient(const struct sockaddr_storage *sa) {
502 struct rtp_recipient *r, **rr;
503 int rc;
504 pthread_mutex_lock(&rtp_lock);
505 for(rr = &rtp_recipient_list;
506 (r = *rr) && sockaddrcmp((struct sockaddr *)sa,
507 (struct sockaddr *)&r->sa);
508 rr = &r->next)
509 ;
510 if(r) {
511 *rr = r->next;
512 xfree(r);
513 rc = 0;
514 } else {
515 disorder_error(0, "bogus rtp_remove_recipient");
516 rc = -1;
517 }
518 pthread_mutex_unlock(&rtp_lock);
519 return rc;
520}
521
7a2c7068
RK
522const struct uaudio uaudio_rtp = {
523 .name = "rtp",
524 .options = rtp_options,
525 .start = rtp_start,
526 .stop = rtp_stop,
b1f6ca8c
RK
527 .activate = uaudio_thread_activate,
528 .deactivate = uaudio_thread_deactivate,
ba70caca 529 .configure = rtp_configure,
06385470 530 .flags = UAUDIO_API_SERVER,
7a2c7068
RK
531};
532
533/*
534Local Variables:
535c-basic-offset:2
536comment-column:40
537fill-column:79
538indent-tabs-mode:nil
539End:
540*/