Skip to main content

alpha2_audio/
delay.rs

1#![expect(
2    clippy::cast_precision_loss,
3    reason = "sample rates are exact in `f32`"
4)]
5
6use crate::biquad::flush_denormal;
7use crate::control::Ramp;
8use crate::{ProcessCtx, Processor, StateBlob, StateError};
9
10/// Longest time a [`Delay`] renders, in milliseconds; the shortest is one.
11pub const MAX_DELAY_MS: f32 = 2_000.0;
12
13/// Most feedback a [`Delay`] renders.
14pub const MAX_DELAY_FEEDBACK: f32 = 0.95;
15
16/// A feedback delay line on up to two channels.
17///
18/// Each channel repeats after the delay time: with the sample `x` and the line's oldest sample
19/// `d`, the line takes `x + feedback * d` and the output is `x * (1 - mix) + d * mix`. It adds
20/// no latency.
21///
22/// Retuned ([`Processor::control`]), its feedback and mix move in a straight line from one
23/// control point's values to the next's.
24#[derive(Clone, Debug)]
25pub struct Delay {
26    time_ms: f32,
27    feedback_and_mix: [f32; 2],
28    lines: [Vec<f32>; 2],
29    cursor: usize,
30    ramp: Option<Ramp<2>>,
31}
32
33fn clamped(values: &[f32]) -> Option<[f32; 2]> {
34    let &[feedback, mix] = values else {
35        return None;
36    };
37    let finite = |value: f32| if value.is_finite() { value } else { 0.0 };
38    Some([
39        finite(feedback).clamp(0.0, MAX_DELAY_FEEDBACK),
40        finite(mix).clamp(0.0, 1.0),
41    ])
42}
43
44impl Delay {
45    /// Creates a delay of `time_ms` milliseconds, clamped to 1 to [`MAX_DELAY_MS`], with
46    /// `feedback` clamped to 0 to [`MAX_DELAY_FEEDBACK`] and `mix` to 0 to 1. A non-finite time
47    /// becomes 250 ms and non-finite feedback or mix 0.
48    #[must_use]
49    pub fn new(time_ms: f32, feedback: f32, mix: f32) -> Self {
50        Self {
51            time_ms: if time_ms.is_finite() { time_ms } else { 250.0 }.clamp(1.0, MAX_DELAY_MS),
52            feedback_and_mix: clamped(&[feedback, mix]).unwrap_or([0.0; 2]),
53            lines: [Vec::new(), Vec::new()],
54            cursor: 0,
55            ramp: None,
56        }
57    }
58
59    fn run(
60        &mut self,
61        inputs: &[&[f32]],
62        outputs: &mut [&mut [f32]],
63        feedback_and_mix_at_frame: impl Fn(usize) -> [f32; 2],
64    ) -> usize {
65        let channels = inputs.len().min(outputs.len()).min(2);
66        let frames = inputs
67            .iter()
68            .take(channels)
69            .map(|input| input.len())
70            .chain(outputs.iter().take(channels).map(|output| output.len()))
71            .min()
72            .unwrap_or(0);
73        let length = self.lines[0].len();
74        if length == 0 {
75            return 0;
76        }
77        for frame in 0..frames {
78            let [feedback, mix] = feedback_and_mix_at_frame(frame);
79            for channel in 0..channels {
80                let input = inputs[channel][frame];
81                let input = if input.is_finite() { input } else { 0.0 };
82                let delayed = self.lines[channel][self.cursor];
83                self.lines[channel][self.cursor] = flush_denormal(input + feedback * delayed);
84                outputs[channel][frame] = input * (1.0 - mix) + delayed * mix;
85            }
86            self.cursor = (self.cursor + 1) % length;
87        }
88        frames
89    }
90}
91
92impl Processor for Delay {
93    /// The feedback and the mix.
94    fn control_params(&self) -> usize {
95        2
96    }
97
98    fn control(&mut self, span: &crate::ControlSpan<'_>) {
99        let (Some(from), Some(to)) = (clamped(span.from), clamped(span.to)) else {
100            return;
101        };
102        if span.is_steady() {
103            self.feedback_and_mix = from;
104            self.ramp = None;
105        } else {
106            self.ramp = Some(Ramp::between(from, to, span.phase));
107        }
108    }
109
110    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
111        #[expect(
112            clippy::cast_possible_truncation,
113            clippy::cast_sign_loss,
114            reason = "the delay time is clamped to 1 ms and up"
115        )]
116        let length = ((self.time_ms * 0.001 * sample_rate.max(1) as f32).round() as usize).max(1);
117        self.lines = [vec![0.0; length], vec![0.0; length]];
118        self.cursor = 0;
119    }
120
121    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
122        match self.ramp {
123            None => {
124                let steady = self.feedback_and_mix;
125                self.run(inputs, outputs, |_| steady);
126            }
127            Some(ramp) => {
128                let frames = self.run(inputs, outputs, |frame| ramp.at(frame));
129                self.ramp = Some(ramp.after(frames));
130            }
131        }
132    }
133
134    fn reset(&mut self) {
135        for line in &mut self.lines {
136            line.fill(0.0);
137        }
138        self.cursor = 0;
139    }
140
141    fn history_samples(&self) -> u32 {
142        let length = u32::try_from(self.lines[0].len()).unwrap_or(u32::MAX);
143        let feedback = f64::from(self.feedback_and_mix[0]);
144        if feedback <= 0.0 {
145            return length;
146        }
147        #[expect(
148            clippy::cast_possible_truncation,
149            clippy::cast_sign_loss,
150            reason = "feedback is clamped below 1, so the count is small"
151        )]
152        let repeats = libm::ceil(32.0 / -libm::log(feedback)) as u32;
153        length.saturating_mul(repeats)
154    }
155
156    fn save_state(&self) -> StateBlob {
157        let mut bytes = Vec::with_capacity(8 + self.lines.iter().map(Vec::len).sum::<usize>() * 4);
158        bytes.extend_from_slice(&(u64::try_from(self.cursor).unwrap_or(0)).to_le_bytes());
159        for value in self.lines.iter().flatten() {
160            bytes.extend_from_slice(&value.to_le_bytes());
161        }
162        StateBlob::new(bytes)
163    }
164
165    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
166        let bytes = state.as_bytes();
167        if bytes.len() != 8 + self.lines.iter().map(Vec::len).sum::<usize>() * 4 {
168            return Err(StateError::Mismatch);
169        }
170        let cursor = usize::try_from(u64::from_le_bytes(
171            bytes[..8].try_into().expect("fixed range"),
172        ))
173        .ok();
174        let values = bytes[8..]
175            .as_chunks::<4>()
176            .0
177            .iter()
178            .map(|word| f32::from_le_bytes(*word));
179        if cursor.is_none_or(|cursor| cursor >= self.lines[0].len().max(1))
180            || values.clone().any(|value| !value.is_finite())
181        {
182            return Err(StateError::Invalid);
183        }
184        self.cursor = cursor.unwrap_or(0);
185        for (target, value) in self.lines.iter_mut().flatten().zip(values) {
186            *target = value;
187        }
188        Ok(())
189    }
190}