Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/tests/no_alloc.rs3//! Description: Proves that no engine allocates or frees memory in its real-time calls, with a4//! counting global allocator. Runs alone in this test binary so that nothing else allocates.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_dsp::core::midi_to_hz;10use sonata_instruments::{create_instrument, engine_registry, NoteOn};11use sonata_ir::{Articulation, InstrumentSpec, ParamValue, Params, PatchInput, PatchNode, PatchSpec, Rate, Span, Unit};12use std::alloc::{GlobalAlloc, Layout, System};13use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};1415struct Counting;16static ARMED: AtomicBool = AtomicBool::new(false);17static EVENTS: AtomicUsize = AtomicUsize::new(0);1819// SAFETY: defers to the system allocator; only counts calls while armed.20unsafe impl GlobalAlloc for Counting {21 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {22 if ARMED.load(Ordering::Relaxed) {23 EVENTS.fetch_add(1, Ordering::Relaxed);24 }25 System.alloc(layout)26 }27 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {28 if ARMED.load(Ordering::Relaxed) {29 EVENTS.fetch_add(1, Ordering::Relaxed);30 }31 System.dealloc(ptr, layout)32 }33 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {34 if ARMED.load(Ordering::Relaxed) {35 EVENTS.fetch_add(1, Ordering::Relaxed);36 }37 System.realloc(ptr, layout, new_size)38 }39}4041#[global_allocator]42static GLOBAL: Counting = Counting;4344fn note(id: u64, pitch: f32) -> NoteOn {45 NoteOn { id, pitch, freq: midi_to_hz(pitch, 440.0), velocity: 0.9, articulation: Articulation::Normal }46}4748#[test]49fn real_time_calls_never_allocate() {50 let mut specs: Vec<(InstrumentSpec, Vec<(usize, f32)>)> = Vec::new();51 for desc in engine_registry() {52 if desc.model == "patch" {53 continue;54 }55 let automatable: Vec<(usize, f32)> = desc56 .params57 .iter()58 .enumerate()59 .filter(|(_, p)| p.automatable && !matches!(p.unit, Unit::Choice | Unit::HertzList | Unit::ScalarList))60 .map(|(i, p)| (i, ((p.min + p.max) * 0.5) as f32))61 .collect();62 specs.push((InstrumentSpec { name: "T".into(), model: desc.model.clone(), params: Params::new(), patch: None }, automatable.clone()));63 for preset in &desc.presets {64 let mut params = Params::new();65 params.insert("preset".into(), ParamValue::Text(preset.name.clone()));66 specs.push((InstrumentSpec { name: "T".into(), model: desc.model.clone(), params, patch: None }, automatable.clone()));67 }68 }69 let n = |name: &str, kind: &str, inputs: &[(&str, PatchInput)]| PatchNode {70 name: name.into(),71 kind: kind.into(),72 inputs: inputs.iter().cloned().map(|(k, v)| (k.to_string(), v)).collect(),73 rate: Rate::Audio,74 span: Span::default(),75 };76 let patch = PatchSpec {77 nodes: vec![78 n("o", "saw", &[]),79 n("w", "wavetable", &[]),80 n("e", "adsr", &[]),81 n("f", "lowpass", &[("in", PatchInput::Node(0)), ("cutoff", PatchInput::Const(900.0))]),82 n(83 "d",84 "delay",85 &[("in", PatchInput::Node(3)), ("time", PatchInput::Const(0.02)), ("feedback", PatchInput::Const(0.3)), ("max", PatchInput::Const(0.1))],86 ),87 n("m", "modal", &[("in", PatchInput::Node(1))]),88 n("s", "add", &[("a", PatchInput::Node(4)), ("b", PatchInput::Node(5))]),89 n("out", "mul", &[("a", PatchInput::Node(6)), ("b", PatchInput::Node(2))]),90 ],91 output: 7,92 amp_envelope: Some(2),93 };94 specs.push((InstrumentSpec { name: "T".into(), model: "patch".into(), params: Params::new(), patch: Some(patch) }, vec![(0, -6.0)]));9596 let mut buffers = (vec![0.0f32; 512], vec![0.0f32; 512]);97 for (spec, automatable) in &specs {98 let mut inst = create_instrument(spec, 440.0, 3).unwrap();99 inst.prepare(48_000.0, 512, 4);100 EVENTS.store(0, Ordering::SeqCst);101 ARMED.store(true, Ordering::SeqCst);102 // Notes beyond the voice limit (stealing), pedal, bends, automation, releases, tails, reset.103 for step in 0..60u64 {104 if step < 12 {105 inst.note_on(¬e(step + 1, 40.0 + 3.0 * step as f32));106 }107 if step == 5 {108 inst.sustain(true);109 }110 if step % 7 == 3 {111 inst.pitch_bend(step, 0.5);112 inst.note_off(step.saturating_sub(2));113 }114 if step == 20 {115 inst.sustain(false);116 }117 if let Some((index, value)) = automatable.get(step as usize % automatable.len().max(1)) {118 inst.set_param(*index, *value);119 }120 if step == 40 {121 inst.all_notes_off();122 }123 if step == 55 {124 inst.reset();125 }126 let frames = [512, 64, 1, 300][step as usize % 4];127 buffers.0[..frames].fill(0.0);128 buffers.1[..frames].fill(0.0);129 inst.process(&mut buffers.0[..frames], &mut buffers.1[..frames]);130 let _ = inst.active_voices();131 }132 ARMED.store(false, Ordering::SeqCst);133 let events = EVENTS.load(Ordering::SeqCst);134 assert_eq!(events, 0, "model '{}' ({:?}) made {events} allocator calls in real-time code", spec.model, spec.params.get("preset"));135 }136}137