Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/tests/patch.rs3//! Description: The patch engine: graph validation, node behaviour, feedback through delays, voice life cycle.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78mod common;9use common::*;10use sonata_dsp::core::{cents, estimate_f0, goertzel_amplitude};11use sonata_instruments::{create_instrument, patch_node_registry};12use sonata_ir::{InstrumentSpec, NoteInput, Params, PatchInput, PatchNode, PatchSpec, Rate, Span};1314const SR: f32 = 48_000.0;1516fn node(name: &str, kind: &str, inputs: &[(&str, PatchInput)]) -> PatchNode {17 PatchNode {18 name: name.into(),19 kind: kind.into(),20 inputs: inputs.iter().cloned().map(|(k, v)| (k.to_string(), v)).collect(),21 rate: Rate::Audio,22 span: Span::default(),23 }24}2526fn patch_spec(nodes: Vec<PatchNode>, output: u32, amp_envelope: Option<u32>) -> InstrumentSpec {27 InstrumentSpec { name: "P".into(), model: "patch".into(), params: Params::new(), patch: Some(PatchSpec { nodes, output, amp_envelope }) }28}2930use PatchInput::{Const, Node as N, Note};3132/// saw -> lowpass (cutoff swept by an envelope) -> times amplitude envelope.33fn classic() -> InstrumentSpec {34 patch_spec(35 vec![36 node("osc", "saw", &[]),37 node("env", "adsr", &[("attack", Const(0.005)), ("decay", Const(0.2)), ("sustain", Const(0.5)), ("release", Const(0.1))]),38 node("sweep", "mul", &[("a", N(1)), ("b", Const(4000.0))]),39 node("cut", "add", &[("a", N(2)), ("b", Const(300.0))]),40 node("filt", "lowpass", &[("in", N(0)), ("cutoff", N(3)), ("q", Const(1.5))]),41 node("out", "mul", &[("a", N(4)), ("b", N(1))]),42 ],43 5,44 Some(1),45 )46}4748#[test]49fn classic_subtractive_patch_plays_in_tune_and_ends_with_its_envelope() {50 let mut inst = make(&classic(), SR, 4);51 inst.note_on(¬e(1, 57.0, 1.0));52 let (l, r) = render(inst.as_mut(), SR, 0.6);53 assert!(all_finite(&l, &r) && peak(&l, &r) > 0.02 && peak(&l, &r) <= 1.0);54 let est = estimate_f0(&l[9600..], SR, 207.0, 233.0).unwrap();55 assert!(cents(est, 220.0).abs() < 1.0, "{est}");56 assert_eq!(inst.active_voices(), 1);57 inst.note_off(1);58 render(inst.as_mut(), SR, 0.5);59 assert_eq!(inst.active_voices(), 0, "the voice ends when the amplitude envelope is idle");60 let (l, r) = render(inst.as_mut(), SR, 0.1);61 assert_eq!(peak(&l, &r), 0.0);62}6364#[test]65fn every_node_kind_runs_and_stays_finite() {66 // One patch using every kind at least once.67 let nodes = vec![68 node("a", "sine", &[("pm", Const(0.3))]),69 node("b", "saw", &[]),70 node("c", "square", &[("freq", Const(110.0))]),71 node("d", "pulse", &[("width", Const(0.2))]),72 node("e", "triangle", &[]),73 node("f", "noise", &[("amp", Const(0.1))]),74 node("g", "pink", &[("amp", Const(0.1))]),75 node("h", "wavetable", &[("shape", Const(1.0))]),76 node("lfo", "lfo", &[("rate", Const(6.0)), ("shape", Const(1.0)), ("amp", Const(0.5))]),77 node("i", "fm", &[("ratio", Const(2.0)), ("pm", N(0)), ("feedback", Const(0.5))]),78 node("env", "adsr", &[]),79 node("s1", "add", &[("a", N(1)), ("b", N(2))]),80 node("s2", "add", &[("a", N(3)), ("b", N(4))]),81 node("s3", "add", &[("a", N(5)), ("b", N(6))]),82 node("s4", "add", &[("a", N(7)), ("b", N(9))]),83 node("s5", "add", &[("a", N(11)), ("b", N(12))]),84 node("s6", "add", &[("a", N(13)), ("b", N(14))]),85 node("s7", "mix", &[("a", N(15)), ("b", N(16)), ("t", N(8))]),86 node("lp", "lowpass", &[("in", N(17)), ("cutoff", Const(3000.0))]),87 node("hp", "highpass", &[("in", N(18)), ("cutoff", Const(80.0))]),88 node("bp", "bandpass", &[("in", N(17)), ("cutoff", Const(900.0))]),89 node("sv", "svf", &[("in", N(17)), ("cutoff", Const(1200.0)), ("mode", Const(3.0))]),90 node("m", "modal", &[("in", N(5)), ("decay", Const(0.3))]),91 node("t1", "add", &[("a", N(19)), ("b", N(20))]),92 node("t2", "add", &[("a", N(21)), ("b", N(22))]),93 node("t3", "sub", &[("a", N(23)), ("b", N(24))]),94 node("dl", "delay", &[("in", N(25)), ("time", Const(0.031)), ("feedback", Const(0.4)), ("max", Const(0.1))]),95 node("t4", "add", &[("a", N(25)), ("b", N(26))]),96 node("sat", "saturate", &[("in", N(27)), ("drive", Const(2.0))]),97 node("cl", "clip", &[("in", N(28)), ("lo", Const(-0.8)), ("hi", Const(0.8))]),98 node("g", "gain", &[("in", N(29)), ("db", Const(-6.0))]),99 node("vel", "mul", &[("a", N(30)), ("b", Note(NoteInput::Velocity))]),100 node("out", "mul", &[("a", N(31)), ("b", N(10))]),101 ];102 let kinds: std::collections::BTreeSet<String> = nodes.iter().map(|n| n.kind.clone()).collect();103 for d in patch_node_registry() {104 assert!(kinds.contains(&d.kind), "node kind {} is not exercised", d.kind);105 }106 let out = nodes.len() as u32 - 1;107 let s = patch_spec(nodes, out, Some(10));108 for sr in [44_100.0, 48_000.0, 96_000.0, 192_000.0] {109 let mut inst = make(&s, sr, 4);110 inst.note_on(¬e(1, 60.0, 1.0));111 inst.note_on(¬e(2, 96.0, 0.5));112 let (l, r) = render(inst.as_mut(), sr, 0.5);113 assert!(all_finite(&l, &r) && peak(&l, &r) > 0.01 && peak(&l, &r) <= 1.0, "sr {sr}: peak {}", peak(&l, &r));114 }115 // Deterministic.116 let run = || {117 let mut inst = make(&s, SR, 4);118 inst.note_on(¬e(1, 60.0, 1.0));119 render(inst.as_mut(), SR, 0.3)120 };121 assert!(run() == run());122}123124#[test]125fn feedback_through_a_delay_makes_a_tuned_comb() {126 // Karplus-Strong written as a patch: a noise burst into a delay of one period with feedback127 // through a low-pass. The delay reads a later node (the filter): allowed only for `delay.in`.128 let nodes = vec![129 node("burst_env", "adsr", &[("attack", Const(0.0)), ("decay", Const(0.01)), ("sustain", Const(0.0)), ("release", Const(0.01))]),130 node("noise", "noise", &[]),131 node("burst", "mul", &[("a", N(1)), ("b", N(0))]),132 node("line", "delay", &[("in", N(5)), ("time", Const(1.0 / 220.0 - 1.5 / 48_000.0)), ("max", Const(0.05))]),133 node("damp", "lowpass", &[("in", N(3)), ("cutoff", Const(9000.0)), ("q", Const(0.5))]),134 node("sum", "add", &[("a", N(2)), ("b", N(4))]),135 ];136 let mut s = patch_spec(nodes, 3, None);137 s.params.insert("release".into(), sonata_ir::ParamValue::Num(0.05));138 let mut inst = make(&s, SR, 2);139 inst.note_on(¬e(1, 57.0, 1.0));140 let (l, r) = render(inst.as_mut(), SR, 1.0);141 assert!(all_finite(&l, &r) && peak(&l, &r) > 0.01);142 let est = estimate_f0(&l[4800..28_800], SR, 200.0, 240.0).unwrap();143 assert!(cents(est, 220.0).abs() < 25.0, "comb at {est} Hz");144 assert!(goertzel_amplitude(&l[24_000..], est, SR) > 1e-3, "the loop keeps ringing");145 // Without an amplitude envelope the voice ends `release` seconds after note-off.146 inst.note_off(1);147 render(inst.as_mut(), SR, 0.2);148 assert_eq!(inst.active_voices(), 0);149}150151#[test]152fn invalid_graphs_are_rejected() {153 let err = |s: InstrumentSpec| create_instrument(&s, 440.0, 1).err().expect("must be rejected");154 // Loop without a delay.155 let looped = patch_spec(vec![node("a", "add", &[("a", N(1))]), node("b", "gain", &[("in", N(0))])], 1, None);156 assert!(err(looped).contains("loop without a delay"));157 // Unknown kind, unknown port, constant out of range, modulated constant-only port, wrong envelope kind.158 assert!(err(patch_spec(vec![node("a", "theremin", &[])], 0, None)).contains("unknown kind"));159 assert!(err(patch_spec(vec![node("a", "sine", &[("colour", Const(1.0))])], 0, None)).contains("no port"));160 assert!(err(patch_spec(vec![node("a", "pulse", &[("width", Const(7.0))])], 0, None)).contains("outside"));161 assert!(err(patch_spec(vec![node("l", "lfo", &[]), node("d", "delay", &[("in", N(0)), ("max", N(0))])], 1, None)).contains("must be a constant"));162 assert!(err(patch_spec(vec![node("a", "sine", &[])], 0, Some(0))).contains("adsr"));163 assert!(err(patch_spec(vec![], 0, None)).contains("no node"));164 assert!(err(patch_spec(vec![node("a", "sine", &[("pm", Const(f64::NAN))])], 0, None)).contains("outside"));165}166167#[test]168fn output_is_bounded_even_for_a_hot_graph() {169 let nodes = vec![node("o", "saw", &[("amp", Const(16.0))]), node("g", "gain", &[("in", N(0)), ("db", Const(36.0))])];170 let mut inst = make(&patch_spec(nodes, 1, None), SR, 2);171 inst.note_on(¬e(1, 60.0, 1.0));172 let (l, r) = render(inst.as_mut(), SR, 0.2);173 assert!(peak(&l, &r) <= 1.0 && all_finite(&l, &r));174}175