Repository Public
1//! ORIX Sonata2//! File: crates/sonata-dsp/src/effects/color.rs3//! Description: Non-linear effects: oversampled distortion and saturation, bit crusher.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use super::{choice, desc, num, preset};9use crate::core::{db_to_lin, DcBlocker, OnePoleSmoother};10use crate::effect::Effect;11use crate::filter::{OnePole, Oversampler2x, Oversampler4x};12use sonata_ir::{EffectDesc, LatencySpec, Unit};1314#[inline]15fn shape(mode: usize, x: f32) -> f32 {16 match mode {17 // Soft: hyperbolic tangent.18 0 => x.tanh(),19 // Hard: clip at +/- 1.20 1 => x.clamp(-1.0, 1.0),21 // Fold: reflect at +/- 1 (triangle wave folder).22 2 => {23 let t = (x + 1.0).rem_euclid(4.0);24 if t < 2.0 {25 t - 1.026 } else {27 3.0 - t28 }29 }30 // Asymmetric: the positive half saturates sooner (even harmonics); DC is removed after.31 _ => {32 if x >= 0.0 {33 (1.5 * x).tanh() / 1.534 } else {35 x.tanh()36 }37 }38 }39}4041/// Latency of [`Distortion`]: the 4x oversampler's round trip, samples.42pub const DISTORTION_LATENCY: u32 = 19;43/// Latency of [`Saturation`]: the 2x oversampler's round trip, samples.44pub const SATURATION_LATENCY: u32 = 15;4546/// Waveshaping distortion at four times the sample rate (anti-aliased by half-band FIRs).47pub struct Distortion {48 sr: f32,49 drive: OnePoleSmoother,50 out: OnePoleSmoother,51 mode: usize,52 tone_hz: f32,53 os: [Oversampler4x; 2],54 tone: [OnePole; 2],55 dc: [DcBlocker; 2],56}5758impl Distortion {59 pub fn new() -> Distortion {60 Distortion {61 sr: 48_000.0,62 drive: OnePoleSmoother::new(db_to_lin(12.0), 0.01, 48_000.0),63 out: OnePoleSmoother::new(1.0, 0.01, 48_000.0),64 mode: 0,65 tone_hz: 8000.0,66 os: [Oversampler4x::new(), Oversampler4x::new()],67 tone: [OnePole::new(8000.0, 48_000.0); 2],68 dc: [DcBlocker::new(10.0, 48_000.0); 2],69 }70 }71 pub fn desc() -> EffectDesc {72 desc(73 "distortion",74 "Distortion",75 "colour",76 "Waveshaper computed at 4x the sample rate. `soft` is tanh, `hard` clips, `fold` reflects the wave at full scale, `asym` saturates the positive half sooner.",77 vec![78 num("drive", Unit::Decibel, 0.0, 48.0, 12.0, "Gain into the shaper."),79 choice("mode", &["soft", "hard", "fold", "asym"], "soft", "Shape of the non-linearity."),80 num("tone", Unit::Hertz, 500.0, 20_000.0, 8000.0, "Low-pass after the shaper (6 dB/octave)."),81 num("output", Unit::Decibel, -36.0, 12.0, -6.0, "Gain after the shaper."),82 ],83 vec![84 preset("crunch", "Edge of break-up.", &[("drive", 9.0), ("tone", 6000.0), ("output", -4.0)]),85 preset("fuzz", "Squared off.", &[("drive", 36.0), ("tone", 4000.0), ("output", -10.0)]),86 preset("warm", "Slight asymmetric colour.", &[("drive", 4.0), ("tone", 12_000.0), ("output", -2.0)]),87 ],88 LatencySpec { seconds: 0.0, samples: DISTORTION_LATENCY },89 1.0,90 )91 }92}9394impl Default for Distortion {95 fn default() -> Self {96 Self::new()97 }98}99100impl Effect for Distortion {101 fn prepare(&mut self, sample_rate: f32, _: usize) {102 self.sr = sample_rate;103 let (d, o, t) = (self.drive.target(), self.out.target(), self.tone_hz);104 self.drive = OnePoleSmoother::new(d, 0.01, sample_rate);105 self.out = OnePoleSmoother::new(o, 0.01, sample_rate);106 self.tone = [OnePole::new(t, sample_rate); 2];107 self.dc = [DcBlocker::new(10.0, sample_rate); 2];108 }109 fn reset(&mut self) {110 for c in 0..2 {111 self.os[c].reset();112 self.tone[c].reset();113 self.dc[c].reset();114 }115 let (d, o) = (self.drive.target(), self.out.target());116 self.drive.snap(d);117 self.out.snap(o);118 }119 fn set_param(&mut self, index: usize, value: f32) {120 match index {121 0 => self.drive.set_target(db_to_lin(value)),122 2 => {123 self.tone_hz = value;124 for t in &mut self.tone {125 t.set(value, self.sr);126 }127 }128 3 => self.out.set_target(db_to_lin(value)),129 _ => {}130 }131 }132 fn set_choice(&mut self, index: usize, choice: usize) {133 if index == 1 {134 self.mode = choice;135 }136 }137 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {138 let mode = self.mode;139 for i in 0..left.len() {140 let (g, o) = (self.drive.tick(), self.out.tick());141 let l = self.os[0].process(left[i] * g, |x| shape(mode, x));142 let r = self.os[1].process(right[i] * g, |x| shape(mode, x));143 let (l, r) = if mode == 3 { (self.dc[0].tick(l), self.dc[1].tick(r)) } else { (l, r) };144 left[i] = self.tone[0].lowpass(l) * o;145 right[i] = self.tone[1].lowpass(r) * o;146 }147 }148 fn latency(&self) -> u32 {149 DISTORTION_LATENCY150 }151}152153/// Gentle saturation: `tanh(g x) / g` at twice the sample rate. Unity gain for small signals,154/// progressively compressed peaks; the output never exceeds `1 / g`.155pub struct Saturation {156 drive: OnePoleSmoother,157 os: [Oversampler2x; 2],158}159160impl Saturation {161 pub fn new() -> Saturation {162 Saturation { drive: OnePoleSmoother::new(db_to_lin(6.0), 0.01, 48_000.0), os: [Oversampler2x::new(), Oversampler2x::new()] }163 }164 pub fn desc() -> EffectDesc {165 desc(166 "saturation",167 "Saturation",168 "colour",169 "Soft saturation with unity small-signal gain, computed at 2x the sample rate.",170 vec![num("drive", Unit::Decibel, 0.0, 24.0, 6.0, "How hard the signal is pushed into the curve (0 dB = almost clean).")],171 vec![preset("tape", "Rounded peaks.", &[("drive", 8.0)]), preset("hot", "Clearly compressed.", &[("drive", 16.0)])],172 LatencySpec { seconds: 0.0, samples: SATURATION_LATENCY },173 1.0,174 )175 }176}177178impl Default for Saturation {179 fn default() -> Self {180 Self::new()181 }182}183184impl Effect for Saturation {185 fn prepare(&mut self, sample_rate: f32, _: usize) {186 let d = self.drive.target();187 self.drive = OnePoleSmoother::new(d, 0.01, sample_rate);188 }189 fn reset(&mut self) {190 self.os[0].reset();191 self.os[1].reset();192 let d = self.drive.target();193 self.drive.snap(d);194 }195 fn set_param(&mut self, index: usize, value: f32) {196 if index == 0 {197 self.drive.set_target(db_to_lin(value));198 }199 }200 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {201 for i in 0..left.len() {202 let g = self.drive.tick();203 left[i] = self.os[0].process(left[i], |x| (g * x).tanh() / g);204 right[i] = self.os[1].process(right[i], |x| (g * x).tanh() / g);205 }206 }207 fn latency(&self) -> u32 {208 SATURATION_LATENCY209 }210}211212/// Bit-depth and sample-rate reduction. Deliberately not anti-aliased: the aliasing is the effect.213pub struct BitCrusher {214 bits: f32,215 factor: usize,216 count: usize,217 held: [f32; 2],218}219220impl BitCrusher {221 pub fn new() -> BitCrusher {222 BitCrusher { bits: 8.0, factor: 4, count: 0, held: [0.0; 2] }223 }224 pub fn desc() -> EffectDesc {225 desc(226 "bitcrusher",227 "Bit Crusher",228 "colour",229 "Quantises to a given word length and holds every Nth sample. No anti-aliasing filter: the images and quantisation distortion are the intended result.",230 vec![num("bits", Unit::Count, 1.0, 24.0, 8.0, "Word length after quantisation."), num("downsample", Unit::Count, 1.0, 64.0, 4.0, "Each sample is held for this many samples.")],231 vec![preset("retro", "8-bit, quarter rate.", &[("bits", 8.0), ("downsample", 4.0)]), preset("destroyed", "4-bit, 1/16 rate.", &[("bits", 4.0), ("downsample", 16.0)])],232 LatencySpec::default(),233 1.0,234 )235 }236}237238impl Default for BitCrusher {239 fn default() -> Self {240 Self::new()241 }242}243244impl Effect for BitCrusher {245 fn prepare(&mut self, _: f32, _: usize) {246 self.reset();247 }248 fn reset(&mut self) {249 self.count = 0;250 self.held = [0.0; 2];251 }252 fn set_param(&mut self, index: usize, value: f32) {253 match index {254 0 => self.bits = value.clamp(1.0, 24.0),255 1 => self.factor = (value as usize).clamp(1, 64),256 _ => {}257 }258 }259 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {260 let steps = (self.bits - 1.0).exp2();261 for i in 0..left.len() {262 if self.count == 0 {263 self.held = [(left[i] * steps).round() / steps, (right[i] * steps).round() / steps];264 }265 self.count = (self.count + 1) % self.factor;266 left[i] = self.held[0];267 right[i] = self.held[1];268 }269 }270}271