Skip to main content

qualia_audio/midi/synth/
render_block.rs

1//! Block renderer — sums all active voices of a pool into a caller-provided buffer.
2//!
3//! Production hard rule: allocation-free, no locks, no FS. The output buffer is owned by
4//! the caller; only const-sized voice state is touched here.
5
6use super::voice_allocator::VoiceAllocator;
7use crate::types::AudioError;
8
9/// Render one audio block by summing every active voice into `out` (mono, one sample
10/// per element). Each element is fully mixed before advancing to the next, so voice
11/// phase/envelope stay sample-accurate. Returns `Ok(())`; reserved `AudioError` variants
12/// allow future validation without changing the signature.
13pub fn render_block<const N: usize>(
14    allocator: &mut VoiceAllocator<N>,
15    out: &mut [f32],
16) -> Result<(), AudioError> {
17    for sample in out.iter_mut() {
18        let mut acc = 0.0f32;
19        for v in allocator.voices_mut() {
20            if v.is_active() {
21                acc += v.render_sample();
22            }
23        }
24        *sample = acc;
25    }
26    Ok(())
27}
28
29#[cfg(test)]
30mod tests {
31    use super::super::adsr::AdsrEnvelope;
32    use super::super::oscillator_voice::Waveform;
33    use super::*;
34
35    const SR: f32 = 48_000.0;
36
37    fn env() -> AdsrEnvelope {
38        AdsrEnvelope::new(SR, 0.001, 0.0, 1.0, 0.050)
39    }
40
41    #[test]
42    fn sums_two_voice_chord_bounded_and_finite() {
43        let mut alloc: VoiceAllocator<8> = VoiceAllocator::new(SR, Waveform::Sine, env());
44        alloc.note_on(69, 100, 440.0); // A4
45        alloc.note_on(64, 100, VoiceAllocator::<8>::freq_12tet(64)); // E4
46        assert_eq!(alloc.active_count(), 2);
47
48        let mut out = vec![0.0f32; 1024];
49        render_block(&mut alloc, &mut out).expect("render");
50
51        let mut max_abs = 0.0f32;
52        let mut any_signal = false;
53        for &x in &out {
54            assert!(x.is_finite(), "sample must be finite: {x}");
55            max_abs = max_abs.max(x.abs());
56            if x.abs() > 1e-4 {
57                any_signal = true;
58            }
59        }
60        // Two voices, each gain <= 100/127 ≈ 0.787 → sum bounded well under 2.0.
61        assert!(
62            max_abs <= 2.0,
63            "chord sum should stay bounded, got {max_abs}"
64        );
65        assert!(any_signal, "chord should produce non-zero signal");
66    }
67
68    #[test]
69    fn empty_pool_renders_silence() {
70        let mut alloc: VoiceAllocator<4> = VoiceAllocator::new(SR, Waveform::Sine, env());
71        let mut out = vec![1.0f32; 64];
72        render_block(&mut alloc, &mut out).expect("render");
73        assert!(out.iter().all(|&x| x == 0.0), "no active voices → silence");
74    }
75}