Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/tests/engines.rs3//! Description: Behaviour of every engine and preset: sound, level, tuning, silence after4//! note-off, determinism, voice stealing, sample rates, extreme parameters, pedal, pitch bend.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89mod common;10use common::*;11use sonata_dsp::core::{cents, estimate_f0, midi_to_hz};12use sonata_instruments::{create_instrument, engine_registry, patch_node_registry};13use sonata_ir::{ParamValue, Registry, Unit};1415const MODELS: [&str; 16] = [16 "piano",17 "plucked_string",18 "bowed_string",19 "flute",20 "clarinet",21 "brass",22 "organ",23 "bass",24 "synth",25 "fm",26 "kick",27 "snare",28 "hihat",29 "modal_percussion",30 "voice",31 "patch",32];3334/// Documented tuning tolerance in cents at 48 kHz for the default preset, vibrato and detuning35/// off, measured by autocorrelation on 0.5 s of sustained sound. Engines with exact phase36/// accumulators are held to 2 cents (the estimator's own error on rich spectra). The piano and37/// the modal percussion have inharmonic partials: their fundamental is measured as a spectral peak.38fn tolerance(model: &str) -> f32 {39 match model {40 "bowed_string" => 6.0,41 "clarinet" => 4.0,42 "plucked_string" | "bass" => 3.0,43 _ => 2.0,44 }45}4647#[test]48fn registry_is_complete_and_valid() {49 let reg = Registry { engines: engine_registry(), effects: Vec::new(), patch_nodes: patch_node_registry() };50 reg.validate().unwrap();51 for m in MODELS {52 let e = reg.engine(m).unwrap_or_else(|| panic!("engine {m} missing"));53 assert!(!e.doc.is_empty() && !e.method.is_empty() && !e.title.is_empty());54 if m != "patch" {55 assert!(e.presets.len() >= 4, "{m} has {} presets", e.presets.len());56 let mut names: Vec<&str> = e.presets.iter().map(|p| p.name.as_str()).collect();57 names.sort();58 names.dedup();59 assert_eq!(names.len(), e.presets.len(), "{m} has duplicate preset names");60 // Presets must differ from each other in what they set (no aliases).61 for (i, a) in e.presets.iter().enumerate() {62 for b in &e.presets[i + 1..] {63 assert!(a.values != b.values || a.choices != b.choices, "{m}: presets {} and {} are identical", a.name, b.name);64 }65 }66 }67 }68 assert_eq!(reg.engines.len(), MODELS.len());69 assert!(reg.patch_nodes.len() >= 24);70 for n in ®.patch_nodes {71 assert!(!n.doc.is_empty() && n.ports.iter().all(|p| !p.doc.is_empty() && p.min <= p.default && p.default <= p.max), "{}", n.kind);72 }73}7475#[test]76fn every_preset_sounds_is_finite_and_below_full_scale() {77 let sr = 48_000.0;78 for desc in engine_registry().iter().filter(|d| d.model != "patch") {79 let mut presets: Vec<Option<&str>> = vec![None];80 presets.extend(desc.presets.iter().map(|p| Some(p.name.as_str())));81 let mut peaks = Vec::new();82 for preset in presets {83 let mut inst = make(&spec(&desc.model, preset, &[]), sr, 8);84 inst.note_on(¬e(1, centre(desc), 1.0));85 let (l, r) = render(inst.as_mut(), sr, 1.0);86 let p = peak(&l, &r);87 assert!(all_finite(&l, &r), "{} {:?} produced non-finite samples", desc.model, preset);88 assert!(p > 0.02, "{} {:?} is nearly silent (peak {p})", desc.model, preset);89 assert!(p < 1.0, "{} {:?} exceeds 0 dBFS on one note (peak {p})", desc.model, preset);90 let sustained = ["bowed", "woodwind", "brass", "organ", "voice", "synth"].contains(&desc.family.as_str()) && desc.model != "fm";91 assert!(inst.active_voices() >= 1 || !sustained, "{} {:?} dropped its held note", desc.model, preset);92 peaks.push(p);93 }94 // Level matching: the default preset peaks between -24 and -3 dBFS at velocity 1.95 assert!(peaks[0] > 0.063 && peaks[0] < 0.71, "{} default peak {}", desc.model, peaks[0]);96 }97}9899#[test]100fn velocity_controls_level() {101 let sr = 48_000.0;102 for desc in engine_registry().iter().filter(|d| d.model != "patch") {103 let level = |vel: f32| {104 let mut inst = make(&spec(&desc.model, None, &[]), sr, 4);105 inst.note_on(¬e(1, centre(desc), vel));106 let (l, r) = render(inst.as_mut(), sr, 0.6);107 peak(&l, &r)108 };109 let (soft, loud) = (level(0.2), level(1.0));110 assert!(loud > 1.5 * soft, "{}: velocity 0.2 -> {soft}, 1.0 -> {loud}", desc.model);111 assert!(soft > 1e-3, "{}: a soft note is silent", desc.model);112 }113}114115#[test]116fn pitched_engines_are_in_tune_across_their_range() {117 let sr = 48_000.0;118 for desc in engine_registry().iter().filter(|d| d.pitched && d.model != "patch") {119 let tol = tolerance(&desc.model);120 let (lo, hi) = (desc.range.0 as f32, desc.range.1 as f32);121 // Estimation needs at least a few periods below Nyquist/8: stay within 30 Hz .. 4.2 kHz.122 let pitches = [lo.max(24.0) + 2.0, (lo + hi) * 0.5, (hi - 2.0).min(108.0)];123 let overrides = steady(desc);124 for pitch in pitches {125 let f = midi_to_hz(pitch, 440.0);126 let mut inst = make(&spec(&desc.model, None, &overrides), sr, 2);127 inst.note_on(¬e(1, pitch, 0.9));128 let (l, _) = render(inst.as_mut(), sr, 1.0);129 let from = if desc.family == "percussion" || desc.family == "keyboard" || desc.family == "plucked" { 2400 } else { 24_000 };130 let seg = &l[from..from + 24_000];131 let est = measure_f0(desc, seg, sr, f).unwrap_or_else(|| panic!("{} at {pitch}: no pitch found", desc.model));132 let err = cents(est, f);133 println!("TUNING {} midi {pitch}: {err:+.2} cents", desc.model);134 assert!(err.abs() <= tol, "{} at MIDI {pitch}: {err:+.2} cents (tolerance {tol})", desc.model);135 }136 }137}138139#[test]140fn tuning_holds_at_other_sample_rates() {141 for sr in [44_100.0f32, 96_000.0, 192_000.0] {142 for desc in engine_registry().iter().filter(|d| d.model != "patch") {143 let pitch = centre(desc);144 let f = midi_to_hz(pitch, 440.0);145 let mut inst = make(&spec(&desc.model, None, &steady(desc)), sr, 2);146 inst.note_on(¬e(1, pitch, 0.9));147 let (l, r) = render(inst.as_mut(), sr, 0.8);148 let p = peak(&l, &r);149 assert!(all_finite(&l, &r) && p > 0.02 && p < 1.0, "{} at {sr} Hz: peak {p}", desc.model);150 if desc.pitched {151 let from = (0.2 * sr) as usize;152 let est = measure_f0(desc, &l[from..from + (0.4 * sr) as usize], sr, f).unwrap_or_else(|| panic!("{} at {sr} Hz: no pitch found", desc.model));153 let err = cents(est, f);154 // Twice the 48 kHz tolerance: filters defined in Hz move slightly against the sample grid.155 assert!(err.abs() <= 2.0 * tolerance(&desc.model), "{} at {sr} Hz: {err:+.2} cents", desc.model);156 }157 }158 }159}160161#[test]162fn notes_end_in_silence_after_note_off() {163 let sr = 48_000.0;164 for desc in engine_registry().iter().filter(|d| d.model != "patch") {165 let mut inst = make(&spec(&desc.model, None, &[]), sr, 8);166 for (i, off) in [0.0, 4.0, 7.0].iter().enumerate() {167 inst.note_on(¬e(i as u64 + 1, centre(desc) + off, 0.9));168 }169 render(inst.as_mut(), sr, 0.5);170 for id in 1..=3 {171 inst.note_off(id);172 }173 // Longest default tail: release times are at most a few seconds; unpitched drums and174 // undamped top piano strings end by their own decay.175 let mut waited = 0.0;176 while inst.active_voices() > 0 && waited < 30.0 {177 render(inst.as_mut(), sr, 0.5);178 waited += 0.5;179 }180 assert_eq!(inst.active_voices(), 0, "{} still has voices {waited} s after note-off", desc.model);181 // Shared resonators ring for at most `tail_seconds`; then the output is silent.182 let tail = inst.tail_seconds();183 assert!((0.0..=6.0).contains(&tail), "{}: tail {tail}", desc.model);184 render(inst.as_mut(), sr, tail + 0.05);185 let (l, r) = render(inst.as_mut(), sr, 0.2);186 assert!(peak(&l, &r) < 1e-4, "{} is not silent after its tail (peak {})", desc.model, peak(&l, &r));187 }188}189190fn scripted(model: &str, preset: Option<&str>, seed: u64) -> (Vec<f32>, Vec<f32>) {191 let sr = 48_000.0;192 let mut inst = create_instrument(&spec(model, preset, &[]), 440.0, seed).unwrap();193 inst.prepare(sr, 512, 6);194 let (mut l, mut r) = (Vec::new(), Vec::new());195 let mut step = |inst: &mut dyn sonata_instruments::Instrument, secs: f32| {196 let (a, b) = render(inst, sr, secs);197 l.extend(a);198 r.extend(b);199 };200 inst.note_on(¬e(1, 60.0, 0.8));201 inst.note_on(¬e(2, 64.0, 0.6));202 step(inst.as_mut(), 0.13);203 inst.pitch_bend(1, 0.7);204 inst.sustain(true);205 inst.note_on(¬e(3, 67.0, 1.0));206 step(inst.as_mut(), 0.11);207 inst.note_off(1);208 inst.note_off(2);209 inst.set_param(0, 0.5);210 step(inst.as_mut(), 0.09);211 inst.sustain(false);212 for k in 0..8 {213 inst.note_on(¬e(10 + k, 48.0 + 3.0 * k as f32, 0.7));214 }215 step(inst.as_mut(), 0.2);216 inst.all_notes_off();217 step(inst.as_mut(), 0.2);218 (l, r)219}220221#[test]222fn rendering_is_bit_identical_for_the_same_calls_and_seed() {223 for desc in engine_registry().iter().filter(|d| d.model != "patch") {224 let a = scripted(&desc.model, None, 42);225 let b = scripted(&desc.model, None, 42);226 assert!(a == b, "{} is not deterministic", desc.model);227 assert!(all_finite(&a.0, &a.1));228 }229 // A different seed changes engines that use noise.230 let a = scripted("snare", None, 1);231 let b = scripted("snare", None, 2);232 assert!(a != b);233}234235#[test]236fn voice_stealing_respects_the_limit_and_plays_the_new_note() {237 let sr = 48_000.0;238 for desc in engine_registry().iter().filter(|d| d.model != "patch") {239 let mut inst = make(&spec(&desc.model, None, &steady(desc)), sr, 3);240 let base = centre(desc);241 for k in 0..12u64 {242 inst.note_on(¬e(k + 1, base + (k % 5) as f32, 0.8));243 let (l, r) = render(inst.as_mut(), sr, 0.03);244 assert!(inst.active_voices() <= 3, "{}: {} voices with a limit of 3", desc.model, inst.active_voices());245 assert!(all_finite(&l, &r) && peak(&l, &r) < 1.5, "{}", desc.model);246 }247 // Release everything, then one new note must be the only pitch left.248 inst.reset();249 let top = base + 9.0;250 inst.note_on(¬e(100, top, 0.9));251 let (l, _) = render(inst.as_mut(), sr, 0.8);252 if desc.pitched {253 let f = midi_to_hz(top, 440.0);254 let est = measure_f0(desc, &l[9600..33_600], sr, f).unwrap_or_else(|| panic!("{}: no pitch after stealing", desc.model));255 assert!(cents(est, f).abs() < 2.0 * tolerance(&desc.model) + 2.0, "{}: after stealing, pitch off by {}", desc.model, cents(est, f));256 }257 }258}259260#[test]261fn stolen_voice_fades_without_a_click() {262 // One voice only: the second note steals the first. The largest sample-to-sample jump during263 // the steal must stay within what the instrument itself produces (no discontinuity to zero).264 let sr = 48_000.0;265 let mut inst = make(&spec("organ", None, &[("click", 0.0), ("drawbar.f16", 0.0), ("drawbar.f5_1_3", 0.0)]), sr, 1);266 inst.note_on(¬e(1, 60.0, 1.0));267 let (a, _) = render(inst.as_mut(), sr, 0.2);268 let normal = a[4800..].windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0f32, f32::max);269 inst.note_on(¬e(2, 67.0, 1.0));270 let (b, _) = render(inst.as_mut(), sr, 0.05);271 let during = b.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0f32, f32::max);272 assert!(during < 2.5 * normal, "steal jump {during} vs normal slope {normal}");273 // The fade lasts 5 ms (240 samples): the new note starts right after it, not at a block boundary.274 let level = a[4800..].iter().fold(0.0f32, |m, x| m.max(x.abs()));275 let window = |from: usize, to: usize| b[from..to].iter().fold(0.0f32, |m, x| m.max(x.abs()));276 assert!(window(0, 100) > 0.5 * level, "the old note is still sounding at the start of the fade");277 assert!(window(225, 245) < 0.12 * level, "the old note has faded by 5 ms: {}", window(225, 245));278 assert!(window(480, 960) > 0.5 * level, "the new note sounds 5 ms after the fade (4 ms attack)");279 assert_eq!(inst.active_voices(), 1);280 let f = midi_to_hz(67.0, 440.0);281 let (c, _) = render(inst.as_mut(), sr, 0.5);282 assert!(cents(estimate_f0(&c[2400..], sr, f * 0.94, f * 1.06).unwrap(), f).abs() < 2.0);283}284285#[test]286fn extreme_parameter_values_stay_finite_and_bounded() {287 let sr = 48_000.0;288 for desc in engine_registry().iter().filter(|d| d.model != "patch") {289 for p in &desc.params {290 let values: Vec<f64> = match p.unit {291 Unit::Choice | Unit::HertzList | Unit::ScalarList => continue,292 _ => vec![p.min, p.max],293 };294 for value in values {295 let mut inst = make(&spec(&desc.model, None, &[(p.name.as_str(), value)]), sr, 4);296 let (lo, hi) = (desc.range.0 as f32, desc.range.1 as f32);297 inst.note_on(¬e(1, lo, 1.0));298 inst.note_on(¬e(2, hi, 1.0));299 inst.note_on(¬e(3, centre(desc), 1.0));300 let (l, r) = render(inst.as_mut(), sr, 0.4);301 inst.note_off(1);302 inst.note_off(2);303 inst.note_off(3);304 let (l2, r2) = render(inst.as_mut(), sr, 0.2);305 let pk = peak(&l, &r).max(peak(&l2, &r2));306 assert!(all_finite(&l, &r) && all_finite(&l2, &r2), "{} {}={value}: non-finite", desc.model, p.name);307 // Three notes at velocity 1 with one parameter at its limit: must stay under +6 dBFS308 // and well clear of the +12 dBFS safety clamp of the voice mixer.309 assert!(pk < 2.0, "{} {}={value}: peak {pk}", desc.model, p.name);310 }311 }312 // Automation to both ends while sounding, and garbage values are ignored.313 let mut inst = make(&spec(&desc.model, None, &[]), sr, 4);314 inst.note_on(¬e(1, centre(desc), 1.0));315 for (i, p) in desc.params.iter().enumerate() {316 if matches!(p.unit, Unit::Choice | Unit::HertzList | Unit::ScalarList) || !p.automatable {317 continue;318 }319 for v in [p.min as f32, p.max as f32, f32::NAN, f32::INFINITY] {320 inst.set_param(i, v);321 let (l, r) = render(inst.as_mut(), sr, 0.02);322 assert!(all_finite(&l, &r) && peak(&l, &r) < 2.0, "{} automation of {} to {v}", desc.model, p.name);323 }324 }325 inst.set_param(10_000, 1.0);326 }327}328329#[test]330fn pitch_bend_moves_the_pitch() {331 let sr = 48_000.0;332 for model in ["plucked_string", "bowed_string", "flute", "clarinet", "brass", "organ", "bass", "synth", "fm", "voice"] {333 let desc = engine_registry().into_iter().find(|d| d.model == model).unwrap();334 let pitch = centre(&desc);335 let mut inst = make(&spec(model, None, &steady(&desc)), sr, 2);336 inst.note_on(¬e(1, pitch, 0.9));337 render(inst.as_mut(), sr, 0.3);338 inst.pitch_bend(1, 2.0);339 let (l, _) = render(inst.as_mut(), sr, 0.8);340 let f = midi_to_hz(pitch + 2.0, 440.0);341 let est = estimate_f0(&l[14_400..], sr, f * 0.92, f * 1.08).unwrap_or_else(|| panic!("{model}: no pitch after bend"));342 assert!(cents(est, f).abs() < 2.0 * tolerance(model) + 3.0, "{model}: bent pitch off by {:+.1} cents", cents(est, f));343 }344}345346#[test]347fn sustain_pedal_defers_note_off() {348 let sr = 48_000.0;349 for model in ["piano", "organ", "synth", "bowed_string"] {350 let mut inst = make(&spec(model, None, &[]), sr, 4);351 inst.sustain(true);352 inst.note_on(¬e(1, 60.0, 0.8));353 render(inst.as_mut(), sr, 0.2);354 inst.note_off(1);355 let (l, r) = render(inst.as_mut(), sr, 0.6);356 assert_eq!(inst.active_voices(), 1, "{model}: pedal did not hold the note");357 assert!(peak(&l[24_000..], &r[24_000..]) > 1e-3, "{model}: held note is silent");358 inst.sustain(false);359 let mut waited = 0.0;360 while inst.active_voices() > 0 && waited < 20.0 {361 render(inst.as_mut(), sr, 0.25);362 waited += 0.25;363 }364 assert_eq!(inst.active_voices(), 0, "{model}: note did not end after the pedal was lifted");365 }366}367368#[test]369fn louder_is_brighter_for_brass_and_piano() {370 // Brightness = RMS of the first difference over RMS of the signal (a spectral-tilt measure371 // that does not assume harmonic partials). It must rise with velocity: the nonlinear part372 // of both models.373 let sr = 48_000.0;374 let brightness = |model: &str, vel: f32| -> f32 {375 let mut inst = make(&spec(model, None, &[]), sr, 2);376 inst.note_on(¬e(1, 57.0, vel));377 let (l, _) = render(inst.as_mut(), sr, 0.6);378 let seg = &l[2400..14_400];379 let diff: f32 = seg.windows(2).map(|w| (w[1] - w[0]).powi(2)).sum();380 let energy: f32 = seg.iter().map(|x| x * x).sum();381 (diff / energy).sqrt()382 };383 for model in ["brass", "piano"] {384 let (soft, loud) = (brightness(model, 0.25), brightness(model, 1.0));385 println!("BRIGHTNESS {model}: soft {soft:.4}, loud {loud:.4}");386 assert!(loud > 1.3 * soft, "{model}: brightness {soft} soft, {loud} loud");387 }388}389390#[test]391fn the_mandate_crystal_harp_compiles_to_a_sounding_instrument() {392 let sr = 48_000.0;393 let mut s = spec(394 "plucked_string",395 None,396 &[397 ("damping", 0.015),398 ("excitation.position", 0.35),399 ("envelope.attack", 0.005),400 ("envelope.decay", 0.3),401 ("envelope.sustain", 0.6),402 ("envelope.release", 2.0),403 ],404 );405 s.name = "CrystalHarp".into();406 s.params.insert("excitation".into(), ParamValue::Text("pluck".into()));407 s.params.insert("resonance".into(), ParamValue::Text("modal".into()));408 s.params.insert("resonance.frequencies".into(), ParamValue::List(vec![440.0, 880.0, 1320.0]));409 s.params.insert("envelope".into(), ParamValue::Text("adsr".into()));410 let mut inst = make(&s, sr, 8);411 inst.note_on(¬e(1, 69.0, 0.9));412 let (l, r) = render(inst.as_mut(), sr, 1.0);413 assert!(peak(&l, &r) > 0.05 && peak(&l, &r) < 1.0 && all_finite(&l, &r));414 let est = estimate_f0(&l[4800..28_800], sr, 414.0, 466.0).unwrap();415 assert!(cents(est, 440.0).abs() < 3.0);416 // The pluck at 0.35 of the string leaves little energy in harmonics near a node (n * 0.35 close to an integer: n = 3 is weak relative to n = 1 and 2).417 let h = |n: f32| sonata_dsp::core::goertzel_amplitude(&l[2400..12_000], 440.0 * n, sr);418 assert!(h(1.0) > 0.0 && h(3.0) < h(2.0));419}420421#[test]422fn bad_specs_are_rejected_with_a_message() {423 let mut s = spec("piano", None, &[("no_such_param", 1.0)]);424 assert!(create_instrument(&s, 440.0, 1).err().unwrap().contains("no parameter"));425 s = spec("piano", Some("no_such_preset"), &[]);426 assert!(create_instrument(&s, 440.0, 1).err().unwrap().contains("no preset"));427 s = spec("theremin", None, &[]);428 assert!(create_instrument(&s, 440.0, 1).err().unwrap().contains("unknown model"));429 s = spec("plucked_string", None, &[]);430 s.params.insert("excitation".into(), ParamValue::Text("blow".into()));431 assert!(create_instrument(&s, 440.0, 1).err().unwrap().contains("not a valid"));432 s = spec("plucked_string", None, &[]);433 s.params.insert("resonance".into(), ParamValue::Text("modal".into()));434 assert!(create_instrument(&s, 440.0, 1).err().unwrap().contains("frequencies"));435 s = spec("piano", None, &[]);436 assert!(create_instrument(&s, 10.0, 1).is_err());437 s = spec("patch", None, &[]);438 assert!(create_instrument(&s, 440.0, 1).err().unwrap().contains("needs a graph"));439}440