2 * This file is part of DisOrder
3 * Copyright (C) 2005-2008 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 server/speaker-network.c
19 * @brief Support for @ref BACKEND_NETWORK */
27 #include <sys/socket.h>
32 #include <netinet/in.h>
34 #include "configuration.h"
41 #include "speaker-protocol.h"
44 /** @brief Network socket
46 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
50 /** @brief RTP timestamp
52 * This counts the number of samples played (NB not the number of frames
55 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
56 * stereo, that only gives about half a day before wrapping, which is not
57 * particularly convenient for certain debugging purposes. Therefore the
58 * timestamp is maintained as a 64-bit integer, giving around six million years
59 * before wrapping, and truncated to 32 bits when transmitting.
61 static uint64_t rtp_time
;
63 /** @brief RTP base timestamp
65 * This is the real time correspoding to an @ref rtp_time of 0. It is used
66 * to recalculate the timestamp after idle periods.
68 static struct timeval rtp_time_0
;
70 /** @brief RTP packet sequence number */
71 static uint16_t rtp_seq
;
73 /** @brief RTP SSRC */
74 static uint32_t rtp_id
;
76 /** @brief Error counter */
77 static int audio_errors
;
79 /** @brief Network backend initialization */
80 static void network_init(void) {
81 struct addrinfo
*res
, *sres
;
82 static const struct addrinfo pref
= {
85 .ai_socktype
= SOCK_DGRAM
,
86 .ai_protocol
= IPPROTO_UDP
,
88 static const struct addrinfo prefbind
= {
89 .ai_flags
= AI_PASSIVE
,
91 .ai_socktype
= SOCK_DGRAM
,
92 .ai_protocol
= IPPROTO_UDP
,
94 static const int one
= 1;
95 int sndbuf
, target_sndbuf
= 131072;
97 char *sockname
, *ssockname
;
99 res
= get_address(&config
->broadcast
, &pref
, &sockname
);
101 if(config
->broadcast_from
.n
) {
102 sres
= get_address(&config
->broadcast_from
, &prefbind
, &ssockname
);
106 if((bfd
= socket(res
->ai_family
,
108 res
->ai_protocol
)) < 0)
109 fatal(errno
, "error creating broadcast socket");
110 if(multicast(res
->ai_addr
)) {
112 switch(res
->ai_family
) {
114 const int mttl
= config
->multicast_ttl
;
115 if(setsockopt(bfd
, IPPROTO_IP
, IP_MULTICAST_TTL
, &mttl
, sizeof mttl
) < 0)
116 fatal(errno
, "error setting IP_MULTICAST_TTL on multicast socket");
117 if(setsockopt(bfd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
118 &config
->multicast_loop
, sizeof one
) < 0)
119 fatal(errno
, "error setting IP_MULTICAST_LOOP on multicast socket");
123 const int mttl
= config
->multicast_ttl
;
124 if(setsockopt(bfd
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
125 &mttl
, sizeof mttl
) < 0)
126 fatal(errno
, "error setting IPV6_MULTICAST_HOPS on multicast socket");
127 if(setsockopt(bfd
, IPPROTO_IP
, IPV6_MULTICAST_LOOP
,
128 &config
->multicast_loop
, sizeof (int)) < 0)
129 fatal(errno
, "error setting IPV6_MULTICAST_LOOP on multicast socket");
133 fatal(0, "unsupported address family %d", res
->ai_family
);
135 info("multicasting on %s", sockname
);
139 if(getifaddrs(&ifs
) < 0)
140 fatal(errno
, "error calling getifaddrs");
142 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
143 * still a null pointer. It turns out that there's a subsequent entry
144 * for he same interface which _does_ have ifa_broadaddr though... */
145 if((ifs
->ifa_flags
& IFF_BROADCAST
)
146 && ifs
->ifa_broadaddr
147 && sockaddr_equal(ifs
->ifa_broadaddr
, res
->ai_addr
))
152 if(setsockopt(bfd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof one
) < 0)
153 fatal(errno
, "error setting SO_BROADCAST on broadcast socket");
154 info("broadcasting on %s (%s)", sockname
, ifs
->ifa_name
);
156 info("unicasting on %s", sockname
);
159 if(getsockopt(bfd
, SOL_SOCKET
, SO_SNDBUF
,
161 fatal(errno
, "error getting SO_SNDBUF");
162 if(target_sndbuf
> sndbuf
) {
163 if(setsockopt(bfd
, SOL_SOCKET
, SO_SNDBUF
,
164 &target_sndbuf
, sizeof target_sndbuf
) < 0)
165 error(errno
, "error setting SO_SNDBUF to %d", target_sndbuf
);
167 info("changed socket send buffer size from %d to %d",
168 sndbuf
, target_sndbuf
);
170 info("default socket send buffer is %d",
172 /* We might well want to set additional broadcast- or multicast-related
174 if(sres
&& bind(bfd
, sres
->ai_addr
, sres
->ai_addrlen
) < 0)
175 fatal(errno
, "error binding broadcast socket to %s", ssockname
);
176 if(connect(bfd
, res
->ai_addr
, res
->ai_addrlen
) < 0)
177 fatal(errno
, "error connecting broadcast socket to %s", sockname
);
179 gcry_randomize(&rtp_id
, sizeof rtp_id
, GCRY_STRONG_RANDOM
);
182 /** @brief Play over the network */
183 static size_t network_play(size_t frames
) {
184 struct rtp_header header
;
186 size_t bytes
= frames
* bpf
, written_frames
;
188 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
189 * AVT profile (RFC3551). */
191 /* If we're starting then initialize the base time */
193 xgettimeofday(&rtp_time_0
, 0);
195 /* There may have been a gap. Fix up the RTP time accordingly. */
198 uint64_t target_rtp_time
;
200 /* Find the current time */
201 xgettimeofday(&now
, 0);
202 /* Find the number of microseconds elapsed since rtp_time=0 */
203 delta
= tvsub_us(now
, rtp_time_0
);
204 if(delta
> UINT64_MAX
/ 88200)
205 fatal(0, "rtp_time=%llu now=%ld.%06ld rtp_time_0=%ld.%06ld delta=%llu (%lld)",
207 (long)now
.tv_sec
, (long)now
.tv_usec
,
208 (long)rtp_time_0
.tv_sec
, (long)rtp_time_0
.tv_usec
,
210 target_rtp_time
= (delta
* config
->sample_format
.rate
211 * config
->sample_format
.channels
) / 1000000;
212 /* Overflows at ~6 years uptime with 44100Hz stereo */
214 /* rtp_time is the number of samples we've played. NB that we play
215 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
216 * the value we deduce from time comparison.
218 * Suppose we have 1s track started at t=0, and another track begins to
219 * play at t=2s. Suppose 44100Hz stereo. We send 1s of audio over the
220 * next (about) one second, giving rtp_time=88200. rtp_time stops at this
223 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
224 * set rtp_time=176400 and the player can correctly conclude that it
225 * should leave 1s between the tracks.
227 * It's never right to reduce rtp_time, for that would imply packets with
228 * overlapping timestamp ranges, which does not make sense.
230 target_rtp_time
&= ~(uint64_t)1; /* stereo! */
231 if(target_rtp_time
> rtp_time
) {
232 /* More time has elapsed than we've transmitted samples. That implies
233 * we've been 'sending' silence. */
234 info("advancing rtp_time by %"PRIu64
" samples",
235 target_rtp_time
- rtp_time
);
236 rtp_time
= target_rtp_time
;
237 } else if(target_rtp_time
< rtp_time
) {
238 info("would reverse rtp_time by %"PRIu64
" samples",
239 rtp_time
- target_rtp_time
);
242 header
.vpxcc
= 2 << 6; /* V=2, P=0, X=0, CC=0 */
243 header
.seq
= htons(rtp_seq
++);
244 header
.timestamp
= htonl((uint32_t)rtp_time
);
245 header
.ssrc
= rtp_id
;
246 header
.mpt
= (idled ?
0x80 : 0x00) | 10;
247 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
248 * the sample rate (in a library somewhere so that configuration.c can rule
249 * out invalid rates).
252 if(bytes
> NETWORK_BYTES
- sizeof header
) {
253 bytes
= NETWORK_BYTES
- sizeof header
;
254 /* Always send a whole number of frames */
255 bytes
-= bytes
% bpf
;
257 /* "The RTP clock rate used for generating the RTP timestamp is independent
258 * of the number of channels and the encoding; it equals the number of
259 * sampling periods per second. For N-channel encodings, each sampling
260 * period (say, 1/8000 of a second) generates N samples. (This terminology
261 * is standard, but somewhat confusing, as the total number of samples
262 * generated per second is then the sampling rate times the channel
265 vec
[0].iov_base
= (void *)&header
;
266 vec
[0].iov_len
= sizeof header
;
267 vec
[1].iov_base
= playing
->buffer
+ playing
->start
;
268 vec
[1].iov_len
= bytes
;
270 written_bytes
= writev(bfd
, vec
, 2);
271 } while(written_bytes
< 0 && errno
== EINTR
);
272 if(written_bytes
< 0) {
273 error(errno
, "error transmitting audio data");
275 if(audio_errors
== 10)
276 fatal(0, "too many audio errors");
280 written_bytes
-= sizeof (struct rtp_header
);
281 written_frames
= written_bytes
/ bpf
;
282 /* Advance RTP's notion of the time */
283 rtp_time
+= written_frames
* config
->sample_format
.channels
;
284 return written_frames
;
289 /** @brief Set up poll array for network play */
290 static void network_beforepoll(int *timeoutp
) {
293 uint64_t target_rtp_time
;
294 const int64_t samples_per_second
= config
->sample_format
.rate
295 * config
->sample_format
.channels
;
296 int64_t lead
, ahead_ms
;
298 /* If we're starting then initialize the base time */
300 xgettimeofday(&rtp_time_0
, 0);
301 /* We send audio data whenever we would otherwise get behind */
302 xgettimeofday(&now
, 0);
303 target_us
= tvsub_us(now
, rtp_time_0
);
304 if(target_us
> UINT64_MAX
/ 88200)
305 fatal(0, "rtp_time=%llu rtp_time_0=%ld.%06ld now=%ld.%06ld target_us=%llu (%lld)\n",
307 (long)rtp_time_0
.tv_sec
, (long)rtp_time_0
.tv_usec
,
308 (long)now
.tv_sec
, (long)now
.tv_usec
,
309 target_us
, target_us
);
310 target_rtp_time
= (target_us
* config
->sample_format
.rate
311 * config
->sample_format
.channels
)
313 /* Lead is how far ahead we are */
314 lead
= rtp_time
- target_rtp_time
;
316 /* We're behind or even, so we'll need to write as soon as we can */
317 bfd_slot
= addfd(bfd
, POLLOUT
);
319 /* We've ahead, we can afford to wait a bit even if the IP stack thinks it
320 * can accept more. */
321 ahead_ms
= 1000 * lead
/ samples_per_second
;
322 if(ahead_ms
< *timeoutp
)
323 *timeoutp
= ahead_ms
;
327 /** @brief Process poll() results for network play */
328 static int network_ready(void) {
329 if(fds
[bfd_slot
].revents
& (POLLOUT
| POLLERR
))
335 const struct speaker_backend network_backend
= {