qualia_audio/midi/synth/
render_block.rs1use super::voice_allocator::VoiceAllocator;
7use crate::types::AudioError;
8
9pub 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); alloc.note_on(64, 100, VoiceAllocator::<8>::freq_12tet(64)); 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 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}