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