2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2006, 2007 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 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * 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, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 /** @file server/speaker-network.c
21 * @brief Support for @ref BACKEND_NETWORK */
30 #include <sys/socket.h>
37 #include "configuration.h"
44 #include "speaker-protocol.h"
47 /** @brief Network socket
49 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
53 /** @brief RTP timestamp
55 * This counts the number of samples played (NB not the number of frames
58 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
59 * stereo, that only gives about half a day before wrapping, which is not
60 * particularly convenient for certain debugging purposes. Therefore the
61 * timestamp is maintained as a 64-bit integer, giving around six million years
62 * before wrapping, and truncated to 32 bits when transmitting.
64 static uint64_t rtp_time
;
66 /** @brief RTP base timestamp
68 * This is the real time correspoding to an @ref rtp_time of 0. It is used
69 * to recalculate the timestamp after idle periods.
71 static struct timeval rtp_time_0
;
73 /** @brief RTP packet sequence number */
74 static uint16_t rtp_seq
;
76 /** @brief RTP SSRC */
77 static uint32_t rtp_id
;
79 /** @brief Error counter */
80 static int audio_errors
;
82 /** @brief Network backend initialization */
83 static void network_init(void) {
84 struct addrinfo
*res
, *sres
;
85 static const struct addrinfo pref
= {
95 static const struct addrinfo prefbind
= {
105 static const int one
= 1;
106 int sndbuf
, target_sndbuf
= 131072;
108 char *sockname
, *ssockname
;
110 res
= get_address(&config
->broadcast
, &pref
, &sockname
);
112 if(config
->broadcast_from
.n
) {
113 sres
= get_address(&config
->broadcast_from
, &prefbind
, &ssockname
);
117 if((bfd
= socket(res
->ai_family
,
119 res
->ai_protocol
)) < 0)
120 fatal(errno
, "error creating broadcast socket");
121 if(multicast(res
->ai_addr
)) {
123 switch(res
->ai_family
) {
125 const int mttl
= config
->multicast_ttl
;
126 if(setsockopt(bfd
, IPPROTO_IP
, IP_MULTICAST_TTL
, &mttl
, sizeof mttl
) < 0)
127 fatal(errno
, "error setting IP_MULTICAST_TTL on multicast socket");
128 if(setsockopt(bfd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
129 &config
->multicast_loop
, sizeof one
) < 0)
130 fatal(errno
, "error setting IP_MULTICAST_LOOP on multicast socket");
134 const int mttl
= config
->multicast_ttl
;
135 if(setsockopt(bfd
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
,
136 &mttl
, sizeof mttl
) < 0)
137 fatal(errno
, "error setting IPV6_MULTICAST_HOPS on multicast socket");
138 if(setsockopt(bfd
, IPPROTO_IP
, IPV6_MULTICAST_LOOP
,
139 &config
->multicast_loop
, sizeof (int)) < 0)
140 fatal(errno
, "error setting IPV6_MULTICAST_LOOP on multicast socket");
144 fatal(0, "unsupported address family %d", res
->ai_family
);
146 info("multicasting on %s", sockname
);
150 if(getifaddrs(&ifs
) < 0)
151 fatal(errno
, "error calling getifaddrs");
153 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
154 * still a null pointer. It turns out that there's a subsequent entry
155 * for he same interface which _does_ have ifa_broadaddr though... */
156 if((ifs
->ifa_flags
& IFF_BROADCAST
)
157 && ifs
->ifa_broadaddr
158 && sockaddr_equal(ifs
->ifa_broadaddr
, res
->ai_addr
))
163 if(setsockopt(bfd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof one
) < 0)
164 fatal(errno
, "error setting SO_BROADCAST on broadcast socket");
165 info("broadcasting on %s (%s)", sockname
, ifs
->ifa_name
);
167 info("unicasting on %s", sockname
);
170 if(getsockopt(bfd
, SOL_SOCKET
, SO_SNDBUF
,
172 fatal(errno
, "error getting SO_SNDBUF");
173 if(target_sndbuf
> sndbuf
) {
174 if(setsockopt(bfd
, SOL_SOCKET
, SO_SNDBUF
,
175 &target_sndbuf
, sizeof target_sndbuf
) < 0)
176 error(errno
, "error setting SO_SNDBUF to %d", target_sndbuf
);
178 info("changed socket send buffer size from %d to %d",
179 sndbuf
, target_sndbuf
);
181 info("default socket send buffer is %d",
183 /* We might well want to set additional broadcast- or multicast-related
185 if(sres
&& bind(bfd
, sres
->ai_addr
, sres
->ai_addrlen
) < 0)
186 fatal(errno
, "error binding broadcast socket to %s", ssockname
);
187 if(connect(bfd
, res
->ai_addr
, res
->ai_addrlen
) < 0)
188 fatal(errno
, "error connecting broadcast socket to %s", sockname
);
190 gcry_randomize(&rtp_id
, sizeof rtp_id
, GCRY_STRONG_RANDOM
);
193 /** @brief Play over the network */
194 static size_t network_play(size_t frames
) {
195 struct rtp_header header
;
197 size_t bytes
= frames
* bpf
, written_frames
;
199 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
200 * AVT profile (RFC3551). */
203 /* There may have been a gap. Fix up the RTP time accordingly. */
206 uint64_t target_rtp_time
;
208 /* Find the current time */
209 xgettimeofday(&now
, 0);
210 /* Find the number of microseconds elapsed since rtp_time=0 */
211 delta
= tvsub_us(now
, rtp_time_0
);
212 assert(delta
<= UINT64_MAX
/ 88200);
213 target_rtp_time
= (delta
* config
->sample_format
.rate
214 * config
->sample_format
.channels
) / 1000000;
215 /* Overflows at ~6 years uptime with 44100Hz stereo */
217 /* rtp_time is the number of samples we've played. NB that we play
218 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
219 * the value we deduce from time comparison.
221 * Suppose we have 1s track started at t=0, and another track begins to
222 * play at t=2s. Suppose RTP_AHEAD_MS=1000 and 44100Hz stereo. In that
223 * case we'll send 1s of audio as fast as we can, giving rtp_time=88200.
224 * rtp_time stops at this point.
226 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
227 * set rtp_time=176400 and the player can correctly conclude that it
228 * should leave 1s between the tracks.
230 * Suppose instead that the second track arrives at t=0.5s, and that
231 * we've managed to transmit the whole of the first track already. We'll
232 * have target_rtp_time=44100.
234 * The desired behaviour is to play the second track back to back with
235 * first. In this case therefore we do not modify rtp_time.
237 * Is it ever right to reduce rtp_time? No; for that would imply
238 * transmitting packets with overlapping timestamp ranges, which does not
241 target_rtp_time
&= ~(uint64_t)1; /* stereo! */
242 if(target_rtp_time
> rtp_time
) {
243 /* More time has elapsed than we've transmitted samples. That implies
244 * we've been 'sending' silence. */
245 info("advancing rtp_time by %"PRIu64
" samples",
246 target_rtp_time
- rtp_time
);
247 rtp_time
= target_rtp_time
;
248 } else if(target_rtp_time
< rtp_time
) {
249 const int64_t samples_ahead
= ((uint64_t)RTP_AHEAD_MS
250 * config
->sample_format
.rate
251 * config
->sample_format
.channels
254 if(target_rtp_time
+ samples_ahead
< rtp_time
) {
255 info("reversing rtp_time by %"PRIu64
" samples",
256 rtp_time
- target_rtp_time
);
260 header
.vpxcc
= 2 << 6; /* V=2, P=0, X=0, CC=0 */
261 header
.seq
= htons(rtp_seq
++);
262 header
.timestamp
= htonl((uint32_t)rtp_time
);
263 header
.ssrc
= rtp_id
;
264 header
.mpt
= (idled ?
0x80 : 0x00) | 10;
265 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
266 * the sample rate (in a library somewhere so that configuration.c can rule
267 * out invalid rates).
270 if(bytes
> NETWORK_BYTES
- sizeof header
) {
271 bytes
= NETWORK_BYTES
- sizeof header
;
272 /* Always send a whole number of frames */
273 bytes
-= bytes
% bpf
;
275 /* "The RTP clock rate used for generating the RTP timestamp is independent
276 * of the number of channels and the encoding; it equals the number of
277 * sampling periods per second. For N-channel encodings, each sampling
278 * period (say, 1/8000 of a second) generates N samples. (This terminology
279 * is standard, but somewhat confusing, as the total number of samples
280 * generated per second is then the sampling rate times the channel
283 vec
[0].iov_base
= (void *)&header
;
284 vec
[0].iov_len
= sizeof header
;
285 vec
[1].iov_base
= playing
->buffer
+ playing
->start
;
286 vec
[1].iov_len
= bytes
;
288 written_bytes
= writev(bfd
, vec
, 2);
289 } while(written_bytes
< 0 && errno
== EINTR
);
290 if(written_bytes
< 0) {
291 error(errno
, "error transmitting audio data");
293 if(audio_errors
== 10)
294 fatal(0, "too many audio errors");
298 written_bytes
-= sizeof (struct rtp_header
);
299 written_frames
= written_bytes
/ bpf
;
300 /* Advance RTP's notion of the time */
301 rtp_time
+= written_frames
* config
->sample_format
.channels
;
302 return written_frames
;
307 /** @brief Set up poll array for network play */
308 static void network_beforepoll(int *timeoutp
) {
311 uint64_t target_rtp_time
;
312 const int64_t samples_per_second
= config
->sample_format
.rate
313 * config
->sample_format
.channels
;
314 const int64_t samples_ahead
= ((uint64_t)RTP_AHEAD_MS
317 int64_t lead
, ahead_ms
;
319 /* If we're starting then initialize the base time */
321 xgettimeofday(&rtp_time_0
, 0);
322 /* We send audio data whenever we get RTP_AHEAD seconds or more
324 xgettimeofday(&now
, 0);
325 target_us
= tvsub_us(now
, rtp_time_0
);
326 assert(target_us
<= UINT64_MAX
/ 88200);
327 target_rtp_time
= (target_us
* config
->sample_format
.rate
328 * config
->sample_format
.channels
)
330 lead
= rtp_time
- target_rtp_time
;
331 if(lead
< samples_ahead
)
332 /* We've not reached the desired lead, write as fast as we can */
333 bfd_slot
= addfd(bfd
, POLLOUT
);
335 /* We've reached the desired lead, we can afford to wait a bit even if the
336 * IP stack thinks it can accept more. */
337 ahead_ms
= 1000 * (lead
- samples_ahead
) / samples_per_second
;
338 if(ahead_ms
< *timeoutp
)
339 *timeoutp
= ahead_ms
;
343 /** @brief Process poll() results for network play */
344 static int network_ready(void) {
345 if(fds
[bfd_slot
].revents
& (POLLOUT
| POLLERR
))
351 const struct speaker_backend network_backend
= {