-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelay.rs
More file actions
73 lines (62 loc) · 2 KB
/
Copy pathdelay.rs
File metadata and controls
73 lines (62 loc) · 2 KB
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
pub const SPEED_OF_SOUND: f32 = 343.0;
const GLIDE: f32 = 0.0005;
pub struct DelayLine {
buffer: Vec<f32>,
write: usize,
delay: f32,
}
impl DelayLine {
pub fn new(capacity: usize) -> Self {
Self {
buffer: vec![0.0; capacity.max(2)],
write: 0,
delay: 0.0,
}
}
pub fn process(&mut self, input: f32, target: f32) -> f32 {
let ceiling = (self.buffer.len() - 2) as f32;
self.delay += (target.clamp(0.0, ceiling) - self.delay) * GLIDE;
self.buffer[self.write] = input;
let output = self.read(self.delay);
self.write = (self.write + 1) % self.buffer.len();
output
}
fn read(&self, delay: f32) -> f32 {
let length = self.buffer.len();
let position = self.write as f32 - delay;
let wrapped = position.rem_euclid(length as f32);
let index = wrapped.floor() as usize;
let fraction = wrapped - index as f32;
let next = (index + 1) % length;
self.buffer[index] * (1.0 - fraction) + self.buffer[next] * fraction
}
}
pub fn delay_samples(distance: f32, sample_rate: u32) -> f32 {
distance / SPEED_OF_SOUND * sample_rate as f32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zero_delay_passes_input_through() {
let mut line = DelayLine::new(64);
assert!((line.process(0.7, 0.0) - 0.7).abs() < 1e-6);
assert!((line.process(-0.3, 0.0) + 0.3).abs() < 1e-6);
}
#[test]
fn distance_maps_to_time_of_flight_in_samples() {
assert!((delay_samples(343.0, 48_000) - 48_000.0).abs() < 1e-3);
assert!(delay_samples(0.0, 48_000).abs() < 1e-6);
}
#[test]
fn delay_glides_toward_target_without_overshooting() {
let mut line = DelayLine::new(48_000);
let mut last = 0.0;
for _ in 0..1_000 {
line.process(0.0, 4_800.0);
assert!(line.delay >= last);
assert!(line.delay <= 4_800.0);
last = line.delay;
}
}
}