Repository Public
1//! ORIX Sonata2//! File: crates/sonata-dsp/src/effects/dynamics.rs3//! Description: Dynamics processors: compressor, look-ahead limiter, gate, downward expander.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use super::limiter_core::LimiterCore;9use super::{desc, num, preset};10use crate::core::db_to_lin;11use crate::effect::Effect;12use sonata_ir::{EffectDesc, LatencySpec, Unit};1314fn coef(time_sec: f32, sr: f32) -> f32 {15 (-1.0 / (time_sec.max(1e-5) * sr)).exp()16}1718#[inline]19fn level_db(l: f32, r: f32) -> f32 {20 20.0 * l.abs().max(r.abs()).max(1e-7).log10()21}2223/// Feed-forward, stereo-linked compressor. The gain computer works in dB on the instantaneous24/// peak of both channels (quadratic soft knee); its output is smoothed with separate attack and25/// release time constants (log-domain "smooth decoupled" detector, Giannoulis et al. 2012).26pub struct Compressor {27 sr: f32,28 p: [f32; 6],29 env: f32,30 att: f32,31 rel: f32,32}3334impl Compressor {35 pub fn new() -> Compressor {36 Compressor { sr: 48_000.0, p: [-18.0, 4.0, 0.01, 0.15, 6.0, 0.0], env: 0.0, att: 0.0, rel: 0.0 }37 }38 pub fn desc() -> EffectDesc {39 desc(40 "compressor",41 "Compressor",42 "dynamics",43 "Feed-forward stereo-linked compressor with soft knee. Levels above the threshold are reduced by the ratio; makeup gain is applied after.",44 vec![45 num("threshold", Unit::Decibel, -60.0, 0.0, -18.0, "Level above which gain reduction starts."),46 num("ratio", Unit::Scalar, 1.0, 20.0, 4.0, "Input change in dB per dB of output change above the threshold."),47 num("attack", Unit::Seconds, 0.0001, 0.5, 0.01, "Time constant of the onset of gain reduction."),48 num("release", Unit::Seconds, 0.005, 3.0, 0.15, "Time constant of the recovery."),49 num("knee", Unit::Decibel, 0.0, 24.0, 6.0, "Width of the soft knee centred on the threshold."),50 num("makeup", Unit::Decibel, -12.0, 36.0, 0.0, "Gain applied after compression."),51 ],52 vec![53 preset("gentle", "Light levelling.", &[("threshold", -20.0), ("ratio", 2.0), ("attack", 0.03), ("release", 0.25), ("knee", 12.0)]),54 preset(55 "vocal",56 "Controlled, present.",57 &[("threshold", -22.0), ("ratio", 3.5), ("attack", 0.008), ("release", 0.12), ("knee", 8.0), ("makeup", 4.0)],58 ),59 preset(60 "drums",61 "Fast and firm.",62 &[("threshold", -16.0), ("ratio", 6.0), ("attack", 0.003), ("release", 0.08), ("knee", 3.0), ("makeup", 3.0)],63 ),64 preset(65 "glue",66 "Bus compression.",67 &[("threshold", -14.0), ("ratio", 2.0), ("attack", 0.03), ("release", 0.3), ("knee", 10.0), ("makeup", 1.5)],68 ),69 ],70 LatencySpec::default(),71 1.0,72 )73 }74 /// Static gain reduction (dB, <= 0) for an input level in dB.75 pub fn reduction_db(&self, level_db: f32) -> f32 {76 let (thr, ratio, knee) = (self.p[0], self.p[1].max(1.0), self.p[4]);77 let over = level_db - thr;78 let slope = 1.0 / ratio - 1.0;79 if 2.0 * over < -knee {80 0.081 } else if knee > 0.0 && 2.0 * over.abs() <= knee {82 slope * (over + knee / 2.0) * (over + knee / 2.0) / (2.0 * knee)83 } else {84 slope * over85 }86 }87}8889impl Default for Compressor {90 fn default() -> Self {91 Self::new()92 }93}9495impl Effect for Compressor {96 fn prepare(&mut self, sample_rate: f32, _: usize) {97 self.sr = sample_rate;98 self.reset();99 }100 fn reset(&mut self) {101 self.env = 0.0;102 }103 fn set_param(&mut self, index: usize, value: f32) {104 if let Some(p) = self.p.get_mut(index) {105 *p = value;106 }107 }108 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {109 self.att = coef(self.p[2], self.sr);110 self.rel = coef(self.p[3], self.sr);111 let makeup = self.p[5];112 for i in 0..left.len() {113 let gr = self.reduction_db(level_db(left[i], right[i]));114 let c = if gr < self.env { self.att } else { self.rel };115 self.env = gr + (self.env - gr) * c;116 if self.env > -1e-6 {117 self.env = 0.0f32.min(self.env);118 }119 let g = db_to_lin(self.env + makeup);120 left[i] *= g;121 right[i] *= g;122 }123 }124}125126/// Look-ahead brick-wall limiter (5 ms look-ahead, reported as latency).127pub struct Limiter {128 sr: f32,129 p: [f32; 3],130 core: Option<LimiterCore>,131 gain: f32,132}133134/// Look-ahead of the limiter effect, seconds.135pub const LIMITER_LOOKAHEAD_SEC: f64 = 0.005;136137impl Limiter {138 pub fn new() -> Limiter {139 Limiter { sr: 48_000.0, p: [0.0, -1.0, 0.08], core: None, gain: 1.0 }140 }141 pub fn desc() -> EffectDesc {142 desc(143 "limiter",144 "Limiter",145 "dynamics",146 "Look-ahead brick-wall peak limiter. Sample peaks never exceed the ceiling; the gain ramps in over the 5 ms look-ahead, which is reported as latency.",147 vec![148 num("input", Unit::Decibel, -12.0, 24.0, 0.0, "Gain applied before limiting."),149 num("ceiling", Unit::Decibel, -24.0, 0.0, -1.0, "Maximum output sample peak."),150 num("release", Unit::Seconds, 0.005, 1.0, 0.08, "Time constant of the gain recovery."),151 ],152 vec![preset("master", "Transparent safety.", &[("ceiling", -1.0), ("release", 0.1)]), preset("loud", "Push into the ceiling.", &[("input", 6.0), ("ceiling", -0.3), ("release", 0.05)])],153 LatencySpec { seconds: LIMITER_LOOKAHEAD_SEC, samples: 0 },154 1.0,155 )156 }157}158159impl Default for Limiter {160 fn default() -> Self {161 Self::new()162 }163}164165impl Effect for Limiter {166 fn prepare(&mut self, sample_rate: f32, _: usize) {167 self.sr = sample_rate;168 let look = Self::desc().latency.at(sample_rate as u32) as usize;169 self.core = Some(LimiterCore::new(sample_rate, look, self.p[2], self.p[1]));170 self.gain = db_to_lin(self.p[0]);171 }172 fn reset(&mut self) {173 if let Some(c) = &mut self.core {174 c.reset();175 }176 self.gain = db_to_lin(self.p[0]);177 }178 fn set_param(&mut self, index: usize, value: f32) {179 if let Some(p) = self.p.get_mut(index) {180 *p = value;181 }182 if let Some(c) = &mut self.core {183 match index {184 1 => c.set_ceiling_db(value),185 2 => c.set_release(self.sr, value),186 _ => {}187 }188 }189 }190 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {191 let target = db_to_lin(self.p[0]);192 let step = (target - self.gain) / left.len().max(1) as f32;193 for i in 0..left.len() {194 self.gain += step;195 left[i] *= self.gain;196 right[i] *= self.gain;197 }198 self.gain = target;199 if let Some(c) = &mut self.core {200 c.process(left, right);201 }202 }203 fn latency(&self) -> u32 {204 self.core.as_ref().map(|c| c.lookahead() as u32).unwrap_or(0)205 }206}207208/// Noise gate with hysteresis (3 dB), hold and a floor (`range`).209pub struct Gate {210 sr: f32,211 p: [f32; 5],212 det: f32,213 gain: f32,214 open: bool,215 hold_left: u32,216}217218impl Gate {219 pub fn new() -> Gate {220 Gate { sr: 48_000.0, p: [-50.0, 0.001, 0.05, 0.1, -80.0], det: 0.0, gain: 0.0, open: false, hold_left: 0 }221 }222 pub fn desc() -> EffectDesc {223 desc(224 "gate",225 "Gate",226 "dynamics",227 "Noise gate: attenuates by `range` when the level stays below the threshold. Opens at the threshold, closes 3 dB below it after the hold time.",228 vec![229 num("threshold", Unit::Decibel, -90.0, 0.0, -50.0, "Level that opens the gate."),230 num("attack", Unit::Seconds, 0.0001, 0.1, 0.001, "Opening time constant."),231 num("hold", Unit::Seconds, 0.0, 2.0, 0.05, "Time the gate stays open after the level falls."),232 num("release", Unit::Seconds, 0.005, 3.0, 0.1, "Closing time constant."),233 num("range", Unit::Decibel, -90.0, 0.0, -80.0, "Gain applied while the gate is closed."),234 ],235 vec![236 preset("tight", "Drums.", &[("threshold", -35.0), ("hold", 0.02), ("release", 0.05)]),237 preset("soft", "Halve the noise floor.", &[("threshold", -55.0), ("range", -12.0), ("release", 0.3)]),238 ],239 LatencySpec::default(),240 1.0,241 )242 }243}244245impl Default for Gate {246 fn default() -> Self {247 Self::new()248 }249}250251impl Effect for Gate {252 fn prepare(&mut self, sample_rate: f32, _: usize) {253 self.sr = sample_rate;254 self.reset();255 }256 fn reset(&mut self) {257 self.det = 0.0;258 self.gain = db_to_lin(self.p[4]);259 self.open = false;260 self.hold_left = 0;261 }262 fn set_param(&mut self, index: usize, value: f32) {263 if let Some(p) = self.p.get_mut(index) {264 *p = value;265 }266 }267 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {268 let open_at = db_to_lin(self.p[0]);269 let close_at = db_to_lin(self.p[0] - 3.0);270 let floor = db_to_lin(self.p[4]);271 let (att, rel) = (coef(self.p[1], self.sr), coef(self.p[3], self.sr));272 // Detector: instantaneous peak with a 10 ms fall so a low-frequency cycle does not chatter.273 let det_rel = coef(0.01, self.sr);274 let hold = (self.p[2] * self.sr) as u32;275 for i in 0..left.len() {276 let pk = left[i].abs().max(right[i].abs());277 self.det = if pk > self.det { pk } else { pk + (self.det - pk) * det_rel };278 if self.det >= open_at {279 self.open = true;280 self.hold_left = hold;281 } else if self.det < close_at {282 if self.hold_left > 0 {283 self.hold_left -= 1;284 } else {285 self.open = false;286 }287 }288 let target = if self.open { 1.0 } else { floor };289 let c = if target > self.gain { att } else { rel };290 self.gain = target + (self.gain - target) * c;291 left[i] *= self.gain;292 right[i] *= self.gain;293 }294 }295}296297/// Downward expander: below the threshold, each dB of input change gives `ratio` dB of output change.298pub struct Expander {299 sr: f32,300 p: [f32; 5],301 det: f32,302 env: f32,303}304305impl Expander {306 pub fn new() -> Expander {307 Expander { sr: 48_000.0, p: [-40.0, 2.0, 0.002, 0.15, -60.0], det: 0.0, env: 0.0 }308 }309 pub fn desc() -> EffectDesc {310 desc(311 "expander",312 "Expander",313 "dynamics",314 "Downward expander: levels below the threshold are pushed further down by the ratio, never by more than `range`.",315 vec![316 num("threshold", Unit::Decibel, -90.0, 0.0, -40.0, "Level below which expansion starts."),317 num("ratio", Unit::Scalar, 1.0, 10.0, 2.0, "Output change in dB per dB of input change below the threshold."),318 num("attack", Unit::Seconds, 0.0001, 0.2, 0.002, "Time constant when the gain rises."),319 num("release", Unit::Seconds, 0.005, 3.0, 0.15, "Time constant when the gain falls."),320 num("range", Unit::Decibel, -90.0, 0.0, -60.0, "Largest attenuation applied."),321 ],322 vec![preset("subtle", "Lower the bed between phrases.", &[("threshold", -45.0), ("ratio", 1.5), ("range", -18.0)])],323 LatencySpec::default(),324 1.0,325 )326 }327 /// Static gain (dB, <= 0) for an input level in dB.328 pub fn gain_db(&self, level_db: f32) -> f32 {329 let under = level_db - self.p[0];330 if under >= 0.0 {331 0.0332 } else {333 ((self.p[1].max(1.0) - 1.0) * under).max(self.p[4])334 }335 }336}337338impl Default for Expander {339 fn default() -> Self {340 Self::new()341 }342}343344impl Effect for Expander {345 fn prepare(&mut self, sample_rate: f32, _: usize) {346 self.sr = sample_rate;347 self.reset();348 }349 fn reset(&mut self) {350 self.det = 0.0;351 self.env = self.p[4];352 }353 fn set_param(&mut self, index: usize, value: f32) {354 if let Some(p) = self.p.get_mut(index) {355 *p = value;356 }357 }358 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {359 let (att, rel) = (coef(self.p[2], self.sr), coef(self.p[3], self.sr));360 let det_rel = coef(0.01, self.sr);361 for i in 0..left.len() {362 let pk = left[i].abs().max(right[i].abs());363 self.det = if pk > self.det { pk } else { pk + (self.det - pk) * det_rel };364 let g = self.gain_db(20.0 * self.det.max(1e-7).log10());365 let c = if g > self.env { att } else { rel };366 self.env = g + (self.env - g) * c;367 let lin = db_to_lin(self.env);368 left[i] *= lin;369 right[i] *= lin;370 }371 }372}373