Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/bowed.rs3//! Description: Bowed string — two-segment digital waveguide with a memoryless stick-slip4//! friction curve at the bow, bridge loss filter, vibrato, body modes and section players.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::common::{interp_table, one_pole_coef, one_pole_phase_delay, pan_gains, vibrato_params, EnvSettings, Vibrato};10use crate::instrument::{Instrument, NoteOn};11use crate::params::{envelope_params, num, preset, resolve, Resolved};12use crate::poly::{Engine, Poly};13use sonata_dsp::core::{flush, semitones_to_ratio, DelayLine, Rng};14use sonata_dsp::env::Adsr;15use sonata_dsp::filter::{Biquad, BiquadCoefs};16use sonata_ir::{Articulation, EngineDesc, InstrumentSpec, Unit};1718pub fn desc() -> EngineDesc {19 let mut params = vec![20 num(21 "bow.pressure",22 Unit::Ratio,23 0.0,24 1.0,25 0.6,26 true,27 "Bow force: narrows the sticking region of the friction curve. Low = airy and unstable, high = pressed.",28 ),29 num("bow.speed", Unit::Ratio, 0.05, 1.0, 0.7, true, "Bow velocity, the main loudness control (scaled by note velocity)."),30 num(31 "bow.position",32 Unit::Ratio,33 0.03,34 0.3,35 0.127,36 false,37 "Bowing point as a fraction of the string from the bridge (sul ponticello when small, sul tasto when large).",38 ),39 num("brightness", Unit::Ratio, 0.0, 1.0, 0.5, true, "Cutoff of the string's loss filter at the bridge."),40 num("body.mix", Unit::Ratio, 0.0, 1.0, 0.6, true, "Level of the body resonances."),41 num(42 "body.size",43 Unit::Scalar,44 0.4,45 5.0,46 1.0,47 false,48 "Scale of the body: its mode frequencies are divided by this (violin 1, viola 1.2, cello 2.6, double bass 4.2).",49 ),50 num(51 "players",52 Unit::Count,53 1.0,54 4.0,55 1.0,56 false,57 "Number of independent strings per note (a section). Each has its own tuning offset, vibrato phase and pan; the cost grows in proportion.",58 ),59 num("players.detune", Unit::Semitones, 0.0, 0.5, 0.08, false, "Spread of the tuning between section players."),60 num("width", Unit::Ratio, 0.0, 1.0, 0.5, false, "Stereo spread of the section players."),61 ];62 params.extend(vibrato_params(5.6, 0.18, 0.3));63 params.extend(envelope_params(false, 0.07, 0.15, 0.9, 0.14));64 EngineDesc {65 model: "bowed_string".into(),66 title: "Bowed String".into(),67 family: "bowed".into(),68 method: "Digital waveguide: two delay lines (bow to bridge, bow to nut), stick-slip friction as a memoryless function of the bow-string velocity difference, one-pole bridge loss, modal body".into(),69 doc: "A string driven continuously by a bow. Pressure, speed and position interact as on the instrument: too little pressure whistles, too much chokes. Tuning is calibrated at moderate pressure; extreme pressure flattens the pitch slightly, as on a real string.".into(),70 range: (28, 100),71 params,72 presets: vec![73 preset("violin", "Solo violin.", &[], &[]),74 preset("viola", "Solo viola: larger body, darker.", &[("body.size", 1.22), ("brightness", 0.42)], &[]),75 preset("cello", "Solo cello.", &[("body.size", 2.6), ("brightness", 0.38), ("vibrato.rate", 5.0), ("bow.pressure", 0.65), ("envelope.attack", 0.09)], &[]),76 preset("double_bass", "Double bass, slow bow.", &[("body.size", 4.2), ("brightness", 0.3), ("vibrato.rate", 4.4), ("vibrato.depth", 0.1), ("envelope.attack", 0.12), ("bow.pressure", 0.7)], &[]),77 preset("section", "Three players per note: a small string section.", &[("players", 3.0), ("players.detune", 0.1), ("envelope.attack", 0.12), ("envelope.release", 0.25), ("width", 0.8), ("body.size", 1.4), ("brightness", 0.45)], &[]),78 preset("sul_ponticello", "Bowed next to the bridge: glassy and thin.", &[("bow.position", 0.045), ("bow.pressure", 0.45), ("brightness", 0.85), ("vibrato.depth", 0.05)], &[]),79 ],80 articulations: vec!["normal".into(), "legato".into(), "staccato".into(), "marcato".into(), "accent".into(), "tremolo".into(), "tenuto".into()],81 pitched: true,82 }83}8485const MAX_PLAYERS: usize = 4;86const LEVEL: f32 = 0.7;87/// Residual sharpness of the friction loop in cents by MIDI pitch, measured with88/// `examples/calibrate.rs` (vibrato off, velocity 1, 48 kHz) and subtracted at note start.89const TUNING: &[(f32, f32)] = &[(48.0, 0.1), (60.0, 0.5), (72.0, 0.9), (80.0, 1.3), (84.0, 2.3), (88.0, 4.8), (92.0, 6.5), (96.0, 6.8), (100.0, 12.0)];90const BODY: [(f32, f32); 6] = [(278.0, 0.12), (455.0, 0.1), (540.0, 0.08), (712.0, 0.07), (1090.0, 0.05), (2420.0, 0.03)];9192#[derive(Clone)]93struct Player {94 neck: DelayLine,95 bridge: DelayLine,96 lp: f32,97 base_period: f32,98 /// Phase delay of the bridge filter at the note, refreshed once per block.99 pd: f32,100 detune: f32,101 vib: Vibrato,102 gl: f32,103 gr: f32,104}105106pub struct Bowed {107 sr: f32,108 r: Resolved,109 env: EnvSettings,110 i_pressure: usize,111 i_speed: usize,112 i_bright: usize,113 i_body: usize,114 i_vrate: usize,115 i_vdepth: usize,116 body: Vec<Biquad>,117 players: usize,118}119120pub struct Voice {121 players: [Player; MAX_PLAYERS],122 env: Adsr,123 vel: f32,124 bend: f32,125 trem: f32,126 trem_phase: f32,127 press_boost: f32,128 high: f32,129}130131impl Engine for Bowed {132 type Voice = Voice;133134 fn prepare(&mut self, sample_rate: f32, _max_block: usize) {135 self.sr = sample_rate;136 let size = self.r.get("body.size");137 self.body = BODY.iter().map(|(f, t)| Biquad::new(BiquadCoefs::resonator(f / size, t * size.sqrt(), sample_rate))).collect();138 }139140 fn make_voice(&self, sr: f32) -> Voice {141 let max = (sr / 20.0) as usize;142 let p = Player {143 neck: DelayLine::new(max),144 bridge: DelayLine::new(max / 2),145 lp: 0.0,146 base_period: 100.0,147 pd: 0.0,148 detune: 1.0,149 vib: Vibrato::default(),150 gl: 1.0,151 gr: 1.0,152 };153 Voice {154 players: [p.clone(), p.clone(), p.clone(), p],155 env: Adsr::new(sr),156 vel: 0.0,157 bend: 1.0,158 trem: 0.0,159 trem_phase: 0.0,160 press_boost: 0.0,161 high: 0.0,162 }163 }164165 fn start(&self, v: &mut Voice, note: &NoteOn, seed: u64) {166 let mut rng = Rng::new(seed);167 let corr = semitones_to_ratio(-interp_table(TUNING, note.pitch) / 100.0);168 let spread = self.r.get("players.detune");169 let width = self.r.get("width");170 for (k, p) in v.players.iter_mut().enumerate().take(self.players) {171 p.neck.clear();172 p.bridge.clear();173 p.lp = 0.0;174 p.detune = if self.players == 1 { 1.0 } else { semitones_to_ratio(spread * (k as f32 / (self.players - 1) as f32 - 0.5) + 0.02 * rng.bipolar()) };175 p.base_period = self.sr / (note.freq * p.detune * corr);176 let rate = self.r.v[self.i_vrate] * (1.0 + 0.08 * rng.bipolar());177 p.vib.start(rate, 1.0, self.r.get("vibrato.delay"), self.sr, rng.unipolar());178 let pan = if self.players == 1 { 0.0 } else { width * (2.0 * k as f32 / (self.players - 1) as f32 - 1.0) };179 let (gl, gr) = pan_gains(pan);180 p.gl = gl;181 p.gr = gr;182 }183 v.vel = note.velocity.clamp(0.0, 1.0);184 v.bend = 1.0;185 // Short strings are bowed more lightly: above C6 the bow speed is reduced, which keeps the186 // model in its Helmholtz regime instead of jumping to the octave.187 v.high = ((note.pitch - 82.0) / 10.0).clamp(0.0, 1.0);188 v.trem = if note.articulation == Articulation::Tremolo { 1.0 } else { 0.0 };189 v.trem_phase = 0.0;190 v.press_boost = match note.articulation {191 Articulation::Marcato | Articulation::Accent => 0.15,192 _ => 0.0,193 };194 v.env.reset();195 let attack = match note.articulation {196 Articulation::Marcato | Articulation::Accent | Articulation::Staccato | Articulation::Staccatissimo => self.env.attack * 0.35,197 Articulation::Legato => self.env.attack * 1.5,198 _ => self.env.attack,199 };200 v.env.set(attack, self.env.decay, self.env.sustain, self.env.release);201 v.env.gate_on();202 }203204 fn release(&self, v: &mut Voice) {205 v.env.gate_off();206 }207208 fn bend(&self, v: &mut Voice, semitones: f32) {209 v.bend = semitones_to_ratio(semitones);210 }211212 fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {213 let sr = self.sr;214 let pressure = (self.r.v[self.i_pressure] + v.press_boost).clamp(0.0, 1.0);215 let slope = 5.0 - 4.0 * pressure;216 let max_vel = (0.03 + 0.2 * self.r.v[self.i_speed]) * (0.35 + 0.65 * v.vel) * (1.0 - 0.55 * v.high);217 let beta = self.r.get("bow.position");218 let a = one_pole_coef(2200.0 + 9000.0 * self.r.v[self.i_bright], sr);219 let vdepth = self.r.v[self.i_vdepth];220 let norm = LEVEL / (self.players as f32).sqrt();221 let trem_inc = 11.0 / sr;222 for p in v.players.iter_mut().take(self.players) {223 p.pd = one_pole_phase_delay(a, std::f32::consts::TAU * v.bend / p.base_period);224 }225 for i in 0..left.len() {226 let mut e = v.env.tick();227 if v.trem > 0.0 {228 v.trem_phase += trem_inc;229 if v.trem_phase >= 1.0 {230 v.trem_phase -= 1.0;231 }232 e *= 0.55 + 0.45 * super::common::sin_turns(v.trem_phase);233 }234 let bow_vel = max_vel * e;235 let (mut l, mut r) = (0.0, 0.0);236 for p in v.players.iter_mut().take(self.players) {237 let ratio = v.bend * semitones_to_ratio_fast(p.vib.tick() * vdepth);238 let period = p.base_period / ratio;239 let total = (period - p.pd).max(4.0);240 let db = (total * beta).max(1.0);241 let dn = (total - db).max(1.0);242 let bridge_out = p.bridge.read(db);243 p.lp = flush(p.lp + a * (bridge_out - p.lp));244 let bridge_refl = -0.95 * p.lp;245 let nut_refl = -p.neck.read(dn);246 let string_vel = bridge_refl + nut_refl;247 let dv = bow_vel - string_vel;248 // Friction: 1 inside the sticking zone, falling as (|x| + 0.75)^-4 when slipping.249 let x = (dv + 0.001) * slope;250 let t = x.abs() + 0.75;251 let t2 = t * t;252 let friction = (1.0 / (t2 * t2)).min(1.0);253 let new_vel = dv * friction;254 p.neck.write(bridge_refl + new_vel);255 p.bridge.write(nut_refl + new_vel);256 l += bridge_out * p.gl;257 r += bridge_out * p.gr;258 }259 left[i] = l * norm;260 right[i] = r * norm;261 }262 !v.env.is_idle()263 }264265 fn set_param(&mut self, index: usize, value: f32) {266 if index < self.r.v.len() {267 self.r.v[index] = value;268 }269 }270271 fn post(&mut self, left: &mut [f32], right: &mut [f32], _pedal: bool) {272 let mix = self.r.v[self.i_body] * 0.9;273 for i in 0..left.len() {274 let x = 0.5 * (left[i] + right[i]);275 let mut acc = 0.0;276 for b in &mut self.body {277 acc += b.tick(x);278 }279 left[i] = left[i] * (1.0 - 0.4 * self.r.v[self.i_body]) + acc * mix;280 right[i] = right[i] * (1.0 - 0.4 * self.r.v[self.i_body]) + acc * mix;281 }282 }283284 fn tail_seconds(&self) -> f32 {285 // Longest body mode: 0.12 s scaled by sqrt(body.size).286 0.12 * self.r.get("body.size").sqrt() * 1.5287 }288289 fn reset_shared(&mut self) {290 self.body.iter_mut().for_each(|b| b.reset());291 }292}293294/// 2^(st/12) for small |st| (vibrato): second-order expansion, error below 0.01 cent for |st| <= 1.295#[inline]296pub(crate) fn semitones_to_ratio_fast(st: f32) -> f32 {297 let x = st * (std::f32::consts::LN_2 / 12.0);298 1.0 + x + 0.5 * x * x + x * x * x / 6.0299}300301pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {302 let d = desc();303 let r = resolve(&d, spec)?;304 let e = Bowed {305 sr: 48_000.0,306 env: EnvSettings::read(&r, false),307 i_pressure: r.idx("bow.pressure"),308 i_speed: r.idx("bow.speed"),309 i_bright: r.idx("brightness"),310 i_body: r.idx("body.mix"),311 i_vrate: r.idx("vibrato.rate"),312 i_vdepth: r.idx("vibrato.depth"),313 body: Vec::new(),314 players: (r.get("players").round() as usize).clamp(1, MAX_PLAYERS),315 r,316 };317 Ok(Box::new(Poly::new(e, seed)))318}319