1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
|
use std::{
sync::{
atomic::{self, AtomicU64},
Arc, Mutex,
},
time::{Duration, Instant},
};
use futures::executor::block_on;
use pulseaudio::{protocol, AsPlaybackSource};
use crate::{
traits::StreamTrait, BackendSpecificError, BuildStreamError, Data, FrameCount,
InputCallbackInfo, InputStreamTimestamp, OutputCallbackInfo, OutputStreamTimestamp,
PlayStreamError, SampleFormat, StreamError, StreamInstant,
};
const LATENCY_POLL_INTERVAL: Duration = Duration::from_millis(5);
pub enum Stream {
Playback(pulseaudio::PlaybackStream),
Record(pulseaudio::RecordStream),
}
impl StreamTrait for Stream {
fn play(&self) -> Result<(), PlayStreamError> {
match self {
Stream::Playback(stream) => {
block_on(stream.uncork()).map_err(Into::<BackendSpecificError>::into)?;
}
Stream::Record(stream) => {
block_on(stream.uncork()).map_err(Into::<BackendSpecificError>::into)?;
block_on(stream.started()).map_err(Into::<BackendSpecificError>::into)?;
}
};
Ok(())
}
fn pause(&self) -> Result<(), crate::PauseStreamError> {
let res = match self {
Stream::Playback(stream) => block_on(stream.cork()),
Stream::Record(stream) => block_on(stream.cork()),
};
res.map_err(Into::<BackendSpecificError>::into)?;
Ok(())
}
fn buffer_size(&self) -> Option<FrameCount> {
let (spec, bytes) = match self {
Stream::Playback(s) => (
s.sample_spec(),
s.buffer_attr().minimum_request_length as usize,
),
Stream::Record(s) => (s.sample_spec(), s.buffer_attr().fragment_size as usize),
};
let frame_size = spec.channels as usize * spec.format.bytes_per_sample();
if bytes > 0 {
Some((bytes / frame_size) as _)
} else {
None
}
}
}
impl Stream {
pub fn new_playback<D, E>(
client: pulseaudio::Client,
params: protocol::PlaybackStreamParams,
mut data_callback: D,
error_callback: E,
) -> Result<Self, BuildStreamError>
where
D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static,
E: FnMut(StreamError) + Send + 'static,
{
// Use a monotonic clock relative to stream creation for StreamInstants.
let start = std::time::Instant::now();
let current_latency_micros = Arc::new(AtomicU64::new(0));
// Microseconds since stream creation at the time of the last latency poll, used
// to interpolate the latency between polls.
let last_poll_micros = Arc::new(AtomicU64::new(0));
let latency_clone = current_latency_micros.clone();
let poll_clone = last_poll_micros.clone();
let sample_spec = params.sample_spec;
let format: SampleFormat = sample_spec
.format
.try_into()
.map_err(|_| BuildStreamError::StreamConfigNotSupported)?;
// Silence for unsigned formats is the midpoint, not zero. Among
// PulseAudio's supported formats, only U8 is unsigned and has a
// single-byte repeatable silence representation (0x80). Multi-byte
// unsigned formats (U16, U32, ...) are not currently supported.
let silence_byte = if format == SampleFormat::U8 {
0x80u8
} else {
0u8
};
// Wrap the write callback to match the pulseaudio signature.
let callback = move |buf: &mut [u8]| {
let elapsed = Instant::now().saturating_duration_since(start);
let elapsed_usec = elapsed.as_micros() as u64;
// Interpolate the latency based on elapsed time since the last
// poll: as audio plays, the DAC drains the buffer at a constant
// rate, so the latency decreases linearly between polls.
let stored_latency = latency_clone.load(atomic::Ordering::Relaxed);
let poll_usec = poll_clone.load(atomic::Ordering::Relaxed);
// Cap to one poll interval: the linear-drain assumption is only valid
// for that window, and a stale poll_usec (e.g. after cork/uncork where
// timing_info blocks) would otherwise saturate latency to zero.
let elapsed_since_poll = elapsed_usec
.saturating_sub(poll_usec)
.min(LATENCY_POLL_INTERVAL.as_micros() as u64);
let latency = stored_latency.saturating_sub(elapsed_since_poll);
let playback_time = elapsed + Duration::from_micros(latency);
let timestamp = OutputStreamTimestamp {
callback: StreamInstant {
secs: elapsed.as_secs() as i64,
nanos: elapsed.subsec_nanos(),
},
playback: StreamInstant {
secs: playback_time.as_secs() as i64,
nanos: playback_time.subsec_nanos(),
},
};
// Preemptively fill the buffer with silence in case the user
// callback doesn't fill it completely (cpal's API doesn't allow
// short writes).
buf.fill(silence_byte);
let bps = sample_spec.format.bytes_per_sample();
let n_samples = buf.len() / bps;
// SAFETY: we calculated the number of samples based on
// `sample_spec.format`, and `format` is directly derived from (and
// equivalent to) `sample_spec.format`.
let mut data = unsafe { Data::from_parts(buf.as_mut_ptr().cast(), n_samples, format) };
data_callback(&mut data, &OutputCallbackInfo { timestamp });
// We always consider the full buffer filled, because cpal's
// user-facing API doesn't allow short writes.
buf.len()
};
let stream = block_on(client.create_playback_stream(params, callback.as_playback_source()))
.map_err(Into::<BackendSpecificError>::into)?;
// Share the error callback between the worker and latency threads so
// both can surface errors to the user.
let error_callback = Arc::new(Mutex::new(error_callback));
// Spawn a thread to drive the stream future. It will exit automatically
// when the stream is stopped by the user.
let stream_clone = stream.clone();
let error_callback_clone = error_callback.clone();
std::thread::spawn(move || {
if let Err(e) = block_on(stream_clone.play_all()) {
error_callback_clone.lock().unwrap()(StreamError::from(BackendSpecificError {
description: e.to_string(),
}));
}
});
// Spawn a thread to monitor the stream's latency in a loop. It will
// exit automatically when the stream ends.
let stream_clone = stream.clone();
let latency_clone = current_latency_micros.clone();
let poll_clone = last_poll_micros.clone();
std::thread::spawn(move || loop {
let timing_info = match block_on(stream_clone.timing_info()) {
Ok(timing_info) => timing_info,
Err(e) => {
error_callback.lock().unwrap()(StreamError::from(BackendSpecificError {
description: e.to_string(),
}));
break;
}
};
let poll_since_epoch =
Instant::now().saturating_duration_since(start).as_micros() as u64;
poll_clone.store(poll_since_epoch, atomic::Ordering::Relaxed);
store_latency(
&latency_clone,
sample_spec,
timing_info.sink_usec,
timing_info.write_offset,
timing_info.read_offset,
);
std::thread::sleep(LATENCY_POLL_INTERVAL);
});
Ok(Self::Playback(stream))
}
pub fn new_record<D, E>(
client: pulseaudio::Client,
params: protocol::RecordStreamParams,
mut data_callback: D,
mut error_callback: E,
) -> Result<Self, BuildStreamError>
where
D: FnMut(&Data, &InputCallbackInfo) + Send + 'static,
E: FnMut(StreamError) + Send + 'static,
{
let start = Instant::now();
let current_latency_micros = Arc::new(AtomicU64::new(0));
let latency_clone = current_latency_micros.clone();
let sample_spec = params.sample_spec;
let format: SampleFormat = sample_spec
.format
.try_into()
.map_err(|_| BuildStreamError::StreamConfigNotSupported)?;
let callback = move |buf: &[u8]| {
let elapsed = Instant::now().saturating_duration_since(start);
let latency = latency_clone.load(atomic::Ordering::Relaxed);
let capture_time = elapsed
.checked_sub(Duration::from_micros(latency))
.unwrap_or_default();
let timestamp = InputStreamTimestamp {
callback: StreamInstant {
secs: elapsed.as_secs() as i64,
nanos: elapsed.subsec_nanos(),
},
capture: StreamInstant {
secs: capture_time.as_secs() as i64,
nanos: capture_time.subsec_nanos(),
},
};
let bps = sample_spec.format.bytes_per_sample();
let n_samples = buf.len() / bps;
// SAFETY: we calculated the number of samples based on
// `sample_spec.format`, and `format` is directly derived from (and
// equivalent to) `sample_spec.format`. The pointer is cast from
// *const to *mut, but cpal's Data type for input streams only
// exposes shared references (&[T]), so no mutation occurs.
let data = unsafe { Data::from_parts(buf.as_ptr() as *mut _, n_samples, format) };
data_callback(&data, &InputCallbackInfo { timestamp });
};
let stream = block_on(client.create_record_stream(params, callback))
.map_err(Into::<BackendSpecificError>::into)?;
// Spawn a thread to monitor the stream's latency in a loop. It will
// exit automatically when the stream ends.
let stream_clone = stream.clone();
let latency_clone = current_latency_micros.clone();
std::thread::spawn(move || loop {
let timing_info = match block_on(stream_clone.timing_info()) {
Ok(timing_info) => timing_info,
Err(e) => {
error_callback(StreamError::from(BackendSpecificError {
description: e.to_string(),
}));
break;
}
};
store_latency(
&latency_clone,
sample_spec,
timing_info.source_usec,
timing_info.write_offset,
timing_info.read_offset,
);
std::thread::sleep(LATENCY_POLL_INTERVAL);
});
Ok(Self::Record(stream))
}
}
fn store_latency(
latency_micros: &AtomicU64,
sample_spec: protocol::SampleSpec,
device_latency_usec: u64,
write_offset: i64,
read_offset: i64,
) {
let offset = (write_offset - read_offset).max(0) as u64;
let latency =
Duration::from_micros(device_latency_usec) + sample_spec.bytes_to_duration(offset as usize);
latency_micros.store(
latency.as_micros().try_into().unwrap_or(u64::MAX),
atomic::Ordering::Relaxed,
);
}
|