chiark / gitweb /
Mildly more vigorous uninstall rules
[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 *
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.
9 *
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.
14 *
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
18 * USA
19 */
20/** @file server/speaker-network.c
21 * @brief Support for @ref BACKEND_NETWORK */
22
05b75f8d 23#include "common.h"
1c3f1e73 24
25#include <unistd.h>
26#include <poll.h>
27#include <netdb.h>
28#include <gcrypt.h>
29#include <sys/socket.h>
30#include <sys/uio.h>
81b1bf12 31#include <net/if.h>
db2c19dc 32#include <ifaddrs.h>
6d2d327c 33#include <errno.h>
edbd470f 34#include <netinet/in.h>
1c3f1e73 35
36#include "configuration.h"
37#include "syscalls.h"
38#include "log.h"
39#include "addr.h"
40#include "timeval.h"
41#include "rtp.h"
81b1bf12 42#include "ifreq.h"
1c3f1e73 43#include "speaker-protocol.h"
44#include "speaker.h"
45
46/** @brief Network socket
47 *
48 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
49 */
50static int bfd = -1;
51
52/** @brief RTP timestamp
53 *
54 * This counts the number of samples played (NB not the number of frames
55 * played).
56 *
57 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
58 * stereo, that only gives about half a day before wrapping, which is not
59 * particularly convenient for certain debugging purposes. Therefore the
60 * timestamp is maintained as a 64-bit integer, giving around six million years
61 * before wrapping, and truncated to 32 bits when transmitting.
62 */
63static uint64_t rtp_time;
64
65/** @brief RTP base timestamp
66 *
67 * This is the real time correspoding to an @ref rtp_time of 0. It is used
68 * to recalculate the timestamp after idle periods.
69 */
70static struct timeval rtp_time_0;
71
72/** @brief RTP packet sequence number */
73static uint16_t rtp_seq;
74
75/** @brief RTP SSRC */
76static uint32_t rtp_id;
77
78/** @brief Error counter */
79static int audio_errors;
80
81/** @brief Network backend initialization */
82static void network_init(void) {
83 struct addrinfo *res, *sres;
84 static const struct addrinfo pref = {
66613034
RK
85 .ai_flags = 0,
86 .ai_family = PF_INET,
87 .ai_socktype = SOCK_DGRAM,
88 .ai_protocol = IPPROTO_UDP,
1c3f1e73 89 };
90 static const struct addrinfo prefbind = {
66613034
RK
91 .ai_flags = AI_PASSIVE,
92 .ai_family = PF_INET,
93 .ai_socktype = SOCK_DGRAM,
94 .ai_protocol = IPPROTO_UDP,
1c3f1e73 95 };
96 static const int one = 1;
db2c19dc 97 int sndbuf, target_sndbuf = 131072;
1c3f1e73 98 socklen_t len;
99 char *sockname, *ssockname;
100
101 res = get_address(&config->broadcast, &pref, &sockname);
102 if(!res) exit(-1);
103 if(config->broadcast_from.n) {
104 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
105 if(!sres) exit(-1);
106 } else
107 sres = 0;
108 if((bfd = socket(res->ai_family,
109 res->ai_socktype,
110 res->ai_protocol)) < 0)
111 fatal(errno, "error creating broadcast socket");
6fba990c 112 if(multicast(res->ai_addr)) {
23205f9c
RK
113 /* Multicasting */
114 switch(res->ai_family) {
115 case PF_INET: {
116 const int mttl = config->multicast_ttl;
117 if(setsockopt(bfd, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, sizeof mttl) < 0)
118 fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
61941295
RK
119 if(setsockopt(bfd, IPPROTO_IP, IP_MULTICAST_LOOP,
120 &config->multicast_loop, sizeof one) < 0)
121 fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
23205f9c
RK
122 break;
123 }
124 case PF_INET6: {
125 const int mttl = config->multicast_ttl;
126 if(setsockopt(bfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
127 &mttl, sizeof mttl) < 0)
128 fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
61941295
RK
129 if(setsockopt(bfd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
130 &config->multicast_loop, sizeof (int)) < 0)
131 fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
23205f9c
RK
132 break;
133 }
134 default:
135 fatal(0, "unsupported address family %d", res->ai_family);
136 }
81b1bf12 137 info("multicasting on %s", sockname);
23205f9c 138 } else {
db2c19dc 139 struct ifaddrs *ifs;
81b1bf12 140
db2c19dc
RK
141 if(getifaddrs(&ifs) < 0)
142 fatal(errno, "error calling getifaddrs");
143 while(ifs) {
3aa6f359
RK
144 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
145 * still a null pointer. It turns out that there's a subsequent entry
146 * for he same interface which _does_ have ifa_broadaddr though... */
db2c19dc 147 if((ifs->ifa_flags & IFF_BROADCAST)
3aa6f359 148 && ifs->ifa_broadaddr
db2c19dc 149 && sockaddr_equal(ifs->ifa_broadaddr, res->ai_addr))
81b1bf12 150 break;
db2c19dc 151 ifs = ifs->ifa_next;
81b1bf12 152 }
db2c19dc 153 if(ifs) {
81b1bf12
RK
154 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
155 fatal(errno, "error setting SO_BROADCAST on broadcast socket");
db2c19dc 156 info("broadcasting on %s (%s)", sockname, ifs->ifa_name);
81b1bf12
RK
157 } else
158 info("unicasting on %s", sockname);
23205f9c 159 }
1c3f1e73 160 len = sizeof sndbuf;
161 if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
162 &sndbuf, &len) < 0)
163 fatal(errno, "error getting SO_SNDBUF");
164 if(target_sndbuf > sndbuf) {
165 if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
166 &target_sndbuf, sizeof target_sndbuf) < 0)
167 error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
168 else
169 info("changed socket send buffer size from %d to %d",
170 sndbuf, target_sndbuf);
171 } else
172 info("default socket send buffer is %d",
173 sndbuf);
174 /* We might well want to set additional broadcast- or multicast-related
175 * options here */
176 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
177 fatal(errno, "error binding broadcast socket to %s", ssockname);
178 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
179 fatal(errno, "error connecting broadcast socket to %s", sockname);
180 /* Select an SSRC */
181 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
1c3f1e73 182}
183
184/** @brief Play over the network */
185static size_t network_play(size_t frames) {
186 struct rtp_header header;
187 struct iovec vec[2];
6d2d327c 188 size_t bytes = frames * bpf, written_frames;
1c3f1e73 189 int written_bytes;
190 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
191 * AVT profile (RFC3551). */
192
23741390
RK
193 /* If we're starting then initialize the base time */
194 if(!rtp_time)
195 xgettimeofday(&rtp_time_0, 0);
1c3f1e73 196 if(idled) {
197 /* There may have been a gap. Fix up the RTP time accordingly. */
198 struct timeval now;
199 uint64_t delta;
200 uint64_t target_rtp_time;
201
202 /* Find the current time */
203 xgettimeofday(&now, 0);
204 /* Find the number of microseconds elapsed since rtp_time=0 */
205 delta = tvsub_us(now, rtp_time_0);
23741390
RK
206 if(delta > UINT64_MAX / 88200)
207 fatal(0, "rtp_time=%llu now=%ld.%06ld rtp_time_0=%ld.%06ld delta=%llu (%lld)",
208 rtp_time,
209 (long)now.tv_sec, (long)now.tv_usec,
210 (long)rtp_time_0.tv_sec, (long)rtp_time_0.tv_usec,
211 delta, delta);
6d2d327c
RK
212 target_rtp_time = (delta * config->sample_format.rate
213 * config->sample_format.channels) / 1000000;
1c3f1e73 214 /* Overflows at ~6 years uptime with 44100Hz stereo */
215
216 /* rtp_time is the number of samples we've played. NB that we play
217 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
218 * the value we deduce from time comparison.
219 *
220 * Suppose we have 1s track started at t=0, and another track begins to
24d6fd25
RK
221 * play at t=2s. Suppose 44100Hz stereo. We send 1s of audio over the
222 * next (about) one second, giving rtp_time=88200. rtp_time stops at this
223 * point.
1c3f1e73 224 *
225 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
226 * set rtp_time=176400 and the player can correctly conclude that it
227 * should leave 1s between the tracks.
228 *
24d6fd25
RK
229 * It's never right to reduce rtp_time, for that would imply packets with
230 * overlapping timestamp ranges, which does not make sense.
1c3f1e73 231 */
232 target_rtp_time &= ~(uint64_t)1; /* stereo! */
233 if(target_rtp_time > rtp_time) {
234 /* More time has elapsed than we've transmitted samples. That implies
235 * we've been 'sending' silence. */
236 info("advancing rtp_time by %"PRIu64" samples",
237 target_rtp_time - rtp_time);
238 rtp_time = target_rtp_time;
239 } else if(target_rtp_time < rtp_time) {
24d6fd25
RK
240 info("would reverse rtp_time by %"PRIu64" samples",
241 rtp_time - target_rtp_time);
1c3f1e73 242 }
243 }
244 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
245 header.seq = htons(rtp_seq++);
246 header.timestamp = htonl((uint32_t)rtp_time);
247 header.ssrc = rtp_id;
248 header.mpt = (idled ? 0x80 : 0x00) | 10;
249 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
250 * the sample rate (in a library somewhere so that configuration.c can rule
251 * out invalid rates).
252 */
253 idled = 0;
254 if(bytes > NETWORK_BYTES - sizeof header) {
255 bytes = NETWORK_BYTES - sizeof header;
256 /* Always send a whole number of frames */
6d2d327c 257 bytes -= bytes % bpf;
1c3f1e73 258 }
259 /* "The RTP clock rate used for generating the RTP timestamp is independent
260 * of the number of channels and the encoding; it equals the number of
261 * sampling periods per second. For N-channel encodings, each sampling
262 * period (say, 1/8000 of a second) generates N samples. (This terminology
263 * is standard, but somewhat confusing, as the total number of samples
264 * generated per second is then the sampling rate times the channel
265 * count.)"
266 */
267 vec[0].iov_base = (void *)&header;
268 vec[0].iov_len = sizeof header;
269 vec[1].iov_base = playing->buffer + playing->start;
270 vec[1].iov_len = bytes;
271 do {
272 written_bytes = writev(bfd, vec, 2);
273 } while(written_bytes < 0 && errno == EINTR);
274 if(written_bytes < 0) {
275 error(errno, "error transmitting audio data");
276 ++audio_errors;
277 if(audio_errors == 10)
278 fatal(0, "too many audio errors");
279 return 0;
280 } else
281 audio_errors /= 2;
282 written_bytes -= sizeof (struct rtp_header);
6d2d327c 283 written_frames = written_bytes / bpf;
1c3f1e73 284 /* Advance RTP's notion of the time */
6d2d327c 285 rtp_time += written_frames * config->sample_format.channels;
1c3f1e73 286 return written_frames;
287}
288
289static int bfd_slot;
290
291/** @brief Set up poll array for network play */
e84fb5f0 292static void network_beforepoll(int *timeoutp) {
1c3f1e73 293 struct timeval now;
294 uint64_t target_us;
295 uint64_t target_rtp_time;
e84fb5f0
RK
296 const int64_t samples_per_second = config->sample_format.rate
297 * config->sample_format.channels;
e84fb5f0 298 int64_t lead, ahead_ms;
1c3f1e73 299
300 /* If we're starting then initialize the base time */
301 if(!rtp_time)
302 xgettimeofday(&rtp_time_0, 0);
24d6fd25 303 /* We send audio data whenever we would otherwise get behind */
1c3f1e73 304 xgettimeofday(&now, 0);
305 target_us = tvsub_us(now, rtp_time_0);
23741390
RK
306 if(target_us > UINT64_MAX / 88200)
307 fatal(0, "rtp_time=%llu rtp_time_0=%ld.%06ld now=%ld.%06ld target_us=%llu (%lld)\n",
308 rtp_time,
309 (long)rtp_time_0.tv_sec, (long)rtp_time_0.tv_usec,
310 (long)now.tv_sec, (long)now.tv_usec,
311 target_us, target_us);
1c3f1e73 312 target_rtp_time = (target_us * config->sample_format.rate
313 * config->sample_format.channels)
314 / 1000000;
24d6fd25 315 /* Lead is how far ahead we are */
e84fb5f0 316 lead = rtp_time - target_rtp_time;
24d6fd25
RK
317 if(lead <= 0)
318 /* We're behind or even, so we'll need to write as soon as we can */
1c3f1e73 319 bfd_slot = addfd(bfd, POLLOUT);
e84fb5f0 320 else {
24d6fd25
RK
321 /* We've ahead, we can afford to wait a bit even if the IP stack thinks it
322 * can accept more. */
323 ahead_ms = 1000 * lead / samples_per_second;
e84fb5f0
RK
324 if(ahead_ms < *timeoutp)
325 *timeoutp = ahead_ms;
326 }
1c3f1e73 327}
328
329/** @brief Process poll() results for network play */
330static int network_ready(void) {
331 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
332 return 1;
333 else
334 return 0;
335}
336
337const struct speaker_backend network_backend = {
338 BACKEND_NETWORK,
6d2d327c 339 0,
1c3f1e73 340 network_init,
341 0, /* activate */
342 network_play,
343 0, /* deactivate */
344 network_beforepoll,
345 network_ready
346};
347
348/*
349Local Variables:
350c-basic-offset:2
351comment-column:40
352fill-column:79
353indent-tabs-mode:nil
354End:
355*/