Skip to main content

wavegraph_dsp/
dsp.rs

1//! Block operations used by the patch interpreter.
2use wavegraph_sample::{I24, types::i24};
3
4pub use wavegraph_core::Dsp;
5
6/// Portable implementations for normalized `f32` and signed Q23 PCM.
7#[derive(Clone, Copy, Debug, Default)]
8pub struct Software;
9
10impl Dsp<f32> for Software {
11    fn gain(&mut self, input: &[f32], level: u8, output: &mut [f32]) {
12        let scale = f32::from(level) / 128.0;
13        for (out, &sample) in output.iter_mut().zip(input) {
14            *out = (sample * scale).clamp(-1.0, 1.0);
15        }
16    }
17
18    fn mix(&mut self, left: &[f32], right: &[f32], output: &mut [f32]) {
19        for ((out, &a), &b) in output.iter_mut().zip(left).zip(right) {
20            *out = (a + b).clamp(-1.0, 1.0);
21        }
22    }
23}
24
25#[inline]
26fn q23(value: i32) -> I24 {
27    I24::new_unchecked(value.clamp(i24::MIN.inner(), i24::MAX.inner()))
28}
29
30impl Dsp<I24> for Software {
31    fn gain(&mut self, input: &[I24], level: u8, output: &mut [I24]) {
32        for (out, &sample) in output.iter_mut().zip(input) {
33            // The product of a signed 24-bit sample and a byte fits in i32.
34            *out = q23(sample.inner().saturating_mul(i32::from(level)) >> 7);
35        }
36    }
37
38    fn mix(&mut self, left: &[I24], right: &[I24], output: &mut [I24]) {
39        for ((out, &a), &b) in output.iter_mut().zip(left).zip(right) {
40            *out = q23(a.inner().saturating_add(b.inner()));
41        }
42    }
43}