use crate::control::Ramp;
use crate::{ProcessCtx, Processor, StateBlob, StateError};
pub const MAX_MATRIX_GAIN: f32 = 4.0;
#[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 {
#[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 {
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)
}
}
}