use crate::synth::va::dsp::coef;
use crate::synth::va::engine::param;
use crate::synth::va::fx::{Effect, Params};
use crate::synth::va::m;
#[derive(Clone, Copy)]
pub struct Compressor {
env: f32,
}
impl Compressor {
pub const fn new() -> Self {
Compressor { env: 0.0 }
}
pub fn process(
&mut self,
x: [f32; 2],
threshold_db: f32,
ratio: f32,
attack: f32,
release: f32,
makeup_db: f32,
) -> [f32; 2] {
let peak = x[0].abs().max(x[1].abs());
let k = if peak > self.env { attack } else { release };
self.env += (peak - self.env) * k;
let mut gain_db = makeup_db;
if self.env > 1e-6 {
let level = 20.0 * m::log10(self.env);
if level > threshold_db {
gain_db -= (level - threshold_db) * (1.0 - 1.0 / ratio);
}
}
let g = m::powf(10.0, gain_db / 20.0);
[x[0] * g, x[1] * g]
}
pub fn clear(&mut self) {
*self = Self::new();
}
}
pub(crate) struct CompFx {
dsp: Compressor,
on: bool,
threshold_db: f32,
ratio: f32,
attack: f32,
release: f32,
makeup_db: f32,
}
impl CompFx {
pub(crate) const fn new() -> Self {
CompFx {
dsp: Compressor::new(),
on: false,
threshold_db: 0.0,
ratio: 1.0,
attack: 1.0,
release: 1.0,
makeup_db: 0.0,
}
}
}
impl Effect for CompFx {
fn update(&mut self, p: &Params<'_>, sample_rate: f32) -> bool {
let amount = p.get(param::COMP) / 100.0;
self.on |= amount > 0.0;
if self.on {
self.threshold_db = -30.0 * amount;
self.ratio = 1.0 + 7.0 * amount;
self.makeup_db = -self.threshold_db * (1.0 - 1.0 / self.ratio) * 0.5;
self.attack = coef(p.get(param::COMP_ATTACK) / 1000.0, sample_rate);
self.release = coef(p.get(param::COMP_RELEASE) / 100.0, sample_rate);
}
self.on
}
fn process(&mut self, x: [f32; 2], _sample_rate: f32) -> [f32; 2] {
self.dsp.process(
x,
self.threshold_db,
self.ratio,
self.attack,
self.release,
self.makeup_db,
)
}
fn clear(&mut self) {
self.dsp.clear();
self.on = false;
}
}