2 * This file is part of DisOrder.
3 * Copyright (C) 2009 Richard Kettlewell
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.
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.
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/>.
18 /** @file lib/uaudio-oss.c
19 * @brief Support for RTP network play backend */
38 /** @brief Bytes to send per network packet
40 * This is the maximum number of bytes we pass to write(2); to determine actual
41 * packet sizes, add a UDP header and an IP header (and a link layer header if
42 * it's the link layer size you care about).
44 * Don't make this too big or arithmetic will start to overflow.
46 #define NETWORK_BYTES (1500-8/*UDP*/-40/*IP*/-8/*conservatism*/)
48 /** @brief RTP payload type */
49 static int rtp_payload
;
51 /** @brief RTP output socket */
54 /** @brief RTP SSRC */
55 static uint32_t rtp_id
;
57 /** @brief RTP sequence number */
58 static uint16_t rtp_sequence
;
60 /** @brief RTP timestamp
62 * This is the timestamp that will be used on the next outbound packet.
64 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
65 * stereo, that only gives about half a day before wrapping, which is not
66 * particularly convenient for certain debugging purposes. Therefore the
67 * timestamp is maintained as a 64-bit integer, giving around six million years
68 * before wrapping, and truncated to 32 bits when transmitting.
70 static uint64_t rtp_timestamp
;
72 /** @brief Actual time corresponding to @ref rtp_timestamp
74 * This is the time, on this machine, at which the sample at @ref rtp_timestamp
75 * ought to be sent, interpreted as the time the last packet was sent plus the
76 * time length of the packet. */
77 static struct timeval rtp_timeval
;
79 /** @brief Set when we (re-)activate, to provoke timestamp resync */
80 static int rtp_reactivated
;
82 /** @brief Network error count
84 * If too many errors occur in too short a time, we give up.
86 static int rtp_errors
;
88 /** @brief Delay threshold in microseconds
90 * rtp_play() never attempts to introduce a delay shorter than this.
92 static int64_t rtp_delay_threshold
;
94 static const char *const rtp_options
[] = {
96 "rtp-destination-port",
101 "rtp-delay-threshold",
105 static size_t rtp_play(void *buffer
, size_t nsamples
) {
106 struct rtp_header header
;
110 /* We do as much work as possible before checking what time it is */
111 /* Fill out header */
112 header
.vpxcc
= 2 << 6; /* V=2, P=0, X=0, CC=0 */
113 header
.seq
= htons(rtp_sequence
++);
114 header
.ssrc
= rtp_id
;
115 header
.mpt
= (rtp_reactivated ?
0x80 : 0x00) | rtp_payload
;
117 /* Convert samples to network byte order */
118 uint16_t *u
= buffer
, *const limit
= u
+ nsamples
;
124 vec
[0].iov_base
= (void *)&header
;
125 vec
[0].iov_len
= sizeof header
;
126 vec
[1].iov_base
= buffer
;
127 vec
[1].iov_len
= nsamples
* uaudio_sample_size
;
129 xgettimeofday(&now
, NULL
);
130 if(rtp_reactivated
) {
131 /* We've been deactivated for some unknown interval. We need to advance
132 * rtp_timestamp to account for the dead air. */
133 /* On the first run through we'll set the start time. */
134 if(!rtp_timeval
.tv_sec
)
136 /* See how much time we missed.
138 * This will be 0 on the first run through, in which case we'll not modify
141 * It'll be negative in the (rare) situation where the deactivation
142 * interval is shorter than the last packet we sent. In this case we wait
143 * for that much time and then return having sent no samples, which will
144 * cause uaudio_play_thread_fn() to retry.
146 * In the normal case it will be positive.
148 const int64_t delay
= tvsub_us(now
, rtp_timeval
); /* microseconds */
153 /* Advance the RTP timestamp to the present. With 44.1KHz stereo this will
154 * overflow the intermediate value with a delay of a bit over 6 years.
155 * This seems acceptable. */
156 uint64_t update
= (delay
* uaudio_rate
* uaudio_channels
) / 1000000;
157 /* Don't throw off channel synchronization */
158 update
-= update
% uaudio_channels
;
159 /* We log nontrivial changes */
161 info("advancing rtp_time by %"PRIu64
" samples", update
);
162 rtp_timestamp
+= update
;
166 /* Chances are we've been called right on the heels of the previous packet.
167 * If we just sent packets as fast as we got audio data we'd get way ahead
168 * of the player and some buffer somewhere would fill (or at least become
169 * unreasonably large).
171 * First find out how far ahead of the target time we are.
173 const int64_t ahead
= tvsub_us(now
, rtp_timeval
); /* microseconds */
174 /* Only delay at all if we are nontrivially ahead. */
175 if(ahead
> rtp_delay_threshold
) {
176 /* Don't delay by the full amount */
177 usleep(ahead
- rtp_delay_threshold
/ 2);
178 /* Refetch time (so we don't get out of step with reality) */
179 xgettimeofday(&now
, NULL
);
182 header
.timestamp
= htonl((uint32_t)rtp_timestamp
);
185 written_bytes
= writev(rtp_fd
, vec
, 2);
186 } while(written_bytes
< 0 && errno
== EINTR
);
187 if(written_bytes
< 0) {
188 error(errno
, "error transmitting audio data");
191 fatal(0, "too many audio tranmission errors");
194 rtp_errors
/= 2; /* gradual decay */
195 written_bytes
-= sizeof (struct rtp_header
);
196 size_t written_samples
= written_bytes
/ uaudio_sample_size
;
197 /* rtp_timestamp and rtp_timestamp are supposed to refer to the first sample
198 * of the next packet */
199 rtp_timestamp
+= written_samples
;
200 const unsigned usec
= (rtp_timeval
.tv_usec
201 + 1000000 * written_samples
/ (uaudio_rate
203 /* ...will only overflow 32 bits if one packet is more than about half an
204 * hour long, which is not plausible. */
205 rtp_timeval
.tv_sec
+= usec
/ 1000000;
206 rtp_timeval
.tv_usec
= usec
% 1000000;
207 return written_samples
;
210 static void rtp_open(void) {
211 struct addrinfo
*res
, *sres
;
212 static const struct addrinfo pref
= {
214 .ai_family
= PF_INET
,
215 .ai_socktype
= SOCK_DGRAM
,
216 .ai_protocol
= IPPROTO_UDP
,
218 static const struct addrinfo prefbind
= {
219 .ai_flags
= AI_PASSIVE
,
220 .ai_family
= PF_INET
,
221 .ai_socktype
= SOCK_DGRAM
,
222 .ai_protocol
= IPPROTO_UDP
,
224 static const int one
= 1;
225 int sndbuf
, target_sndbuf
= 131072;
227 char *sockname
, *ssockname
;
228 struct stringlist dst
, src
;
231 /* Get configuration */
233 dst
.s
= xcalloc(2, sizeof *dst
.s
);
234 dst
.s
[0] = uaudio_get("rtp-destination");
235 dst
.s
[1] = uaudio_get("rtp-destination-port");
237 src
.s
= xcalloc(2, sizeof *dst
.s
);
238 src
.s
[0] = uaudio_get("rtp-source");
239 src
.s
[1] = uaudio_get("rtp-source-port");
241 fatal(0, "'rtp-destination' not set");
243 fatal(0, "'rtp-destination-port' not set");
246 fatal(0, "'rtp-source-port' not set");
250 if((delay
= uaudio_get("rtp-delay-threshold")))
251 rtp_delay_threshold
= atoi(delay
);
253 rtp_delay_threshold
= 1000; /* microseconds */
255 /* Resolve addresses */
256 res
= get_address(&dst
, &pref
, &sockname
);
259 sres
= get_address(&src
, &prefbind
, &ssockname
);
263 /* Create the socket */
264 if((rtp_fd
= socket(res
->ai_family
,
266 res
->ai_protocol
)) < 0)
267 fatal(errno
, "error creating broadcast socket");
268 if(multicast(res
->ai_addr
)) {
269 /* Enable multicast options */
270 const char *ttls
= uaudio_get("multicast-ttl");
271 const int ttl
= ttls ?
atoi(ttls
) : 1;
272 const char *loops
= uaudio_get("multicast-loop");
273 const int loop
= loops ?
!strcmp(loops
, "yes") : 1;
274 switch(res
->ai_family
) {
276 if(setsockopt(rtp_fd
, IPPROTO_IP
, IP_MULTICAST_TTL
,
277 &ttl
, sizeof ttl
) < 0)
278 fatal(errno
, "error setting IP_MULTICAST_TTL on multicast socket");
279 if(setsockopt(rtp_fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
280 &loop
, sizeof loop
) < 0)
281 fatal(errno
, "error setting IP_MULTICAST_LOOP on multicast socket");
285 if(setsockopt(rtp_fd
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
286 &ttl
, sizeof ttl
) < 0)
287 fatal(errno
, "error setting IPV6_MULTICAST_HOPS on multicast socket");
288 if(setsockopt(rtp_fd
, IPPROTO_IP
, IPV6_MULTICAST_LOOP
,
289 &loop
, sizeof loop
) < 0)
290 fatal(errno
, "error setting IPV6_MULTICAST_LOOP on multicast socket");
294 fatal(0, "unsupported address family %d", res
->ai_family
);
296 info("multicasting on %s TTL=%d loop=%s",
297 sockname
, ttl
, loop ?
"yes" : "no");
301 if(getifaddrs(&ifs
) < 0)
302 fatal(errno
, "error calling getifaddrs");
304 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
305 * still a null pointer. It turns out that there's a subsequent entry
306 * for he same interface which _does_ have ifa_broadaddr though... */
307 if((ifs
->ifa_flags
& IFF_BROADCAST
)
308 && ifs
->ifa_broadaddr
309 && sockaddr_equal(ifs
->ifa_broadaddr
, res
->ai_addr
))
314 if(setsockopt(rtp_fd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof one
) < 0)
315 fatal(errno
, "error setting SO_BROADCAST on broadcast socket");
316 info("broadcasting on %s (%s)", sockname
, ifs
->ifa_name
);
318 info("unicasting on %s", sockname
);
320 /* Enlarge the socket buffer */
322 if(getsockopt(rtp_fd
, SOL_SOCKET
, SO_SNDBUF
,
324 fatal(errno
, "error getting SO_SNDBUF");
325 if(target_sndbuf
> sndbuf
) {
326 if(setsockopt(rtp_fd
, SOL_SOCKET
, SO_SNDBUF
,
327 &target_sndbuf
, sizeof target_sndbuf
) < 0)
328 error(errno
, "error setting SO_SNDBUF to %d", target_sndbuf
);
330 info("changed socket send buffer size from %d to %d",
331 sndbuf
, target_sndbuf
);
333 info("default socket send buffer is %d",
335 /* We might well want to set additional broadcast- or multicast-related
337 if(sres
&& bind(rtp_fd
, sres
->ai_addr
, sres
->ai_addrlen
) < 0)
338 fatal(errno
, "error binding broadcast socket to %s", ssockname
);
339 if(connect(rtp_fd
, res
->ai_addr
, res
->ai_addrlen
) < 0)
340 fatal(errno
, "error connecting broadcast socket to %s", sockname
);
341 /* Various fields are required to have random initial values by RFC3550. The
342 * packet contents are highly public so there's no point asking for very
343 * strong randomness. */
344 gcry_create_nonce(&rtp_id
, sizeof rtp_id
);
345 gcry_create_nonce(&rtp_sequence
, sizeof rtp_sequence
);
346 gcry_create_nonce(&rtp_timestamp
, sizeof rtp_timestamp
);
347 /* rtp_play() will spot this and choose an initial value */
348 rtp_timeval
.tv_sec
= 0;
351 static void rtp_start(uaudio_callback
*callback
,
353 /* We only support L16 (but we do stereo and mono and will convert sign) */
354 if(uaudio_channels
== 2
356 && uaudio_rate
== 44100)
358 else if(uaudio_channels
== 1
360 && uaudio_rate
== 44100)
363 fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
364 uaudio_bits
, uaudio_rate
, uaudio_channels
);
366 uaudio_thread_start(callback
,
369 256 / uaudio_sample_size
,
370 (NETWORK_BYTES
- sizeof(struct rtp_header
))
371 / uaudio_sample_size
);
374 static void rtp_stop(void) {
375 uaudio_thread_stop();
380 static void rtp_activate(void) {
382 uaudio_thread_activate();
385 static void rtp_deactivate(void) {
386 uaudio_thread_deactivate();
389 const struct uaudio uaudio_rtp
= {
391 .options
= rtp_options
,
394 .activate
= rtp_activate
,
395 .deactivate
= rtp_deactivate