Skip to main content

alpha2_audio/
expander.rs

1#![expect(
2    clippy::cast_precision_loss,
3    reason = "sample rates are exact in `f32`"
4)]
5
6use crate::compressor::{
7    DetectorFilter, clamped_ratio, clamped_threshold, detected_peak, finite, positive,
8};
9use crate::control::Ramp;
10use crate::{Biquad, ProcessCtx, Processor, StateBlob, StateError};
11
12/// Deepest attenuation an expander renders, in decibels.
13pub const MAX_EXPANDER_RANGE_DB: f32 = 96.0;
14
15/// Longest hold an expander renders, in milliseconds.
16pub const MAX_HOLD_MS: f32 = 10_000.0;
17
18/// What an [`Expander`] is built from. Invalid values are replaced by conservative defaults
19/// and the rest clamped to what renders.
20#[derive(Copy, Clone, Debug, PartialEq)]
21pub struct ExpanderSettings {
22    /// Level below which attenuation begins, in decibels from -96 to 0.
23    pub threshold_db: f32,
24    /// Downward ratio below the threshold, from 1 to [`crate::MAX_RATIO`]: the output falls
25    /// this many decibels for each decibel the level falls.
26    pub ratio: f32,
27    /// Most attenuation, in decibels up to [`MAX_EXPANDER_RANGE_DB`].
28    pub range_db: f32,
29    /// Time the gain takes to open, in milliseconds.
30    pub attack_ms: f32,
31    /// How long the gain stays where it is after the level falls, in milliseconds up to
32    /// [`MAX_HOLD_MS`].
33    pub hold_ms: f32,
34    /// Time the gain takes to close, in milliseconds.
35    pub release_ms: f32,
36    /// Lookahead in milliseconds, up to 100; the expander's latency.
37    pub lookahead_ms: f32,
38    /// A filter before the detector.
39    pub detector_filter: Option<DetectorFilter>,
40}
41
42impl ExpanderSettings {
43    /// An expander with the full range and no hold, lookahead or detector filter.
44    #[must_use]
45    pub const fn new(threshold_db: f32, ratio: f32, attack_ms: f32, release_ms: f32) -> Self {
46        Self {
47            threshold_db,
48            ratio,
49            range_db: MAX_EXPANDER_RANGE_DB,
50            attack_ms,
51            hold_ms: 0.0,
52            release_ms,
53            lookahead_ms: 0.0,
54            detector_filter: None,
55        }
56    }
57}
58
59/// Linked-channel downward expander; with a high ratio, a gate.
60///
61/// The level is a peak follower with the attack and release times. Under the threshold `T` a
62/// level `x` in decibels asks for `min((T - x) (R - 1), range)` decibels of attenuation. The
63/// gain moves to what is asked with the attack time while it opens; when it must close it
64/// first holds for the hold time, then closes with the release time.
65///
66/// Retuned ([`Processor::control`]), its threshold, ratio and range move in a straight line
67/// from one control point's values to the next's.
68#[derive(Clone, Debug)]
69pub struct Expander {
70    curve: [f32; 3],
71    attack_ms: f32,
72    hold_ms: f32,
73    release_ms: f32,
74    lookahead_ms: f32,
75    filter: Option<Biquad>,
76    envelope: f32,
77    gain: f32,
78    holding: u32,
79    attack_coefficient: f32,
80    release_coefficient: f32,
81    hold_samples: u32,
82    open_at_or_over: f32,
83    delay: [Vec<f32>; 2],
84    cursor: usize,
85    latency: u32,
86    keyed: bool,
87    ramp: Option<(Ramp<3>, f32)>,
88}
89
90fn clamped_curve(values: &[f32]) -> Option<[f32; 3]> {
91    let &[threshold_db, ratio, range_db] = values else {
92        return None;
93    };
94    Some([
95        clamped_threshold(threshold_db),
96        clamped_ratio(ratio),
97        finite(range_db, MAX_EXPANDER_RANGE_DB).clamp(0.0, MAX_EXPANDER_RANGE_DB),
98    ])
99}
100
101fn open_at_or_over(threshold_db: f32) -> f32 {
102    libm::exp10f(threshold_db / 20.0) * (1.0 + 1.0e-4)
103}
104
105impl Expander {
106    /// Creates an expander.
107    #[must_use]
108    pub fn new(settings: ExpanderSettings) -> Self {
109        let curve = clamped_curve(&[settings.threshold_db, settings.ratio, settings.range_db])
110            .unwrap_or([0.0, 1.0, 0.0]);
111        Self {
112            curve,
113            attack_ms: positive(settings.attack_ms, 1.0),
114            hold_ms: finite(settings.hold_ms, 0.0).clamp(0.0, MAX_HOLD_MS),
115            release_ms: positive(settings.release_ms, 100.0),
116            lookahead_ms: finite(settings.lookahead_ms, 0.0).clamp(0.0, 100.0),
117            filter: DetectorFilter::build(settings.detector_filter),
118            envelope: 0.0,
119            gain: 1.0,
120            holding: 0,
121            attack_coefficient: 0.0,
122            release_coefficient: 0.0,
123            hold_samples: 0,
124            open_at_or_over: open_at_or_over(curve[0]),
125            delay: [Vec::new(), Vec::new()],
126            cursor: 0,
127            latency: 0,
128            keyed: false,
129            ramp: None,
130        }
131    }
132
133    /// Makes the level of a key drive the gain instead of the program's own: the inputs are
134    /// then the program channels followed by matching key channels.
135    #[must_use]
136    pub const fn keyed(mut self) -> Self {
137        self.keyed = true;
138        self
139    }
140
141    fn run(
142        &mut self,
143        inputs: &[&[f32]],
144        outputs: &mut [&mut [f32]],
145        curve_at_frame: impl Fn(usize) -> ([f32; 3], f32),
146    ) -> usize {
147        let planes = if self.keyed { 2 } else { 1 };
148        let channels = (inputs.len() / planes).min(outputs.len()).min(2);
149        let frames = inputs
150            .iter()
151            .take(channels * planes)
152            .map(|input| input.len())
153            .chain(outputs.iter().take(channels).map(|output| output.len()))
154            .min()
155            .unwrap_or(0);
156        if self.delay[0].is_empty() {
157            return 0;
158        }
159        let detected = (if self.keyed { channels } else { 0 }, channels);
160        for frame in 0..frames {
161            let ([threshold_db, ratio, range_db], open_at_or_over) = curve_at_frame(frame);
162            let peak = detected_peak(&mut self.filter, inputs, detected, frame);
163            if !self.envelope.is_finite() {
164                self.envelope = 0.0;
165            }
166            let coefficient = if peak > self.envelope {
167                self.attack_coefficient
168            } else {
169                self.release_coefficient
170            };
171            self.envelope = coefficient * self.envelope + (1.0 - coefficient) * peak;
172            if self.envelope < 1.0e-30 {
173                self.envelope = 0.0;
174            }
175            let target = if self.envelope >= open_at_or_over {
176                1.0
177            } else {
178                let level_db = 20.0 * libm::log10f(self.envelope.max(1.0e-12));
179                let under = threshold_db - level_db;
180                if under <= 0.0 {
181                    1.0
182                } else {
183                    libm::exp10f(-(under * (ratio - 1.0)).min(range_db) / 20.0)
184                }
185            };
186            if target >= self.gain {
187                self.holding = self.hold_samples;
188                self.gain =
189                    self.attack_coefficient * self.gain + (1.0 - self.attack_coefficient) * target;
190            } else if self.holding > 0 {
191                self.holding -= 1;
192            } else {
193                self.gain = self.release_coefficient * self.gain
194                    + (1.0 - self.release_coefficient) * target;
195            }
196            for channel in 0..channels {
197                let input = finite(inputs[channel][frame], 0.0);
198                let delayed = if self.latency == 0 {
199                    input
200                } else {
201                    let delayed = self.delay[channel][self.cursor];
202                    self.delay[channel][self.cursor] = input;
203                    finite(delayed, 0.0)
204                };
205                outputs[channel][frame] = delayed * self.gain;
206            }
207            if self.latency != 0 {
208                self.cursor = (self.cursor + 1) % self.delay[0].len();
209            }
210        }
211        frames
212    }
213}
214
215impl Processor for Expander {
216    /// The program, then the key when [`Expander::keyed`].
217    fn inputs_per_output(&self) -> usize {
218        if self.keyed { 2 } else { 1 }
219    }
220
221    /// The threshold in decibels, the ratio and the range in decibels.
222    fn control_params(&self) -> usize {
223        3
224    }
225
226    fn control(&mut self, span: &crate::ControlSpan<'_>) {
227        let (Some(from), Some(to)) = (clamped_curve(span.from), clamped_curve(span.to)) else {
228            return;
229        };
230        if span.is_steady() {
231            self.curve = from;
232            self.open_at_or_over = open_at_or_over(from[0]);
233            self.ramp = None;
234            return;
235        }
236        self.ramp = Some((
237            Ramp::between(from, to, span.phase),
238            open_at_or_over(from[0].max(to[0])),
239        ));
240    }
241
242    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
243        let rate = sample_rate.max(1) as f32;
244        self.attack_coefficient = libm::expf(-1.0 / (self.attack_ms * 0.001 * rate));
245        self.release_coefficient = libm::expf(-1.0 / (self.release_ms * 0.001 * rate));
246        #[expect(
247            clippy::cast_possible_truncation,
248            clippy::cast_sign_loss,
249            reason = "hold and lookahead are clamped, a few seconds at most"
250        )]
251        {
252            self.hold_samples = (self.hold_ms * 0.001 * rate).round() as u32;
253            self.latency = (self.lookahead_ms * 0.001 * rate).round() as u32;
254        }
255        let size = usize::try_from(self.latency).unwrap_or(0).max(1);
256        self.delay = [vec![0.0; size], vec![0.0; size]];
257        if let Some(filter) = &mut self.filter {
258            filter.prepare(sample_rate, 1);
259        }
260        self.reset();
261    }
262
263    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
264        match self.ramp {
265            None => {
266                let steady = (self.curve, self.open_at_or_over);
267                self.run(inputs, outputs, |_| steady);
268            }
269            Some((ramp, open_at_or_over)) => {
270                let frames = self.run(inputs, outputs, |frame| (ramp.at(frame), open_at_or_over));
271                self.ramp = Some((ramp.after(frames), open_at_or_over));
272            }
273        }
274    }
275
276    fn reset(&mut self) {
277        self.envelope = 0.0;
278        self.gain = 1.0;
279        self.holding = 0;
280        self.cursor = 0;
281        for channel in &mut self.delay {
282            channel.fill(0.0);
283        }
284        if let Some(filter) = &mut self.filter {
285            filter.reset();
286        }
287    }
288
289    fn latency_samples(&self) -> u32 {
290        self.latency
291    }
292
293    fn history_samples(&self) -> u32 {
294        crate::processor::settling_samples(f64::from(
295            self.attack_coefficient.max(self.release_coefficient),
296        ))
297        .saturating_add(self.hold_samples)
298        .saturating_add(self.filter.as_ref().map_or(0, Processor::history_samples))
299    }
300
301    fn save_state(&self) -> StateBlob {
302        let mut bytes = Vec::with_capacity(24 + self.delay.iter().map(Vec::len).sum::<usize>() * 4);
303        bytes.extend_from_slice(&self.envelope.to_le_bytes());
304        bytes.extend_from_slice(&self.gain.to_le_bytes());
305        bytes.extend_from_slice(&self.holding.to_le_bytes());
306        bytes.extend_from_slice(&(u64::try_from(self.cursor).unwrap_or(0)).to_le_bytes());
307        bytes.extend_from_slice(&self.latency.to_le_bytes());
308        for value in self.delay.iter().flatten() {
309            bytes.extend_from_slice(&value.to_le_bytes());
310        }
311        if let Some(filter) = &self.filter {
312            bytes.extend_from_slice(filter.save_state().as_bytes());
313        }
314        StateBlob::new(bytes)
315    }
316
317    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
318        let delayed = 24 + self.delay.iter().map(Vec::len).sum::<usize>() * 4;
319        let (bytes, filter_state) = state
320            .as_bytes()
321            .split_at_checked(delayed)
322            .ok_or(StateError::Mismatch)?;
323        let filter = match &self.filter {
324            Some(filter) => {
325                let mut loaded = filter.clone();
326                loaded.load_state(&StateBlob::new(filter_state.to_vec()))?;
327                Some(loaded)
328            }
329            None if filter_state.is_empty() => None,
330            None => return Err(StateError::Mismatch),
331        };
332        let word = |at: usize| -> [u8; 4] { bytes[at..at + 4].try_into().expect("fixed range") };
333        let envelope = f32::from_le_bytes(word(0));
334        let gain = f32::from_le_bytes(word(4));
335        let holding = u32::from_le_bytes(word(8));
336        let cursor = usize::try_from(u64::from_le_bytes(
337            bytes[12..20].try_into().expect("fixed range"),
338        ))
339        .ok();
340        if u32::from_le_bytes(word(20)) != self.latency {
341            return Err(StateError::Mismatch);
342        }
343        let values = bytes[24..]
344            .as_chunks::<4>()
345            .0
346            .iter()
347            .map(|word| f32::from_le_bytes(*word));
348        let level_and_gain_hold =
349            envelope.is_finite() && envelope >= 0.0 && (0.0..=1.0).contains(&gain);
350        if !level_and_gain_hold
351            || holding > self.hold_samples
352            || cursor.is_none_or(|value| value >= self.delay[0].len())
353            || values.clone().any(|value| !value.is_finite())
354        {
355            return Err(StateError::Invalid);
356        }
357        (self.envelope, self.gain, self.holding) = (envelope, gain, holding);
358        self.cursor = cursor.unwrap_or(0);
359        for (target, value) in self.delay.iter_mut().flatten().zip(values) {
360            *target = value;
361        }
362        self.filter = filter;
363        Ok(())
364    }
365}