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 harmless | Why it is not | Instead |
|---|---|---|
vec.push(x) / extend | may reallocate | preallocate in prepare() with capacity; use fixed arrays |
iter().collect::<Vec<_>>() | allocates | write into a preallocated buffer |
format!, to_string(), println! | allocate, and print blocks | publish numbers through streams or read-only parameters |
Box::new, Arc::new, Rc::new | allocate | build in prepare() |
vec.clone() | allocates | copy_from_slice into existing storage |
assigning a new Vec/Box to a field | frees the old one on the audio thread | build once; or use Soundor resources, freed off-thread |
dropping the last Arc clone in process() | runs the destructor, frees | keep the Arc alive in the struct |
HashMap insert | may allocate and rehash | fixed-size arrays or indices computed in prepare() |
FftPlanner::plan_fft_* | allocates twiddle tables, caches | plan in prepare() |
Fft::process(&mut buf) | allocates scratch on each call | process_with_scratch with scratch from prepare() |
| building a FunDSP graph | allocates nodes and buffers | build and allocate() in prepare() |
Mutex::lock, RwLock, channel.recv() | block | parameters, audio state, resources, atomics |
unwrap(), slice [i] out of range | panics; the instance goes silent | bound 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_capacityinprepare()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
statefields withaudio: true; both reachprocess()as values, without locks. - Data to the UI:
ctx.streams.<name>.publish(...), orbuffer_mut()pluscommit(len), andctx.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
-
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_allocationsmeasures other operations). A test binary has one global allocator: keep this test in its own file underlib/tests/, as the scaffold does withrealtime.rs. -
Read the code path, including dependency functions you call from
process(): look for the operations in the table. -
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.