Repository Public
1//! ORIX Sonata2//! File: crates/sonata-runtime/tests/no_alloc.rs3//! Description: Proves that `Processor::process` neither allocates nor frees: a counting global4//! allocator is armed around every call while the engine plays, receives commands and hot swaps.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai8#![allow(clippy::needless_range_loop)] // sample indices are the subject of these assertions910use sonata_ir::*;11use sonata_runtime::testing::*;12use sonata_runtime::*;13use std::alloc::{GlobalAlloc, Layout, System};14use std::cell::Cell;15use std::sync::atomic::{AtomicU64, Ordering};1617struct Counting;18static EVENTS: AtomicU64 = AtomicU64::new(0);19thread_local! { static ARMED: Cell<bool> = const { Cell::new(false) }; }2021unsafe impl GlobalAlloc for Counting {22 unsafe fn alloc(&self, l: Layout) -> *mut u8 {23 if ARMED.try_with(|a| a.get()).unwrap_or(false) {24 EVENTS.fetch_add(1, Ordering::Relaxed);25 }26 unsafe { System.alloc(l) }27 }28 unsafe fn dealloc(&self, p: *mut u8, l: Layout) {29 if ARMED.try_with(|a| a.get()).unwrap_or(false) {30 EVENTS.fetch_add(1, Ordering::Relaxed);31 }32 unsafe { System.dealloc(p, l) }33 }34 unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {35 if ARMED.try_with(|a| a.get()).unwrap_or(false) {36 EVENTS.fetch_add(1, Ordering::Relaxed);37 }38 unsafe { System.realloc(p, l, n) }39 }40}4142#[global_allocator]43static GLOBAL: Counting = Counting;4445fn program(seed: u64, registry: bool) -> Program {46 let mut p = Program::empty("alloc");47 p.seed = seed;48 let model = if registry { sonata_instruments::engine_registry().first().map(|e| e.model.clone()) } else { None };49 for t in 0..6u32 {50 let notes = (0..400)51 .map(|k| test_note(t, k, k as f64 * 0.011 + t as f64 * 0.003, k as f64 * 0.011 + 0.09, 40.0 + ((k * 7 + t * 3) % 40) as f64, 0.6))52 .collect();53 let mut tr = test_track(t, model.as_deref().unwrap_or("test_sine"), notes);54 tr.pan = t as f64 / 3.0 - 1.0;55 tr.effects.push(test_effect("test_delay", 0.5, &[]));56 tr.effects.push(test_effect("test_gain", 1.0, &[("gain", 0.9)]));57 if registry {58 for d in sonata_dsp::effect_registry() {59 tr.effects.push(test_effect(&d.kind, d.default_mix, &[]));60 }61 }62 tr.sends.push(Send { bus: 0, gain_db: -12.0, pre_fader: t % 2 == 0 });63 tr.automation.push(AutomationLane {64 target: AutomationTarget::Gain,65 points: (0..50)66 .map(|k| AutomationPoint {67 at: Rational::ZERO,68 at_sec: k as f64 * 0.09,69 value: -(k % 5) as f64 * 3.0,70 curve: if k % 2 == 0 { Curve::Linear } else { Curve::Exponential },71 })72 .collect(),73 span: Span::default(),74 });75 p.tracks.push(tr);76 }77 p.buses.push(Bus {78 id: 0,79 name: "fx".into(),80 gain_db: -3.0,81 pan: 0.0,82 mute: false,83 effects: vec![test_effect("test_gain", 1.0, &[])],84 sends: vec![],85 output: Output::Master,86 automation: vec![],87 span: Span::default(),88 });89 p.refresh_stats();90 p91}9293fn exercise(registry: bool) {94 let prep = |seed: u64| {95 let p = program(seed, registry);96 let g = basic_graph(&p, 48_000, &TestFactory, 240).unwrap();97 PreparedProgram::prepare_with(&p, &g, 48_000, 512, &NoAssets, &Limits::default(), &TestFactory).unwrap()98 };99 let (ctl, mut proc_) = engine(EngineConfig::realtime(48_000));100 ctl.load(prep(1)).ok().unwrap();101 ctl.play();102 let (mut l, mut r) = (vec![0.0f32; 512], vec![0.0f32; 512]);103 let mut heard = 0.0f32;104 for block in 0..1500u32 {105 // Control-thread activity between callbacks (allowed to allocate).106 match block % 97 {107 5 => ctl.set_gain_db(Strip::Track(block % 6), Some(-3.0)),108 11 => ctl.set_pan(Strip::Track(1), Some(0.3)),109 17 => ctl.set_mute(Strip::Track(2), Some(block % 2 == 0)),110 23 => ctl.set_solo(Strip::Track(3), Some(block % 194 == 23)),111 29 => ctl.note_on(0, (1 << 63) | block as u64, 64.0, 0.5),112 31 => ctl.all_notes_off(),113 37 => ctl.set_effect_bypass(Strip::Track(4), 0, block % 2 == 1),114 41 => ctl.set_effect_param(Strip::Track(5), 1, 0, 0.7),115 43 => ctl.seek_seconds((block % 4) as f64),116 47 => ctl.set_loop(Some((0, 96_000))),117 53 => ctl.set_tap(TapPoint::Track(2)),118 59 => {119 let _ = ctl.load(prep(block as u64));120 }121 61 => ctl.set_metronome(true, -20.0),122 67 => ctl.pause(),123 68 => ctl.play_with_count_in(1),124 71 => {125 ctl.collect_garbage();126 }127 _ => {}128 }129 let n = [512usize, 128, 100, 64, 1][(block % 5) as usize];130 ARMED.with(|a| a.set(true));131 proc_.process(&mut l[..n], &mut r[..n]);132 ARMED.with(|a| a.set(false));133 heard = heard.max(l[..n].iter().fold(0.0f32, |a, b| a.max(b.abs())));134 assert!(l[..n].iter().chain(r[..n].iter()).all(|x| x.is_finite() && x.abs() <= 1.0));135 }136 assert!(heard > 0.01, "the session must produce sound for the test to mean anything");137 assert_eq!(EVENTS.load(Ordering::Relaxed), 0, "process() allocated or freed memory (registry components: {registry})");138 assert!(ctl.shared().program_generation() > 3);139}140141#[test]142fn process_never_allocates_with_test_components() {143 exercise(false);144}145146/// The same session with the first registry instrument and every registry effect inserted on147/// every track, so each shipped component is covered by the real-time allocation check.148#[test]149fn process_never_allocates_with_registry_components() {150 exercise(true);151}152