use ::anyhow::Result;
use crate::agc;
use crate::dsp::{db_to_gain, follow, power_db, smoothing};
use crate::param::Param;
use crate::stage::{Frame, Stage};
pub struct Compressor {
power: f32,
reduction_db: f32,
threshold: Param,
ratio: Param,
target: Param,
}
pub const THRESHOLD_DB: f32 = -24.;
pub const RATIO: f32 = 3.;
pub const KNEE_DB: f32 = 6.;
const DETECTOR_TAU: f32 = 0.005;
const ATTACK_TAU: f32 = 0.005;
const RELEASE_TAU: f32 = 0.12;
pub fn reduction_db(level_db: f32, threshold_db: f32, ratio: f32) -> f32 {
let over = level_db - threshold_db;
let slope = 1. / ratio - 1.;
if 2. * over <= -KNEE_DB {
0.
} else if 2. * over >= KNEE_DB {
slope * over
} else {
slope * (over + KNEE_DB / 2.).powi(2) / (2. * KNEE_DB)
}
}
pub fn makeup_db(target_db: f32, threshold_db: f32, ratio: f32) -> f32 {
-reduction_db(target_db + 3., threshold_db, ratio)
}
impl Compressor {
pub fn new() -> Self {
Self {
power: 0.,
reduction_db: 0.,
threshold: Param::new(
"threshold",
"Threshold",
"dBFS",
(-40., -6., 0.5),
THRESHOLD_DB,
),
ratio: Param::new("ratio", "Ratio", ":1", (1., 10., 0.1), RATIO),
target: agc::target_param(),
}
}
pub fn following(self, target: Param) -> Self {
Self { target, ..self }
}
pub fn reduction(&self) -> f32 {
self.reduction_db
}
}
impl Default for Compressor {
fn default() -> Self {
Self::new()
}
}
impl Stage for Compressor {
fn name(&self) -> &'static str {
"compressor"
}
fn latency(&self) -> usize {
0
}
fn resume_frames(&self) -> usize {
3
}
fn params(&self) -> Vec<Param> {
vec![self.threshold.clone(), self.ratio.clone()]
}
fn trace(&self) -> Option<(&'static str, f32)> {
Some(("reduction", self.reduction_db))
}
fn process(&mut self, frame: &mut Frame) -> Result<()> {
let detector = smoothing(DETECTOR_TAU);
let attack = smoothing(ATTACK_TAU);
let release = smoothing(RELEASE_TAU);
let (threshold, ratio) = (self.threshold.get(), self.ratio.get());
let makeup = makeup_db(self.target.get(), threshold, ratio);
let knee_power = 10f32.powf((threshold - KNEE_DB / 2.) / 10.);
for sample in frame.iter_mut() {
self.power += (*sample * *sample - self.power) * detector;
let wanted = if self.power + 1e-12 > knee_power {
reduction_db(power_db(self.power), threshold, ratio)
} else {
0.
};
self.reduction_db = follow(self.reduction_db, wanted, attack, release);
*sample *= db_to_gain(self.reduction_db + makeup);
}
Ok(())
}
}