chiark / gitweb /
mad-based mp3 decoder. non-44.1KHz does not work right yet l-(
[disorder] / server / speaker-network.c
CommitLineData
1c3f1e73 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>
81b1bf12 33#include <net/if.h>
db2c19dc 34#include <ifaddrs.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 = {
85 0,
86 PF_INET,
87 SOCK_DGRAM,
88 IPPROTO_UDP,
89 0,
90 0,
91 0,
92 0
93 };
94 static const struct addrinfo prefbind = {
95 AI_PASSIVE,
96 PF_INET,
97 SOCK_DGRAM,
98 IPPROTO_UDP,
99 0,
100 0,
101 0,
102 0
103 };
104 static const int one = 1;
db2c19dc 105 int sndbuf, target_sndbuf = 131072;
1c3f1e73 106 socklen_t len;
107 char *sockname, *ssockname;
108
803f6e52 109 /* Override sample format */
110 config->sample_format.rate = 44100;
111 config->sample_format.channels = 2;
112 config->sample_format.bits = 16;
113 config->sample_format.byte_format = AO_FMT_BIG;
1c3f1e73 114 res = get_address(&config->broadcast, &pref, &sockname);
115 if(!res) exit(-1);
116 if(config->broadcast_from.n) {
117 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
118 if(!sres) exit(-1);
119 } else
120 sres = 0;
121 if((bfd = socket(res->ai_family,
122 res->ai_socktype,
123 res->ai_protocol)) < 0)
124 fatal(errno, "error creating broadcast socket");
23205f9c
RK
125 if((res->ai_family == PF_INET
126 && IN_MULTICAST(
127 ntohl(((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr)
128 ))
129 || (res->ai_family == PF_INET6
130 && IN6_IS_ADDR_MULTICAST(
131 &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr
132 ))) {
133 /* Multicasting */
134 switch(res->ai_family) {
135 case PF_INET: {
136 const int mttl = config->multicast_ttl;
137 if(setsockopt(bfd, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, sizeof mttl) < 0)
138 fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
139 break;
140 }
141 case PF_INET6: {
142 const int mttl = config->multicast_ttl;
143 if(setsockopt(bfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
144 &mttl, sizeof mttl) < 0)
145 fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
146 break;
147 }
148 default:
149 fatal(0, "unsupported address family %d", res->ai_family);
150 }
81b1bf12 151 info("multicasting on %s", sockname);
23205f9c 152 } else {
db2c19dc 153 struct ifaddrs *ifs;
81b1bf12 154
db2c19dc
RK
155 if(getifaddrs(&ifs) < 0)
156 fatal(errno, "error calling getifaddrs");
157 while(ifs) {
3aa6f359
RK
158 /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
159 * still a null pointer. It turns out that there's a subsequent entry
160 * for he same interface which _does_ have ifa_broadaddr though... */
db2c19dc 161 if((ifs->ifa_flags & IFF_BROADCAST)
3aa6f359 162 && ifs->ifa_broadaddr
db2c19dc 163 && sockaddr_equal(ifs->ifa_broadaddr, res->ai_addr))
81b1bf12 164 break;
db2c19dc 165 ifs = ifs->ifa_next;
81b1bf12 166 }
db2c19dc 167 if(ifs) {
81b1bf12
RK
168 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
169 fatal(errno, "error setting SO_BROADCAST on broadcast socket");
db2c19dc 170 info("broadcasting on %s (%s)", sockname, ifs->ifa_name);
81b1bf12
RK
171 } else
172 info("unicasting on %s", sockname);
23205f9c 173 }
1c3f1e73 174 len = sizeof sndbuf;
175 if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
176 &sndbuf, &len) < 0)
177 fatal(errno, "error getting SO_SNDBUF");
178 if(target_sndbuf > sndbuf) {
179 if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
180 &target_sndbuf, sizeof target_sndbuf) < 0)
181 error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
182 else
183 info("changed socket send buffer size from %d to %d",
184 sndbuf, target_sndbuf);
185 } else
186 info("default socket send buffer is %d",
187 sndbuf);
188 /* We might well want to set additional broadcast- or multicast-related
189 * options here */
190 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
191 fatal(errno, "error binding broadcast socket to %s", ssockname);
192 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
193 fatal(errno, "error connecting broadcast socket to %s", sockname);
194 /* Select an SSRC */
195 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
196 info("selected network backend, sending to %s", sockname);
1c3f1e73 197}
198
199/** @brief Play over the network */
200static size_t network_play(size_t frames) {
201 struct rtp_header header;
202 struct iovec vec[2];
203 size_t bytes = frames * device_bpf, written_frames;
204 int written_bytes;
205 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
206 * AVT profile (RFC3551). */
207
208 if(idled) {
209 /* There may have been a gap. Fix up the RTP time accordingly. */
210 struct timeval now;
211 uint64_t delta;
212 uint64_t target_rtp_time;
213
214 /* Find the current time */
215 xgettimeofday(&now, 0);
216 /* Find the number of microseconds elapsed since rtp_time=0 */
217 delta = tvsub_us(now, rtp_time_0);
218 assert(delta <= UINT64_MAX / 88200);
219 target_rtp_time = (delta * playing->format.rate
220 * playing->format.channels) / 1000000;
221 /* Overflows at ~6 years uptime with 44100Hz stereo */
222
223 /* rtp_time is the number of samples we've played. NB that we play
224 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
225 * the value we deduce from time comparison.
226 *
227 * Suppose we have 1s track started at t=0, and another track begins to
228 * play at t=2s. Suppose RTP_AHEAD_MS=1000 and 44100Hz stereo. In that
229 * case we'll send 1s of audio as fast as we can, giving rtp_time=88200.
230 * rtp_time stops at this point.
231 *
232 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
233 * set rtp_time=176400 and the player can correctly conclude that it
234 * should leave 1s between the tracks.
235 *
236 * Suppose instead that the second track arrives at t=0.5s, and that
237 * we've managed to transmit the whole of the first track already. We'll
238 * have target_rtp_time=44100.
239 *
240 * The desired behaviour is to play the second track back to back with
241 * first. In this case therefore we do not modify rtp_time.
242 *
243 * Is it ever right to reduce rtp_time? No; for that would imply
244 * transmitting packets with overlapping timestamp ranges, which does not
245 * make sense.
246 */
247 target_rtp_time &= ~(uint64_t)1; /* stereo! */
248 if(target_rtp_time > rtp_time) {
249 /* More time has elapsed than we've transmitted samples. That implies
250 * we've been 'sending' silence. */
251 info("advancing rtp_time by %"PRIu64" samples",
252 target_rtp_time - rtp_time);
253 rtp_time = target_rtp_time;
254 } else if(target_rtp_time < rtp_time) {
255 const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
256 * config->sample_format.rate
257 * config->sample_format.channels
258 / 1000);
259
260 if(target_rtp_time + samples_ahead < rtp_time) {
261 info("reversing rtp_time by %"PRIu64" samples",
262 rtp_time - target_rtp_time);
263 }
264 }
265 }
266 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
267 header.seq = htons(rtp_seq++);
268 header.timestamp = htonl((uint32_t)rtp_time);
269 header.ssrc = rtp_id;
270 header.mpt = (idled ? 0x80 : 0x00) | 10;
271 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
272 * the sample rate (in a library somewhere so that configuration.c can rule
273 * out invalid rates).
274 */
275 idled = 0;
276 if(bytes > NETWORK_BYTES - sizeof header) {
277 bytes = NETWORK_BYTES - sizeof header;
278 /* Always send a whole number of frames */
279 bytes -= bytes % device_bpf;
280 }
281 /* "The RTP clock rate used for generating the RTP timestamp is independent
282 * of the number of channels and the encoding; it equals the number of
283 * sampling periods per second. For N-channel encodings, each sampling
284 * period (say, 1/8000 of a second) generates N samples. (This terminology
285 * is standard, but somewhat confusing, as the total number of samples
286 * generated per second is then the sampling rate times the channel
287 * count.)"
288 */
289 vec[0].iov_base = (void *)&header;
290 vec[0].iov_len = sizeof header;
291 vec[1].iov_base = playing->buffer + playing->start;
292 vec[1].iov_len = bytes;
293 do {
294 written_bytes = writev(bfd, vec, 2);
295 } while(written_bytes < 0 && errno == EINTR);
296 if(written_bytes < 0) {
297 error(errno, "error transmitting audio data");
298 ++audio_errors;
299 if(audio_errors == 10)
300 fatal(0, "too many audio errors");
301 return 0;
302 } else
303 audio_errors /= 2;
304 written_bytes -= sizeof (struct rtp_header);
305 written_frames = written_bytes / device_bpf;
306 /* Advance RTP's notion of the time */
307 rtp_time += written_frames * playing->format.channels;
308 return written_frames;
309}
310
311static int bfd_slot;
312
313/** @brief Set up poll array for network play */
314static void network_beforepoll(void) {
315 struct timeval now;
316 uint64_t target_us;
317 uint64_t target_rtp_time;
318 const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
319 * config->sample_format.rate
320 * config->sample_format.channels
321 / 1000);
322
323 /* If we're starting then initialize the base time */
324 if(!rtp_time)
325 xgettimeofday(&rtp_time_0, 0);
326 /* We send audio data whenever we get RTP_AHEAD seconds or more
327 * behind */
328 xgettimeofday(&now, 0);
329 target_us = tvsub_us(now, rtp_time_0);
330 assert(target_us <= UINT64_MAX / 88200);
331 target_rtp_time = (target_us * config->sample_format.rate
332 * config->sample_format.channels)
333 / 1000000;
334 if((int64_t)(rtp_time - target_rtp_time) < samples_ahead)
335 bfd_slot = addfd(bfd, POLLOUT);
336}
337
338/** @brief Process poll() results for network play */
339static int network_ready(void) {
340 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
341 return 1;
342 else
343 return 0;
344}
345
346const struct speaker_backend network_backend = {
347 BACKEND_NETWORK,
348 FIXED_FORMAT,
349 network_init,
350 0, /* activate */
351 network_play,
352 0, /* deactivate */
353 network_beforepoll,
354 network_ready
355};
356
357/*
358Local Variables:
359c-basic-offset:2
360comment-column:40
361fill-column:79
362indent-tabs-mode:nil
363End:
364*/