Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/plucked.rs3//! Description: Plucked string — extended Karplus-Strong waveguide with pluck position,4//! frequency-dependent loss, stiffness dispersion and a modal body resonator.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::common::{pan_gains, EnvSettings, StringLoop};10use crate::instrument::{Instrument, NoteOn};11use crate::params::{choice, envelope_params, list, num, preset, resolve, Resolved};12use crate::poly::{Engine, Poly};13use sonata_dsp::core::{semitones_to_ratio, DcBlocker};14use sonata_dsp::env::Adsr;15use sonata_dsp::filter::{Biquad, BiquadCoefs, OnePole};16use sonata_ir::{Articulation, EngineDesc, InstrumentSpec, Unit};1718pub fn desc() -> EngineDesc {19 let mut params = vec![20 num(21 "damping",22 Unit::Scalar,23 0.0005,24 1.0,25 0.012,26 true,27 "String loss. The fundamental of A3 (220 Hz) decays by 60 dB in 0.06 / damping seconds; higher notes decay faster (proportional to 1/sqrt(f)).",28 ),29 num("brightness", Unit::Ratio, 0.0, 1.0, 0.6, true, "High-frequency content kept at each round trip of the string (0 = dull nylon, 1 = bright steel)."),30 num("stiffness", Unit::Ratio, 0.0, 1.0, 0.1, false, "Bending stiffness: stretches the upper partials sharp through an allpass in the loop."),31 choice(32 "excitation",33 &["pluck", "strike"],34 "pluck",35 "How the string is set in motion: `pluck` releases a triangular displacement, `strike` injects a hammer-like velocity pulse.",36 ),37 num(38 "excitation.position",39 Unit::Ratio,40 0.02,41 0.5,42 0.2,43 false,44 "Excitation point as a fraction of the string length from the bridge; harmonics with a node there are missing.",45 ),46 num("excitation.hardness", Unit::Ratio, 0.0, 1.0, 0.5, false, "Hardness of the plectrum or hammer: harder means more high harmonics."),47 choice(48 "resonance",49 &["none", "body", "modal"],50 "body",51 "Resonator after the string: `body` is a small set of guitar-like modes, `modal` uses `resonance.frequencies`.",52 ),53 ParamList::desc(),54 num("resonance.mix", Unit::Ratio, 0.0, 1.0, 0.25, true, "Level of the resonator relative to the direct string."),55 num("resonance.decay", Unit::Seconds, 0.01, 5.0, 0.15, false, "Decay time (60 dB) of the resonator modes."),56 num("width", Unit::Ratio, 0.0, 1.0, 0.3, false, "Stereo spread of the strings by pitch."),57 ];58 params.extend(envelope_params(true, 0.002, 0.3, 0.6, 0.25));59 EngineDesc {60 model: "plucked_string".into(),61 title: "Plucked String".into(),62 family: "plucked".into(),63 method: "Digital waveguide (extended Karplus-Strong): tuned delay loop with loss and dispersion filters, analytic pluck excitation, modal body".into(),64 doc: "A single vibrating string per voice, plucked or struck at a chosen point, with a resonant body. Suits guitars, harps, harpsichords, kotos and invented string instruments.".into(),65 range: (28, 96),66 params,67 presets: vec![68 preset("nylon_guitar", "Classical guitar: mellow, medium sustain.", &[("damping", 0.016), ("brightness", 0.45), ("stiffness", 0.05), ("excitation.position", 0.22), ("excitation.hardness", 0.3), ("resonance.mix", 0.35)], &[("resonance", "body")]),69 preset("steel_guitar", "Steel-string guitar: bright, long sustain.", &[("damping", 0.008), ("brightness", 0.85), ("stiffness", 0.2), ("excitation.position", 0.13), ("excitation.hardness", 0.7), ("resonance.mix", 0.3)], &[("resonance", "body")]),70 preset("harp", "Concert harp: soft finger pluck near the middle, no body colouring.", &[("damping", 0.01), ("brightness", 0.55), ("stiffness", 0.02), ("excitation.position", 0.38), ("excitation.hardness", 0.15), ("resonance.mix", 0.1)], &[("resonance", "body")]),71 preset("harpsichord", "Quill pluck close to the bridge: nasal and bright.", &[("damping", 0.02), ("brightness", 0.95), ("stiffness", 0.1), ("excitation.position", 0.07), ("excitation.hardness", 0.95), ("resonance.mix", 0.15), ("envelope.release", 0.08)], &[("resonance", "body")]),72 preset("banjo", "Short, bright, strongly coloured by the head.", &[("damping", 0.06), ("brightness", 0.9), ("stiffness", 0.15), ("excitation.position", 0.1), ("excitation.hardness", 0.85), ("resonance.mix", 0.6), ("resonance.decay", 0.06)], &[("resonance", "body")]),73 preset("dulcimer", "Struck string with a long ring.", &[("damping", 0.007), ("brightness", 0.7), ("stiffness", 0.25), ("excitation.position", 0.15), ("excitation.hardness", 0.6), ("resonance.mix", 0.2)], &[("excitation", "strike"), ("resonance", "body")]),74 ],75 articulations: vec!["normal".into(), "staccato".into(), "legato".into(), "accent".into(), "pizzicato".into()],76 pitched: true,77 }78}7980struct ParamList;81impl ParamList {82 fn desc() -> sonata_ir::ParamDesc {83 sonata_ir::ParamDesc::list("resonance.frequencies", Unit::HertzList, 20.0, 20_000.0, "Mode frequencies of the `modal` resonator (at most 16 are used).")84 }85}8687const LEVEL: f32 = 0.3;88const BODY_MODES: [f32; 5] = [98.0, 204.0, 287.0, 414.0, 592.0];8990pub struct Plucked {91 sr: f32,92 r: Resolved,93 env: EnvSettings,94 i_damping: usize,95 i_bright: usize,96 i_mix: usize,97 strike: bool,98 mode_freqs: Vec<f32>,99 body: Vec<Biquad>,100}101102pub struct Voice {103 string: StringLoop,104 lp: OnePole,105 dc: DcBlocker,106 env: Adsr,107 n: u32,108 period: f32,109 pos: f32,110 hard: f32,111 amp: f32,112 freq: f32,113 t60: f32,114 gl: f32,115 gr: f32,116 released: bool,117}118119impl Plucked {120 fn t60(&self, freq: f32) -> f32 {121 (0.06 / self.r.v[self.i_damping]) * (220.0 / freq.max(20.0)).sqrt()122 }123 fn damp(&self) -> f32 {124 0.45 * (1.0 - self.r.v[self.i_bright]).powi(2) + 0.004125 }126}127128impl Engine for Plucked {129 type Voice = Voice;130131 fn prepare(&mut self, sample_rate: f32, _max_block: usize) {132 self.sr = sample_rate;133 let decay = self.r.get("resonance.decay");134 self.body = self.mode_freqs.iter().filter(|f| **f < 0.45 * sample_rate).map(|f| Biquad::new(BiquadCoefs::resonator(*f, decay, sample_rate))).collect();135 }136137 fn make_voice(&self, sr: f32) -> Voice {138 Voice {139 string: StringLoop::new(sr, 20.0),140 lp: OnePole::new(8000.0, sr),141 dc: DcBlocker::new(15.0, sr),142 env: Adsr::new(sr),143 n: 0,144 period: 100.0,145 pos: 0.2,146 hard: 0.5,147 amp: 0.0,148 freq: 220.0,149 t60: 2.0,150 gl: 1.0,151 gr: 1.0,152 released: false,153 }154 }155156 fn start(&self, v: &mut Voice, note: &NoteOn, _seed: u64) {157 let vel = note.velocity.clamp(0.0, 1.0);158 v.string.clear();159 v.lp.reset();160 v.dc.reset();161 v.freq = note.freq;162 v.t60 = self.t60(note.freq) * if note.articulation == Articulation::Pizzicato { 0.12 } else { 1.0 };163 v.string.tune(note.freq, v.t60, self.damp(), 0.6 * self.r.get("stiffness"));164 v.period = v.string.period();165 v.pos = self.r.get("excitation.position");166 v.hard = (self.r.get("excitation.hardness") * (0.5 + 0.5 * vel)).clamp(0.0, 1.0);167 v.lp.set((note.freq * (3.0 + 60.0 * v.hard * v.hard)).min(0.45 * self.sr), self.sr);168 let accent = match note.articulation {169 Articulation::Accent | Articulation::Marcato => 1.15,170 _ => 1.0,171 };172 v.amp = LEVEL * vel.powf(1.3) * accent;173 v.n = 0;174 v.released = false;175 let (gl, gr) = pan_gains(((note.pitch - 60.0) / 36.0).clamp(-1.0, 1.0) * self.r.get("width"));176 v.gl = gl;177 v.gr = gr;178 self.env.start(&mut v.env);179 }180181 fn release(&self, v: &mut Voice) {182 v.released = true;183 v.env.gate_off();184 v.string.set_t60(self.env.release.min(v.t60));185 }186187 fn bend(&self, v: &mut Voice, semitones: f32) {188 v.string.set_freq(v.freq * semitones_to_ratio(semitones));189 }190191 fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {192 let n_exc = (v.period * if self.strike { 1.0 + v.pos } else { 1.0 }) as u32 + 1;193 for i in 0..left.len() {194 let exc = if v.n < n_exc {195 let t = v.n as f32 / v.period;196 let raw = if self.strike {197 // Hammer: half-sine velocity pulse, reflected with inversion from the near end.198 let len = 0.08 + 0.35 * (1.0 - v.hard);199 let pulse = |x: f32| if (0.0..len).contains(&x) { (std::f32::consts::PI * x / len).sin() } else { 0.0 };200 0.6 * (pulse(t) - pulse(t - v.pos))201 } else if t < 1.0 {202 // Pluck: one period of the released triangular displacement (zero mean),203 // blended with its derivative for a harder plectrum.204 let tri = if t < v.pos { t / v.pos } else { (1.0 - t) / (1.0 - v.pos) };205 let sq = if t < v.pos { 1.0 - v.pos } else { -v.pos };206 (1.0 - v.hard) * (2.0 * tri - 1.0) + v.hard * 1.6 * sq207 } else {208 0.0209 };210 v.n += 1;211 v.lp.lowpass(raw) * v.amp212 } else {213 0.0214 };215 let y = v.dc.tick(v.string.tick(exc)) * v.env.tick();216 left[i] = y * v.gl;217 right[i] = y * v.gr;218 }219 !v.env.is_idle()220 }221222 fn set_param(&mut self, index: usize, value: f32) {223 if index < self.r.v.len() {224 self.r.v[index] = value;225 }226 }227228 fn post(&mut self, left: &mut [f32], right: &mut [f32], _pedal: bool) {229 if self.body.is_empty() {230 return;231 }232 let mix = self.r.v[self.i_mix] * 1.5 / (self.body.len() as f32).sqrt();233 for i in 0..left.len() {234 let x = 0.5 * (left[i] + right[i]);235 let mut acc = 0.0;236 for b in &mut self.body {237 acc += b.tick(x);238 }239 left[i] += acc * mix;240 right[i] += acc * mix;241 }242 }243244 fn reset_shared(&mut self) {245 self.body.iter_mut().for_each(|b| b.reset());246 }247248 fn tail_seconds(&self) -> f32 {249 if self.body.is_empty() {250 0.0251 } else {252 self.r.get("resonance.decay")253 }254 }255256 fn decays_naturally(&self) -> bool {257 true258 }259}260261pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {262 let d = desc();263 let r = resolve(&d, spec)?;264 let mode_freqs: Vec<f32> = match r.pick("resonance") {265 0 => Vec::new(),266 1 => BODY_MODES.to_vec(),267 _ => {268 let l = list(spec, "resonance.frequencies");269 if l.is_empty() {270 return Err(format!("instrument '{}': `resonance modal` needs `frequencies`", spec.name));271 }272 l.into_iter().take(16).collect()273 }274 };275 let e = Plucked {276 sr: 48_000.0,277 env: EnvSettings::read(&r, true),278 i_damping: r.idx("damping"),279 i_bright: r.idx("brightness"),280 i_mix: r.idx("resonance.mix"),281 strike: r.pick("excitation") == 1,282 mode_freqs,283 body: Vec::new(),284 r,285 };286 Ok(Box::new(Poly::new(e, seed)))287}288