alpha2-audio 0.10.0

Platform-independent audio DSP core for alpha2.
Documentation
use crate::control::Ramp;
use crate::{ProcessCtx, Processor, StateBlob, StateError};

/// Largest magnitude of a [`Matrix`] gain.
pub const MAX_MATRIX_GAIN: f32 = 4.0;

/// A two-by-two gain matrix over a stereo pair: `left = ll * L + lr * R` and
/// `right = rl * L + rr * R`. Width, swap, mono, polarity and balance are settings of it.
///
/// One channel takes the fold of the stereo result of a signal at unity on both sides:
/// `((ll + lr) + (rl + rr)) * 0.5` times the sample.
///
/// Retuned ([`Processor::control`]), its gains move in a straight line from one control point's
/// values to the next's.
#[derive(Clone, Debug)]
pub struct Matrix {
    gains: [f32; 4],
    ramp: Option<Ramp<4>>,
}

fn clamped(values: &[f32]) -> Option<[f32; 4]> {
    let gains: [f32; 4] = values.try_into().ok()?;
    Some(gains.map(|gain| {
        if gain.is_finite() {
            gain.clamp(-MAX_MATRIX_GAIN, MAX_MATRIX_GAIN)
        } else {
            0.0
        }
    }))
}

impl Matrix {
    /// Creates a matrix from the gains the left output takes from left and right, then those
    /// the right output takes, each clamped to [`MAX_MATRIX_GAIN`] either way. A non-finite
    /// gain becomes 0.
    #[must_use]
    pub fn new(left: [f32; 2], right: [f32; 2]) -> Self {
        Self {
            gains: clamped(&[left[0], left[1], right[0], right[1]]).unwrap_or([0.0; 4]),
            ramp: None,
        }
    }

    fn run(
        inputs: &[&[f32]],
        outputs: &mut [&mut [f32]],
        gains_at_frame: impl Fn(usize) -> [f32; 4],
    ) -> usize {
        let silenced = |sample: f32| if sample.is_finite() { sample } else { 0.0 };
        match (inputs, outputs) {
            ([left, right, ..], [left_out, right_out, ..]) => {
                let frames = left
                    .len()
                    .min(right.len())
                    .min(left_out.len())
                    .min(right_out.len());
                for frame in 0..frames {
                    let [ll, lr, rl, rr] = gains_at_frame(frame);
                    let (l, r) = (silenced(left[frame]), silenced(right[frame]));
                    left_out[frame] = ll * l + lr * r;
                    right_out[frame] = rl * l + rr * r;
                }
                frames
            }
            ([input, ..], [output, ..]) => {
                let frames = input.len().min(output.len());
                for frame in 0..frames {
                    let [ll, lr, rl, rr] = gains_at_frame(frame);
                    output[frame] = ((ll + lr) + (rl + rr)) * 0.5 * silenced(input[frame]);
                }
                frames
            }
            _ => 0,
        }
    }
}

impl Processor for Matrix {
    /// The gains the left output takes from left and right, then those the right output takes.
    fn control_params(&self) -> usize {
        4
    }

    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.gains = from;
            self.ramp = None;
        } else {
            self.ramp = Some(Ramp::between(from, to, span.phase));
        }
    }

    fn prepare(&mut self, _sample_rate: u32, _max_block: usize) {}

    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
        match self.ramp {
            None => {
                let steady = self.gains;
                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) {}

    fn save_state(&self) -> StateBlob {
        StateBlob::default()
    }

    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
        if state.as_bytes().is_empty() {
            Ok(())
        } else {
            Err(StateError::Mismatch)
        }
    }
}