SPB Git

Repository Public

drums.rs 15.3 KB 409 lines rust

1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/drums.rs3//! Description: Synthesised drums — kick (swept sine), snare (shell modes and noise) and4//! hi-hat (six inharmonic square oscillators through band-pass filters).5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::common::sin_turns;10use crate::instrument::{Instrument, NoteOn};11use crate::params::{num, preset, resolve, Resolved};12use crate::poly::{Engine, Poly};13use sonata_dsp::core::{fast_tanh, Rng};14use sonata_dsp::filter::{OnePole, Svf};15use sonata_dsp::osc::{Oscillator, Waveform};16use sonata_ir::{EngineDesc, InstrumentSpec, Unit};1718fn drum_articulations() -> Vec<String> {19    vec!["normal".into(), "accent".into()]20}2122// ───────────────────────────── Kick ─────────────────────────────2324pub fn kick_desc() -> EngineDesc {25    EngineDesc {26        model: "kick".into(),27        title: "Kick Drum".into(),28        family: "percussion".into(),29        method: "Sine oscillator with an exponential downward pitch sweep and exponential amplitude decay, filtered-noise click, tanh drive".into(),30        doc: "A synthesised bass drum. Unpitched: the note number is ignored, `tune` sets the resting frequency.".into(),31        range: (0, 127),32        params: vec![33            num("tune", Unit::Hertz, 25.0, 120.0, 50.0, true, "Frequency the drum settles on."),34            num("sweep", Unit::Semitones, 0.0, 60.0, 26.0, true, "How far above `tune` the pitch starts."),35            num("sweep.time", Unit::Seconds, 0.003, 0.4, 0.045, false, "Time constant of the pitch drop."),36            num("decay", Unit::Seconds, 0.03, 3.0, 0.4, true, "Amplitude decay time (60 dB)."),37            num("click", Unit::Ratio, 0.0, 1.0, 0.3, true, "Level of the beater click."),38            num("drive", Unit::Ratio, 0.0, 1.0, 0.2, true, "Saturation: adds harmonics so the kick reads on small speakers."),39        ],40        presets: vec![41            preset(42                "punchy",43                "Tight, clicky kick.",44                &[("tune", 55.0), ("sweep", 30.0), ("sweep.time", 0.03), ("decay", 0.28), ("click", 0.5), ("drive", 0.35)],45                &[],46            ),47            preset(48                "boom",49                "Long, low 808-style boom.",50                &[("tune", 42.0), ("sweep", 18.0), ("sweep.time", 0.06), ("decay", 1.4), ("click", 0.1), ("drive", 0.1)],51                &[],52            ),53            preset(54                "acoustic",55                "Short, with a strong beater.",56                &[("tune", 62.0), ("sweep", 14.0), ("sweep.time", 0.02), ("decay", 0.22), ("click", 0.8), ("drive", 0.15)],57                &[],58            ),59            preset("sub", "Pure sub drop.", &[("tune", 36.0), ("sweep", 36.0), ("sweep.time", 0.09), ("decay", 0.9), ("click", 0.0), ("drive", 0.0)], &[]),60        ],61        articulations: drum_articulations(),62        pitched: false,63    }64}6566pub struct Kick {67    sr: f32,68    r: Resolved,69}7071pub struct KickVoice {72    phase: f32,73    sweep: f32,74    sweep_decay: f32,75    amp: f32,76    amp_decay: f32,77    click: f32,78    click_decay: f32,79    lp: OnePole,80    rng: Rng,81    vel: f32,82    fade: f32,83}8485impl Engine for Kick {86    type Voice = KickVoice;87    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {88        self.sr = sample_rate;89    }90    fn make_voice(&self, sr: f32) -> KickVoice {91        KickVoice {92            phase: 0.0,93            sweep: 0.0,94            sweep_decay: 0.99,95            amp: 0.0,96            amp_decay: 0.999,97            click: 0.0,98            click_decay: 0.9,99            lp: OnePole::new(3500.0, sr),100            rng: Rng::new(1),101            vel: 0.0,102            fade: 1.0,103        }104    }105    fn start(&self, v: &mut KickVoice, note: &NoteOn, seed: u64) {106        let sr = self.sr;107        v.vel = note.velocity.clamp(0.0, 1.0);108        v.phase = 0.0;109        v.sweep = self.r.get("sweep") * (0.6 + 0.4 * v.vel);110        v.sweep_decay = (-1.0 / (self.r.get("sweep.time") * sr)).exp();111        v.amp = 1.0;112        v.amp_decay = (-6.9 / (self.r.get("decay") * sr)).exp();113        v.click = self.r.get("click");114        v.click_decay = (-1.0 / (0.004 * sr)).exp();115        v.lp.reset();116        v.rng = Rng::new(seed);117        v.fade = 1.0;118    }119    fn release(&self, _v: &mut KickVoice) {}120    fn bend(&self, _v: &mut KickVoice, _semitones: f32) {}121    fn render(&self, v: &mut KickVoice, left: &mut [f32], right: &mut [f32]) -> bool {122        let sr = self.sr;123        let tune = self.r.get("tune");124        let drive = self.r.get("drive");125        let pre = 1.0 + 5.0 * drive;126        let post = 0.5 / fast_tanh(pre).max(0.3);127        for i in 0..left.len() {128            let f = tune * (v.sweep * (std::f32::consts::LN_2 / 12.0)).exp();129            v.sweep *= v.sweep_decay;130            v.phase += f / sr;131            if v.phase >= 1.0 {132                v.phase -= 1.0;133            }134            let mut y = sin_turns(v.phase) * v.amp;135            if v.click > 1e-4 {136                y += v.lp.lowpass(v.rng.bipolar()) * v.click * 0.8;137                v.click *= v.click_decay;138            }139            v.amp *= v.amp_decay;140            let y = fast_tanh(y * pre) * post * (0.15 + 0.85 * v.vel * v.vel);141            left[i] = y;142            right[i] = y;143        }144        v.amp > 1e-4145    }146    fn set_param(&mut self, index: usize, value: f32) {147        if index < self.r.v.len() {148            self.r.v[index] = value;149        }150    }151    fn decays_naturally(&self) -> bool {152        true153    }154}155156pub fn kick_build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {157    let r = resolve(&kick_desc(), spec)?;158    Ok(Box::new(Poly::new(Kick { sr: 48_000.0, r }, seed)))159}160161// ───────────────────────────── Snare ─────────────────────────────162163pub fn snare_desc() -> EngineDesc {164    EngineDesc {165        model: "snare".into(),166        title: "Snare Drum".into(),167        family: "percussion".into(),168        method: "Two decaying sinusoids for the shell modes (ratio 1 : 1.78) with a short pitch drop, plus band-passed white noise for the snare wires".into(),169        doc: "A synthesised snare drum. Unpitched: the note number is ignored.".into(),170        range: (0, 127),171        params: vec![172            num("tune", Unit::Hertz, 100.0, 400.0, 185.0, true, "Frequency of the lower shell mode."),173            num("tone", Unit::Ratio, 0.0, 1.0, 0.5, true, "Balance of the shell tone against the wires."),174            num("snappy", Unit::Ratio, 0.0, 1.0, 0.6, true, "Level of the snare wires."),175            num("decay", Unit::Seconds, 0.03, 2.0, 0.2, true, "Decay time of the wires (60 dB); the shell decays in 60 % of it."),176            num("noise.color", Unit::Hertz, 800.0, 12_000.0, 4500.0, true, "Centre frequency of the wire noise."),177        ],178        presets: vec![179            preset("tight", "Short and crisp.", &[("decay", 0.14), ("snappy", 0.7), ("tune", 205.0), ("noise.color", 6000.0)], &[]),180            preset("fat", "Low, long and heavy.", &[("decay", 0.4), ("snappy", 0.55), ("tune", 150.0), ("tone", 0.7), ("noise.color", 3200.0)], &[]),181            preset(182                "electro",183                "808-style: tonal, bright noise.",184                &[("decay", 0.25), ("snappy", 0.5), ("tune", 175.0), ("tone", 0.75), ("noise.color", 7500.0)],185                &[],186            ),187            preset("brush", "Mostly wires, soft.", &[("decay", 0.3), ("snappy", 0.9), ("tone", 0.15), ("noise.color", 3800.0)], &[]),188        ],189        articulations: drum_articulations(),190        pitched: false,191    }192}193194pub struct Snare {195    sr: f32,196    r: Resolved,197}198199pub struct SnareVoice {200    p1: f32,201    p2: f32,202    drop: f32,203    drop_decay: f32,204    tone_amp: f32,205    tone_decay: f32,206    noise_amp: f32,207    noise_decay: f32,208    bp: Svf,209    hp: OnePole,210    rng: Rng,211    vel: f32,212}213214impl Engine for Snare {215    type Voice = SnareVoice;216    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {217        self.sr = sample_rate;218    }219    fn make_voice(&self, sr: f32) -> SnareVoice {220        SnareVoice {221            p1: 0.0,222            p2: 0.0,223            drop: 0.0,224            drop_decay: 0.99,225            tone_amp: 0.0,226            tone_decay: 0.99,227            noise_amp: 0.0,228            noise_decay: 0.99,229            bp: Svf::new(sr),230            hp: OnePole::new(700.0, sr),231            rng: Rng::new(1),232            vel: 0.0,233        }234    }235    fn start(&self, v: &mut SnareVoice, note: &NoteOn, seed: u64) {236        let sr = self.sr;237        let decay = self.r.get("decay");238        v.vel = note.velocity.clamp(0.0, 1.0);239        v.p1 = 0.0;240        v.p2 = 0.0;241        v.drop = 5.0;242        v.drop_decay = (-1.0 / (0.012 * sr)).exp();243        v.tone_amp = 1.0;244        v.tone_decay = (-6.9 / (0.6 * decay * sr)).exp();245        v.noise_amp = 1.0;246        v.noise_decay = (-6.9 / (decay * sr)).exp();247        v.bp.reset();248        v.hp.reset();249        v.rng = Rng::new(seed);250    }251    fn release(&self, _v: &mut SnareVoice) {}252    fn bend(&self, _v: &mut SnareVoice, _semitones: f32) {}253    fn render(&self, v: &mut SnareVoice, left: &mut [f32], right: &mut [f32]) -> bool {254        let sr = self.sr;255        let tune = self.r.get("tune");256        let tone = self.r.get("tone");257        let snappy = self.r.get("snappy");258        v.bp.set(self.r.get("noise.color").min(0.4 * sr), 0.8);259        let level = 0.55 * (0.1 + 0.9 * v.vel * v.vel);260        for i in 0..left.len() {261            let f = tune * (v.drop * (std::f32::consts::LN_2 / 12.0)).exp();262            v.drop *= v.drop_decay;263            v.p1 += f / sr;264            v.p2 += 1.78 * f / sr;265            if v.p1 >= 1.0 {266                v.p1 -= 1.0;267            }268            if v.p2 >= 1.0 {269                v.p2 -= 1.0;270            }271            let shell = (sin_turns(v.p1) + 0.55 * sin_turns(v.p2)) * v.tone_amp * (0.3 + 0.9 * tone);272            let wires = v.hp.highpass(v.bp.tick(v.rng.bipolar()).band) * v.noise_amp * snappy * 1.6;273            v.tone_amp *= v.tone_decay;274            v.noise_amp *= v.noise_decay;275            let y = fast_tanh((shell + wires) * 1.2) * level;276            left[i] = y;277            right[i] = y;278        }279        v.noise_amp > 1e-4 || v.tone_amp > 1e-4280    }281    fn set_param(&mut self, index: usize, value: f32) {282        if index < self.r.v.len() {283            self.r.v[index] = value;284        }285    }286    fn decays_naturally(&self) -> bool {287        true288    }289}290291pub fn snare_build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {292    let r = resolve(&snare_desc(), spec)?;293    Ok(Box::new(Poly::new(Snare { sr: 48_000.0, r }, seed)))294}295296// ───────────────────────────── Hi-hat ─────────────────────────────297298pub fn hihat_desc() -> EngineDesc {299    EngineDesc {300        model: "hihat".into(),301        title: "Hi-Hat".into(),302        family: "percussion".into(),303        method: "Six band-limited square oscillators at inharmonic ratios, summed through two band-pass filters and a high-pass, with an exponential envelope".into(),304        doc: "A synthesised hi-hat or cymbal. Unpitched: the note number is ignored. A new note chokes nothing by itself: use a short `decay` for closed and a long one for open sounds.".into(),305        range: (0, 127),306        params: vec![307            num("decay", Unit::Seconds, 0.01, 6.0, 0.07, true, "Decay time (60 dB): about 0.07 s closed, 0.5 s open, 2 s and more for a ride or crash."),308            num("tune", Unit::Scalar, 0.5, 2.0, 1.0, true, "Multiplier of the six oscillator frequencies."),309            num("tone", Unit::Ratio, 0.0, 1.0, 0.6, true, "High-pass cutoff: higher is thinner and brighter."),310            num("metal", Unit::Ratio, 0.0, 1.0, 0.6, true, "Emphasis of the metallic band-pass resonances."),311        ],312        presets: vec![313            preset("closed", "Closed hi-hat.", &[], &[]),314            preset("open", "Open hi-hat.", &[("decay", 0.55)], &[]),315            preset("pedal", "Pedal chick: very short, darker.", &[("decay", 0.035), ("tone", 0.4)], &[]),316            preset("ride", "Ride cymbal: long, lower, pingy.", &[("decay", 2.6), ("tune", 0.72), ("tone", 0.35), ("metal", 0.9)], &[]),317            preset("crash", "Crash: long and bright.", &[("decay", 3.5), ("tune", 0.9), ("tone", 0.5), ("metal", 0.3)], &[]),318        ],319        articulations: drum_articulations(),320        pitched: false,321    }322}323324const HAT_FREQS: [f32; 6] = [205.3, 304.4, 369.6, 522.7, 540.0, 800.0];325326pub struct HiHat {327    sr: f32,328    r: Resolved,329}330331pub struct HatVoice {332    osc: [Oscillator; 6],333    bp1: Svf,334    bp2: Svf,335    hp: Svf,336    amp: f32,337    decay: f32,338    attack: f32,339    vel: f32,340}341342impl Engine for HiHat {343    type Voice = HatVoice;344    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {345        self.sr = sample_rate;346    }347    fn make_voice(&self, sr: f32) -> HatVoice {348        let mut o = Oscillator::new(sr);349        o.waveform = Waveform::Square;350        HatVoice { osc: [o; 6], bp1: Svf::new(sr), bp2: Svf::new(sr), hp: Svf::new(sr), amp: 0.0, decay: 0.99, attack: 0.0, vel: 0.0 }351    }352    fn start(&self, v: &mut HatVoice, note: &NoteOn, seed: u64) {353        let mut rng = Rng::new(seed);354        for o in &mut v.osc {355            o.set_phase(rng.unipolar());356        }357        v.bp1.reset();358        v.bp2.reset();359        v.hp.reset();360        v.amp = 1.0;361        v.decay = (-6.9 / (self.r.get("decay") * self.sr)).exp();362        v.attack = 0.0;363        v.vel = note.velocity.clamp(0.0, 1.0);364    }365    fn release(&self, _v: &mut HatVoice) {}366    fn bend(&self, _v: &mut HatVoice, _semitones: f32) {}367    fn render(&self, v: &mut HatVoice, left: &mut [f32], right: &mut [f32]) -> bool {368        let sr = self.sr;369        let tune = self.r.get("tune");370        for (o, f) in v.osc.iter_mut().zip(HAT_FREQS) {371            // The 808 ratios, moved up 6.5x so the cluster sits in the cymbal range.372            o.set_freq((f * tune * 6.5).min(0.45 * sr));373        }374        let metal = self.r.get("metal");375        v.bp1.set((3440.0 * tune).min(0.4 * sr), 1.0 + 6.0 * metal);376        v.bp2.set((7100.0 * tune).min(0.4 * sr), 1.0 + 6.0 * metal);377        v.hp.set((2500.0 + 7000.0 * self.r.get("tone")).min(0.4 * sr), 0.7);378        let level = 0.28 * (0.08 + 0.92 * v.vel * v.vel);379        let attack_step = 1.0 / (0.0006 * sr);380        for i in 0..left.len() {381            let mut x = 0.0;382            for o in &mut v.osc {383                x += o.tick();384            }385            x *= 1.0 / 6.0;386            let y = v.hp.tick(x * (1.0 - 0.5 * metal) + (v.bp1.tick(x).band + v.bp2.tick(x).band) * 0.5 * metal).high;387            v.attack = (v.attack + attack_step).min(1.0);388            let y = y * v.amp * v.attack * level * 3.0;389            v.amp *= v.decay;390            left[i] = y;391            right[i] = y;392        }393        v.amp > 1e-4394    }395    fn set_param(&mut self, index: usize, value: f32) {396        if index < self.r.v.len() {397            self.r.v[index] = value;398        }399    }400    fn decays_naturally(&self) -> bool {401        true402    }403}404405pub fn hihat_build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {406    let r = resolve(&hihat_desc(), spec)?;407    Ok(Box::new(Poly::new(HiHat { sr: 48_000.0, r }, seed)))408}409
Files main
Menu

Theme