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::biquad::flush_denormal;
use crate::control::Ramp;
use crate::{ProcessCtx, Processor, StateBlob, StateError};

/// Longest time a [`Delay`] renders, in milliseconds; the shortest is one.
pub const MAX_DELAY_MS: f32 = 2_000.0;

/// Most feedback a [`Delay`] renders.
pub const MAX_DELAY_FEEDBACK: f32 = 0.95;

/// A feedback delay line on up to two channels.
///
/// Each channel repeats after the delay time: with the sample `x` and the line's oldest sample
/// `d`, the line takes `x + feedback * d` and the output is `x * (1 - mix) + d * mix`. It adds
/// no latency.
///
/// Retuned ([`Processor::control`]), its feedback and mix move in a straight line from one
/// control point's values to the next's.
#[derive(Clone, Debug)]
pub struct Delay {
    time_ms: f32,
    feedback_and_mix: [f32; 2],
    lines: [Vec<f32>; 2],
    cursor: usize,
    ramp: Option<Ramp<2>>,
}

fn clamped(values: &[f32]) -> Option<[f32; 2]> {
    let &[feedback, mix] = values else {
        return None;
    };
    let finite = |value: f32| if value.is_finite() { value } else { 0.0 };
    Some([
        finite(feedback).clamp(0.0, MAX_DELAY_FEEDBACK),
        finite(mix).clamp(0.0, 1.0),
    ])
}

impl Delay {
    /// Creates a delay of `time_ms` milliseconds, clamped to 1 to [`MAX_DELAY_MS`], with
    /// `feedback` clamped to 0 to [`MAX_DELAY_FEEDBACK`] and `mix` to 0 to 1. A non-finite time
    /// becomes 250 ms and non-finite feedback or mix 0.
    #[must_use]
    pub fn new(time_ms: f32, feedback: f32, mix: f32) -> Self {
        Self {
            time_ms: if time_ms.is_finite() { time_ms } else { 250.0 }.clamp(1.0, MAX_DELAY_MS),
            feedback_and_mix: clamped(&[feedback, mix]).unwrap_or([0.0; 2]),
            lines: [Vec::new(), Vec::new()],
            cursor: 0,
            ramp: None,
        }
    }

    fn run(
        &mut self,
        inputs: &[&[f32]],
        outputs: &mut [&mut [f32]],
        feedback_and_mix_at_frame: impl Fn(usize) -> [f32; 2],
    ) -> usize {
        let channels = inputs.len().min(outputs.len()).min(2);
        let frames = inputs
            .iter()
            .take(channels)
            .map(|input| input.len())
            .chain(outputs.iter().take(channels).map(|output| output.len()))
            .min()
            .unwrap_or(0);
        let length = self.lines[0].len();
        if length == 0 {
            return 0;
        }
        for frame in 0..frames {
            let [feedback, mix] = feedback_and_mix_at_frame(frame);
            for channel in 0..channels {
                let input = inputs[channel][frame];
                let input = if input.is_finite() { input } else { 0.0 };
                let delayed = self.lines[channel][self.cursor];
                self.lines[channel][self.cursor] = flush_denormal(input + feedback * delayed);
                outputs[channel][frame] = input * (1.0 - mix) + delayed * mix;
            }
            self.cursor = (self.cursor + 1) % length;
        }
        frames
    }
}

impl Processor for Delay {
    /// The feedback and the mix.
    fn control_params(&self) -> usize {
        2
    }

    fn control(&mut self, span: &crate::ControlSpan<'_>) {
        let (Some(from), Some(to)) = (clamped(span.from), clamped(span.to)) else {
            return;
        };
        if span.is_steady() {
            self.feedback_and_mix = from;
            self.ramp = None;
        } else {
            self.ramp = Some(Ramp::between(from, to, span.phase));
        }
    }

    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "the delay time is clamped to 1 ms and up"
        )]
        let length = ((self.time_ms * 0.001 * sample_rate.max(1) as f32).round() as usize).max(1);
        self.lines = [vec![0.0; length], vec![0.0; length]];
        self.cursor = 0;
    }

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

    fn reset(&mut self) {
        for line in &mut self.lines {
            line.fill(0.0);
        }
        self.cursor = 0;
    }

    fn history_samples(&self) -> u32 {
        let length = u32::try_from(self.lines[0].len()).unwrap_or(u32::MAX);
        let feedback = f64::from(self.feedback_and_mix[0]);
        if feedback <= 0.0 {
            return length;
        }
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "feedback is clamped below 1, so the count is small"
        )]
        let repeats = libm::ceil(32.0 / -libm::log(feedback)) as u32;
        length.saturating_mul(repeats)
    }

    fn save_state(&self) -> StateBlob {
        let mut bytes = Vec::with_capacity(8 + self.lines.iter().map(Vec::len).sum::<usize>() * 4);
        bytes.extend_from_slice(&(u64::try_from(self.cursor).unwrap_or(0)).to_le_bytes());
        for value in self.lines.iter().flatten() {
            bytes.extend_from_slice(&value.to_le_bytes());
        }
        StateBlob::new(bytes)
    }

    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
        let bytes = state.as_bytes();
        if bytes.len() != 8 + self.lines.iter().map(Vec::len).sum::<usize>() * 4 {
            return Err(StateError::Mismatch);
        }
        let cursor = usize::try_from(u64::from_le_bytes(
            bytes[..8].try_into().expect("fixed range"),
        ))
        .ok();
        let values = bytes[8..]
            .as_chunks::<4>()
            .0
            .iter()
            .map(|word| f32::from_le_bytes(*word));
        if cursor.is_none_or(|cursor| cursor >= self.lines[0].len().max(1))
            || values.clone().any(|value| !value.is_finite())
        {
            return Err(StateError::Invalid);
        }
        self.cursor = cursor.unwrap_or(0);
        for (target, value) in self.lines.iter_mut().flatten().zip(values) {
            *target = value;
        }
        Ok(())
    }
}