chiark / gitweb /
Doxygen file headers for most files
[disorder] / server / speaker-network.c
CommitLineData
1c3f1e73 1/*
2 * This file is part of DisOrder
5aff007d 3 * Copyright (C) 2005-2008 Richard Kettlewell
1c3f1e73 4 *
e7eb3a27 5 * This program is free software: you can redistribute it and/or modify
1c3f1e73 6 * it under the terms of the GNU General Public License as published by
e7eb3a27 7 * the Free Software Foundation, either version 3 of the License, or
1c3f1e73 8 * (at your option) any later version.
9 *
e7eb3a27
RK
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.
14 *
1c3f1e73 15 * You should have received a copy of the GNU General Public License
e7eb3a27 16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
1c3f1e73 17 */
18/** @file server/speaker-network.c
19 * @brief Support for @ref BACKEND_NETWORK */
20
05b75f8d 21#include "common.h"
1c3f1e73 22
23#include <unistd.h>
24#include <poll.h>
25#include <netdb.h>
26#include <gcrypt.h>
27#include <sys/socket.h>
28#include <sys/uio.h>
81b1bf12 29#include <net/if.h>
db2c19dc 30#include <ifaddrs.h>
6d2d327c 31#include <errno.h>
edbd470f 32#include <netinet/in.h>
1c3f1e73 33
34#include "configuration.h"
35#include "syscalls.h"
36#include "log.h"
37#include "addr.h"
38#include "timeval.h"
39#include "rtp.h"
81b1bf12 40#include "ifreq.h"
1c3f1e73 41#include "speaker-protocol.h"
42#include "speaker.h"
43
44/** @brief Network socket
45 *
46 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
47 */
48static int bfd = -1;
49
50/** @brief RTP timestamp
51 *
52 * This counts the number of samples played (NB not the number of frames
53 * played).
54 *
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.
60 */
61static uint64_t rtp_time;
62
63/** @brief RTP base timestamp
64 *
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.
67 */
68static struct timeval rtp_time_0;
69
70/** @brief RTP packet sequence number */
71static uint16_t rtp_seq;
72
73/** @brief RTP SSRC */
74static uint32_t rtp_id;
75
76/** @brief Error counter */
77static int audio_errors;
78
79/** @brief Network backend initialization */
80static void network_init(void) {
81 struct addrinfo *res, *sres;
82 static const struct addrinfo pref = {
66613034
RK
83 .ai_flags = 0,
84 .ai_family = PF_INET,
85 .ai_socktype = SOCK_DGRAM,
86 .ai_protocol = IPPROTO_UDP,
1c3f1e73 87 };
88 static const struct addrinfo prefbind = {
66613034
RK
89 .ai_flags = AI_PASSIVE,
90 .ai_family = PF_INET,
91 .ai_socktype = SOCK_DGRAM,
92 .ai_protocol = IPPROTO_UDP,
1c3f1e73 93 };
94 static const int one = 1;
db2c19dc 95 int sndbuf, target_sndbuf = 131072;
1c3f1e73 96 socklen_t len;
97 char *sockname, *ssockname;
98
99 res = get_address(&config->broadcast, &pref, &sockname);
100 if(!res) exit(-1);
101 if(config->broadcast_from.n) {
102 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
103 if(!sres) exit(-1);
104 } else
105 sres = 0;
106 if((bfd = socket(res->ai_family,
107 res->ai_socktype,
108 res->ai_protocol)) < 0)
109 fatal(errno, "error creating broadcast socket");
6fba990c 110 if(multicast(res->ai_addr)) {
23205f9c
RK
111 /* Multicasting */
112 switch(res->ai_family) {
113 case PF_INET: {
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");
61941295
RK
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");
23205f9c
RK
120 break;
121 }
122 case PF_INET6: {
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");
61941295
RK
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");
23205f9c
RK
130 break;
131 }
132 default:
133 fatal(0, "unsupported address family %d", res->ai_family);
134 }
81b1bf12 135 info("multicasting on %s", sockname);
23205f9c 136 } else {
db2c19dc 137 struct ifaddrs *ifs;
81b1bf12 138
db2c19dc
RK
139 if(getifaddrs(&ifs) < 0)
140 fatal(errno, "error calling getifaddrs");
141 while(ifs) {
3aa6f359
RK
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... */
db2c19dc 145 if((ifs->ifa_flags & IFF_BROADCAST)
3aa6f359 146 && ifs->ifa_broadaddr
db2c19dc 147 && sockaddr_equal(ifs->ifa_broadaddr, res->ai_addr))
81b1bf12 148 break;
db2c19dc 149 ifs = ifs->ifa_next;
81b1bf12 150 }
db2c19dc 151 if(ifs) {
81b1bf12
RK
152 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
153 fatal(errno, "error setting SO_BROADCAST on broadcast socket");
db2c19dc 154 info("broadcasting on %s (%s)", sockname, ifs->ifa_name);
81b1bf12
RK
155 } else
156 info("unicasting on %s", sockname);
23205f9c 157 }
1c3f1e73 158 len = sizeof sndbuf;
159 if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
160 &sndbuf, &len) < 0)
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);
166 else
167 info("changed socket send buffer size from %d to %d",
168 sndbuf, target_sndbuf);
169 } else
170 info("default socket send buffer is %d",
171 sndbuf);
172 /* We might well want to set additional broadcast- or multicast-related
173 * options here */
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);
178 /* Select an SSRC */
179 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
1c3f1e73 180}
181
182/** @brief Play over the network */
183static size_t network_play(size_t frames) {
184 struct rtp_header header;
185 struct iovec vec[2];
6d2d327c 186 size_t bytes = frames * bpf, written_frames;
1c3f1e73 187 int written_bytes;
188 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
189 * AVT profile (RFC3551). */
190
23741390
RK
191 /* If we're starting then initialize the base time */
192 if(!rtp_time)
193 xgettimeofday(&rtp_time_0, 0);
1c3f1e73 194 if(idled) {
195 /* There may have been a gap. Fix up the RTP time accordingly. */
196 struct timeval now;
197 uint64_t delta;
198 uint64_t target_rtp_time;
199
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);
23741390
RK
204 if(delta > UINT64_MAX / 88200)
205 fatal(0, "rtp_time=%llu now=%ld.%06ld rtp_time_0=%ld.%06ld delta=%llu (%lld)",
206 rtp_time,
207 (long)now.tv_sec, (long)now.tv_usec,
208 (long)rtp_time_0.tv_sec, (long)rtp_time_0.tv_usec,
209 delta, delta);
6d2d327c
RK
210 target_rtp_time = (delta * config->sample_format.rate
211 * config->sample_format.channels) / 1000000;
1c3f1e73 212 /* Overflows at ~6 years uptime with 44100Hz stereo */
213
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.
217 *
218 * Suppose we have 1s track started at t=0, and another track begins to
24d6fd25
RK
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
221 * point.
1c3f1e73 222 *
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.
226 *
24d6fd25
RK
227 * It's never right to reduce rtp_time, for that would imply packets with
228 * overlapping timestamp ranges, which does not make sense.
1c3f1e73 229 */
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) {
24d6fd25
RK
238 info("would reverse rtp_time by %"PRIu64" samples",
239 rtp_time - target_rtp_time);
1c3f1e73 240 }
241 }
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).
250 */
251 idled = 0;
252 if(bytes > NETWORK_BYTES - sizeof header) {
253 bytes = NETWORK_BYTES - sizeof header;
254 /* Always send a whole number of frames */
6d2d327c 255 bytes -= bytes % bpf;
1c3f1e73 256 }
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
263 * count.)"
264 */
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;
269 do {
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");
274 ++audio_errors;
275 if(audio_errors == 10)
276 fatal(0, "too many audio errors");
277 return 0;
278 } else
279 audio_errors /= 2;
280 written_bytes -= sizeof (struct rtp_header);
6d2d327c 281 written_frames = written_bytes / bpf;
1c3f1e73 282 /* Advance RTP's notion of the time */
6d2d327c 283 rtp_time += written_frames * config->sample_format.channels;
1c3f1e73 284 return written_frames;
285}
286
287static int bfd_slot;
288
289/** @brief Set up poll array for network play */
e84fb5f0 290static void network_beforepoll(int *timeoutp) {
1c3f1e73 291 struct timeval now;
292 uint64_t target_us;
293 uint64_t target_rtp_time;
e84fb5f0
RK
294 const int64_t samples_per_second = config->sample_format.rate
295 * config->sample_format.channels;
e84fb5f0 296 int64_t lead, ahead_ms;
1c3f1e73 297
298 /* If we're starting then initialize the base time */
299 if(!rtp_time)
300 xgettimeofday(&rtp_time_0, 0);
24d6fd25 301 /* We send audio data whenever we would otherwise get behind */
1c3f1e73 302 xgettimeofday(&now, 0);
303 target_us = tvsub_us(now, rtp_time_0);
23741390
RK
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",
306 rtp_time,
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);
1c3f1e73 310 target_rtp_time = (target_us * config->sample_format.rate
311 * config->sample_format.channels)
312 / 1000000;
24d6fd25 313 /* Lead is how far ahead we are */
e84fb5f0 314 lead = rtp_time - target_rtp_time;
24d6fd25
RK
315 if(lead <= 0)
316 /* We're behind or even, so we'll need to write as soon as we can */
1c3f1e73 317 bfd_slot = addfd(bfd, POLLOUT);
e84fb5f0 318 else {
24d6fd25
RK
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;
e84fb5f0
RK
322 if(ahead_ms < *timeoutp)
323 *timeoutp = ahead_ms;
324 }
1c3f1e73 325}
326
327/** @brief Process poll() results for network play */
328static int network_ready(void) {
329 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
330 return 1;
331 else
332 return 0;
333}
334
335const struct speaker_backend network_backend = {
336 BACKEND_NETWORK,
6d2d327c 337 0,
1c3f1e73 338 network_init,
339 0, /* activate */
340 network_play,
341 0, /* deactivate */
342 network_beforepoll,
343 network_ready
344};
345
346/*
347Local Variables:
348c-basic-offset:2
349comment-column:40
350fill-column:79
351indent-tabs-mode:nil
352End:
353*/