chiark / gitweb /
A batch of copyright date updates.
[disorder] / lib / uaudio-rtp.c
CommitLineData
7a2c7068
RK
1/*
2 * This file is part of DisOrder.
3 * Copyright (C) 2009 Richard Kettlewell
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>
7a2c7068
RK
32
33#include "uaudio.h"
34#include "mem.h"
35#include "log.h"
36#include "syscalls.h"
dfa51bb7
RK
37#include "rtp.h"
38#include "addr.h"
39#include "ifreq.h"
40#include "timeval.h"
ba70caca 41#include "configuration.h"
dfa51bb7
RK
42
43/** @brief Bytes to send per network packet
44 *
45 * This is the maximum number of bytes we pass to write(2); to determine actual
46 * packet sizes, add a UDP header and an IP header (and a link layer header if
47 * it's the link layer size you care about).
48 *
49 * Don't make this too big or arithmetic will start to overflow.
50 */
51#define NETWORK_BYTES (1500-8/*UDP*/-40/*IP*/-8/*conservatism*/)
52
53/** @brief RTP payload type */
54static int rtp_payload;
55
56/** @brief RTP output socket */
57static int rtp_fd;
58
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
b1f6ca8c
RK
74/** @brief Set while paused */
75static volatile int rtp_paused;
7a2c7068
RK
76
77static const char *const rtp_options[] = {
dfa51bb7
RK
78 "rtp-destination",
79 "rtp-destination-port",
80 "rtp-source",
81 "rtp-source-port",
82 "multicast-ttl",
83 "multicast-loop",
7a2c7068
RK
84 NULL
85};
86
76e72f65
RK
87static void rtp_get_netconfig(const char *af,
88 const char *addr,
89 const char *port,
90 struct netaddress *na) {
91 char *vec[3];
92
93 vec[0] = uaudio_get(af, NULL);
94 vec[1] = uaudio_get(addr, NULL);
95 vec[2] = uaudio_get(port, NULL);
96 if(!*vec)
97 na->af = -1;
98 else
99 if(netaddress_parse(na, 3, vec))
2e9ba080 100 disorder_fatal(0, "invalid RTP address");
76e72f65
RK
101}
102
103static void rtp_set_netconfig(const char *af,
104 const char *addr,
105 const char *port,
106 const struct netaddress *na) {
107 uaudio_set(af, NULL);
108 uaudio_set(addr, NULL);
109 uaudio_set(port, NULL);
110 if(na->af != -1) {
111 int nvec;
112 char **vec;
113
114 netaddress_format(na, &nvec, &vec);
115 if(nvec > 0) {
116 uaudio_set(af, vec[0]);
117 xfree(vec[0]);
118 }
119 if(nvec > 1) {
120 uaudio_set(addr, vec[1]);
121 xfree(vec[1]);
122 }
123 if(nvec > 2) {
124 uaudio_set(port, vec[2]);
125 xfree(vec[2]);
126 }
127 xfree(vec);
128 }
129}
130
b1f6ca8c 131static size_t rtp_play(void *buffer, size_t nsamples, unsigned flags) {
dfa51bb7
RK
132 struct rtp_header header;
133 struct iovec vec[2];
b1f6ca8c
RK
134
135#if 0
136 if(flags & (UAUDIO_PAUSE|UAUDIO_RESUME))
137 fprintf(stderr, "rtp_play %zu samples%s%s%s%s\n", nsamples,
138 flags & UAUDIO_PAUSE ? " UAUDIO_PAUSE" : "",
139 flags & UAUDIO_RESUME ? " UAUDIO_RESUME" : "",
140 flags & UAUDIO_PLAYING ? " UAUDIO_PLAYING" : "",
141 flags & UAUDIO_PAUSED ? " UAUDIO_PAUSED" : "");
142#endif
143
dfa51bb7
RK
144 /* We do as much work as possible before checking what time it is */
145 /* Fill out header */
146 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
147 header.seq = htons(rtp_sequence++);
148 header.ssrc = rtp_id;
b1f6ca8c
RK
149 header.mpt = rtp_payload;
150 /* If we've come out of a pause, set the marker bit */
151 if(flags & UAUDIO_RESUME)
152 header.mpt |= 0x80;
dfa51bb7
RK
153#if !WORDS_BIGENDIAN
154 /* Convert samples to network byte order */
155 uint16_t *u = buffer, *const limit = u + nsamples;
156 while(u < limit) {
157 *u = htons(*u);
158 ++u;
159 }
160#endif
161 vec[0].iov_base = (void *)&header;
162 vec[0].iov_len = sizeof header;
163 vec[1].iov_base = buffer;
164 vec[1].iov_len = nsamples * uaudio_sample_size;
b1f6ca8c
RK
165 const uint32_t timestamp = uaudio_schedule_sync();
166 header.timestamp = htonl(rtp_base + (uint32_t)timestamp);
87864f77
RK
167
168 /* We send ~120 packets a second with current arrangements. So if we log
169 * once every 8192 packets we log about once a minute. */
170
171 if(!(ntohs(header.seq) & 8191)
172 && config->rtp_verbose)
173 disorder_info("RTP: seq %04"PRIx16" %08"PRIx32"+%08"PRIx32"=%08"PRIx32" ns %zu%s",
174 ntohs(header.seq),
175 rtp_base,
176 timestamp,
177 header.timestamp,
178 nsamples,
179 flags & UAUDIO_PAUSED ? " [paused]" : "");
180
b1f6ca8c
RK
181 /* If we're paused don't actually end a packet, we just pretend */
182 if(flags & UAUDIO_PAUSED) {
183 uaudio_schedule_sent(nsamples);
184 return nsamples;
185 }
dfa51bb7
RK
186 int written_bytes;
187 do {
188 written_bytes = writev(rtp_fd, vec, 2);
189 } while(written_bytes < 0 && errno == EINTR);
190 if(written_bytes < 0) {
2e9ba080 191 disorder_error(errno, "error transmitting audio data");
dfa51bb7
RK
192 ++rtp_errors;
193 if(rtp_errors == 10)
2e9ba080 194 disorder_fatal(0, "too many audio tranmission errors");
dfa51bb7
RK
195 return 0;
196 } else
197 rtp_errors /= 2; /* gradual decay */
b1f6ca8c
RK
198 /* TODO what can we sensibly do about short writes here? Really that's just
199 * an error and we ought to be using smaller packets. */
200 uaudio_schedule_sent(nsamples);
201 return nsamples;
dfa51bb7
RK
202}
203
204static void rtp_open(void) {
205 struct addrinfo *res, *sres;
dfa51bb7
RK
206 static const int one = 1;
207 int sndbuf, target_sndbuf = 131072;
208 socklen_t len;
76e72f65 209 struct netaddress dst[1], src[1];
dfa51bb7
RK
210
211 /* Get configuration */
76e72f65
RK
212 rtp_get_netconfig("rtp-destination-af",
213 "rtp-destination",
214 "rtp-destination-port",
215 dst);
216 rtp_get_netconfig("rtp-source-af",
217 "rtp-source",
218 "rtp-source-port",
219 src);
b50cfb8a 220 /* ...microseconds */
dfa51bb7
RK
221
222 /* Resolve addresses */
76e72f65
RK
223 res = netaddress_resolve(dst, 0, IPPROTO_UDP);
224 if(!res)
225 exit(-1);
226 if(src->af != -1) {
227 sres = netaddress_resolve(src, 1, IPPROTO_UDP);
228 if(!sres)
229 exit(-1);
dfa51bb7
RK
230 } else
231 sres = 0;
232 /* Create the socket */
233 if((rtp_fd = socket(res->ai_family,
234 res->ai_socktype,
235 res->ai_protocol)) < 0)
2e9ba080 236 disorder_fatal(errno, "error creating broadcast socket");
dfa51bb7
RK
237 if(multicast(res->ai_addr)) {
238 /* Enable multicast options */
b50cfb8a
RK
239 const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
240 const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
dfa51bb7
RK
241 switch(res->ai_family) {
242 case PF_INET: {
243 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
244 &ttl, sizeof ttl) < 0)
2e9ba080 245 disorder_fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
dfa51bb7
RK
246 if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
247 &loop, sizeof loop) < 0)
2e9ba080 248 disorder_fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
249 break;
250 }
251 case PF_INET6: {
252 if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
253 &ttl, sizeof ttl) < 0)
2e9ba080 254 disorder_fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
dfa51bb7
RK
255 if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
256 &loop, sizeof loop) < 0)
2e9ba080 257 disorder_fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
dfa51bb7
RK
258 break;
259 }
260 default:
2e9ba080 261 disorder_fatal(0, "unsupported address family %d", res->ai_family);
dfa51bb7 262 }
2e9ba080
RK
263 disorder_info("multicasting on %s TTL=%d loop=%s",
264 format_sockaddr(res->ai_addr), ttl, loop ? "yes" : "no");
dfa51bb7
RK
265 } else {
266 struct ifaddrs *ifs;
267
268 if(getifaddrs(&ifs) < 0)
2e9ba080 269 disorder_fatal(errno, "error calling getifaddrs");
dfa51bb7
RK
270 while(ifs) {
271 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
272 * still a null pointer. It turns out that there's a subsequent entry
273 * for he same interface which _does_ have ifa_broadaddr though... */
274 if((ifs->ifa_flags & IFF_BROADCAST)
275 && ifs->ifa_broadaddr
276 && sockaddr_equal(ifs->ifa_broadaddr, res->ai_addr))
277 break;
278 ifs = ifs->ifa_next;
279 }
280 if(ifs) {
281 if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
2e9ba080
RK
282 disorder_fatal(errno, "error setting SO_BROADCAST on broadcast socket");
283 disorder_info("broadcasting on %s (%s)",
76e72f65 284 format_sockaddr(res->ai_addr), ifs->ifa_name);
dfa51bb7 285 } else
2e9ba080 286 disorder_info("unicasting on %s", format_sockaddr(res->ai_addr));
dfa51bb7
RK
287 }
288 /* Enlarge the socket buffer */
289 len = sizeof sndbuf;
290 if(getsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
291 &sndbuf, &len) < 0)
2e9ba080 292 disorder_fatal(errno, "error getting SO_SNDBUF");
dfa51bb7
RK
293 if(target_sndbuf > sndbuf) {
294 if(setsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
295 &target_sndbuf, sizeof target_sndbuf) < 0)
2e9ba080 296 disorder_error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
dfa51bb7 297 else
2e9ba080 298 disorder_info("changed socket send buffer size from %d to %d",
dfa51bb7
RK
299 sndbuf, target_sndbuf);
300 } else
2e9ba080 301 disorder_info("default socket send buffer is %d", sndbuf);
dfa51bb7
RK
302 /* We might well want to set additional broadcast- or multicast-related
303 * options here */
304 if(sres && bind(rtp_fd, sres->ai_addr, sres->ai_addrlen) < 0)
2e9ba080
RK
305 disorder_fatal(errno, "error binding broadcast socket to %s",
306 format_sockaddr(sres->ai_addr));
dfa51bb7 307 if(connect(rtp_fd, res->ai_addr, res->ai_addrlen) < 0)
2e9ba080
RK
308 disorder_fatal(errno, "error connecting broadcast socket to %s",
309 format_sockaddr(res->ai_addr));
87864f77
RK
310 if(config->rtp_verbose)
311 disorder_info("RTP: prepared socket");
dfa51bb7
RK
312}
313
7a2c7068
RK
314static void rtp_start(uaudio_callback *callback,
315 void *userdata) {
dfa51bb7
RK
316 /* We only support L16 (but we do stereo and mono and will convert sign) */
317 if(uaudio_channels == 2
318 && uaudio_bits == 16
319 && uaudio_rate == 44100)
320 rtp_payload = 10;
321 else if(uaudio_channels == 1
322 && uaudio_bits == 16
323 && uaudio_rate == 44100)
324 rtp_payload = 11;
325 else
2e9ba080
RK
326 disorder_fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
327 uaudio_bits, uaudio_rate, uaudio_channels);
87864f77
RK
328 if(config->rtp_verbose)
329 disorder_info("RTP: %d channels %d bits %d Hz payload type %d",
330 uaudio_channels, uaudio_bits, uaudio_rate, rtp_payload);
ec57f6c9
RK
331 /* Various fields are required to have random initial values by RFC3550. The
332 * packet contents are highly public so there's no point asking for very
333 * strong randomness. */
334 gcry_create_nonce(&rtp_id, sizeof rtp_id);
b1f6ca8c 335 gcry_create_nonce(&rtp_base, sizeof rtp_base);
ec57f6c9 336 gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
87864f77
RK
337 if(config->rtp_verbose)
338 disorder_info("RTP: id %08"PRIx32" base %08"PRIx32" initial seq %08"PRIx16,
339 rtp_id, rtp_base, rtp_sequence);
dfa51bb7 340 rtp_open();
ec57f6c9 341 uaudio_schedule_init();
87864f77
RK
342 if(config->rtp_verbose)
343 disorder_info("RTP: initialized schedule");
dfa51bb7
RK
344 uaudio_thread_start(callback,
345 userdata,
346 rtp_play,
347 256 / uaudio_sample_size,
348 (NETWORK_BYTES - sizeof(struct rtp_header))
63761c19
RK
349 / uaudio_sample_size,
350 0);
87864f77
RK
351 if(config->rtp_verbose)
352 disorder_info("RTP: created thread");
7a2c7068
RK
353}
354
355static void rtp_stop(void) {
dfa51bb7
RK
356 uaudio_thread_stop();
357 close(rtp_fd);
358 rtp_fd = -1;
7a2c7068
RK
359}
360
ba70caca
RK
361static void rtp_configure(void) {
362 char buffer[64];
363
76e72f65
RK
364 rtp_set_netconfig("rtp-destination-af",
365 "rtp-destination",
366 "rtp-destination-port", &config->broadcast);
367 rtp_set_netconfig("rtp-source-af",
368 "rtp-source",
369 "rtp-source-port", &config->broadcast_from);
ba70caca
RK
370 snprintf(buffer, sizeof buffer, "%ld", config->multicast_ttl);
371 uaudio_set("multicast-ttl", buffer);
372 uaudio_set("multicast-loop", config->multicast_loop ? "yes" : "no");
87864f77
RK
373 if(config->rtp_verbose)
374 disorder_info("RTP: configured");
ba70caca
RK
375}
376
7a2c7068
RK
377const struct uaudio uaudio_rtp = {
378 .name = "rtp",
379 .options = rtp_options,
380 .start = rtp_start,
381 .stop = rtp_stop,
b1f6ca8c
RK
382 .activate = uaudio_thread_activate,
383 .deactivate = uaudio_thread_deactivate,
ba70caca 384 .configure = rtp_configure,
7a2c7068
RK
385};
386
387/*
388Local Variables:
389c-basic-offset:2
390comment-column:40
391fill-column:79
392indent-tabs-mode:nil
393End:
394*/