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>
36 #include <netinet/in.h>
38 #include "configuration.h"
45 #include "speaker-protocol.h"
48 /** @brief Network socket
50 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
54 /** @brief RTP timestamp
56 * This counts the number of samples played (NB not the number of frames
59 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
60 * stereo, that only gives about half a day before wrapping, which is not
61 * particularly convenient for certain debugging purposes. Therefore the
62 * timestamp is maintained as a 64-bit integer, giving around six million years
63 * before wrapping, and truncated to 32 bits when transmitting.
65 static uint64_t rtp_time;
67 /** @brief RTP base timestamp
69 * This is the real time correspoding to an @ref rtp_time of 0. It is used
70 * to recalculate the timestamp after idle periods.
72 static struct timeval rtp_time_0;
74 /** @brief RTP packet sequence number */
75 static uint16_t rtp_seq;
77 /** @brief RTP SSRC */
78 static uint32_t rtp_id;
80 /** @brief Error counter */
81 static int audio_errors;
83 /** @brief Network backend initialization */
84 static void network_init(void) {
85 struct addrinfo *res, *sres;
86 static const struct addrinfo pref = {
96 static const struct addrinfo prefbind = {
106 static const int one = 1;
107 int sndbuf, target_sndbuf = 131072;
109 char *sockname, *ssockname;
111 res = get_address(&config->broadcast, &pref, &sockname);
113 if(config->broadcast_from.n) {
114 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
118 if((bfd = socket(res->ai_family,
120 res->ai_protocol)) < 0)
121 fatal(errno, "error creating broadcast socket");
122 if(multicast(res->ai_addr)) {
124 switch(res->ai_family) {
126 const int mttl = config->multicast_ttl;
127 if(setsockopt(bfd, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, sizeof mttl) < 0)
128 fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
129 if(setsockopt(bfd, IPPROTO_IP, IP_MULTICAST_LOOP,
130 &config->multicast_loop, sizeof one) < 0)
131 fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
135 const int mttl = config->multicast_ttl;
136 if(setsockopt(bfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
137 &mttl, sizeof mttl) < 0)
138 fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
139 if(setsockopt(bfd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
140 &config->multicast_loop, sizeof (int)) < 0)
141 fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
145 fatal(0, "unsupported address family %d", res->ai_family);
147 info("multicasting on %s", sockname);
151 if(getifaddrs(&ifs) < 0)
152 fatal(errno, "error calling getifaddrs");
154 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
155 * still a null pointer. It turns out that there's a subsequent entry
156 * for he same interface which _does_ have ifa_broadaddr though... */
157 if((ifs->ifa_flags & IFF_BROADCAST)
158 && ifs->ifa_broadaddr
159 && sockaddr_equal(ifs->ifa_broadaddr, res->ai_addr))
164 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
165 fatal(errno, "error setting SO_BROADCAST on broadcast socket");
166 info("broadcasting on %s (%s)", sockname, ifs->ifa_name);
168 info("unicasting on %s", sockname);
171 if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
173 fatal(errno, "error getting SO_SNDBUF");
174 if(target_sndbuf > sndbuf) {
175 if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
176 &target_sndbuf, sizeof target_sndbuf) < 0)
177 error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
179 info("changed socket send buffer size from %d to %d",
180 sndbuf, target_sndbuf);
182 info("default socket send buffer is %d",
184 /* We might well want to set additional broadcast- or multicast-related
186 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
187 fatal(errno, "error binding broadcast socket to %s", ssockname);
188 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
189 fatal(errno, "error connecting broadcast socket to %s", sockname);
191 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
194 /** @brief Play over the network */
195 static size_t network_play(size_t frames) {
196 struct rtp_header header;
198 size_t bytes = frames * bpf, written_frames;
200 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
201 * AVT profile (RFC3551). */
204 /* There may have been a gap. Fix up the RTP time accordingly. */
207 uint64_t target_rtp_time;
209 /* Find the current time */
210 xgettimeofday(&now, 0);
211 /* Find the number of microseconds elapsed since rtp_time=0 */
212 delta = tvsub_us(now, rtp_time_0);
213 assert(delta <= UINT64_MAX / 88200);
214 target_rtp_time = (delta * config->sample_format.rate
215 * config->sample_format.channels) / 1000000;
216 /* Overflows at ~6 years uptime with 44100Hz stereo */
218 /* rtp_time is the number of samples we've played. NB that we play
219 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
220 * the value we deduce from time comparison.
222 * Suppose we have 1s track started at t=0, and another track begins to
223 * play at t=2s. Suppose 44100Hz stereo. We send 1s of audio over the
224 * next (about) one second, giving rtp_time=88200. rtp_time stops at this
227 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
228 * set rtp_time=176400 and the player can correctly conclude that it
229 * should leave 1s between the tracks.
231 * It's never right to reduce rtp_time, for that would imply packets with
232 * overlapping timestamp ranges, which does not make sense.
234 target_rtp_time &= ~(uint64_t)1; /* stereo! */
235 if(target_rtp_time > rtp_time) {
236 /* More time has elapsed than we've transmitted samples. That implies
237 * we've been 'sending' silence. */
238 info("advancing rtp_time by %"PRIu64" samples",
239 target_rtp_time - rtp_time);
240 rtp_time = target_rtp_time;
241 } else if(target_rtp_time < rtp_time) {
242 info("would reverse rtp_time by %"PRIu64" samples",
243 rtp_time - target_rtp_time);
246 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
247 header.seq = htons(rtp_seq++);
248 header.timestamp = htonl((uint32_t)rtp_time);
249 header.ssrc = rtp_id;
250 header.mpt = (idled ? 0x80 : 0x00) | 10;
251 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
252 * the sample rate (in a library somewhere so that configuration.c can rule
253 * out invalid rates).
256 if(bytes > NETWORK_BYTES - sizeof header) {
257 bytes = NETWORK_BYTES - sizeof header;
258 /* Always send a whole number of frames */
259 bytes -= bytes % bpf;
261 /* "The RTP clock rate used for generating the RTP timestamp is independent
262 * of the number of channels and the encoding; it equals the number of
263 * sampling periods per second. For N-channel encodings, each sampling
264 * period (say, 1/8000 of a second) generates N samples. (This terminology
265 * is standard, but somewhat confusing, as the total number of samples
266 * generated per second is then the sampling rate times the channel
269 vec[0].iov_base = (void *)&header;
270 vec[0].iov_len = sizeof header;
271 vec[1].iov_base = playing->buffer + playing->start;
272 vec[1].iov_len = bytes;
274 written_bytes = writev(bfd, vec, 2);
275 } while(written_bytes < 0 && errno == EINTR);
276 if(written_bytes < 0) {
277 error(errno, "error transmitting audio data");
279 if(audio_errors == 10)
280 fatal(0, "too many audio errors");
284 written_bytes -= sizeof (struct rtp_header);
285 written_frames = written_bytes / bpf;
286 /* Advance RTP's notion of the time */
287 rtp_time += written_frames * config->sample_format.channels;
288 return written_frames;
293 /** @brief Set up poll array for network play */
294 static void network_beforepoll(int *timeoutp) {
297 uint64_t target_rtp_time;
298 const int64_t samples_per_second = config->sample_format.rate
299 * config->sample_format.channels;
300 int64_t lead, ahead_ms;
302 /* If we're starting then initialize the base time */
304 xgettimeofday(&rtp_time_0, 0);
305 /* We send audio data whenever we would otherwise get behind */
306 xgettimeofday(&now, 0);
307 target_us = tvsub_us(now, rtp_time_0);
308 assert(target_us <= UINT64_MAX / 88200);
309 target_rtp_time = (target_us * config->sample_format.rate
310 * config->sample_format.channels)
312 /* Lead is how far ahead we are */
313 lead = rtp_time - target_rtp_time;
315 /* We're behind or even, so we'll need to write as soon as we can */
316 bfd_slot = addfd(bfd, POLLOUT);
318 /* We've ahead, we can afford to wait a bit even if the IP stack thinks it
319 * can accept more. */
320 ahead_ms = 1000 * lead / samples_per_second;
321 if(ahead_ms < *timeoutp)
322 *timeoutp = ahead_ms;
326 /** @brief Process poll() results for network play */
327 static int network_ready(void) {
328 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
334 const struct speaker_backend network_backend = {