SPB Git

Repository Public

testing.rs 14.4 KB 381 lines rust

1//! ORIX Sonata2//! File: crates/sonata-runtime/src/testing.rs3//! Description: Reference graph builder mirroring the documented mixer shape, and simple4//! deterministic test components (instruments, effects). Used by the tests and benches of the5//! runtime and renderer; the compiler's graph builder is the production path.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use crate::plan::Factory;11use sonata_dsp::Effect;12use sonata_instruments::{Instrument, NoteOn};13use sonata_ir::{14    Articulation, DspGraph, DspNode, Edge, EffectDesc, EffectSpec, EngineDesc, InstrumentSpec, LatencySpec, NodeKind, NoteEvent, Output, ParamDesc, Params,15    Program, Rational, Span, Strip, Track, TrackKind, Unit,16};1718/// Builds the mixing graph of a program in the documented shape:19/// `source → inserts → fader → [sends] → sum(bus | master) → master inserts → master fader →20/// limiter → output`, with `LatencyDelay` nodes so every input of a sum is aligned.21/// `limiter_lookahead` is the latency given to the master limiter (when `peak_limit_db` is set).22pub fn basic_graph(program: &Program, sample_rate: u32, factory: &dyn Factory, limiter_lookahead: u32) -> Result<DspGraph, String> {23    let mut nodes: Vec<DspNode> = Vec::new();24    let mut edges: Vec<Edge> = Vec::new();25    fn add(nodes: &mut Vec<DspNode>, kind: NodeKind, cin: u8, latency: u32) -> u32 {26        let id = nodes.len() as u32;27        nodes.push(DspNode { id, kind, channels_in: cin, channels_out: 2, latency, total_latency: 0 });28        id29    }30    let fx_latency = |spec: &EffectSpec| -> Result<u32, String> {31        Ok(factory.effect_desc(&spec.kind).ok_or(format!("unknown effect '{}'", spec.kind))?.latency.at(sample_rate))32    };3334    let master_sum = add(&mut nodes, NodeKind::Sum { strip: Strip::Master }, 2, 0);35    let bus_sums: Vec<(u32, u32)> = program.buses.iter().map(|b| (b.id, add(&mut nodes, NodeKind::Sum { strip: Strip::Bus(b.id) }, 2, 0))).collect();36    let sum_of = |o: Output| -> Result<u32, String> {37        match o {38            Output::Master => Ok(master_sum),39            Output::Bus(b) => bus_sums.iter().find(|x| x.0 == b).map(|x| x.1).ok_or(format!("missing bus {b}")),40        }41    };42    let strip_chain = |nodes: &mut Vec<DspNode>,43                       edges: &mut Vec<Edge>,44                       strip: Strip,45                       source: u32,46                       effects: &[EffectSpec],47                       sends: &[sonata_ir::Send],48                       output: Output|49     -> Result<(), String> {50        let mut cur = source;51        for (i, spec) in effects.iter().enumerate() {52            let n = add(nodes, NodeKind::Effect { strip, index: i as u32, spec: spec.clone() }, 2, fx_latency(spec)?);53            edges.push(Edge { from: cur, to: n });54            cur = n;55        }56        let fader = add(nodes, NodeKind::Fader { strip }, 2, 0);57        edges.push(Edge { from: cur, to: fader });58        for s in sends {59            let n = add(nodes, NodeKind::Send { from: strip, to_bus: s.bus, gain_db: s.gain_db, pre_fader: s.pre_fader }, 2, 0);60            edges.push(Edge { from: if s.pre_fader { cur } else { fader }, to: n });61            edges.push(Edge { from: n, to: sum_of(Output::Bus(s.bus))? });62        }63        edges.push(Edge { from: fader, to: sum_of(output)? });64        Ok(())65    };66    for t in &program.tracks {67        let kind = if t.kind == TrackKind::Instrument { NodeKind::Instrument { track: t.id } } else { NodeKind::AudioClips { track: t.id } };68        let src = add(&mut nodes, kind, 0, 0);69        strip_chain(&mut nodes, &mut edges, Strip::Track(t.id), src, &t.effects, &t.sends, t.output)?;70    }71    for b in &program.buses {72        let src = sum_of(Output::Bus(b.id))?;73        strip_chain(&mut nodes, &mut edges, Strip::Bus(b.id), src, &b.effects, &b.sends, b.output)?;74    }75    let mut cur = master_sum;76    for (i, spec) in program.master.effects.iter().enumerate() {77        let n = add(&mut nodes, NodeKind::Effect { strip: Strip::Master, index: i as u32, spec: spec.clone() }, 2, fx_latency(spec)?);78        edges.push(Edge { from: cur, to: n });79        cur = n;80    }81    let fader = add(&mut nodes, NodeKind::Fader { strip: Strip::Master }, 2, 0);82    edges.push(Edge { from: cur, to: fader });83    cur = fader;84    if let Some(ceiling_db) = program.master.peak_limit_db {85        let n = add(&mut nodes, NodeKind::Limiter { ceiling_db }, 2, limiter_lookahead);86        edges.push(Edge { from: cur, to: n });87        cur = n;88    }89    let output = add(&mut nodes, NodeKind::Output, 2, 0);90    edges.push(Edge { from: cur, to: output });9192    // Latency compensation in topological order.93    let order = DspGraph::topological_order(&nodes, &edges).map_err(|c| format!("routing forms a cycle through nodes {c:?}"))?;94    for id in order {95        let ins: Vec<usize> = edges.iter().enumerate().filter(|(_, e)| e.to == id).map(|(i, _)| i).collect();96        let max_in = ins.iter().map(|i| nodes[edges[*i].from as usize].total_latency).max().unwrap_or(0);97        if matches!(nodes[id as usize].kind, NodeKind::Sum { .. }) {98            for i in ins {99                let short = max_in - nodes[edges[i].from as usize].total_latency;100                if short > 0 {101                    let d = add(&mut nodes, NodeKind::LatencyDelay { samples: short }, 2, short);102                    nodes[d as usize].total_latency = max_in;103                    let from = edges[i].from;104                    edges[i].from = d;105                    edges.push(Edge { from, to: d });106                }107            }108        }109        nodes[id as usize].total_latency = max_in + nodes[id as usize].latency;110    }111    let order = DspGraph::topological_order(&nodes, &edges).map_err(|_| "cycle after compensation".to_string())?;112    let total_latency = nodes[output as usize].total_latency;113    let g = DspGraph { sample_rate, nodes, edges, order, output, total_latency };114    g.validate()?;115    Ok(g)116}117118/// A note for hand-built test programs: seconds in, exact rationals approximated at 1/960.119pub fn test_note(track: u32, index: u32, start_sec: f64, end_sec: f64, pitch: f64, velocity: f32) -> NoteEvent {120    let r = |s: f64| Rational::approximate(s / 2.0, 1 << 20).unwrap_or(Rational::ZERO);121    NoteEvent {122        id: ((track as u64) << 32) | index as u64,123        start: r(start_sec),124        duration: r(end_sec - start_sec),125        notated_start: r(start_sec),126        notated_duration: r(end_sec - start_sec),127        start_sec,128        end_sec,129        pitch,130        velocity,131        voice: 0,132        articulation: Articulation::Normal,133        tied_from_previous: false,134        bend: Vec::new(),135        span: Span::default(),136    }137}138139/// An instrument track for hand-built test programs (120 bpm assumed by `test_note`).140pub fn test_track(id: u32, model: &str, notes: Vec<NoteEvent>) -> Track {141    Track {142        id,143        name: format!("track{id}"),144        kind: TrackKind::Instrument,145        instrument: Some(InstrumentSpec { name: model.to_string(), model: model.to_string(), params: Params::new(), patch: None }),146        gain_db: 0.0,147        pan: 0.0,148        mute: false,149        solo: false,150        effects: Vec::new(),151        sends: Vec::new(),152        output: Output::Master,153        notes,154        clips: Vec::new(),155        automation: Vec::new(),156        score_transposition: 0,157        span: Span::default(),158    }159}160161pub fn test_effect(kind: &str, mix: f64, params: &[(&str, f64)]) -> EffectSpec {162    EffectSpec {163        kind: kind.to_string(),164        preset: None,165        params: params.iter().map(|(k, v)| (k.to_string(), sonata_ir::ParamValue::Num(*v))).collect(),166        mix,167        bypass: false,168        span: Span::default(),169    }170}171172/// Latency reported by the `test_delay` effect, samples.173pub const TEST_DELAY_LATENCY: u32 = 32;174175/// Deterministic components for tests.176///177/// Instruments (`model`): `test_dc` outputs `velocity * level` on both channels while a note is178/// held (no envelope); `test_sine` outputs a sine at the note frequency, amplitude179/// `0.25 * velocity * level`, phase starting at 0, hard gated; `test_nan` outputs NaN while a note180/// is held. All have one parameter, `level` (default 1).181///182/// Effects (`kind`): `test_gain` multiplies by `gain` (default 0.5); `test_delay` delays by183/// [`TEST_DELAY_LATENCY`] samples and reports that latency; `test_nan` outputs NaN.184/// Falls back to the registry for any other name.185pub struct TestFactory;186187#[derive(Clone, Copy, PartialEq)]188enum TestKind {189    Dc,190    Sine,191    Nan,192}193194struct TestVoice {195    id: u64,196    freq: f32,197    velocity: f32,198    phase: f64,199}200201struct TestInstrument {202    kind: TestKind,203    voices: Vec<TestVoice>,204    level: f32,205    sample_rate: f32,206}207208impl Instrument for TestInstrument {209    fn prepare(&mut self, sample_rate: f32, _max_block: usize, max_voices: usize) {210        self.sample_rate = sample_rate;211        self.voices = Vec::with_capacity(max_voices);212    }213    fn note_on(&mut self, n: &NoteOn) {214        if self.voices.len() == self.voices.capacity() {215            self.voices.remove(0);216        }217        self.voices.push(TestVoice { id: n.id, freq: n.freq, velocity: n.velocity, phase: 0.0 });218    }219    fn note_off(&mut self, id: u64) {220        self.voices.retain(|v| v.id != id);221    }222    fn pitch_bend(&mut self, id: u64, semitones: f32) {223        for v in self.voices.iter_mut().filter(|v| v.id == id) {224            v.freq *= (semitones / 12.0).exp2();225        }226    }227    fn set_param(&mut self, index: usize, value: f32) {228        if index == 0 {229            self.level = value;230        }231    }232    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {233        for v in &mut self.voices {234            for i in 0..left.len() {235                let s = match self.kind {236                    TestKind::Dc => v.velocity * self.level,237                    TestKind::Nan => f32::NAN,238                    TestKind::Sine => {239                        let s = (v.phase * std::f64::consts::TAU).sin() as f32 * 0.25 * v.velocity * self.level;240                        v.phase += v.freq as f64 / self.sample_rate as f64;241                        v.phase -= v.phase.floor();242                        s243                    }244                };245                left[i] += s;246                right[i] += s;247            }248        }249    }250    fn active_voices(&self) -> usize {251        self.voices.len()252    }253    fn all_notes_off(&mut self) {254        self.voices.clear();255    }256    fn reset(&mut self) {257        self.voices.clear();258    }259}260261struct TestGain(f32);262impl Effect for TestGain {263    fn prepare(&mut self, _: f32, _: usize) {}264    fn reset(&mut self) {}265    fn set_param(&mut self, index: usize, value: f32) {266        if index == 0 {267            self.0 = value;268        }269    }270    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {271        for i in 0..left.len() {272            left[i] *= self.0;273            right[i] *= self.0;274        }275    }276}277278struct TestDelay {279    l: Vec<f32>,280    r: Vec<f32>,281    pos: usize,282}283impl Effect for TestDelay {284    fn prepare(&mut self, _: f32, _: usize) {285        self.l = vec![0.0; TEST_DELAY_LATENCY as usize];286        self.r = vec![0.0; TEST_DELAY_LATENCY as usize];287    }288    fn reset(&mut self) {289        self.l.fill(0.0);290        self.r.fill(0.0);291    }292    fn set_param(&mut self, _: usize, _: f32) {}293    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {294        for i in 0..left.len() {295            std::mem::swap(&mut left[i], &mut self.l[self.pos]);296            std::mem::swap(&mut right[i], &mut self.r[self.pos]);297            self.pos = (self.pos + 1) % self.l.len();298        }299    }300    fn latency(&self) -> u32 {301        TEST_DELAY_LATENCY302    }303}304305struct TestNan;306impl Effect for TestNan {307    fn prepare(&mut self, _: f32, _: usize) {}308    fn reset(&mut self) {}309    fn set_param(&mut self, _: usize, _: f32) {}310    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {311        left.fill(f32::NAN);312        right.fill(f32::INFINITY);313    }314}315316fn test_kind(model: &str) -> Option<TestKind> {317    match model {318        "test_dc" => Some(TestKind::Dc),319        "test_sine" => Some(TestKind::Sine),320        "test_nan" => Some(TestKind::Nan),321        _ => None,322    }323}324325impl Factory for TestFactory {326    fn instrument(&self, spec: &InstrumentSpec, tuning_hz: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {327        match test_kind(&spec.model) {328            Some(kind) => Ok(Box::new(TestInstrument {329                kind,330                voices: Vec::new(),331                level: spec.params.get("level").and_then(|v| v.as_f64()).unwrap_or(1.0) as f32,332                sample_rate: 48_000.0,333            })),334            None => sonata_instruments::create_instrument(spec, tuning_hz, seed),335        }336    }337    fn engine_desc(&self, model: &str) -> Option<EngineDesc> {338        if test_kind(model).is_some() {339            return Some(EngineDesc {340                model: model.to_string(),341                title: model.to_string(),342                family: "synth".into(),343                method: "test signal".into(),344                doc: "Deterministic test instrument.".into(),345                range: (0, 127),346                params: vec![ParamDesc::num("level", Unit::Scalar, 0.0, 4.0, 1.0, true, "Output level.")],347                presets: Vec::new(),348                articulations: Vec::new(),349                pitched: true,350            });351        }352        sonata_instruments::engine_registry().into_iter().find(|e| e.model == model)353    }354    fn effect(&self, kind: &str) -> Option<Box<dyn Effect>> {355        match kind {356            "test_gain" => Some(Box::new(TestGain(0.5))),357            "test_delay" => Some(Box::new(TestDelay { l: Vec::new(), r: Vec::new(), pos: 0 })),358            "test_nan" => Some(Box::new(TestNan)),359            _ => sonata_dsp::create_effect(kind),360        }361    }362    fn effect_desc(&self, kind: &str) -> Option<EffectDesc> {363        let mk = |params: Vec<ParamDesc>, samples: u32| EffectDesc {364            kind: kind.to_string(),365            title: kind.to_string(),366            category: "test".into(),367            doc: "Deterministic test effect.".into(),368            params,369            presets: Vec::new(),370            latency: LatencySpec { seconds: 0.0, samples },371            default_mix: 1.0,372        };373        match kind {374            "test_gain" => Some(mk(vec![ParamDesc::num("gain", Unit::Scalar, 0.0, 4.0, 0.5, true, "Linear gain.")], 0)),375            "test_delay" => Some(mk(Vec::new(), TEST_DELAY_LATENCY)),376            "test_nan" => Some(mk(Vec::new(), 0)),377            _ => sonata_dsp::effect_registry().into_iter().find(|e| e.kind == kind),378        }379    }380}381
Files main
Menu

Theme