Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/bass.rs3//! Description: Bass — an electric bass (plucked waveguide string through a pickup and amp4//! model) or a monophonic-style synth bass (saw/square with a resonant 24 dB filter).5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::common::{sin_turns, EnvSettings, StringLoop};10use crate::instrument::{Instrument, NoteOn};11use crate::params::{choice, envelope_params, num, preset, resolve, Resolved};12use crate::poly::{Engine, Poly};13use sonata_dsp::core::{fast_tanh, semitones_to_ratio, DcBlocker};14use sonata_dsp::env::Adsr;15use sonata_dsp::filter::{OnePole, Svf};16use sonata_dsp::osc::{Oscillator, Waveform};17use sonata_ir::{EngineDesc, InstrumentSpec, Unit};1819pub fn desc() -> EngineDesc {20 let mut params = vec![21 choice("type", &["electric", "synth"], "electric", "`electric`: plucked string, pickup and amplifier. `synth`: oscillators and resonant filter."),22 num("tone", Unit::Ratio, 0.0, 1.0, 0.5, true, "Electric: tone control of the pickup. Synth: filter cutoff."),23 num("drive", Unit::Ratio, 0.0, 1.0, 0.15, true, "Amplifier saturation."),24 num("damping", Unit::Scalar, 0.002, 1.0, 0.02, false, "Electric: string loss (as in plucked_string). Palm muting is a high value."),25 num("excitation.position", Unit::Ratio, 0.03, 0.5, 0.2, false, "Electric: plucking point from the bridge."),26 num("excitation.hardness", Unit::Ratio, 0.0, 1.0, 0.4, false, "Electric: finger (soft) to pick (hard)."),27 num("pickup.position", Unit::Ratio, 0.05, 0.5, 0.18, false, "Electric: pickup location from the bridge; it combs the spectrum."),28 num("shape", Unit::Ratio, 0.0, 1.0, 0.3, true, "Synth: blend from sawtooth (0) to square (1)."),29 num("sub", Unit::Ratio, 0.0, 1.0, 0.3, true, "Synth: level of the sine one octave below."),30 num("filter.resonance", Unit::Ratio, 0.0, 1.0, 0.3, true, "Synth: filter resonance."),31 num("filter.envelope", Unit::Scalar, 0.0, 6.0, 2.5, true, "Synth: filter envelope depth in octaves."),32 num("filter.decay", Unit::Seconds, 0.01, 5.0, 0.18, false, "Synth: filter envelope decay."),33 ];34 params.extend(envelope_params(true, 0.002, 0.4, 0.7, 0.08));35 EngineDesc {36 model: "bass".into(),37 title: "Bass".into(),38 family: "bass".into(),39 method: "Electric: Karplus-Strong waveguide string, pickup comb filter, one-pole tone control, tanh amplifier. Synth: polyBLEP saw/square plus sub sine through two cascaded state-variable low-pass filters with an envelope".into(),40 doc: "Two bass instruments under one model. The `type` choice selects which engine a preset uses; parameters marked Electric or Synth only affect that type.".into(),41 range: (16, 72),42 params,43 presets: vec![44 preset("finger", "Fingered electric bass: round and warm.", &[], &[]),45 preset("pick", "Picked electric bass: bright attack.", &[("tone", 0.8), ("excitation.hardness", 0.9), ("excitation.position", 0.1), ("drive", 0.3), ("pickup.position", 0.12)], &[]),46 preset("muted", "Palm-muted, short.", &[("damping", 0.25), ("tone", 0.35), ("excitation.hardness", 0.6)], &[]),47 preset("sub", "Deep synth sub bass.", &[("tone", 0.18), ("sub", 0.9), ("shape", 0.0), ("filter.envelope", 0.5), ("drive", 0.05), ("envelope.sustain", 1.0)], &[("type", "synth"), ("envelope", "adsr")]),48 preset("acid", "Resonant squelch.", &[("tone", 0.22), ("shape", 0.0), ("sub", 0.0), ("filter.resonance", 0.85), ("filter.envelope", 4.0), ("filter.decay", 0.14), ("drive", 0.5), ("envelope.decay", 0.2), ("envelope.sustain", 0.6)], &[("type", "synth"), ("envelope", "adsr")]),49 preset("reese", "Dark square bass with drive.", &[("tone", 0.3), ("shape", 1.0), ("sub", 0.5), ("filter.resonance", 0.2), ("filter.envelope", 1.0), ("filter.decay", 0.5), ("drive", 0.6), ("envelope.sustain", 0.9)], &[("type", "synth"), ("envelope", "adsr")]),50 ],51 articulations: vec!["normal".into(), "staccato".into(), "legato".into(), "accent".into()],52 pitched: true,53 }54}5556const LEVEL_ELECTRIC: f32 = 0.6;57const LEVEL_SYNTH: f32 = 0.45;5859pub struct Bass {60 sr: f32,61 r: Resolved,62 env: EnvSettings,63 synth: bool,64}6566pub struct Voice {67 string: StringLoop,68 exc_lp: OnePole,69 tone_lp: OnePole,70 pickup: sonata_dsp::core::DelayLine,71 dc: DcBlocker,72 saw: Oscillator,73 sq: Oscillator,74 sub_phase: f32,75 f1: Svf,76 f2: Svf,77 fenv: f32,78 fenv_decay: f32,79 env: Adsr,80 n: u32,81 period: f32,82 pos: f32,83 hard: f32,84 amp: f32,85 freq: f32,86 bend: f32,87 vel: f32,88 t60: f32,89}9091impl Engine for Bass {92 type Voice = Voice;93 fn prepare(&mut self, sample_rate: f32, _max_block: usize) {94 self.sr = sample_rate;95 }96 fn make_voice(&self, sr: f32) -> Voice {97 let mut saw = Oscillator::new(sr);98 saw.waveform = Waveform::Saw;99 let mut sq = Oscillator::new(sr);100 sq.waveform = Waveform::Square;101 Voice {102 string: StringLoop::new(sr, 18.0),103 exc_lp: OnePole::new(2000.0, sr),104 tone_lp: OnePole::new(2000.0, sr),105 pickup: sonata_dsp::core::DelayLine::new((sr / 18.0) as usize),106 dc: DcBlocker::new(12.0, sr),107 saw,108 sq,109 sub_phase: 0.0,110 f1: Svf::new(sr),111 f2: Svf::new(sr),112 fenv: 0.0,113 fenv_decay: 0.999,114 env: Adsr::new(sr),115 n: 0,116 period: 100.0,117 pos: 0.2,118 hard: 0.4,119 amp: 0.0,120 freq: 55.0,121 bend: 1.0,122 vel: 0.0,123 t60: 2.0,124 }125 }126 fn start(&self, v: &mut Voice, note: &NoteOn, _seed: u64) {127 let sr = self.sr;128 v.vel = note.velocity.clamp(0.0, 1.0);129 v.freq = note.freq;130 v.bend = 1.0;131 v.dc.reset();132 if self.synth {133 v.saw.set_phase(0.0);134 v.sq.set_phase(0.0);135 v.sub_phase = 0.0;136 v.f1.reset();137 v.f2.reset();138 v.fenv = 1.0;139 v.fenv_decay = (-6.9 / (self.r.get("filter.decay") * sr)).exp();140 } else {141 v.string.clear();142 v.exc_lp.reset();143 v.tone_lp.reset();144 v.pickup.clear();145 v.t60 = (0.06 / self.r.get("damping")) * (110.0 / note.freq.max(20.0)).sqrt();146 v.string.tune(note.freq, v.t60, 0.12 + 0.2 * (1.0 - self.r.get("tone")), 0.12);147 v.period = v.string.period();148 v.pos = self.r.get("excitation.position");149 v.hard = (self.r.get("excitation.hardness") * (0.6 + 0.4 * v.vel)).clamp(0.0, 1.0);150 v.exc_lp.set((note.freq * (4.0 + 50.0 * v.hard * v.hard)).min(0.45 * sr), sr);151 v.amp = v.vel.powf(1.2);152 v.n = 0;153 }154 self.env.start(&mut v.env);155 }156 fn release(&self, v: &mut Voice) {157 v.env.gate_off();158 if !self.synth {159 v.string.set_t60(self.env.release.min(v.t60));160 }161 }162 fn bend(&self, v: &mut Voice, semitones: f32) {163 v.bend = semitones_to_ratio(semitones);164 if !self.synth {165 v.string.set_freq(v.freq * v.bend);166 }167 }168 fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {169 let sr = self.sr;170 let tone = self.r.get("tone");171 let drive = self.r.get("drive");172 let pre = 1.0 + 8.0 * drive;173 let post = 1.0 / (1.0 + 3.0 * drive);174 if self.synth {175 let shape = self.r.get("shape");176 let sub = self.r.get("sub");177 let q = 0.6 + 9.0 * self.r.get("filter.resonance").powi(2);178 let env_oct = self.r.get("filter.envelope") * (0.5 + 0.5 * v.vel);179 let base = 40.0 * 2f32.powf(tone * 8.0);180 let f = v.freq * v.bend;181 v.saw.set_freq(f);182 v.sq.set_freq(f);183 for i in 0..left.len() {184 if i.is_multiple_of(8) {185 let c = (base * 2f32.powf(env_oct * v.fenv)).clamp(30.0, 0.45 * sr);186 v.f1.set(c, q);187 v.f2.set(c, 0.6);188 }189 v.fenv *= v.fenv_decay;190 v.sub_phase += 0.5 * f / sr;191 if v.sub_phase >= 1.0 {192 v.sub_phase -= 1.0;193 }194 let x = (1.0 - shape) * v.saw.tick() + shape * v.sq.tick() * 0.8;195 let y = v.f2.tick(v.f1.tick(x).low).low + sub * sin_turns(v.sub_phase);196 let y = fast_tanh(y * pre) * post * LEVEL_SYNTH * (0.3 + 0.7 * v.vel) * v.env.tick();197 left[i] = y;198 right[i] = y;199 }200 } else {201 v.tone_lp.set(250.0 * 2f32.powf(tone * 4.6), sr);202 let pick_d = (v.period * self.r.get("pickup.position") / v.bend).max(1.0);203 for i in 0..left.len() {204 let exc = if (v.n as f32) < v.period {205 let t = v.n as f32 / v.period;206 let tri = if t < v.pos { t / v.pos } else { (1.0 - t) / (1.0 - v.pos) };207 let sq = if t < v.pos { 1.0 - v.pos } else { -v.pos };208 v.n += 1;209 v.exc_lp.lowpass((1.0 - v.hard) * (2.0 * tri - 1.0) + v.hard * 1.6 * sq) * v.amp210 } else {211 0.0212 };213 let s = v.string.tick(exc);214 // Pickup: senses the string at one point, i.e. the wave minus its reflection delayed215 // by the round trip to the bridge.216 let p = s - v.pickup.read(pick_d);217 v.pickup.write(s);218 let y = v.tone_lp.lowpass(v.dc.tick(p)) * 0.5;219 let y = fast_tanh(y * pre) * post * LEVEL_ELECTRIC * v.env.tick();220 left[i] = y;221 right[i] = y;222 }223 }224 !v.env.is_idle()225 }226 fn set_param(&mut self, index: usize, value: f32) {227 if index < self.r.v.len() {228 self.r.v[index] = value;229 }230 }231 fn decays_naturally(&self) -> bool {232 !self.synth233 }234}235236pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {237 let r = resolve(&desc(), spec)?;238 let synth = r.pick("type") == 1;239 Ok(Box::new(Poly::new(Bass { sr: 48_000.0, env: EnvSettings::read(&r, true), synth, r }, seed)))240}241