chiark / gitweb /
lib/configuration.c, lib/uaudio-rtp.c: Allow configuring payload size.
[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 43
2a2b84aa
MW
44/** @brief Bytes to send per network packet */
45static int rtp_max_payload;
dfa51bb7
RK
46
47/** @brief RTP payload type */
48static int rtp_payload;
49
ac52c873 50/** @brief RTP broadcast/multicast output socket */
4285d0cf 51static int rtp_fd = -1;
dfa51bb7 52
ac52c873
MW
53/** @brief RTP unicast output socket (IPv4) */
54static int rtp_fd4 = -1;
55
4285d0cf
MW
56/** @brief RTP unicast output socket (IPv6) */
57static int rtp_fd6 = -1;
80fb0bd9 58
dfa51bb7
RK
59/** @brief RTP SSRC */
60static uint32_t rtp_id;
61
b1f6ca8c
RK
62/** @brief Base for timestamp */
63static uint32_t rtp_base;
64
dfa51bb7
RK
65/** @brief RTP sequence number */
66static uint16_t rtp_sequence;
67
dfa51bb7
RK
68/** @brief Network error count
69 *
70 * If too many errors occur in too short a time, we give up.
71 */
72static int rtp_errors;
73
80fb0bd9
RK
74/** @brief RTP mode */
75static int rtp_mode;
76
77#define RTP_BROADCAST 1
78#define RTP_MULTICAST 2
79#define RTP_UNICAST 3
80#define RTP_REQUEST 4
81#define RTP_AUTO 5
82
83/** @brief A unicast client */
84struct rtp_recipient {
85 struct rtp_recipient *next;
86 struct sockaddr_storage sa;
87};
88
89/** @brief List of unicast clients */
90static struct rtp_recipient *rtp_recipient_list;
91
92/** @brief Mutex protecting data structures */
93static pthread_mutex_t rtp_lock = PTHREAD_MUTEX_INITIALIZER;
94
7a2c7068 95static const char *const rtp_options[] = {
dfa51bb7
RK
96 "rtp-destination",
97 "rtp-destination-port",
98 "rtp-source",
99 "rtp-source-port",
100 "multicast-ttl",
101 "multicast-loop",
80fb0bd9 102 "rtp-mode",
2a2b84aa 103 "rtp-max-payload",
7a2c7068
RK
104 NULL
105};
106
76e72f65
RK
107static void rtp_get_netconfig(const char *af,
108 const char *addr,
109 const char *port,
110 struct netaddress *na) {
111 char *vec[3];
112
113 vec[0] = uaudio_get(af, NULL);
114 vec[1] = uaudio_get(addr, NULL);
115 vec[2] = uaudio_get(port, NULL);
116 if(!*vec)
117 na->af = -1;
118 else
119 if(netaddress_parse(na, 3, vec))
2e9ba080 120 disorder_fatal(0, "invalid RTP address");
76e72f65
RK
121}
122
123static void rtp_set_netconfig(const char *af,
124 const char *addr,
125 const char *port,
126 const struct netaddress *na) {
127 uaudio_set(af, NULL);
128 uaudio_set(addr, NULL);
129 uaudio_set(port, NULL);
130 if(na->af != -1) {
131 int nvec;
132 char **vec;
133
134 netaddress_format(na, &nvec, &vec);
135 if(nvec > 0) {
136 uaudio_set(af, vec[0]);
137 xfree(vec[0]);
138 }
139 if(nvec > 1) {
140 uaudio_set(addr, vec[1]);
141 xfree(vec[1]);
142 }
143 if(nvec > 2) {
144 uaudio_set(port, vec[2]);
145 xfree(vec[2]);
146 }
147 xfree(vec);
148 }
149}
150
b1f6ca8c 151static size_t rtp_play(void *buffer, size_t nsamples, unsigned flags) {
dfa51bb7
RK
152 struct rtp_header header;
153 struct iovec vec[2];
b1f6ca8c
RK
154
155#if 0
156 if(flags & (UAUDIO_PAUSE|UAUDIO_RESUME))
157 fprintf(stderr, "rtp_play %zu samples%s%s%s%s\n", nsamples,
158 flags & UAUDIO_PAUSE ? " UAUDIO_PAUSE" : "",
159 flags & UAUDIO_RESUME ? " UAUDIO_RESUME" : "",
160 flags & UAUDIO_PLAYING ? " UAUDIO_PLAYING" : "",
161 flags & UAUDIO_PAUSED ? " UAUDIO_PAUSED" : "");
162#endif
163
dfa51bb7
RK
164 /* We do as much work as possible before checking what time it is */
165 /* Fill out header */
166 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
167 header.seq = htons(rtp_sequence++);
168 header.ssrc = rtp_id;
b1f6ca8c
RK
169 header.mpt = rtp_payload;
170 /* If we've come out of a pause, set the marker bit */
171 if(flags & UAUDIO_RESUME)
172 header.mpt |= 0x80;
dfa51bb7
RK
173#if !WORDS_BIGENDIAN
174 /* Convert samples to network byte order */
175 uint16_t *u = buffer, *const limit = u + nsamples;
176 while(u < limit) {
177 *u = htons(*u);
178 ++u;
179 }
180#endif
181 vec[0].iov_base = (void *)&header;
182 vec[0].iov_len = sizeof header;
183 vec[1].iov_base = buffer;
184 vec[1].iov_len = nsamples * uaudio_sample_size;
b1f6ca8c
RK
185 const uint32_t timestamp = uaudio_schedule_sync();
186 header.timestamp = htonl(rtp_base + (uint32_t)timestamp);
87864f77
RK
187
188 /* We send ~120 packets a second with current arrangements. So if we log
189 * once every 8192 packets we log about once a minute. */
190
191 if(!(ntohs(header.seq) & 8191)
192 && config->rtp_verbose)
193 disorder_info("RTP: seq %04"PRIx16" %08"PRIx32"+%08"PRIx32"=%08"PRIx32" ns %zu%s",
194 ntohs(header.seq),
195 rtp_base,
196 timestamp,
197 header.timestamp,
198 nsamples,
199 flags & UAUDIO_PAUSED ? " [paused]" : "");
200
b1f6ca8c
RK
201 /* If we're paused don't actually end a packet, we just pretend */
202 if(flags & UAUDIO_PAUSED) {
203 uaudio_schedule_sent(nsamples);
204 return nsamples;
205 }
43e7474d
MW
206 /* Send stuff to explicitly registerd unicast addresses unconditionally */
207 struct rtp_recipient *r;
208 struct msghdr m;
209 memset(&m, 0, sizeof m);
210 m.msg_iov = vec;
211 m.msg_iovlen = 2;
212 pthread_mutex_lock(&rtp_lock);
213 for(r = rtp_recipient_list; r; r = r->next) {
214 m.msg_name = &r->sa;
215 m.msg_namelen = r->sa.ss_family == AF_INET ?
216 sizeof(struct sockaddr_in) : sizeof (struct sockaddr_in6);
217 sendmsg(r->sa.ss_family == AF_INET ? rtp_fd4 : rtp_fd6,
218 &m, MSG_DONTWAIT|MSG_NOSIGNAL);
219 // TODO similar error handling to other case?
220 }
221 pthread_mutex_unlock(&rtp_lock);
222 if(rtp_mode != RTP_REQUEST) {
80fb0bd9
RK
223 int written_bytes;
224 do {
225 written_bytes = writev(rtp_fd, vec, 2);
226 } while(written_bytes < 0 && errno == EINTR);
227 if(written_bytes < 0) {
228 disorder_error(errno, "error transmitting audio data");
229 ++rtp_errors;
230 if(rtp_errors == 10)
231 disorder_fatal(0, "too many audio transmission errors");
232 return 0;
233 } else
234 rtp_errors /= 2; /* gradual decay */
235 }
b1f6ca8c
RK
236 /* TODO what can we sensibly do about short writes here? Really that's just
237 * an error and we ought to be using smaller packets. */
238 uaudio_schedule_sent(nsamples);
239 return nsamples;
dfa51bb7
RK
240}
241
d5172201
MW
242static void hack_send_buffer_size(int fd, const char *what) {
243 int sndbuf, target_sndbuf = 131072;
244 socklen_t len = sizeof sndbuf;
245
246 if(getsockopt(fd, SOL_SOCKET, SO_SNDBUF,
247 &sndbuf, &len) < 0)
248 disorder_fatal(errno, "error getting SO_SNDBUF on %s socket", what);
249 if(target_sndbuf > sndbuf) {
250 if(setsockopt(fd, SOL_SOCKET, SO_SNDBUF,
251 &target_sndbuf, sizeof target_sndbuf) < 0)
252 disorder_error(errno, "error setting SO_SNDBUF on %s socket to %d",
253 what, target_sndbuf);
254 else
255 disorder_info("changed socket send buffer size on %socket from %d to %d",
256 what, sndbuf, target_sndbuf);
257 } else
258 disorder_info("default socket send buffer on %s socket is %d",
259 what, sndbuf);
260}
261
dfa51bb7 262static void rtp_open(void) {
80fb0bd9 263 struct addrinfo *dres, *sres;
dfa51bb7 264 static const int one = 1;
76e72f65 265 struct netaddress dst[1], src[1];
80fb0bd9 266 const char *mode;
dfa51bb7 267
80fb0bd9
RK
268 /* Get the mode */
269 mode = uaudio_get("rtp-mode", "auto");
270 if(!strcmp(mode, "broadcast")) rtp_mode = RTP_BROADCAST;
271 else if(!strcmp(mode, "multicast")) rtp_mode = RTP_MULTICAST;
272 else if(!strcmp(mode, "unicast")) rtp_mode = RTP_UNICAST;
273 else if(!strcmp(mode, "request")) rtp_mode = RTP_REQUEST;
274 else rtp_mode = RTP_AUTO;
275 /* Get the source and destination addresses (which might be missing) */
76e72f65
RK
276 rtp_get_netconfig("rtp-destination-af",
277 "rtp-destination",
278 "rtp-destination-port",
279 dst);
280 rtp_get_netconfig("rtp-source-af",
281 "rtp-source",
282 "rtp-source-port",
283 src);
80fb0bd9
RK
284 if(dst->af != -1) {
285 dres = netaddress_resolve(dst, 0, IPPROTO_UDP);
286 if(!dres)
287 exit(-1);
288 } else
289 dres = 0;
76e72f65
RK
290 if(src->af != -1) {
291 sres = netaddress_resolve(src, 1, IPPROTO_UDP);
292 if(!sres)
293 exit(-1);
dfa51bb7
RK
294 } else
295 sres = 0;
80fb0bd9
RK
296 /* _AUTO inspects the destination address and acts accordingly */
297 if(rtp_mode == RTP_AUTO) {
298 if(!dres)
299 rtp_mode = RTP_REQUEST;
300 else if(multicast(dres->ai_addr))
301 rtp_mode = RTP_MULTICAST;
302 else {
303 struct ifaddrs *ifs;
304
305 if(getifaddrs(&ifs) < 0)
306 disorder_fatal(errno, "error calling getifaddrs");
307 while(ifs) {
308 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
309 * still a null pointer. It turns out that there's a subsequent entry
310 * for he same interface which _does_ have ifa_broadaddr though... */
311 if((ifs->ifa_flags & IFF_BROADCAST)
312 && ifs->ifa_broadaddr
313 && sockaddr_equal(ifs->ifa_broadaddr, dres->ai_addr))
314 break;
315 ifs = ifs->ifa_next;
316 }
317 if(ifs)
318 rtp_mode = RTP_BROADCAST;
319 else
320 rtp_mode = RTP_UNICAST;
321 }
322 }
2a2b84aa
MW
323 rtp_max_payload = atoi(uaudio_get("rtp-max-payload", "-1"));
324 if(rtp_max_payload < 0)
325 rtp_max_payload = 1500 - 8/*UDP*/ - 40/*IP*/ - 8/*conservatism*/;
ac52c873 326 /* Create the sockets */
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");
80fb0bd9 332 }
ac52c873
MW
333 if((rtp_fd4 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
334 disorder_fatal(errno, "error creating v4 RTP transmission socket");
335 if((rtp_fd6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0)
336 disorder_fatal(errno, "error creating v6 RTP transmission socket");
80fb0bd9
RK
337 /* Configure the socket according to the desired mode */
338 switch(rtp_mode) {
339 case RTP_MULTICAST: {
dfa51bb7 340 /* Enable multicast options */
b50cfb8a
RK
341 const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
342 const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
80fb0bd9 343 switch(dres->ai_family) {
dfa51bb7
RK
344 case PF_INET: {
345 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
346 &ttl, sizeof ttl) < 0)
2e9ba080 347 disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
dfa51bb7
RK
348 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
349 &loop, sizeof loop) < 0)
2e9ba080 350 disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
351 break;
352 }
353 case PF_INET6: {
354 if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
355 &ttl, sizeof ttl) < 0)
2e9ba080 356 disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
dfa51bb7
RK
357 if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
358 &loop, sizeof loop) < 0)
2e9ba080 359 disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
360 break;
361 }
362 default:
80fb0bd9 363 disorder_fatal(0, "unsupported address family %d", dres->ai_family);
dfa51bb7 364 }
2e9ba080 365 disorder_info("multicasting on %s TTL=%d loop=%s",
80fb0bd9
RK
366 format_sockaddr(dres->ai_addr), ttl, loop ? "yes" : "no");
367 break;
368 }
369 case RTP_UNICAST: {
370 disorder_info("unicasting on %s", format_sockaddr(dres->ai_addr));
371 break;
372 }
373 case RTP_BROADCAST: {
374 if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
375 disorder_fatal(errno, "error setting SO_BROADCAST on broadcast socket");
376 disorder_info("broadcasting on %s",
377 format_sockaddr(dres->ai_addr));
378 break;
379 }
380 case RTP_REQUEST: {
381 disorder_info("will transmit on request");
382 break;
383 }
dfa51bb7 384 }
d5172201 385 /* Enlarge the socket buffers */
ac52c873
MW
386 if (rtp_fd != -1) hack_send_buffer_size(rtp_fd, "master socket");
387 hack_send_buffer_size(rtp_fd4, "IPv4 on-demand socket");
dc24572f 388 hack_send_buffer_size(rtp_fd6, "IPv6 on-demand socket");
dfa51bb7
RK
389 /* We might well want to set additional broadcast- or multicast-related
390 * options here */
80fb0bd9
RK
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));
398 }
87864f77
RK
399 if(config->rtp_verbose)
400 disorder_info("RTP: prepared socket");
dfa51bb7
RK
401}
402
7a2c7068
RK
403static void rtp_start(uaudio_callback *callback,
404 void *userdata) {
dfa51bb7
RK
405 /* We only support L16 (but we do stereo and mono and will convert sign) */
406 if(uaudio_channels == 2
407 && uaudio_bits == 16
408 && uaudio_rate == 44100)
409 rtp_payload = 10;
410 else if(uaudio_channels == 1
411 && uaudio_bits == 16
412 && uaudio_rate == 44100)
413 rtp_payload = 11;
414 else
2e9ba080
RK
415 disorder_fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
416 uaudio_bits, uaudio_rate, uaudio_channels);
87864f77
RK
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);
ec57f6c9
RK
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);
b1f6ca8c 424 gcry_create_nonce(&rtp_base, sizeof rtp_base);
ec57f6c9 425 gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
87864f77
RK
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);
dfa51bb7 429 rtp_open();
ec57f6c9 430 uaudio_schedule_init();
87864f77
RK
431 if(config->rtp_verbose)
432 disorder_info("RTP: initialized schedule");
dfa51bb7
RK
433 uaudio_thread_start(callback,
434 userdata,
435 rtp_play,
436 256 / uaudio_sample_size,
2a2b84aa 437 (rtp_max_payload - sizeof(struct rtp_header))
63761c19
RK
438 / uaudio_sample_size,
439 0);
87864f77
RK
440 if(config->rtp_verbose)
441 disorder_info("RTP: created thread");
7a2c7068
RK
442}
443
444static void rtp_stop(void) {
dfa51bb7 445 uaudio_thread_stop();
ac52c873
MW
446 if(rtp_fd >= 0) { close(rtp_fd); rtp_fd = -1; }
447 if(rtp_fd4 >= 0) { close(rtp_fd4); rtp_fd4 = -1; }
2301e915 448 if(rtp_fd6 >= 0) { close(rtp_fd6); rtp_fd6 = -1; }
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");
2a2b84aa
MW
464 snprintf(buffer, sizeof buffer, "%ld", config->rtp_max_payload);
465 uaudio_set("rtp-max-payload", buffer);
87864f77
RK
466 if(config->rtp_verbose)
467 disorder_info("RTP: configured");
ba70caca
RK
468}
469
80fb0bd9
RK
470/** @brief Add an RTP recipient address
471 * @param sa Pointer to recipient address
472 * @return 0 on success, -1 on error
473 */
474int rtp_add_recipient(const struct sockaddr_storage *sa) {
475 struct rtp_recipient *r;
476 int rc;
477 pthread_mutex_lock(&rtp_lock);
478 for(r = rtp_recipient_list;
479 r && sockaddrcmp((struct sockaddr *)sa,
480 (struct sockaddr *)&r->sa);
481 r = r->next)
482 ;
483 if(r)
484 rc = -1;
485 else {
486 r = xmalloc(sizeof *r);
c0dadbae 487 memcpy(&r->sa, sa, sizeof *sa);
80fb0bd9
RK
488 r->next = rtp_recipient_list;
489 rtp_recipient_list = r;
490 rc = 0;
491 }
492 pthread_mutex_unlock(&rtp_lock);
493 return rc;
494}
495
496/** @brief Remove an RTP recipient address
497 * @param sa Pointer to recipient address
498 * @return 0 on success, -1 on error
499 */
500int rtp_remove_recipient(const struct sockaddr_storage *sa) {
501 struct rtp_recipient *r, **rr;
502 int rc;
503 pthread_mutex_lock(&rtp_lock);
504 for(rr = &rtp_recipient_list;
505 (r = *rr) && sockaddrcmp((struct sockaddr *)sa,
506 (struct sockaddr *)&r->sa);
507 rr = &r->next)
508 ;
509 if(r) {
510 *rr = r->next;
511 xfree(r);
512 rc = 0;
513 } else {
514 disorder_error(0, "bogus rtp_remove_recipient");
515 rc = -1;
516 }
517 pthread_mutex_unlock(&rtp_lock);
518 return rc;
519}
520
7a2c7068
RK
521const struct uaudio uaudio_rtp = {
522 .name = "rtp",
523 .options = rtp_options,
524 .start = rtp_start,
525 .stop = rtp_stop,
b1f6ca8c
RK
526 .activate = uaudio_thread_activate,
527 .deactivate = uaudio_thread_deactivate,
ba70caca 528 .configure = rtp_configure,
06385470 529 .flags = UAUDIO_API_SERVER,
7a2c7068
RK
530};
531
532/*
533Local Variables:
534c-basic-offset:2
535comment-column:40
536fill-column:79
537indent-tabs-mode:nil
538End:
539*/