Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/winds.rs3//! Description: Wind instruments on a waveguide bore: clarinet (self-oscillating reed), flute4//! (prescribed air-jet oscillation into an open tube) and brass (prescribed lip valve into a tube with a bell).5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::bowed::semitones_to_ratio_fast;10use super::common::{one_pole_coef, one_pole_phase_delay, sin_turns, vibrato_params, EnvSettings, Vibrato};11use crate::instrument::{Instrument, NoteOn};12use crate::params::{envelope_params, num, preset, resolve, Resolved};13use crate::poly::{Engine, Poly};14use sonata_dsp::core::{flush, semitones_to_ratio, DcBlocker, DelayLine, Rng};15use sonata_dsp::env::Adsr;16use sonata_dsp::filter::OnePole;17use sonata_ir::{Articulation, EngineDesc, InstrumentSpec, Unit};1819fn wind_articulations() -> Vec<String> {20 ["normal", "legato", "staccato", "marcato", "accent", "tenuto"].iter().map(|s| s.to_string()).collect()21}2223fn start_env(env: &mut Adsr, s: &EnvSettings, art: Articulation) {24 env.reset();25 let attack = match art {26 Articulation::Marcato | Articulation::Accent | Articulation::Staccato | Articulation::Staccatissimo => s.attack * 0.4,27 Articulation::Legato => s.attack * 1.4,28 _ => s.attack,29 };30 env.set(attack, s.decay, s.sustain, s.release);31 env.gate_on();32}3334// ───────────────────────────── Clarinet ─────────────────────────────3536pub fn clarinet_desc() -> EngineDesc {37 let mut params = vec![38 num("breath", Unit::Ratio, 0.0, 1.0, 0.7, true, "Blowing effort (scaled by note velocity): mostly loudness. The mouth pressure itself only moves inside the narrow window where the reed oscillates."),39 num("reed.stiffness", Unit::Ratio, 0.0, 1.0, 0.5, true, "Reed stiffness: a soft reed closes easily and sounds buzzy, a hard reed is purer."),40 num("noise", Unit::Ratio, 0.0, 1.0, 0.12, true, "Breath turbulence added to the mouth pressure."),41 num("brightness", Unit::Ratio, 0.0, 1.0, 0.5, true, "Cutoff of the bell reflection filter."),42 ];43 params.extend(vibrato_params(5.0, 0.06, 0.4));44 params.extend(envelope_params(false, 0.035, 0.08, 0.92, 0.07));45 EngineDesc {46 model: "clarinet".into(),47 title: "Clarinet".into(),48 family: "woodwind".into(),49 method: "Digital waveguide: half-period cylindrical bore closed at the reed, linear reed reflection table with saturation, one-pole bell reflection".into(),50 doc: "A cylindrical tube closed at the mouthpiece, which favours odd harmonics and gives the hollow clarinet timbre. The reed is a pressure-controlled valve.".into(),51 range: (38, 96),52 params,53 presets: vec![54 preset("clarinet", "B-flat clarinet, middle register.", &[], &[]),55 preset("bass_clarinet", "Dark, breathy low clarinet.", &[("brightness", 0.3), ("noise", 0.2), ("reed.stiffness", 0.4), ("envelope.attack", 0.05)], &[]),56 preset("soft", "Subtone: gentle breath, little edge.", &[("breath", 0.25), ("reed.stiffness", 0.75), ("brightness", 0.35), ("noise", 0.2)], &[]),57 preset("bright", "Hard blown, edgy.", &[("breath", 0.9), ("reed.stiffness", 0.3), ("brightness", 0.85), ("noise", 0.08)], &[]),58 ],59 articulations: wind_articulations(),60 pitched: true,61 }62}6364const CLARINET_LEVEL: f32 = 0.55;6566pub struct Clarinet {67 sr: f32,68 r: Resolved,69 env: EnvSettings,70}7172pub struct ClarinetVoice {73 bore: DelayLine,74 lp: f32,75 env: Adsr,76 vib: Vibrato,77 rng: Rng,78 period: f32,79 vel: f32,80 bend: f32,81 dc: DcBlocker,82}8384impl Engine for Clarinet {85 type Voice = ClarinetVoice;86 fn prepare(&mut self, sample_rate: f32, _max_block: usize) {87 self.sr = sample_rate;88 }89 fn make_voice(&self, sr: f32) -> ClarinetVoice {90 ClarinetVoice {91 bore: DelayLine::new((sr / 40.0) as usize),92 lp: 0.0,93 env: Adsr::new(sr),94 vib: Vibrato::default(),95 rng: Rng::new(1),96 period: 100.0,97 vel: 0.0,98 bend: 1.0,99 dc: DcBlocker::new(20.0, sr),100 }101 }102 fn start(&self, v: &mut ClarinetVoice, note: &NoteOn, seed: u64) {103 v.bore.clear();104 v.lp = 0.0;105 v.dc.reset();106 v.rng = Rng::new(seed);107 v.period = self.sr / note.freq;108 v.vel = note.velocity.clamp(0.0, 1.0);109 v.bend = 1.0;110 v.vib.start(self.r.get("vibrato.rate"), 1.0, self.r.get("vibrato.delay"), self.sr, 0.0);111 start_env(&mut v.env, &self.env, note.articulation);112 }113 fn release(&self, v: &mut ClarinetVoice) {114 v.env.gate_off();115 }116 fn bend(&self, v: &mut ClarinetVoice, semitones: f32) {117 v.bend = semitones_to_ratio(semitones);118 }119 fn render(&self, v: &mut ClarinetVoice, left: &mut [f32], right: &mut [f32]) -> bool {120 let sr = self.sr;121 // Reed table: opening = 0.7 + slope * (p_bore - p_mouth), clipped to [-1, 1].122 // With this table the tube oscillates only for mouth pressures between about 0.24 / |slope|123 // (loop gain reaches 1) and 0.30 / |slope| (the reed is pressed shut): `breath` and124 // velocity move inside that window, so every setting speaks.125 let slope = -0.44 + 0.17 * self.r.get("reed.stiffness");126 let x = self.r.get("breath") * (0.25 + 0.75 * v.vel);127 let breath = (0.247 + 0.048 * x) / -slope;128 let level = CLARINET_LEVEL * (0.3 + 0.7 * v.vel) * (0.55 + 0.45 * self.r.get("breath")) * (-slope / 0.36);129 let noise = self.r.get("noise") * 0.2;130 let a = one_pole_coef(1500.0 + 7000.0 * self.r.get("brightness"), sr);131 let vdepth = self.r.get("vibrato.depth");132 // Phase delay of the reflection filter at the note (it barely moves under vibrato): once per block.133 let pd = one_pole_phase_delay(a, std::f32::consts::TAU * v.bend / v.period);134 for i in 0..left.len() {135 let e = v.env.tick();136 let p_mouth = breath * e * (1.0 + noise * v.rng.bipolar());137 let period = v.period / (v.bend * semitones_to_ratio_fast(v.vib.tick() * vdepth));138 // Closed-open tube: the round trip (two passes through the delay, one inverting139 // reflection) is one period; the bell filter's phase delay is part of it.140 let d = (0.5 * period - pd).max(2.0);141 let bore_out = v.bore.read(d);142 v.lp = flush(v.lp + a * (bore_out - v.lp));143 let p_diff = -0.95 * v.lp - p_mouth;144 // Reed: opening falls linearly with the pressure difference, clipped to [-1, 1].145 let reed = (0.7 + slope * p_diff).clamp(-1.0, 1.0);146 v.bore.write(p_mouth + p_diff * reed);147 let y = v.dc.tick(bore_out) * level;148 left[i] = y;149 right[i] = y;150 }151 !v.env.is_idle()152 }153 fn set_param(&mut self, index: usize, value: f32) {154 if index < self.r.v.len() {155 self.r.v[index] = value;156 }157 }158}159160pub fn clarinet_build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {161 let r = resolve(&clarinet_desc(), spec)?;162 Ok(Box::new(Poly::new(Clarinet { sr: 48_000.0, env: EnvSettings::read(&r, false), r }, seed)))163}164165// ───────────────────────────── Flute ─────────────────────────────166167pub fn flute_desc() -> EngineDesc {168 let mut params = vec![169 num(170 "breath",171 Unit::Ratio,172 0.0,173 1.0,174 0.6,175 true,176 "Blowing pressure (scaled by note velocity): drives the jet harder, which is louder and richer in harmonics.",177 ),178 num(179 "jet.offset",180 Unit::Ratio,181 0.0,182 1.0,183 0.3,184 true,185 "Aim of the air jet relative to the edge. Centred (0) gives odd harmonics only; off-centre adds the even ones.",186 ),187 num("noise", Unit::Ratio, 0.0, 1.0, 0.3, true, "Turbulence of the jet, heard as breath resonating in the tube."),188 num("brightness", Unit::Ratio, 0.0, 1.0, 0.5, true, "Cutoff of the tube's end reflection: how many harmonics the tube sustains."),189 ];190 params.extend(vibrato_params(5.2, 0.1, 0.35));191 params.extend(envelope_params(false, 0.06, 0.1, 0.9, 0.1));192 EngineDesc {193 model: "flute".into(),194 title: "Flute".into(),195 family: "woodwind".into(),196 method: "Forced-jet waveguide: an air jet oscillating at the note frequency is switched by a tanh edge nonlinearity and, with its turbulence noise, drives a one-period waveguide tube with a low-pass end reflection".into(),197 doc: "An open tube excited by an air jet. The jet's oscillation is prescribed at the note frequency instead of emerging from the jet-tube feedback loop: a self-oscillating jet model hops between tube modes, and this engine trades that behaviour for reliable tuning. The tube, the edge nonlinearity and the breath noise are modelled.".into(),198 range: (55, 100),199 params,200 presets: vec![201 preset("concert", "Concert flute.", &[], &[]),202 preset("breathy", "Much air in the tone.", &[("noise", 0.8), ("breath", 0.45), ("brightness", 0.4)], &[]),203 preset("pure", "Almost no breath noise, light vibrato.", &[("noise", 0.05), ("vibrato.depth", 0.05), ("brightness", 0.55), ("jet.offset", 0.15)], &[]),204 preset("pan_flute", "Stopped pipe: hollow, slow airy attack.", &[("noise", 0.65), ("envelope.attack", 0.1), ("brightness", 0.3), ("vibrato.depth", 0.04), ("jet.offset", 0.0)], &[]),205 preset("piccolo_bright", "Hard blown and edgy.", &[("breath", 0.95), ("brightness", 0.85), ("jet.offset", 0.5), ("noise", 0.2)], &[]),206 ],207 articulations: wind_articulations(),208 pitched: true,209 }210}211212const FLUTE_LEVEL: f32 = 0.085;213214pub struct Flute {215 sr: f32,216 r: Resolved,217 env: EnvSettings,218}219220pub struct FluteVoice {221 bore: DelayLine,222 lp: f32,223 dc: DcBlocker,224 env: Adsr,225 vib: Vibrato,226 rng: Rng,227 noise_lp: OnePole,228 noise_hp: OnePole,229 phase: f32,230 freq: f32,231 vel: f32,232 bend: f32,233}234235impl Engine for Flute {236 type Voice = FluteVoice;237 fn prepare(&mut self, sample_rate: f32, _max_block: usize) {238 self.sr = sample_rate;239 }240 fn make_voice(&self, sr: f32) -> FluteVoice {241 FluteVoice {242 bore: DelayLine::new((sr / 60.0) as usize),243 lp: 0.0,244 dc: DcBlocker::new(20.0, sr),245 env: Adsr::new(sr),246 vib: Vibrato::default(),247 rng: Rng::new(1),248 noise_lp: OnePole::new(7000.0, sr),249 noise_hp: OnePole::new(500.0, sr),250 phase: 0.0,251 freq: 440.0,252 vel: 0.0,253 bend: 1.0,254 }255 }256 fn start(&self, v: &mut FluteVoice, note: &NoteOn, seed: u64) {257 v.bore.clear();258 v.lp = 0.0;259 v.dc.reset();260 v.noise_lp.reset();261 v.noise_hp.reset();262 v.rng = Rng::new(seed);263 v.phase = 0.0;264 v.freq = note.freq;265 v.vel = note.velocity.clamp(0.0, 1.0);266 v.bend = 1.0;267 v.vib.start(self.r.get("vibrato.rate"), 1.0, self.r.get("vibrato.delay"), self.sr, 0.0);268 start_env(&mut v.env, &self.env, note.articulation);269 }270 fn release(&self, v: &mut FluteVoice) {271 v.env.gate_off();272 }273 fn bend(&self, v: &mut FluteVoice, semitones: f32) {274 v.bend = semitones_to_ratio(semitones);275 }276 fn render(&self, v: &mut FluteVoice, left: &mut [f32], right: &mut [f32]) -> bool {277 let sr = self.sr;278 let drive = (0.25 + 0.75 * self.r.get("breath")) * (0.4 + 0.6 * v.vel);279 let edge_gain = 0.5 + 2.6 * drive;280 let offset = 0.6 * self.r.get("jet.offset");281 let dc_term = sonata_dsp::core::fast_tanh(edge_gain * offset);282 let noise = self.r.get("noise") * 0.5;283 let a = one_pole_coef(1200.0 + 7000.0 * self.r.get("brightness"), sr);284 let vdepth = self.r.get("vibrato.depth");285 let pd = one_pole_phase_delay(a, std::f32::consts::TAU * v.freq * v.bend / sr);286 for i in 0..left.len() {287 let e = v.env.tick();288 let f = (v.freq * v.bend * semitones_to_ratio_fast(v.vib.tick() * vdepth)).min(0.24 * sr);289 v.phase += f / sr;290 if v.phase >= 1.0 {291 v.phase -= 1.0;292 }293 let jet = sin_turns(v.phase);294 // The tone builds up more slowly than the breath noise: the attack "chiff".295 let tone = (sonata_dsp::core::fast_tanh(edge_gain * (jet + offset)) - dc_term) * drive * e * e;296 let breath = v.noise_hp.highpass(v.noise_lp.lowpass(v.rng.bipolar())) * noise * drive * e * (0.5 + 0.5 * jet.abs());297 // Open tube: one period per round trip, every harmonic resonates.298 let period = sr / f;299 let d = (period - pd).max(2.0);300 let bore_out = v.bore.read(d);301 v.lp = flush(v.lp + a * (bore_out - v.lp));302 let refl = 0.93 * v.lp;303 v.bore.write(tone + breath + refl);304 let y = v.dc.tick(bore_out - 0.5 * refl) * FLUTE_LEVEL;305 left[i] = y;306 right[i] = y;307 }308 !v.env.is_idle()309 }310 fn set_param(&mut self, index: usize, value: f32) {311 if index < self.r.v.len() {312 self.r.v[index] = value;313 }314 }315}316317pub fn flute_build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {318 let r = resolve(&flute_desc(), spec)?;319 Ok(Box::new(Poly::new(Flute { sr: 48_000.0, env: EnvSettings::read(&r, false), r }, seed)))320}321322// ───────────────────────────── Brass ─────────────────────────────323324pub fn brass_desc() -> EngineDesc {325 let mut params = vec![326 num(327 "breath",328 Unit::Ratio,329 0.0,330 1.0,331 0.7,332 true,333 "Blowing pressure (scaled by note velocity). Louder is also much brighter: the lips stay open for a shorter part of each cycle.",334 ),335 num(336 "lip.tension",337 Unit::Semitones,338 -2.0,339 2.0,340 0.0,341 true,342 "Mistuning of the tube against the lips. At 0 the tube resonates exactly on the note; an offset weakens and thins the tone (lipping).",343 ),344 num("brightness", Unit::Ratio, 0.0, 1.0, 0.5, true, "Cutoff of the bell: above it the sound radiates instead of being reflected back into the tube."),345 num("growl", Unit::Ratio, 0.0, 1.0, 0.0, true, "Turbulence in the lip opening."),346 ];347 params.extend(vibrato_params(5.0, 0.05, 0.5));348 params.extend(envelope_params(false, 0.045, 0.12, 0.88, 0.09));349 EngineDesc {350 model: "brass".into(),351 title: "Brass".into(),352 family: "brass".into(),353 method: "Forced lip-valve waveguide: lips opening periodically at the note frequency gate mouth pressure into a one-period waveguide tube; the bell reflects low frequencies and radiates the rest".into(),354 doc: "A lip-reed instrument. The lips' motion is prescribed at the note frequency instead of emerging from the lip-tube feedback: a self-oscillating lip model does not hold its pitch over a usable range, and this engine trades that behaviour for reliable tuning. The valve nonlinearity (brighter when louder), the tube resonances and the bell are modelled.".into(),355 range: (34, 86),356 params,357 presets: vec![358 preset("trumpet", "Bright and direct.", &[("brightness", 0.7)], &[]),359 preset("trombone", "Broad and warm.", &[("brightness", 0.42), ("envelope.attack", 0.06), ("vibrato.depth", 0.03)], &[]),360 preset("horn", "Mellow, distant.", &[("brightness", 0.2), ("breath", 0.5), ("envelope.attack", 0.07), ("vibrato.depth", 0.02)], &[]),361 preset("tuba", "Low and round.", &[("brightness", 0.28), ("envelope.attack", 0.08), ("breath", 0.65), ("vibrato.depth", 0.0)], &[]),362 preset("growl", "Rough, noisy blowing.", &[("growl", 0.7), ("breath", 0.95), ("brightness", 0.8)], &[]),363 ],364 articulations: wind_articulations(),365 pitched: true,366 }367}368369const BRASS_LEVEL: f32 = 0.4;370371pub struct Brass {372 sr: f32,373 r: Resolved,374 env: EnvSettings,375}376377pub struct BrassVoice {378 bore: DelayLine,379 lp: f32,380 dc: DcBlocker,381 env: Adsr,382 vib: Vibrato,383 rng: Rng,384 noise_lp: OnePole,385 phase: f32,386 freq: f32,387 vel: f32,388 bend: f32,389}390391impl Engine for Brass {392 type Voice = BrassVoice;393 fn prepare(&mut self, sample_rate: f32, _max_block: usize) {394 self.sr = sample_rate;395 }396 fn make_voice(&self, sr: f32) -> BrassVoice {397 BrassVoice {398 bore: DelayLine::new((sr / 25.0) as usize),399 lp: 0.0,400 dc: DcBlocker::new(20.0, sr),401 env: Adsr::new(sr),402 vib: Vibrato::default(),403 rng: Rng::new(1),404 noise_lp: OnePole::new(900.0, sr),405 phase: 0.0,406 freq: 220.0,407 vel: 0.0,408 bend: 1.0,409 }410 }411 fn start(&self, v: &mut BrassVoice, note: &NoteOn, seed: u64) {412 v.bore.clear();413 v.lp = 0.0;414 v.dc.reset();415 v.noise_lp.reset();416 v.rng = Rng::new(seed);417 v.phase = 0.0;418 v.freq = note.freq;419 v.vel = note.velocity.clamp(0.0, 1.0);420 v.bend = 1.0;421 v.vib.start(self.r.get("vibrato.rate"), 1.0, self.r.get("vibrato.delay"), self.sr, 0.0);422 start_env(&mut v.env, &self.env, note.articulation);423 }424 fn release(&self, v: &mut BrassVoice) {425 v.env.gate_off();426 }427 fn bend(&self, v: &mut BrassVoice, semitones: f32) {428 v.bend = semitones_to_ratio(semitones);429 }430 fn render(&self, v: &mut BrassVoice, left: &mut [f32], right: &mut [f32]) -> bool {431 let sr = self.sr;432 let breath = (0.25 + 0.75 * self.r.get("breath")) * (0.2 + 0.8 * v.vel);433 let growl = self.r.get("growl");434 let tube_ratio = semitones_to_ratio(self.r.get("lip.tension"));435 // Bell cutoff follows the instrument's register a little: low brass has a lower cutoff.436 let a = one_pole_coef((500.0 + 2600.0 * self.r.get("brightness")) * (v.freq / 233.0).powf(0.35), sr);437 let vdepth = self.r.get("vibrato.depth");438 let pd = one_pole_phase_delay(a, std::f32::consts::TAU * v.freq * v.bend * tube_ratio / sr);439 for i in 0..left.len() {440 let e = v.env.tick();441 let f = (v.freq * v.bend * semitones_to_ratio_fast(v.vib.tick() * vdepth)).min(0.24 * sr);442 v.phase += f / sr;443 if v.phase >= 1.0 {444 v.phase -= 1.0;445 }446 let drive = breath * e;447 // Lip opening: the part of the sine above a threshold that rises with pressure, squared.448 // Soft playing: nearly sinusoidal flow. Loud playing: short pulses, many harmonics.449 let threshold = (-0.9 + 2.0 * drive).min(0.7);450 let mut lips = sin_turns(v.phase) - threshold;451 if growl > 0.0 {452 lips += growl * 0.6 * v.noise_lp.lowpass(v.rng.bipolar());453 }454 let open = lips.max(0.0);455 let area = open * open / ((1.0 - threshold) * (1.0 - threshold));456 let period = sr / (f * tube_ratio);457 let d = (period - pd).clamp(2.0, v.bore.capacity() as f32 - 2.0);458 let bore_out = v.bore.read(d);459 v.lp = flush(v.lp + a * (bore_out - v.lp));460 let refl = 0.8 * v.lp;461 // Flow through the valve falls as the pressure in the mouthpiece rises.462 let flow = area * drive * (1.0 - 0.25 * bore_out.clamp(-1.0, 1.0));463 v.bore.write(flow + refl);464 // Radiated sound: what the bell does not reflect, plus a little of the rest.465 let y = v.dc.tick(bore_out - 0.8 * refl) * BRASS_LEVEL;466 left[i] = y;467 right[i] = y;468 }469 !v.env.is_idle()470 }471 fn set_param(&mut self, index: usize, value: f32) {472 if index < self.r.v.len() {473 self.r.v[index] = value;474 }475 }476}477478pub fn brass_build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {479 let r = resolve(&brass_desc(), spec)?;480 Ok(Box::new(Poly::new(Brass { sr: 48_000.0, env: EnvSettings::read(&r, false), r }, seed)))481}482