chiark / gitweb /
Fix type of shift in disorder-choose.
[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
23#include <config.h>
24#include "types.h"
25
26#include <unistd.h>
27#include <poll.h>
28#include <netdb.h>
29#include <gcrypt.h>
30#include <sys/socket.h>
31#include <sys/uio.h>
32#include <assert.h>
81b1bf12 33#include <net/if.h>
db2c19dc 34#include <ifaddrs.h>
6d2d327c 35#include <errno.h>
edbd470f 36#include <netinet/in.h>
1c3f1e73 37
38#include "configuration.h"
39#include "syscalls.h"
40#include "log.h"
41#include "addr.h"
42#include "timeval.h"
43#include "rtp.h"
81b1bf12 44#include "ifreq.h"
1c3f1e73 45#include "speaker-protocol.h"
46#include "speaker.h"
47
48/** @brief Network socket
49 *
50 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
51 */
52static int bfd = -1;
53
54/** @brief RTP timestamp
55 *
56 * This counts the number of samples played (NB not the number of frames
57 * played).
58 *
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.
64 */
65static uint64_t rtp_time;
66
67/** @brief RTP base timestamp
68 *
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.
71 */
72static struct timeval rtp_time_0;
73
74/** @brief RTP packet sequence number */
75static uint16_t rtp_seq;
76
77/** @brief RTP SSRC */
78static uint32_t rtp_id;
79
80/** @brief Error counter */
81static int audio_errors;
82
83/** @brief Network backend initialization */
84static void network_init(void) {
85 struct addrinfo *res, *sres;
86 static const struct addrinfo pref = {
66613034
RK
87 .ai_flags = 0,
88 .ai_family = PF_INET,
89 .ai_socktype = SOCK_DGRAM,
90 .ai_protocol = IPPROTO_UDP,
1c3f1e73 91 };
92 static const struct addrinfo prefbind = {
66613034
RK
93 .ai_flags = AI_PASSIVE,
94 .ai_family = PF_INET,
95 .ai_socktype = SOCK_DGRAM,
96 .ai_protocol = IPPROTO_UDP,
1c3f1e73 97 };
98 static const int one = 1;
db2c19dc 99 int sndbuf, target_sndbuf = 131072;
1c3f1e73 100 socklen_t len;
101 char *sockname, *ssockname;
102
103 res = get_address(&config->broadcast, &pref, &sockname);
104 if(!res) exit(-1);
105 if(config->broadcast_from.n) {
106 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
107 if(!sres) exit(-1);
108 } else
109 sres = 0;
110 if((bfd = socket(res->ai_family,
111 res->ai_socktype,
112 res->ai_protocol)) < 0)
113 fatal(errno, "error creating broadcast socket");
6fba990c 114 if(multicast(res->ai_addr)) {
23205f9c
RK
115 /* Multicasting */
116 switch(res->ai_family) {
117 case PF_INET: {
118 const int mttl = config->multicast_ttl;
119 if(setsockopt(bfd, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, sizeof mttl) < 0)
120 fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
61941295
RK
121 if(setsockopt(bfd, IPPROTO_IP, IP_MULTICAST_LOOP,
122 &config->multicast_loop, sizeof one) < 0)
123 fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
23205f9c
RK
124 break;
125 }
126 case PF_INET6: {
127 const int mttl = config->multicast_ttl;
128 if(setsockopt(bfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
129 &mttl, sizeof mttl) < 0)
130 fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
61941295
RK
131 if(setsockopt(bfd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
132 &config->multicast_loop, sizeof (int)) < 0)
133 fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
23205f9c
RK
134 break;
135 }
136 default:
137 fatal(0, "unsupported address family %d", res->ai_family);
138 }
81b1bf12 139 info("multicasting on %s", sockname);
23205f9c 140 } else {
db2c19dc 141 struct ifaddrs *ifs;
81b1bf12 142
db2c19dc
RK
143 if(getifaddrs(&ifs) < 0)
144 fatal(errno, "error calling getifaddrs");
145 while(ifs) {
3aa6f359
RK
146 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
147 * still a null pointer. It turns out that there's a subsequent entry
148 * for he same interface which _does_ have ifa_broadaddr though... */
db2c19dc 149 if((ifs->ifa_flags & IFF_BROADCAST)
3aa6f359 150 && ifs->ifa_broadaddr
db2c19dc 151 && sockaddr_equal(ifs->ifa_broadaddr, res->ai_addr))
81b1bf12 152 break;
db2c19dc 153 ifs = ifs->ifa_next;
81b1bf12 154 }
db2c19dc 155 if(ifs) {
81b1bf12
RK
156 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
157 fatal(errno, "error setting SO_BROADCAST on broadcast socket");
db2c19dc 158 info("broadcasting on %s (%s)", sockname, ifs->ifa_name);
81b1bf12
RK
159 } else
160 info("unicasting on %s", sockname);
23205f9c 161 }
1c3f1e73 162 len = sizeof sndbuf;
163 if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
164 &sndbuf, &len) < 0)
165 fatal(errno, "error getting SO_SNDBUF");
166 if(target_sndbuf > sndbuf) {
167 if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
168 &target_sndbuf, sizeof target_sndbuf) < 0)
169 error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
170 else
171 info("changed socket send buffer size from %d to %d",
172 sndbuf, target_sndbuf);
173 } else
174 info("default socket send buffer is %d",
175 sndbuf);
176 /* We might well want to set additional broadcast- or multicast-related
177 * options here */
178 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
179 fatal(errno, "error binding broadcast socket to %s", ssockname);
180 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
181 fatal(errno, "error connecting broadcast socket to %s", sockname);
182 /* Select an SSRC */
183 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
1c3f1e73 184}
185
186/** @brief Play over the network */
187static size_t network_play(size_t frames) {
188 struct rtp_header header;
189 struct iovec vec[2];
6d2d327c 190 size_t bytes = frames * bpf, written_frames;
1c3f1e73 191 int written_bytes;
192 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
193 * AVT profile (RFC3551). */
194
23741390
RK
195 /* If we're starting then initialize the base time */
196 if(!rtp_time)
197 xgettimeofday(&rtp_time_0, 0);
1c3f1e73 198 if(idled) {
199 /* There may have been a gap. Fix up the RTP time accordingly. */
200 struct timeval now;
201 uint64_t delta;
202 uint64_t target_rtp_time;
203
204 /* Find the current time */
205 xgettimeofday(&now, 0);
206 /* Find the number of microseconds elapsed since rtp_time=0 */
207 delta = tvsub_us(now, rtp_time_0);
23741390
RK
208 if(delta > UINT64_MAX / 88200)
209 fatal(0, "rtp_time=%llu now=%ld.%06ld rtp_time_0=%ld.%06ld delta=%llu (%lld)",
210 rtp_time,
211 (long)now.tv_sec, (long)now.tv_usec,
212 (long)rtp_time_0.tv_sec, (long)rtp_time_0.tv_usec,
213 delta, delta);
6d2d327c
RK
214 target_rtp_time = (delta * config->sample_format.rate
215 * config->sample_format.channels) / 1000000;
1c3f1e73 216 /* Overflows at ~6 years uptime with 44100Hz stereo */
217
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.
221 *
222 * Suppose we have 1s track started at t=0, and another track begins to
24d6fd25
RK
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
225 * point.
1c3f1e73 226 *
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.
230 *
24d6fd25
RK
231 * It's never right to reduce rtp_time, for that would imply packets with
232 * overlapping timestamp ranges, which does not make sense.
1c3f1e73 233 */
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) {
24d6fd25
RK
242 info("would reverse rtp_time by %"PRIu64" samples",
243 rtp_time - target_rtp_time);
1c3f1e73 244 }
245 }
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).
254 */
255 idled = 0;
256 if(bytes > NETWORK_BYTES - sizeof header) {
257 bytes = NETWORK_BYTES - sizeof header;
258 /* Always send a whole number of frames */
6d2d327c 259 bytes -= bytes % bpf;
1c3f1e73 260 }
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
267 * count.)"
268 */
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;
273 do {
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");
278 ++audio_errors;
279 if(audio_errors == 10)
280 fatal(0, "too many audio errors");
281 return 0;
282 } else
283 audio_errors /= 2;
284 written_bytes -= sizeof (struct rtp_header);
6d2d327c 285 written_frames = written_bytes / bpf;
1c3f1e73 286 /* Advance RTP's notion of the time */
6d2d327c 287 rtp_time += written_frames * config->sample_format.channels;
1c3f1e73 288 return written_frames;
289}
290
291static int bfd_slot;
292
293/** @brief Set up poll array for network play */
e84fb5f0 294static void network_beforepoll(int *timeoutp) {
1c3f1e73 295 struct timeval now;
296 uint64_t target_us;
297 uint64_t target_rtp_time;
e84fb5f0
RK
298 const int64_t samples_per_second = config->sample_format.rate
299 * config->sample_format.channels;
e84fb5f0 300 int64_t lead, ahead_ms;
1c3f1e73 301
302 /* If we're starting then initialize the base time */
303 if(!rtp_time)
304 xgettimeofday(&rtp_time_0, 0);
24d6fd25 305 /* We send audio data whenever we would otherwise get behind */
1c3f1e73 306 xgettimeofday(&now, 0);
307 target_us = tvsub_us(now, rtp_time_0);
23741390
RK
308 if(target_us > UINT64_MAX / 88200)
309 fatal(0, "rtp_time=%llu rtp_time_0=%ld.%06ld now=%ld.%06ld target_us=%llu (%lld)\n",
310 rtp_time,
311 (long)rtp_time_0.tv_sec, (long)rtp_time_0.tv_usec,
312 (long)now.tv_sec, (long)now.tv_usec,
313 target_us, target_us);
1c3f1e73 314 target_rtp_time = (target_us * config->sample_format.rate
315 * config->sample_format.channels)
316 / 1000000;
24d6fd25 317 /* Lead is how far ahead we are */
e84fb5f0 318 lead = rtp_time - target_rtp_time;
24d6fd25
RK
319 if(lead <= 0)
320 /* We're behind or even, so we'll need to write as soon as we can */
1c3f1e73 321 bfd_slot = addfd(bfd, POLLOUT);
e84fb5f0 322 else {
24d6fd25
RK
323 /* We've ahead, we can afford to wait a bit even if the IP stack thinks it
324 * can accept more. */
325 ahead_ms = 1000 * lead / samples_per_second;
e84fb5f0
RK
326 if(ahead_ms < *timeoutp)
327 *timeoutp = ahead_ms;
328 }
1c3f1e73 329}
330
331/** @brief Process poll() results for network play */
332static int network_ready(void) {
333 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
334 return 1;
335 else
336 return 0;
337}
338
339const struct speaker_backend network_backend = {
340 BACKEND_NETWORK,
6d2d327c 341 0,
1c3f1e73 342 network_init,
343 0, /* activate */
344 network_play,
345 0, /* deactivate */
346 network_beforepoll,
347 network_ready
348};
349
350/*
351Local Variables:
352c-basic-offset:2
353comment-column:40
354fill-column:79
355indent-tabs-mode:nil
356End:
357*/