chiark / gitweb /
leave a TODO relating to revno 78
[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
34#include "configuration.h"
35#include "syscalls.h"
36#include "log.h"
37#include "addr.h"
38#include "timeval.h"
39#include "rtp.h"
40#include "speaker-protocol.h"
41#include "speaker.h"
42
43/** @brief Network socket
44 *
45 * This is the file descriptor to write to for @ref BACKEND_NETWORK.
46 */
47static int bfd = -1;
48
49/** @brief RTP timestamp
50 *
51 * This counts the number of samples played (NB not the number of frames
52 * played).
53 *
54 * The timestamp in the packet header is only 32 bits wide. With 44100Hz
55 * stereo, that only gives about half a day before wrapping, which is not
56 * particularly convenient for certain debugging purposes. Therefore the
57 * timestamp is maintained as a 64-bit integer, giving around six million years
58 * before wrapping, and truncated to 32 bits when transmitting.
59 */
60static uint64_t rtp_time;
61
62/** @brief RTP base timestamp
63 *
64 * This is the real time correspoding to an @ref rtp_time of 0. It is used
65 * to recalculate the timestamp after idle periods.
66 */
67static struct timeval rtp_time_0;
68
69/** @brief RTP packet sequence number */
70static uint16_t rtp_seq;
71
72/** @brief RTP SSRC */
73static uint32_t rtp_id;
74
75/** @brief Error counter */
76static int audio_errors;
77
78/** @brief Network backend initialization */
79static void network_init(void) {
80 struct addrinfo *res, *sres;
81 static const struct addrinfo pref = {
82 0,
83 PF_INET,
84 SOCK_DGRAM,
85 IPPROTO_UDP,
86 0,
87 0,
88 0,
89 0
90 };
91 static const struct addrinfo prefbind = {
92 AI_PASSIVE,
93 PF_INET,
94 SOCK_DGRAM,
95 IPPROTO_UDP,
96 0,
97 0,
98 0,
99 0
100 };
101 static const int one = 1;
102 int sndbuf, target_sndbuf = 131072;
103 socklen_t len;
104 char *sockname, *ssockname;
105
106 /* Override sample format */
107 config->sample_format.rate = 44100;
108 config->sample_format.channels = 2;
109 config->sample_format.bits = 16;
110 config->sample_format.byte_format = AO_FMT_BIG;
111 res = get_address(&config->broadcast, &pref, &sockname);
112 if(!res) exit(-1);
113 if(config->broadcast_from.n) {
114 sres = get_address(&config->broadcast_from, &prefbind, &ssockname);
115 if(!sres) exit(-1);
116 } else
117 sres = 0;
118 if((bfd = socket(res->ai_family,
119 res->ai_socktype,
120 res->ai_protocol)) < 0)
121 fatal(errno, "error creating broadcast socket");
122 if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
123 fatal(errno, "error setting SO_BROADCAST on broadcast socket");
124 len = sizeof sndbuf;
125 if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
126 &sndbuf, &len) < 0)
127 fatal(errno, "error getting SO_SNDBUF");
128 if(target_sndbuf > sndbuf) {
129 if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF,
130 &target_sndbuf, sizeof target_sndbuf) < 0)
131 error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
132 else
133 info("changed socket send buffer size from %d to %d",
134 sndbuf, target_sndbuf);
135 } else
136 info("default socket send buffer is %d",
137 sndbuf);
138 /* We might well want to set additional broadcast- or multicast-related
139 * options here */
140 if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0)
141 fatal(errno, "error binding broadcast socket to %s", ssockname);
142 if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0)
143 fatal(errno, "error connecting broadcast socket to %s", sockname);
144 /* Select an SSRC */
145 gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM);
146 info("selected network backend, sending to %s", sockname);
147}
148
149/** @brief Play over the network */
150static size_t network_play(size_t frames) {
151 struct rtp_header header;
152 struct iovec vec[2];
153 size_t bytes = frames * device_bpf, written_frames;
154 int written_bytes;
155 /* We transmit using RTP (RFC3550) and attempt to conform to the internet
156 * AVT profile (RFC3551). */
157
158 if(idled) {
159 /* There may have been a gap. Fix up the RTP time accordingly. */
160 struct timeval now;
161 uint64_t delta;
162 uint64_t target_rtp_time;
163
164 /* Find the current time */
165 xgettimeofday(&now, 0);
166 /* Find the number of microseconds elapsed since rtp_time=0 */
167 delta = tvsub_us(now, rtp_time_0);
168 assert(delta <= UINT64_MAX / 88200);
169 target_rtp_time = (delta * playing->format.rate
170 * playing->format.channels) / 1000000;
171 /* Overflows at ~6 years uptime with 44100Hz stereo */
172
173 /* rtp_time is the number of samples we've played. NB that we play
174 * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of
175 * the value we deduce from time comparison.
176 *
177 * Suppose we have 1s track started at t=0, and another track begins to
178 * play at t=2s. Suppose RTP_AHEAD_MS=1000 and 44100Hz stereo. In that
179 * case we'll send 1s of audio as fast as we can, giving rtp_time=88200.
180 * rtp_time stops at this point.
181 *
182 * At t=2s we'll have calculated target_rtp_time=176400. In this case we
183 * set rtp_time=176400 and the player can correctly conclude that it
184 * should leave 1s between the tracks.
185 *
186 * Suppose instead that the second track arrives at t=0.5s, and that
187 * we've managed to transmit the whole of the first track already. We'll
188 * have target_rtp_time=44100.
189 *
190 * The desired behaviour is to play the second track back to back with
191 * first. In this case therefore we do not modify rtp_time.
192 *
193 * Is it ever right to reduce rtp_time? No; for that would imply
194 * transmitting packets with overlapping timestamp ranges, which does not
195 * make sense.
196 */
197 target_rtp_time &= ~(uint64_t)1; /* stereo! */
198 if(target_rtp_time > rtp_time) {
199 /* More time has elapsed than we've transmitted samples. That implies
200 * we've been 'sending' silence. */
201 info("advancing rtp_time by %"PRIu64" samples",
202 target_rtp_time - rtp_time);
203 rtp_time = target_rtp_time;
204 } else if(target_rtp_time < rtp_time) {
205 const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
206 * config->sample_format.rate
207 * config->sample_format.channels
208 / 1000);
209
210 if(target_rtp_time + samples_ahead < rtp_time) {
211 info("reversing rtp_time by %"PRIu64" samples",
212 rtp_time - target_rtp_time);
213 }
214 }
215 }
216 header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */
217 header.seq = htons(rtp_seq++);
218 header.timestamp = htonl((uint32_t)rtp_time);
219 header.ssrc = rtp_id;
220 header.mpt = (idled ? 0x80 : 0x00) | 10;
221 /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from
222 * the sample rate (in a library somewhere so that configuration.c can rule
223 * out invalid rates).
224 */
225 idled = 0;
226 if(bytes > NETWORK_BYTES - sizeof header) {
227 bytes = NETWORK_BYTES - sizeof header;
228 /* Always send a whole number of frames */
229 bytes -= bytes % device_bpf;
230 }
231 /* "The RTP clock rate used for generating the RTP timestamp is independent
232 * of the number of channels and the encoding; it equals the number of
233 * sampling periods per second. For N-channel encodings, each sampling
234 * period (say, 1/8000 of a second) generates N samples. (This terminology
235 * is standard, but somewhat confusing, as the total number of samples
236 * generated per second is then the sampling rate times the channel
237 * count.)"
238 */
239 vec[0].iov_base = (void *)&header;
240 vec[0].iov_len = sizeof header;
241 vec[1].iov_base = playing->buffer + playing->start;
242 vec[1].iov_len = bytes;
243 do {
244 written_bytes = writev(bfd, vec, 2);
245 } while(written_bytes < 0 && errno == EINTR);
246 if(written_bytes < 0) {
247 error(errno, "error transmitting audio data");
248 ++audio_errors;
249 if(audio_errors == 10)
250 fatal(0, "too many audio errors");
251 return 0;
252 } else
253 audio_errors /= 2;
254 written_bytes -= sizeof (struct rtp_header);
255 written_frames = written_bytes / device_bpf;
256 /* Advance RTP's notion of the time */
257 rtp_time += written_frames * playing->format.channels;
258 return written_frames;
259}
260
261static int bfd_slot;
262
263/** @brief Set up poll array for network play */
264static void network_beforepoll(void) {
265 struct timeval now;
266 uint64_t target_us;
267 uint64_t target_rtp_time;
268 const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS
269 * config->sample_format.rate
270 * config->sample_format.channels
271 / 1000);
272
273 /* If we're starting then initialize the base time */
274 if(!rtp_time)
275 xgettimeofday(&rtp_time_0, 0);
276 /* We send audio data whenever we get RTP_AHEAD seconds or more
277 * behind */
278 xgettimeofday(&now, 0);
279 target_us = tvsub_us(now, rtp_time_0);
280 assert(target_us <= UINT64_MAX / 88200);
281 target_rtp_time = (target_us * config->sample_format.rate
282 * config->sample_format.channels)
283 / 1000000;
284 if((int64_t)(rtp_time - target_rtp_time) < samples_ahead)
285 bfd_slot = addfd(bfd, POLLOUT);
286}
287
288/** @brief Process poll() results for network play */
289static int network_ready(void) {
290 if(fds[bfd_slot].revents & (POLLOUT | POLLERR))
291 return 1;
292 else
293 return 0;
294}
295
296const struct speaker_backend network_backend = {
297 BACKEND_NETWORK,
298 FIXED_FORMAT,
299 network_init,
300 0, /* activate */
301 network_play,
302 0, /* deactivate */
303 network_beforepoll,
304 network_ready
305};
306
307/*
308Local Variables:
309c-basic-offset:2
310comment-column:40
311fill-column:79
312indent-tabs-mode:nil
313End:
314*/