Skip to main content

alpha2_audio/
matrix.rs

1use crate::control::Ramp;
2use crate::{ProcessCtx, Processor, StateBlob, StateError};
3
4/// Largest magnitude of a [`Matrix`] gain.
5pub const MAX_MATRIX_GAIN: f32 = 4.0;
6
7/// A two-by-two gain matrix over a stereo pair: `left = ll * L + lr * R` and
8/// `right = rl * L + rr * R`. Width, swap, mono, polarity and balance are settings of it.
9///
10/// One channel takes the fold of the stereo result of a signal at unity on both sides:
11/// `((ll + lr) + (rl + rr)) * 0.5` times the sample.
12///
13/// Retuned ([`Processor::control`]), its gains move in a straight line from one control point's
14/// values to the next's.
15#[derive(Clone, Debug)]
16pub struct Matrix {
17    gains: [f32; 4],
18    ramp: Option<Ramp<4>>,
19}
20
21fn clamped(values: &[f32]) -> Option<[f32; 4]> {
22    let gains: [f32; 4] = values.try_into().ok()?;
23    Some(gains.map(|gain| {
24        if gain.is_finite() {
25            gain.clamp(-MAX_MATRIX_GAIN, MAX_MATRIX_GAIN)
26        } else {
27            0.0
28        }
29    }))
30}
31
32impl Matrix {
33    /// Creates a matrix from the gains the left output takes from left and right, then those
34    /// the right output takes, each clamped to [`MAX_MATRIX_GAIN`] either way. A non-finite
35    /// gain becomes 0.
36    #[must_use]
37    pub fn new(left: [f32; 2], right: [f32; 2]) -> Self {
38        Self {
39            gains: clamped(&[left[0], left[1], right[0], right[1]]).unwrap_or([0.0; 4]),
40            ramp: None,
41        }
42    }
43
44    fn run(
45        inputs: &[&[f32]],
46        outputs: &mut [&mut [f32]],
47        gains_at_frame: impl Fn(usize) -> [f32; 4],
48    ) -> usize {
49        let silenced = |sample: f32| if sample.is_finite() { sample } else { 0.0 };
50        match (inputs, outputs) {
51            ([left, right, ..], [left_out, right_out, ..]) => {
52                let frames = left
53                    .len()
54                    .min(right.len())
55                    .min(left_out.len())
56                    .min(right_out.len());
57                for frame in 0..frames {
58                    let [ll, lr, rl, rr] = gains_at_frame(frame);
59                    let (l, r) = (silenced(left[frame]), silenced(right[frame]));
60                    left_out[frame] = ll * l + lr * r;
61                    right_out[frame] = rl * l + rr * r;
62                }
63                frames
64            }
65            ([input, ..], [output, ..]) => {
66                let frames = input.len().min(output.len());
67                for frame in 0..frames {
68                    let [ll, lr, rl, rr] = gains_at_frame(frame);
69                    output[frame] = ((ll + lr) + (rl + rr)) * 0.5 * silenced(input[frame]);
70                }
71                frames
72            }
73            _ => 0,
74        }
75    }
76}
77
78impl Processor for Matrix {
79    /// The gains the left output takes from left and right, then those the right output takes.
80    fn control_params(&self) -> usize {
81        4
82    }
83
84    fn control(&mut self, span: &crate::ControlSpan<'_>) {
85        let (Some(from), Some(to)) = (clamped(span.from), clamped(span.to)) else {
86            return;
87        };
88        if span.is_steady() {
89            self.gains = from;
90            self.ramp = None;
91        } else {
92            self.ramp = Some(Ramp::between(from, to, span.phase));
93        }
94    }
95
96    fn prepare(&mut self, _sample_rate: u32, _max_block: usize) {}
97
98    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
99        match self.ramp {
100            None => {
101                let steady = self.gains;
102                Self::run(inputs, outputs, |_| steady);
103            }
104            Some(ramp) => {
105                let frames = Self::run(inputs, outputs, |frame| ramp.at(frame));
106                self.ramp = Some(ramp.after(frames));
107            }
108        }
109    }
110
111    fn reset(&mut self) {}
112
113    fn save_state(&self) -> StateBlob {
114        StateBlob::default()
115    }
116
117    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
118        if state.as_bytes().is_empty() {
119            Ok(())
120        } else {
121            Err(StateError::Mismatch)
122        }
123    }
124}