alpha2-audio 0.9.0

Platform-independent audio DSP core for alpha2.
Documentation
#![expect(
    clippy::cast_precision_loss,
    reason = "sample rates are exact in `f32`"
)]

use crate::compressor::{
    DetectorFilter, clamped_ratio, clamped_threshold, detected_peak, finite, positive,
};
use crate::control::Ramp;
use crate::{Biquad, ProcessCtx, Processor, StateBlob, StateError};

/// Deepest attenuation an expander renders, in decibels.
pub const MAX_EXPANDER_RANGE_DB: f32 = 96.0;

/// Longest hold an expander renders, in milliseconds.
pub const MAX_HOLD_MS: f32 = 10_000.0;

/// What an [`Expander`] is built from. Invalid values are replaced by conservative defaults
/// and the rest clamped to what renders.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ExpanderSettings {
    /// Level below which attenuation begins, in decibels from -96 to 0.
    pub threshold_db: f32,
    /// Downward ratio below the threshold, from 1 to [`crate::MAX_RATIO`]: the output falls
    /// this many decibels for each decibel the level falls.
    pub ratio: f32,
    /// Most attenuation, in decibels up to [`MAX_EXPANDER_RANGE_DB`].
    pub range_db: f32,
    /// Time the gain takes to open, in milliseconds.
    pub attack_ms: f32,
    /// How long the gain stays where it is after the level falls, in milliseconds up to
    /// [`MAX_HOLD_MS`].
    pub hold_ms: f32,
    /// Time the gain takes to close, in milliseconds.
    pub release_ms: f32,
    /// Lookahead in milliseconds, up to 100; the expander's latency.
    pub lookahead_ms: f32,
    /// A filter before the detector.
    pub detector_filter: Option<DetectorFilter>,
}

impl ExpanderSettings {
    /// An expander with the full range and no hold, lookahead or detector filter.
    #[must_use]
    pub const fn new(threshold_db: f32, ratio: f32, attack_ms: f32, release_ms: f32) -> Self {
        Self {
            threshold_db,
            ratio,
            range_db: MAX_EXPANDER_RANGE_DB,
            attack_ms,
            hold_ms: 0.0,
            release_ms,
            lookahead_ms: 0.0,
            detector_filter: None,
        }
    }
}

/// Linked-channel downward expander; with a high ratio, a gate.
///
/// The level is a peak follower with the attack and release times. Under the threshold `T` a
/// level `x` in decibels asks for `min((T - x) (R - 1), range)` decibels of attenuation. The
/// gain moves to what is asked with the attack time while it opens; when it must close it
/// first holds for the hold time, then closes with the release time.
///
/// Retuned ([`Processor::control`]), its threshold, ratio and range move in a straight line
/// from one control point's values to the next's.
#[derive(Clone, Debug)]
pub struct Expander {
    curve: [f32; 3],
    attack_ms: f32,
    hold_ms: f32,
    release_ms: f32,
    lookahead_ms: f32,
    filter: Option<Biquad>,
    envelope: f32,
    gain: f32,
    holding: u32,
    attack_coefficient: f32,
    release_coefficient: f32,
    hold_samples: u32,
    open_at_or_over: f32,
    delay: [Vec<f32>; 2],
    cursor: usize,
    latency: u32,
    keyed: bool,
    ramp: Option<(Ramp<3>, f32)>,
}

fn clamped_curve(values: &[f32]) -> Option<[f32; 3]> {
    let &[threshold_db, ratio, range_db] = values else {
        return None;
    };
    Some([
        clamped_threshold(threshold_db),
        clamped_ratio(ratio),
        finite(range_db, MAX_EXPANDER_RANGE_DB).clamp(0.0, MAX_EXPANDER_RANGE_DB),
    ])
}

fn open_at_or_over(threshold_db: f32) -> f32 {
    libm::exp10f(threshold_db / 20.0) * (1.0 + 1.0e-4)
}

impl Expander {
    /// Creates an expander.
    #[must_use]
    pub fn new(settings: ExpanderSettings) -> Self {
        let curve = clamped_curve(&[settings.threshold_db, settings.ratio, settings.range_db])
            .unwrap_or([0.0, 1.0, 0.0]);
        Self {
            curve,
            attack_ms: positive(settings.attack_ms, 1.0),
            hold_ms: finite(settings.hold_ms, 0.0).clamp(0.0, MAX_HOLD_MS),
            release_ms: positive(settings.release_ms, 100.0),
            lookahead_ms: finite(settings.lookahead_ms, 0.0).clamp(0.0, 100.0),
            filter: DetectorFilter::build(settings.detector_filter),
            envelope: 0.0,
            gain: 1.0,
            holding: 0,
            attack_coefficient: 0.0,
            release_coefficient: 0.0,
            hold_samples: 0,
            open_at_or_over: open_at_or_over(curve[0]),
            delay: [Vec::new(), Vec::new()],
            cursor: 0,
            latency: 0,
            keyed: false,
            ramp: None,
        }
    }

    /// Makes the level of a key drive the gain instead of the program's own: the inputs are
    /// then the program channels followed by matching key channels.
    #[must_use]
    pub const fn keyed(mut self) -> Self {
        self.keyed = true;
        self
    }

    fn run(
        &mut self,
        inputs: &[&[f32]],
        outputs: &mut [&mut [f32]],
        curve_at_frame: impl Fn(usize) -> ([f32; 3], f32),
    ) -> usize {
        let planes = if self.keyed { 2 } else { 1 };
        let channels = (inputs.len() / planes).min(outputs.len()).min(2);
        let frames = inputs
            .iter()
            .take(channels * planes)
            .map(|input| input.len())
            .chain(outputs.iter().take(channels).map(|output| output.len()))
            .min()
            .unwrap_or(0);
        if self.delay[0].is_empty() {
            return 0;
        }
        let detected = (if self.keyed { channels } else { 0 }, channels);
        for frame in 0..frames {
            let ([threshold_db, ratio, range_db], open_at_or_over) = curve_at_frame(frame);
            let peak = detected_peak(&mut self.filter, inputs, detected, frame);
            if !self.envelope.is_finite() {
                self.envelope = 0.0;
            }
            let coefficient = if peak > self.envelope {
                self.attack_coefficient
            } else {
                self.release_coefficient
            };
            self.envelope = coefficient * self.envelope + (1.0 - coefficient) * peak;
            if self.envelope < 1.0e-30 {
                self.envelope = 0.0;
            }
            let target = if self.envelope >= open_at_or_over {
                1.0
            } else {
                let level_db = 20.0 * libm::log10f(self.envelope.max(1.0e-12));
                let under = threshold_db - level_db;
                if under <= 0.0 {
                    1.0
                } else {
                    libm::exp10f(-(under * (ratio - 1.0)).min(range_db) / 20.0)
                }
            };
            if target >= self.gain {
                self.holding = self.hold_samples;
                self.gain =
                    self.attack_coefficient * self.gain + (1.0 - self.attack_coefficient) * target;
            } else if self.holding > 0 {
                self.holding -= 1;
            } else {
                self.gain = self.release_coefficient * self.gain
                    + (1.0 - self.release_coefficient) * target;
            }
            for channel in 0..channels {
                let input = finite(inputs[channel][frame], 0.0);
                let delayed = if self.latency == 0 {
                    input
                } else {
                    let delayed = self.delay[channel][self.cursor];
                    self.delay[channel][self.cursor] = input;
                    finite(delayed, 0.0)
                };
                outputs[channel][frame] = delayed * self.gain;
            }
            if self.latency != 0 {
                self.cursor = (self.cursor + 1) % self.delay[0].len();
            }
        }
        frames
    }
}

impl Processor for Expander {
    /// The program, then the key when [`Expander::keyed`].
    fn inputs_per_output(&self) -> usize {
        if self.keyed { 2 } else { 1 }
    }

    /// The threshold in decibels, the ratio and the range in decibels.
    fn control_params(&self) -> usize {
        3
    }

    fn control(&mut self, span: &crate::ControlSpan<'_>) {
        let (Some(from), Some(to)) = (clamped_curve(span.from), clamped_curve(span.to)) else {
            return;
        };
        if span.is_steady() {
            self.curve = from;
            self.open_at_or_over = open_at_or_over(from[0]);
            self.ramp = None;
            return;
        }
        self.ramp = Some((
            Ramp::between(from, to, span.phase),
            open_at_or_over(from[0].max(to[0])),
        ));
    }

    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
        let rate = sample_rate.max(1) as f32;
        self.attack_coefficient = libm::expf(-1.0 / (self.attack_ms * 0.001 * rate));
        self.release_coefficient = libm::expf(-1.0 / (self.release_ms * 0.001 * rate));
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "hold and lookahead are clamped, a few seconds at most"
        )]
        {
            self.hold_samples = (self.hold_ms * 0.001 * rate).round() as u32;
            self.latency = (self.lookahead_ms * 0.001 * rate).round() as u32;
        }
        let size = usize::try_from(self.latency).unwrap_or(0).max(1);
        self.delay = [vec![0.0; size], vec![0.0; size]];
        if let Some(filter) = &mut self.filter {
            filter.prepare(sample_rate, 1);
        }
        self.reset();
    }

    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
        match self.ramp {
            None => {
                let steady = (self.curve, self.open_at_or_over);
                self.run(inputs, outputs, |_| steady);
            }
            Some((ramp, open_at_or_over)) => {
                let frames = self.run(inputs, outputs, |frame| (ramp.at(frame), open_at_or_over));
                self.ramp = Some((ramp.after(frames), open_at_or_over));
            }
        }
    }

    fn reset(&mut self) {
        self.envelope = 0.0;
        self.gain = 1.0;
        self.holding = 0;
        self.cursor = 0;
        for channel in &mut self.delay {
            channel.fill(0.0);
        }
        if let Some(filter) = &mut self.filter {
            filter.reset();
        }
    }

    fn latency_samples(&self) -> u32 {
        self.latency
    }

    fn history_samples(&self) -> u32 {
        crate::processor::settling_samples(f64::from(
            self.attack_coefficient.max(self.release_coefficient),
        ))
        .saturating_add(self.hold_samples)
        .saturating_add(self.filter.as_ref().map_or(0, Processor::history_samples))
    }

    fn save_state(&self) -> StateBlob {
        let mut bytes = Vec::with_capacity(24 + self.delay.iter().map(Vec::len).sum::<usize>() * 4);
        bytes.extend_from_slice(&self.envelope.to_le_bytes());
        bytes.extend_from_slice(&self.gain.to_le_bytes());
        bytes.extend_from_slice(&self.holding.to_le_bytes());
        bytes.extend_from_slice(&(u64::try_from(self.cursor).unwrap_or(0)).to_le_bytes());
        bytes.extend_from_slice(&self.latency.to_le_bytes());
        for value in self.delay.iter().flatten() {
            bytes.extend_from_slice(&value.to_le_bytes());
        }
        if let Some(filter) = &self.filter {
            bytes.extend_from_slice(filter.save_state().as_bytes());
        }
        StateBlob::new(bytes)
    }

    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
        let delayed = 24 + self.delay.iter().map(Vec::len).sum::<usize>() * 4;
        let (bytes, filter_state) = state
            .as_bytes()
            .split_at_checked(delayed)
            .ok_or(StateError::Mismatch)?;
        let filter = match &self.filter {
            Some(filter) => {
                let mut loaded = filter.clone();
                loaded.load_state(&StateBlob::new(filter_state.to_vec()))?;
                Some(loaded)
            }
            None if filter_state.is_empty() => None,
            None => return Err(StateError::Mismatch),
        };
        let word = |at: usize| -> [u8; 4] { bytes[at..at + 4].try_into().expect("fixed range") };
        let envelope = f32::from_le_bytes(word(0));
        let gain = f32::from_le_bytes(word(4));
        let holding = u32::from_le_bytes(word(8));
        let cursor = usize::try_from(u64::from_le_bytes(
            bytes[12..20].try_into().expect("fixed range"),
        ))
        .ok();
        if u32::from_le_bytes(word(20)) != self.latency {
            return Err(StateError::Mismatch);
        }
        let values = bytes[24..]
            .as_chunks::<4>()
            .0
            .iter()
            .map(|word| f32::from_le_bytes(*word));
        let level_and_gain_hold =
            envelope.is_finite() && envelope >= 0.0 && (0.0..=1.0).contains(&gain);
        if !level_and_gain_hold
            || holding > self.hold_samples
            || cursor.is_none_or(|value| value >= self.delay[0].len())
            || values.clone().any(|value| !value.is_finite())
        {
            return Err(StateError::Invalid);
        }
        (self.envelope, self.gain, self.holding) = (envelope, gain, holding);
        self.cursor = cursor.unwrap_or(0);
        for (target, value) in self.delay.iter_mut().flatten().zip(values) {
            *target = value;
        }
        self.filter = filter;
        Ok(())
    }
}