use crate::synth::va::engine::param;
use crate::synth::va::fx::{Effect, Params};
#[derive(Clone, Copy)]
pub struct Crusher {
phase: f32,
held: [f32; 2],
}
impl Crusher {
pub const fn new() -> Self {
Crusher {
phase: 1.0,
held: [0.0; 2],
}
}
pub fn process(&mut self, x: [f32; 2], bits: u32, rate_hz: f32, sample_rate: f32) -> [f32; 2] {
if rate_hz > 0.0 {
self.phase += rate_hz / sample_rate;
if self.phase >= 1.0 {
self.phase -= self.phase.floor();
self.held = x;
}
} else {
self.held = x;
}
if bits == 0 {
return self.held;
}
let steps = (1u32 << (bits.clamp(1, 16) - 1)) as f32;
[
(self.held[0] * steps).round() / steps,
(self.held[1] * steps).round() / steps,
]
}
pub fn clear(&mut self) {
*self = Self::new();
}
}
pub(crate) struct CrusherFx {
dsp: Crusher,
bits: u32,
rate_hz: f32,
}
impl CrusherFx {
pub(crate) const fn new() -> Self {
CrusherFx {
dsp: Crusher::new(),
bits: 0,
rate_hz: 0.0,
}
}
}
impl Effect for CrusherFx {
fn update(&mut self, p: &Params<'_>, _sample_rate: f32) -> bool {
self.bits = p.raw(param::CRUSH_BITS);
self.rate_hz = p.get(param::CRUSH_RATE) * 100.0;
self.bits > 0 || self.rate_hz > 0.0
}
fn process(&mut self, x: [f32; 2], sample_rate: f32) -> [f32; 2] {
self.dsp.process(x, self.bits, self.rate_hz, sample_rate)
}
fn clear(&mut self) {
self.dsp.clear();
}
}