Skip to main content

alpha2_audio/
compressor.rs

1#![allow(clippy::cast_precision_loss)]
2
3use crate::{Biquad, BiquadKind, ProcessCtx, Processor, StateBlob, StateError};
4
5/// Largest ratio a compressor or expander renders.
6pub const MAX_RATIO: f32 = 100.0;
7
8/// Widest knee a compressor renders, in decibels.
9pub const MAX_KNEE_DB: f32 = 24.0;
10
11/// Largest makeup gain a compressor renders, in decibels either way.
12pub const MAX_MAKEUP_DB: f32 = 24.0;
13
14/// How a compressor measures the level it compresses by.
15#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
16pub enum Detector {
17    /// The largest sample magnitude, smoothed by the attack and release.
18    #[default]
19    Peak,
20    /// The square root of the mean square, smoothed by the attack and release: a sine reads
21    /// 3 dB under its peak.
22    Rms,
23}
24
25/// One static filter a compressor or expander puts before its level detector, so that only a
26/// band of the detected signal drives the gain.
27#[derive(Copy, Clone, Debug, PartialEq)]
28pub struct DetectorFilter {
29    /// Filter shape. The gain of a peaking or shelving shape is 0 dB.
30    pub kind: BiquadKind,
31    /// Centre or corner frequency in hertz.
32    pub frequency_hz: f32,
33    /// Resonance.
34    pub q: f32,
35}
36
37impl DetectorFilter {
38    pub(crate) fn build(filter: Option<Self>) -> Option<Biquad> {
39        filter.map(|filter| Biquad::new(filter.kind, filter.frequency_hz, filter.q, 0.0))
40    }
41}
42
43/// What a [`Compressor`] is built from. Invalid values are replaced by conservative defaults
44/// and the rest clamped to what renders.
45#[derive(Copy, Clone, Debug, PartialEq)]
46pub struct CompressorSettings {
47    /// Level above which gain reduction begins, in decibels from -96 to 0.
48    pub threshold_db: f32,
49    /// Downward ratio, from 1 to [`MAX_RATIO`].
50    pub ratio: f32,
51    /// Width of the knee centred on the threshold, in decibels up to [`MAX_KNEE_DB`]; 0 is a
52    /// hard knee.
53    pub knee_db: f32,
54    /// Gain applied after the reduction, in decibels up to [`MAX_MAKEUP_DB`] either way.
55    pub makeup_db: f32,
56    /// Attack time in milliseconds.
57    pub attack_ms: f32,
58    /// Release time in milliseconds.
59    pub release_ms: f32,
60    /// Lookahead in milliseconds, up to 100; the compressor's latency.
61    pub lookahead_ms: f32,
62    /// How the level is measured.
63    pub detector: Detector,
64    /// A filter before the detector.
65    pub detector_filter: Option<DetectorFilter>,
66}
67
68impl CompressorSettings {
69    /// A hard-knee peak compressor with no makeup gain, lookahead or detector filter.
70    #[must_use]
71    pub const fn new(threshold_db: f32, ratio: f32, attack_ms: f32, release_ms: f32) -> Self {
72        Self {
73            threshold_db,
74            ratio,
75            knee_db: 0.0,
76            makeup_db: 0.0,
77            attack_ms,
78            release_ms,
79            lookahead_ms: 0.0,
80            detector: Detector::Peak,
81            detector_filter: None,
82        }
83    }
84
85    /// These settings with a lookahead in milliseconds.
86    #[must_use]
87    pub const fn lookahead(mut self, lookahead_ms: f32) -> Self {
88        self.lookahead_ms = lookahead_ms;
89        self
90    }
91}
92
93/// Linked-channel compressor with deterministic lookahead and soft attack/release.
94///
95/// The static curve is the one of Giannoulis, Massberg and Reiss (2012): with level `x`,
96/// threshold `T`, ratio `R` and knee `W` in decibels, the gain is 0 dB while `2 (x - T) < -W`,
97/// `(1/R - 1) (x - T + W/2)^2 / (2 W)` while `2 |x - T| <= W`, and `T + (x - T) / R - x` above.
98///
99/// Retuned ([`Processor::control`]), its threshold, ratio and knee and the linear gain of its
100/// makeup move in a straight line from one control point's values to the next's.
101#[derive(Clone, Debug)]
102pub struct Compressor {
103    threshold_db: f32,
104    ratio: f32,
105    knee_db: f32,
106    makeup_db: f32,
107    makeup: f32,
108    attack_ms: f32,
109    release_ms: f32,
110    lookahead_ms: f32,
111    detector: Detector,
112    filter: Option<Biquad>,
113    envelope: f32,
114    attack_coefficient: f32,
115    release_coefficient: f32,
116    /// Linear threshold; envelopes at or under it skip the logarithm.
117    threshold_amplitude: f32,
118    delay: [Vec<f32>; 2],
119    cursor: usize,
120    latency: u32,
121    bypass: bool,
122    keyed: bool,
123    ramp: Option<CurveRamp>,
124}
125
126#[derive(Clone, Copy, Debug)]
127struct Curve {
128    threshold_db: f32,
129    ratio: f32,
130    knee_db: f32,
131    makeup: f32,
132    unity_at_or_under: f32,
133}
134
135#[derive(Clone, Copy, Debug)]
136struct CurveRamp {
137    from: [f32; 4],
138    change: [f32; 4],
139    unity_at_or_under: f32,
140    phase: usize,
141}
142
143impl CurveRamp {
144    fn at(&self, frame: usize) -> Curve {
145        let progress = crate::control::progress(self.phase, frame);
146        let [threshold_db, ratio, knee_db, makeup] =
147            core::array::from_fn(|index| self.from[index] + self.change[index] * progress);
148        Curve {
149            threshold_db,
150            ratio,
151            knee_db,
152            makeup,
153            unity_at_or_under: self.unity_at_or_under,
154        }
155    }
156}
157
158impl Compressor {
159    /// Creates a compressor.
160    #[must_use]
161    pub fn new(settings: CompressorSettings) -> Self {
162        let makeup_db = clamped_makeup(settings.makeup_db);
163        Self {
164            threshold_db: clamped_threshold(settings.threshold_db),
165            ratio: clamped_ratio(settings.ratio),
166            knee_db: clamped_knee(settings.knee_db),
167            makeup_db,
168            makeup: libm::exp10f(makeup_db / 20.0),
169            attack_ms: positive(settings.attack_ms, 10.0),
170            release_ms: positive(settings.release_ms, 100.0),
171            lookahead_ms: finite(settings.lookahead_ms, 0.0).clamp(0.0, 100.0),
172            detector: settings.detector,
173            filter: DetectorFilter::build(settings.detector_filter),
174            envelope: 0.0,
175            attack_coefficient: 0.0,
176            release_coefficient: 0.0,
177            threshold_amplitude: 0.0,
178            delay: [Vec::new(), Vec::new()],
179            cursor: 0,
180            latency: 0,
181            bypass: false,
182            keyed: false,
183            ramp: None,
184        }
185    }
186
187    /// Makes the level of a key drive the reduction instead of the program's own: the inputs are
188    /// then the program channels followed by matching key channels.
189    #[must_use]
190    pub const fn keyed(mut self) -> Self {
191        self.keyed = true;
192        self
193    }
194
195    /// Enables latency-preserving bypass.
196    pub fn set_bypass(&mut self, bypass: bool) {
197        self.bypass = bypass;
198    }
199}
200
201#[inline]
202pub(crate) fn detected_peak(
203    filter: &mut Option<Biquad>,
204    inputs: &[&[f32]],
205    (first, channels): (usize, usize),
206    frame: usize,
207) -> f32 {
208    let Some(filter) = filter else {
209        return inputs[first..first + channels]
210            .iter()
211            .map(|channel| finite(channel[frame], 0.0).abs())
212            .fold(0.0_f32, f32::max);
213    };
214    let mut peak = 0.0_f32;
215    for channel in 0..channels {
216        let detected = filter.detect(channel, finite(inputs[first + channel][frame], 0.0));
217        peak = peak.max(detected.abs());
218    }
219    peak
220}
221
222impl Compressor {
223    fn run<const PLAIN: bool>(
224        &mut self,
225        inputs: &[&[f32]],
226        outputs: &mut [&mut [f32]],
227        curve_at_frame: impl Fn(usize) -> Curve,
228    ) -> usize {
229        let planes = if self.keyed { 2 } else { 1 };
230        let channels = (inputs.len() / planes).min(outputs.len()).min(2);
231        let frames = inputs
232            .iter()
233            .take(channels * planes)
234            .map(|input| input.len())
235            .chain(outputs.iter().take(channels).map(|output| output.len()))
236            .min()
237            .unwrap_or(0);
238        if self.delay[0].is_empty() {
239            return 0;
240        }
241        let detector = if self.keyed { channels } else { 0 };
242        let rms = !PLAIN && self.detector == Detector::Rms;
243        for frame in 0..frames {
244            let curve = curve_at_frame(frame);
245            let peak = if PLAIN {
246                inputs[detector..detector + channels]
247                    .iter()
248                    .map(|channel| finite(channel[frame], 0.0).abs())
249                    .fold(0.0_f32, f32::max)
250            } else {
251                detected_peak(&mut self.filter, inputs, (detector, channels), frame)
252            };
253            let measured = if rms { peak * peak } else { peak };
254            if !self.envelope.is_finite() {
255                self.envelope = 0.0;
256            }
257            let coefficient = if measured > self.envelope {
258                self.attack_coefficient
259            } else {
260                self.release_coefficient
261            };
262            self.envelope = coefficient * self.envelope + (1.0 - coefficient) * measured;
263            // Keep a released envelope out of the slow subnormal range.
264            if self.envelope < 1.0e-30 {
265                self.envelope = 0.0;
266            }
267            let level = if rms {
268                libm::sqrtf(self.envelope)
269            } else {
270                self.envelope
271            };
272            // Under the threshold the gain is exactly one. Over it, `exp10f` is as portable as
273            // `powf(10, x)` and about nine times cheaper.
274            let reduction_db = if level <= curve.unity_at_or_under {
275                0.0
276            } else {
277                let level_db = 20.0 * libm::log10f(level.max(1.0e-12));
278                if !PLAIN && curve.knee_db > 0.0 {
279                    let over = level_db - curve.threshold_db;
280                    if 2.0 * over < -curve.knee_db {
281                        0.0
282                    } else if 2.0 * over.abs() <= curve.knee_db {
283                        let into_knee = over + curve.knee_db / 2.0;
284                        (1.0 / curve.ratio - 1.0) * into_knee * into_knee / (2.0 * curve.knee_db)
285                    } else {
286                        (curve.threshold_db + over / curve.ratio) - level_db
287                    }
288                } else if level_db > curve.threshold_db {
289                    (curve.threshold_db + (level_db - curve.threshold_db) / curve.ratio) - level_db
290                } else {
291                    0.0
292                }
293            };
294            let gain = if self.bypass || (PLAIN && reduction_db == 0.0) {
295                1.0
296            } else if PLAIN {
297                libm::exp10f(reduction_db / 20.0)
298            } else if reduction_db == 0.0 {
299                curve.makeup
300            } else {
301                libm::exp10f(reduction_db / 20.0) * curve.makeup
302            };
303            for channel in 0..channels {
304                let input = finite(inputs[channel][frame], 0.0);
305                let delayed = if self.latency == 0 {
306                    input
307                } else {
308                    let delayed = self.delay[channel][self.cursor];
309                    self.delay[channel][self.cursor] = input;
310                    finite(delayed, 0.0)
311                };
312                outputs[channel][frame] = delayed * gain;
313            }
314            if self.latency != 0 {
315                self.cursor = (self.cursor + 1) % self.delay[0].len();
316            }
317        }
318        frames
319    }
320
321    fn curve(&self) -> [f32; 4] {
322        [self.threshold_db, self.ratio, self.knee_db, self.makeup]
323    }
324}
325
326fn clamped_curve(values: &[f32]) -> Option<([f32; 4], f32)> {
327    let &[threshold_db, ratio, knee_db, makeup_db] = values else {
328        return None;
329    };
330    let makeup_db = clamped_makeup(makeup_db);
331    Some((
332        [
333            clamped_threshold(threshold_db),
334            clamped_ratio(ratio),
335            clamped_knee(knee_db),
336            libm::exp10f(makeup_db / 20.0),
337        ],
338        makeup_db,
339    ))
340}
341
342impl Processor for Compressor {
343    /// The program, then the key when [`Compressor::keyed`].
344    fn inputs_per_output(&self) -> usize {
345        if self.keyed { 2 } else { 1 }
346    }
347
348    /// The threshold in decibels, the ratio, the knee in decibels and the makeup gain in
349    /// decibels.
350    fn control_params(&self) -> usize {
351        4
352    }
353
354    fn control(&mut self, span: &crate::ControlSpan<'_>) {
355        let (Some((from, makeup_db)), Some((to, _))) =
356            (clamped_curve(span.from), clamped_curve(span.to))
357        else {
358            return;
359        };
360        if span.is_steady() {
361            if from.map(f32::to_bits) != self.curve().map(f32::to_bits) {
362                self.threshold_amplitude = threshold_amplitude(from[0] - from[2] / 2.0);
363            }
364            [self.threshold_db, self.ratio, self.knee_db, self.makeup] = from;
365            self.makeup_db = makeup_db;
366            self.ramp = None;
367            return;
368        }
369        let knee_starts = |curve: [f32; 4]| curve[0] - curve[2] / 2.0;
370        self.ramp = Some(CurveRamp {
371            from,
372            change: core::array::from_fn(|index| to[index] - from[index]),
373            unity_at_or_under: threshold_amplitude(knee_starts(from).min(knee_starts(to))),
374            phase: span.phase,
375        });
376    }
377
378    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
379        let rate = sample_rate.max(1) as f32;
380        self.attack_coefficient = libm::expf(-1.0 / (self.attack_ms * 0.001 * rate));
381        self.release_coefficient = libm::expf(-1.0 / (self.release_ms * 0.001 * rate));
382        self.threshold_amplitude = threshold_amplitude(self.threshold_db - self.knee_db / 2.0);
383        if let Some(filter) = &mut self.filter {
384            filter.prepare(sample_rate, 1);
385        }
386        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
387        {
388            self.latency = (self.lookahead_ms * 0.001 * rate).round() as u32;
389        }
390        let size = usize::try_from(self.latency).unwrap_or(0).max(1);
391        self.delay = [vec![0.0; size], vec![0.0; size]];
392        self.cursor = 0;
393    }
394
395    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
396        match self.ramp {
397            None => {
398                let steady = Curve {
399                    threshold_db: self.threshold_db,
400                    ratio: self.ratio,
401                    knee_db: self.knee_db,
402                    makeup: self.makeup,
403                    unity_at_or_under: self.threshold_amplitude,
404                };
405                let as_before_these_settings = self.filter.is_none()
406                    && self.detector == Detector::Peak
407                    && self.knee_db == 0.0
408                    && self.makeup_db == 0.0;
409                if as_before_these_settings {
410                    self.run::<true>(inputs, outputs, |_| steady);
411                } else {
412                    self.run::<false>(inputs, outputs, |_| steady);
413                }
414            }
415            Some(ramp) => {
416                let frames = self.run::<false>(inputs, outputs, |frame| ramp.at(frame));
417                self.ramp = Some(CurveRamp {
418                    phase: ramp.phase.saturating_add(frames),
419                    ..ramp
420                });
421            }
422        }
423    }
424
425    fn reset(&mut self) {
426        self.envelope = 0.0;
427        self.cursor = 0;
428        for channel in &mut self.delay {
429            channel.fill(0.0);
430        }
431        if let Some(filter) = &mut self.filter {
432            filter.reset();
433        }
434    }
435    fn latency_samples(&self) -> u32 {
436        self.latency
437    }
438    fn history_samples(&self) -> u32 {
439        if self.ratio <= 1.0 {
440            return 0;
441        }
442        crate::processor::settling_samples(f64::from(
443            self.attack_coefficient.max(self.release_coefficient),
444        ))
445        .saturating_add(self.filter.as_ref().map_or(0, Processor::history_samples))
446    }
447    fn save_state(&self) -> StateBlob {
448        let mut bytes = Vec::with_capacity(16 + self.delay.iter().map(Vec::len).sum::<usize>() * 4);
449        bytes.extend_from_slice(&self.envelope.to_le_bytes());
450        bytes.extend_from_slice(&(u64::try_from(self.cursor).unwrap_or(0)).to_le_bytes());
451        bytes.extend_from_slice(&self.latency.to_le_bytes());
452        for channel in &self.delay {
453            for value in channel {
454                bytes.extend_from_slice(&value.to_le_bytes());
455            }
456        }
457        if let Some(filter) = &self.filter {
458            bytes.extend_from_slice(filter.save_state().as_bytes());
459        }
460        StateBlob::new(bytes)
461    }
462    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
463        let delayed = 16 + self.delay.iter().map(Vec::len).sum::<usize>() * 4;
464        let (bytes, filter_state) = state
465            .as_bytes()
466            .split_at_checked(delayed)
467            .ok_or(StateError::Mismatch)?;
468        let filter = match &self.filter {
469            Some(filter) => {
470                let mut loaded = filter.clone();
471                loaded.load_state(&StateBlob::new(filter_state.to_vec()))?;
472                Some(loaded)
473            }
474            None if filter_state.is_empty() => None,
475            None => return Err(StateError::Mismatch),
476        };
477        let envelope = f32::from_le_bytes(bytes[0..4].try_into().expect("fixed range"));
478        let cursor = usize::try_from(u64::from_le_bytes(
479            bytes[4..12].try_into().expect("fixed range"),
480        ))
481        .ok();
482        let latency = u32::from_le_bytes(bytes[12..16].try_into().expect("fixed range"));
483        if latency != self.latency {
484            return Err(StateError::Mismatch);
485        }
486        let values = bytes[16..]
487            .as_chunks::<4>()
488            .0
489            .iter()
490            .map(|word| f32::from_le_bytes(*word));
491        if !envelope.is_finite()
492            || envelope < 0.0
493            || cursor.is_none_or(|value| value >= self.delay[0].len())
494            || values.clone().any(|value| !value.is_finite())
495        {
496            return Err(StateError::Invalid);
497        }
498        self.envelope = envelope;
499        self.cursor = cursor.unwrap_or(0);
500        for (target, value) in self.delay.iter_mut().flatten().zip(values) {
501            *target = value;
502        }
503        self.filter = filter;
504        Ok(())
505    }
506}
507
508pub(crate) fn finite(value: f32, fallback: f32) -> f32 {
509    if value.is_finite() { value } else { fallback }
510}
511pub(crate) fn clamped_threshold(threshold_db: f32) -> f32 {
512    finite(threshold_db, -12.0).clamp(-96.0, 0.0)
513}
514pub(crate) fn clamped_ratio(ratio: f32) -> f32 {
515    finite(ratio, 4.0).clamp(1.0, MAX_RATIO)
516}
517fn clamped_knee(knee_db: f32) -> f32 {
518    finite(knee_db, 0.0).clamp(0.0, MAX_KNEE_DB)
519}
520fn clamped_makeup(makeup_db: f32) -> f32 {
521    finite(makeup_db, 0.0).clamp(-MAX_MAKEUP_DB, MAX_MAKEUP_DB)
522}
523fn threshold_amplitude(threshold_db: f32) -> f32 {
524    // Rounded down slightly so the decibel comparison below still decides borderline cases.
525    libm::exp10f(threshold_db / 20.0) * (1.0 - 1.0e-4)
526}
527pub(crate) fn positive(value: f32, fallback: f32) -> f32 {
528    let value = finite(value, fallback);
529    if value > 0.0 { value } else { fallback }
530}