Skip to main content

qualia_core_db/audio/scene_audio_graph/
pcm.rs

1//! Caller-buffered PCM rendering through the existing scene acoustic buses.
2//! Scheduling, decoding, resampling, authorization and device output belong to
3//! the host. The active graph capacity is not a limit on authored source count.
4use super::{
5    binaural_from_position, evaluate_acoustic_occlusion_zero_heap, length3, sub3,
6    AcousticObstacle, AcousticObstacleShape, AcousticOcclusionResult, BinauralGains,
7    DirectBinauralBus, EarlyReflectionsBus, LateReverbFreeverbBus, SceneAudioBusGraph,
8    MAX_SCENE_AUDIO_EMITTERS, EARLY_REFLECTION_TAPS,
9};
10
11/// An application-qualified clip/revision mapped onto one current graph node.
12/// These keys identify the caller's assignment; they do not grant authority or
13/// assert universal identity equivalence. Change generation after seek/rebind.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct PcmSourceBinding {
16    pub source_key: u64,
17    pub generation: u64,
18    pub node_id: u32,
19    pub origin_quin_hash: u64,
20}
21
22pub struct PcmVoiceBlock<'a> {
23    pub slot: usize,
24    pub binding: PcmSourceBinding,
25    /// Mono PCM already converted/resampled to the output clock. Exactly one
26    /// sample per output frame; no additional Doppler resampling occurs here.
27    pub samples: &'a [f32],
28    pub gain: f32,
29}
30
31#[derive(Clone, Copy)]
32pub struct PcmRenderBudget {
33    pub max_frames: usize,
34    pub max_active_voices: usize,
35    pub max_obstacles: usize,
36    /// Current bus calibration is 48 kHz. Other rates are refused explicitly.
37    pub sample_rate: u32,
38}
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum PcmRenderError { Budget, Layout, Binding, NumericInput, UnsupportedRate, DspFailure }
42
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub struct PcmRenderReport {
45    pub active_voices: usize,
46    pub frames: usize,
47    pub peak_before_limit: f32,
48    pub limited_samples: usize,
49    /// Conservative assignment/revocation handling resets the shared room
50    /// history, potentially truncating other active sources' existing tails.
51    pub histories_reset: bool,
52}
53
54/// Private caller-owned persistent PCM state, reusing the existing bus types.
55/// Retain this across blocks. Synthesis has separate histories in the graph;
56/// it neither contaminates nor is reset by this PCM rendering path.
57#[derive(Clone)]
58pub struct PcmRenderState {
59    direct: DirectBinauralBus,
60    early: EarlyReflectionsBus,
61    late: LateReverbFreeverbBus,
62    bindings: [Option<PcmSourceBinding>; MAX_SCENE_AUDIO_EMITTERS],
63    initialized: bool,
64}
65impl Default for PcmRenderState {
66    fn default() -> Self {
67        Self { direct: DirectBinauralBus::default(), early: EarlyReflectionsBus::default(),
68            late: LateReverbFreeverbBus::new(0.65, 0.35, 0.22),
69            bindings: [None; MAX_SCENE_AUDIO_EMITTERS], initialized: false }
70    }
71}
72impl PcmRenderState {
73    /// Explicitly clear all PCM histories on transport discontinuity or revoked
74    /// access. The host must cancel queued/device output separately.
75    pub fn reset(&mut self) {
76        self.direct.reset(); self.early.reset(); self.late.reset();
77        self.bindings.fill(None); self.initialized = false;
78    }
79}
80
81// Conservative numeric domain for local scene coordinates, not a global
82// geographic extent. The host should choose an appropriate local origin.
83fn point_ok(p: [f32; 3]) -> bool { p.iter().all(|v| v.is_finite() && v.abs() <= 1_000_000.0) }
84fn size_ok(v: f32) -> bool { (0.0..=1_000_000.0).contains(&v) }
85fn obstacle_ok(o: &AcousticObstacle) -> bool {
86    if !size_ok(o.thickness_m) || !size_ok(o.smooth_blend_radius) { return false; }
87    match o.shape {
88        AcousticObstacleShape::AnalyticalSphere {center, radius} => point_ok(center) && size_ok(radius),
89        AcousticObstacleShape::AnalyticalCapsule {a,b,radius} => point_ok(a) && point_ok(b) && size_ok(radius),
90        AcousticObstacleShape::AnalyticalRoundedBox {center,half_extents,round_radius} =>
91            point_ok(center) && half_extents.iter().all(|&v| size_ok(v)) && size_ok(round_radius),
92        AcousticObstacleShape::Aabb {min,max} => point_ok(min) && point_ok(max) && (0..3).all(|i| min[i] <= max[i]),
93        AcousticObstacleShape::Triangle {v0,v1,v2} => point_ok(v0) && point_ok(v1) && point_ok(v2),
94    }
95}
96fn occlusion_ok(o: &AcousticOcclusionResult) -> bool {
97    (0.0..=1.0).contains(&o.direct_gain) && (0.0..=1.0).contains(&o.enclosure_density)
98        && o.early_reflection_delays_s.iter().all(|v| v.is_finite() && *v >= 0.0)
99        && o.early_reflection_gains.iter().all(|v| (0.0..=1.0).contains(v))
100        && [o.lowpass_biquad.b0,o.lowpass_biquad.b1,o.lowpass_biquad.b2,
101            o.lowpass_biquad.a1,o.lowpass_biquad.a2].iter().all(|v| v.is_finite())
102}
103
104impl SceneAudioBusGraph {
105    /// Render authorized, caller-scheduled PCM voices through scene distance,
106    /// occlusion, existing binaural, early-reflection and late-reverb buses.
107    /// Validation errors leave outputs/state unchanged. Unexpected DSP failure
108    /// clears the outputs and resets PCM state. Output is limited to ±1 and the
109    /// report counts limited samples; this is not a mastering/normalization pass.
110    ///
111    /// The shared early bus uses gain-weighted geometry from active voices.
112    /// This is an explicit room approximation, not per-source path tracing.
113    /// Doppler, propagation time and authored clip scheduling remain host work.
114    pub fn render_pcm_quantum_zero_heap(&self, state: &mut PcmRenderState,
115        voices: &[PcmVoiceBlock<'_>], obstacles: &[AcousticObstacle], budget: PcmRenderBudget,
116        out_l: &mut [f32], out_r: &mut [f32]) -> Result<PcmRenderReport, PcmRenderError> {
117        if budget.sample_rate != 48_000 { return Err(PcmRenderError::UnsupportedRate); }
118        if out_l.is_empty() || out_l.len() != out_r.len() { return Err(PcmRenderError::Layout); }
119        if out_l.len() > budget.max_frames || voices.len() > budget.max_active_voices
120            || budget.max_active_voices > MAX_SCENE_AUDIO_EMITTERS || self.emitter_count > MAX_SCENE_AUDIO_EMITTERS
121            || obstacles.len() > budget.max_obstacles { return Err(PcmRenderError::Budget); }
122        if !point_ok(self.listener.position) || !self.listener.yaw_rad.is_finite()
123            || !(0.0..=4.0).contains(&self.listener.manifold_w) || obstacles.iter().any(|o| !obstacle_ok(o)) {
124            return Err(PcmRenderError::NumericInput);
125        }
126        let mut bindings = [None; MAX_SCENE_AUDIO_EMITTERS];
127        let mut seen = [false; MAX_SCENE_AUDIO_EMITTERS];
128        let mut gains = [BinauralGains::default(); MAX_SCENE_AUDIO_EMITTERS];
129        let mut attenuation = [0.0; MAX_SCENE_AUDIO_EMITTERS];
130        let mut occlusions = [AcousticOcclusionResult::default(); MAX_SCENE_AUDIO_EMITTERS];
131        let mut active = 0;
132        let mut enclosure = 0.0;
133        let mut room_weight = 0.0;
134        let mut delays = [0.0; EARLY_REFLECTION_TAPS];
135        let mut reflections = [0.0; EARLY_REFLECTION_TAPS];
136        for voice in voices {
137            if voice.slot >= self.emitter_count || voice.slot >= MAX_SCENE_AUDIO_EMITTERS || seen[voice.slot]
138                || voice.binding.source_key == 0 { return Err(PcmRenderError::Binding); }
139            seen[voice.slot] = true;
140            let node = &self.emitters[voice.slot];
141            if node.node_id != voice.binding.node_id || node.origin_quin_hash != voice.binding.origin_quin_hash {
142                return Err(PcmRenderError::Binding);
143            }
144            if voice.samples.len() != out_l.len() { return Err(PcmRenderError::Layout); }
145            if !(0.0..=1.0).contains(&voice.gain) || voice.samples.iter().any(|v| !(-1.0..=1.0).contains(v))
146                || !point_ok(node.emitter.position) || !(0.0..=1.0).contains(&node.emitter.amplitude)
147                || !(0.001..=1_000_000.0).contains(&node.emitter.coherence_radius) {
148                return Err(PcmRenderError::NumericInput);
149            }
150            if node.deontic_permit >= 2 || node.emitter.amplitude == 0.0 { continue; }
151            bindings[voice.slot] = Some(voice.binding);
152            let rel = sub3(node.emitter.position, self.listener.position);
153            let distance = length3(rel);
154            if !node.is_ambient && distance > node.emitter.coherence_radius { continue; }
155            evaluate_acoustic_occlusion_zero_heap(self.listener.position, node.emitter.position, obstacles, &mut occlusions[voice.slot]);
156            if !occlusion_ok(&occlusions[voice.slot]) { return Err(PcmRenderError::NumericInput); }
157            let o = &occlusions[voice.slot];
158            let falloff = if node.is_ambient { 1.0 } else { (1.0-distance/node.emitter.coherence_radius).clamp(0.0,1.0)/(1.0+distance*0.45) };
159            let weight = voice.gain * node.emitter.amplitude * falloff;
160            attenuation[voice.slot] = weight * o.direct_gain;
161            gains[voice.slot] = if node.is_ambient {
162                BinauralGains {gain_l: 0.707, gain_r: 0.707, itd_seconds:0.0, azimuth_rad:0.0,elevation_rad:0.0,distance:distance.max(1.0)}
163            } else { binaural_from_position(rel, self.listener.yaw_rad) };
164            active += 1;
165            enclosure += o.enclosure_density * weight; room_weight += weight;
166            for i in 0..EARLY_REFLECTION_TAPS { delays[i] += o.early_reflection_delays_s[i]*weight; reflections[i] += o.early_reflection_gains[i]*weight; }
167        }
168        let reset = !state.initialized || bindings != state.bindings;
169        if reset { state.reset(); state.bindings = bindings; state.initialized = true; }
170        if room_weight > 0.0 { enclosure /= room_weight; for i in 0..EARLY_REFLECTION_TAPS { delays[i] /= room_weight; reflections[i] /= room_weight; } }
171        state.late.configure_from_enclosure(enclosure, self.listener.manifold_w);
172        let mut report = PcmRenderReport {active_voices:active,frames:out_l.len(),peak_before_limit:0.0,limited_samples:0,histories_reset:reset};
173        for frame in 0..out_l.len() {
174            let (mut left, mut right) = (0.0,0.0);
175            for voice in voices {
176                let slot = voice.slot;
177                if bindings[slot].is_none() { continue; }
178                let (l,r) = state.direct.process_emitter_sample(slot, voice.samples[frame]*attenuation[slot],
179                    &occlusions[slot].lowpass_biquad,&gains[slot],48_000.0);
180                left += l; right += r;
181            }
182            let (el,er) = state.early.tick(left,right,&delays,&reflections,48_000.0);
183            let (rl,rr) = state.late.tick(left+el,right+er);
184            let l = left+el+rl; let r = right+er+rr;
185            if !l.is_finite() || !r.is_finite() {
186                out_l.fill(0.0); out_r.fill(0.0); state.reset(); return Err(PcmRenderError::DspFailure);
187            }
188            report.peak_before_limit = report.peak_before_limit.max(l.abs()).max(r.abs());
189            report.limited_samples += usize::from(l.abs()>1.0)+usize::from(r.abs()>1.0);
190            out_l[frame] = l.clamp(-1.0,1.0); out_r[frame] = r.clamp(-1.0,1.0);
191        }
192        Ok(report)
193    }
194}
195
196#[cfg(test)]
197#[path = "pcm_tests.rs"]
198mod tests;