Skip to Content
Soundor Skills

Real-time safety

A reference of the soundor-dsp skill.

soundor-dsp reads this reference when a task needs it. Source on GitHub

Why it matters

The host calls process() for every block on a high-priority audio thread and needs the result before the audio device does. Missing that deadline once is an audible click or dropout. What breaks the deadline is rarely the average cost; it is the occasional operation whose time is unbounded:

  • an allocator call that takes a lock another thread holds, or asks the operating system for memory;
  • a mutex held by a lower-priority thread (priority inversion);
  • I/O, logging and printing, which can block on disks, pipes or terminals;
  • page faults on memory touched for the first time;
  • work proportional to input content instead of block size.

The rules apply to process(), reset(), and everything they call, including third-party crates. Ross Bencina's Real-time audio programming 101 explains the reasoning in depth.

Rust's guarantees are not real-time guarantees

The compiler prevents data races and use-after-free. It does not prevent allocation, locking or blocking, and safe code does all three. Real-time safety is a property you design and test.

Hidden allocations and frees

Looks harmlessWhy it is notInstead
vec.push(x) / extendmay reallocatepreallocate in prepare() with capacity; use fixed arrays
iter().collect::<Vec<_>>()allocateswrite into a preallocated buffer
format!, to_string(), println!allocate, and print blockspublish numbers through streams or read-only parameters
Box::new, Arc::new, Rc::newallocatebuild in prepare()
vec.clone()allocatescopy_from_slice into existing storage
assigning a new Vec/Box to a fieldfrees the old one on the audio threadbuild once; or use Soundor resources, freed off-thread
dropping the last Arc clone in process()runs the destructor, freeskeep the Arc alive in the struct
HashMap insertmay allocate and rehashfixed-size arrays or indices computed in prepare()
FftPlanner::plan_fft_*allocates twiddle tables, cachesplan in prepare()
Fft::process(&mut buf)allocates scratch on each callprocess_with_scratch with scratch from prepare()
building a FunDSP graphallocates nodes and buffersbuild and allocate() in prepare()
Mutex::lock, RwLock, channel.recv()blockparameters, audio state, resources, atomics
unwrap(), slice [i] out of rangepanics; the instance goes silentbound indices by construction; get() with a fallback

Safe patterns

  • Prepare everything: delay lines sized for the maximum delay at the prepared sample rate, scratch buffers sized for max_frames, FFT plans, filter state per channel. Reprepare replaces them, off the audio thread.
  • Fixed capacity: Vec::with_capacity in prepare() and never beyond it; or arrays when the size is a constant.
  • Data from the controller: tables, impulse responses and other large data go through native.resources. Publishing replaces the resource for the next block, and the old one is freed outside the audio thread.
  • Data from the UI: parameters and state fields with audio: true; both reach process() as values, without locks.
  • Data to the UI: ctx.streams.<name>.publish(...), or buffer_mut() plus commit(len), and ctx.publish.<readOnlyParam>(...): lock-free and allocation-free.
  • Logging: don't, in process(). Count events into fields and publish them through a stream while debugging.

Verify

  1. Count allocations in tests. The SDK's counting allocator records allocator calls made on the processing thread during the processor's calls:

    use soundor::testing::{CountingAllocator, TestProcessor};
    
    #[global_allocator]
    static ALLOCATOR: CountingAllocator = CountingAllocator;
    
    #[test]
    fn processing_does_not_allocate() {
        let mut processor = TestProcessor::<my_plugin::PluginProcessor>::new()
            .block_size(512)
            .channels(2)
            .build();
        let input = vec![0.25_f32; 4096];
        processor.process(&[input.clone(), input.clone()]);
        processor.parameters_mut().cutoff = 3000.0; // change what may reallocate
        processor.process(&[input.clone(), input]);
        assert_eq!(processor.allocations(), 0);
    }

    Exercise every path: each mode, bypass, parameter changes, the largest block, reset (count_allocations measures other operations). A test binary has one global allocator: keep this test in its own file under lib/tests/, as the scaffold does with realtime.rs.

  2. Read the code path, including dependency functions you call from process(): look for the operations in the table.

  3. Know the limits. Allocation counts do not detect locks, blocking system calls, page faults or worst-case CPU time. A passing count is necessary, not sufficient.

On this page