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>
34 #include "configuration.h"
40 #include "speaker-protocol.h"
43 /** @brief Network socket
45 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
49 /** @brief RTP timestamp
51 * This counts the number of samples played (NB not the number of frames
54 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
55 * stereo, that only gives about half a day before wrapping, which is not
56 * particularly convenient for certain debugging purposes. Therefore the
57 * timestamp is maintained as a 64-bit integer, giving around six million years
58 * before wrapping, and truncated to 32 bits when transmitting.
60 static uint64_t rtp_time;
62 /** @brief RTP base timestamp
64 * This is the real time correspoding to an @ref rtp_time of 0. It is used
65 * to recalculate the timestamp after idle periods.
67 static struct timeval rtp_time_0;
69 /** @brief RTP packet sequence number */
70 static uint16_t rtp_seq;
72 /** @brief RTP SSRC */
73 static uint32_t rtp_id;
75 /** @brief Error counter */
76 static int audio_errors;
78 /** @brief Network backend initialization */
79 static void network_init(void) {
80 struct addrinfo *res, *sres;
81 static const struct addrinfo pref = {
91 static const struct addrinfo prefbind = {
101 static const int one = 1;
102 int sndbuf, target_sndbuf = 131072;
104 char *sockname, *ssockname;
106 /* Override sample format */
107 config->sample_format.rate = 44100;
108 config->sample_format.channels = 2;
109 config->sample_format.bits = 16;
110 config->sample_format.byte_format = AO_FMT_BIG;
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((res->ai_family == PF_INET
124 ntohl(((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr)
126 || (res->ai_family == PF_INET6
127 && IN6_IS_ADDR_MULTICAST(
128 &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr
131 switch(res->ai_family) {
133 const int mttl = config->multicast_ttl;
134 if(setsockopt(bfd, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, sizeof mttl) < 0)
135 fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
139 const int mttl = config->multicast_ttl;
140 if(setsockopt(bfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
141 &mttl, sizeof mttl) < 0)
142 fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
146 fatal(0, "unsupported address family %d", res->ai_family);
149 /* Presumably just broadcasting */
150 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
151 fatal(errno, "error setting SO_BROADCAST on broadcast socket");
154 if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
156 fatal(errno, "error getting SO_SNDBUF");
157 if(target_sndbuf > sndbuf) {
158 if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
159 &target_sndbuf, sizeof target_sndbuf) < 0)
160 error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
162 info("changed socket send buffer size from %d to %d",
163 sndbuf, target_sndbuf);
165 info("default socket send buffer is %d",
167 /* We might well want to set additional broadcast- or multicast-related
169 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
170 fatal(errno, "error binding broadcast socket to %s", ssockname);
171 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
172 fatal(errno, "error connecting broadcast socket to %s", sockname);
174 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
175 info("selected network backend, sending to %s", sockname);
178 /** @brief Play over the network */
179 static size_t network_play(size_t frames) {
180 struct rtp_header header;
182 size_t bytes = frames * device_bpf, written_frames;
184 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
185 * AVT profile (RFC3551). */
188 /* There may have been a gap. Fix up the RTP time accordingly. */
191 uint64_t target_rtp_time;
193 /* Find the current time */
194 xgettimeofday(&now, 0);
195 /* Find the number of microseconds elapsed since rtp_time=0 */
196 delta = tvsub_us(now, rtp_time_0);
197 assert(delta <= UINT64_MAX / 88200);
198 target_rtp_time = (delta * playing->format.rate
199 * playing->format.channels) / 1000000;
200 /* Overflows at ~6 years uptime with 44100Hz stereo */
202 /* rtp_time is the number of samples we've played. NB that we play
203 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
204 * the value we deduce from time comparison.
206 * Suppose we have 1s track started at t=0, and another track begins to
207 * play at t=2s. Suppose RTP_AHEAD_MS=1000 and 44100Hz stereo. In that
208 * case we'll send 1s of audio as fast as we can, giving rtp_time=88200.
209 * rtp_time stops at this point.
211 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
212 * set rtp_time=176400 and the player can correctly conclude that it
213 * should leave 1s between the tracks.
215 * Suppose instead that the second track arrives at t=0.5s, and that
216 * we've managed to transmit the whole of the first track already. We'll
217 * have target_rtp_time=44100.
219 * The desired behaviour is to play the second track back to back with
220 * first. In this case therefore we do not modify rtp_time.
222 * Is it ever right to reduce rtp_time? No; for that would imply
223 * transmitting packets with overlapping timestamp ranges, which does not
226 target_rtp_time &= ~(uint64_t)1; /* stereo! */
227 if(target_rtp_time > rtp_time) {
228 /* More time has elapsed than we've transmitted samples. That implies
229 * we've been 'sending' silence. */
230 info("advancing rtp_time by %"PRIu64" samples",
231 target_rtp_time - rtp_time);
232 rtp_time = target_rtp_time;
233 } else if(target_rtp_time < rtp_time) {
234 const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
235 * config->sample_format.rate
236 * config->sample_format.channels
239 if(target_rtp_time + samples_ahead < rtp_time) {
240 info("reversing rtp_time by %"PRIu64" samples",
241 rtp_time - target_rtp_time);
245 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
246 header.seq = htons(rtp_seq++);
247 header.timestamp = htonl((uint32_t)rtp_time);
248 header.ssrc = rtp_id;
249 header.mpt = (idled ? 0x80 : 0x00) | 10;
250 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
251 * the sample rate (in a library somewhere so that configuration.c can rule
252 * out invalid rates).
255 if(bytes > NETWORK_BYTES - sizeof header) {
256 bytes = NETWORK_BYTES - sizeof header;
257 /* Always send a whole number of frames */
258 bytes -= bytes % device_bpf;
260 /* "The RTP clock rate used for generating the RTP timestamp is independent
261 * of the number of channels and the encoding; it equals the number of
262 * sampling periods per second. For N-channel encodings, each sampling
263 * period (say, 1/8000 of a second) generates N samples. (This terminology
264 * is standard, but somewhat confusing, as the total number of samples
265 * generated per second is then the sampling rate times the channel
268 vec[0].iov_base = (void *)&header;
269 vec[0].iov_len = sizeof header;
270 vec[1].iov_base = playing->buffer + playing->start;
271 vec[1].iov_len = bytes;
273 written_bytes = writev(bfd, vec, 2);
274 } while(written_bytes < 0 && errno == EINTR);
275 if(written_bytes < 0) {
276 error(errno, "error transmitting audio data");
278 if(audio_errors == 10)
279 fatal(0, "too many audio errors");
283 written_bytes -= sizeof (struct rtp_header);
284 written_frames = written_bytes / device_bpf;
285 /* Advance RTP's notion of the time */
286 rtp_time += written_frames * playing->format.channels;
287 return written_frames;
292 /** @brief Set up poll array for network play */
293 static void network_beforepoll(void) {
296 uint64_t target_rtp_time;
297 const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
298 * config->sample_format.rate
299 * config->sample_format.channels
302 /* If we're starting then initialize the base time */
304 xgettimeofday(&rtp_time_0, 0);
305 /* We send audio data whenever we get RTP_AHEAD seconds or more
307 xgettimeofday(&now, 0);
308 target_us = tvsub_us(now, rtp_time_0);
309 assert(target_us <= UINT64_MAX / 88200);
310 target_rtp_time = (target_us * config->sample_format.rate
311 * config->sample_format.channels)
313 if((int64_t)(rtp_time - target_rtp_time) < samples_ahead)
314 bfd_slot = addfd(bfd, POLLOUT);
317 /** @brief Process poll() results for network play */
318 static int network_ready(void) {
319 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
325 const struct speaker_backend network_backend = {