Skip to main content

qualia_core_db/audio/
acoustic_plane.rs

1//! U3 AcousticPlane — SPSC sonic token ring + parametric uniform for AudioWorklet.
2//!
3//! Shares U1 `Tensor10D` SOA read-only; no dedicated VRAM partition until bake sidecars land.
4
5use core::cell::UnsafeCell;
6use std::sync::atomic::{AtomicU32, Ordering};
7
8use bytemuck::{Pod, Zeroable};
9
10use crate::audio::audio_spectral_sheet::{preview_bins_from_tensor, SPECTRAL_PREVIEW_BINS};
11use crate::audio::dsp_kernel::configure_voice_from_tensor;
12use crate::audio::hrtf::{binaural_from_position, room_damp_from_manifold};
13use crate::gpu_context::{ComputeUniverse, OperationalMode};
14use crate::render::acoustic::{
15    phenomenal_acoustic_params, phenomenal_fm_index, phenomenal_voice_frequency_hz,
16};
17use crate::sonic_token::SonicToken;
18use crate::tensor::Tensor10D;
19
20pub const SONIC_RING_CAP: usize = 128;
21
22/// Worklet uniform — mirrors `AcousticParams` with fixed preview bins.
23#[repr(C)]
24#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
25pub struct AcousticUniform {
26    pub alpha: f32,
27    pub mu: f32,
28    pub position: [f32; 3],
29    pub track_v: f32,
30    pub manifold_w: f32,
31    pub epistemic_q: f32,
32    pub fm_index: f32,
33    pub frequency_hz: f32,
34    pub enabled: u32,
35    pub gain_l: f32,
36    pub gain_r: f32,
37    pub itd_seconds: f32,
38    pub azimuth_rad: f32,
39    pub elevation_rad: f32,
40    pub room_damp: f32,
41    pub stft_frame: f32,
42    pub preview_bins: [f32; SPECTRAL_PREVIEW_BINS],
43}
44
45impl Default for AcousticUniform {
46    fn default() -> Self {
47        Self {
48            alpha: 0.0,
49            mu: 0.0,
50            position: [0.0; 3],
51            track_v: 0.0,
52            manifold_w: 0.0,
53            epistemic_q: 0.0,
54            fm_index: 0.0,
55            frequency_hz: 440.0,
56            enabled: 0,
57            gain_l: 0.707,
58            gain_r: 0.707,
59            itd_seconds: 0.0,
60            azimuth_rad: 0.0,
61            elevation_rad: 0.0,
62            room_damp: 1.0,
63            stft_frame: 0.0,
64            preview_bins: [0.0; SPECTRAL_PREVIEW_BINS],
65        }
66    }
67}
68
69/// Compute binaural gains/ITD/azimuth/elevation from the uniform's position
70/// and listener yaw, and set room damping from the manifold weight.
71#[inline]
72pub fn apply_binaural_to_uniform(u: &mut AcousticUniform, listener_yaw: f32) {
73    let g = binaural_from_position(u.position, listener_yaw);
74    u.gain_l = g.gain_l;
75    u.gain_r = g.gain_r;
76    u.itd_seconds = g.itd_seconds;
77    u.azimuth_rad = g.azimuth_rad;
78    u.elevation_rad = g.elevation_rad;
79    u.room_damp = room_damp_from_manifold(u.manifold_w);
80}
81
82/// Scalar params extracted from a tensor node (no heap).
83#[derive(Debug, Clone, Copy, PartialEq)]
84pub struct AcousticParams {
85    pub alpha: f32,
86    pub mu: f32,
87    pub position: [f32; 3],
88    pub track_v: f32,
89    pub manifold_w: f32,
90    pub epistemic_q: f32,
91    pub preview_bins: [f32; SPECTRAL_PREVIEW_BINS],
92}
93
94impl AcousticParams {
95    /// Extract the acoustic subset of a 10D tensor node (position, velocity
96    /// track, manifold weight, epistemic q, spectral preview bins).
97    #[inline]
98    pub fn from_tensor(t: &Tensor10D) -> Self {
99        Self {
100            alpha: t.alpha,
101            mu: t.mu,
102            position: [t.x, t.y, t.z],
103            track_v: t.v,
104            manifold_w: t.w,
105            epistemic_q: t.q,
106            preview_bins: preview_bins_from_tensor(t),
107        }
108    }
109
110    /// Pack the params into a worklet `AcousticUniform`, deriving FM index
111    /// and frequency via `configure_voice_from_tensor`. `enabled` sets the
112    /// uniform's on/off flag for the synth.
113    #[inline]
114    pub fn to_uniform(self, enabled: bool) -> AcousticUniform {
115        let mut voice = crate::audio::dsp_kernel::ParametricVoiceState::default();
116        configure_voice_from_tensor(
117            &mut voice,
118            self.epistemic_q,
119            self.mu,
120            self.alpha,
121            &self.preview_bins,
122        );
123        let mut u = AcousticUniform {
124            alpha: self.alpha,
125            mu: self.mu,
126            position: self.position,
127            track_v: self.track_v,
128            manifold_w: self.manifold_w,
129            epistemic_q: self.epistemic_q,
130            fm_index: voice.fm_index,
131            frequency_hz: voice.frequency_hz,
132            enabled: u32::from(enabled),
133            preview_bins: self.preview_bins,
134            ..AcousticUniform::default()
135        };
136        u.enabled = u32::from(enabled);
137        u
138    }
139
140    /// Phenomenal uniform — σ oracle frequency (P-F2) aligned with `portal_spectral`.
141    #[inline]
142    pub fn to_phenomenal_uniform(
143        self,
144        enabled: bool,
145        t: &Tensor10D,
146        listener_yaw: f32,
147    ) -> AcousticUniform {
148        let mut u = self.to_uniform(enabled);
149        u.frequency_hz = phenomenal_voice_frequency_hz(t);
150        u.fm_index = phenomenal_fm_index(t);
151        u.stft_frame = (t.t * 32.0).fract() * 32.0;
152        apply_binaural_to_uniform(&mut u, listener_yaw);
153        u
154    }
155}
156
157/// Alias for `phenomenal_acoustic_params` — the canonical tensor→params
158/// extraction used by the U3 plane.
159#[inline]
160pub fn acoustic_params_from_tensor(t: &Tensor10D) -> AcousticParams {
161    phenomenal_acoustic_params(t)
162}
163
164/// True when U3 synthesis is allowed under operational mode (muted in Reserve).
165#[inline]
166pub fn acoustic_enabled_for_mode(mode: OperationalMode) -> bool {
167    !matches!(mode, OperationalMode::Reserve)
168}
169
170/// U3 effective mode — shares U1 ledger; follows viewport pressure in Reserve.
171#[inline]
172pub fn acoustic_effective_mode(global: OperationalMode) -> OperationalMode {
173    crate::gpu_context::universe_orchestrator()
174        .effective_mode(ComputeUniverse::AcousticPlane, global)
175}
176
177/// Fixed-capacity SPSC ring of packed `SonicToken` (`u64`).
178pub struct SonicTokenRing {
179    slots: UnsafeCell<[u64; SONIC_RING_CAP]>,
180    write_seq: AtomicU32,
181    read_seq: AtomicU32,
182}
183
184// SAFETY: SPSC — one producer (U0/U1/portal), one consumer (worklet poll).
185unsafe impl Sync for SonicTokenRing {}
186
187impl SonicTokenRing {
188    /// Create an empty ring. `const` so the global `SONIC_TOKEN_RING` can be
189    /// a static.
190    pub const fn new() -> Self {
191        Self {
192            slots: UnsafeCell::new([0u64; SONIC_RING_CAP]),
193            write_seq: AtomicU32::new(0),
194            read_seq: AtomicU32::new(0),
195        }
196    }
197
198    /// Number of tokens currently queued (wraps correctly across u32
199    /// sequence wraparound).
200    #[inline]
201    pub fn len(&self) -> usize {
202        let w = self.write_seq.load(Ordering::Acquire);
203        let r = self.read_seq.load(Ordering::Acquire);
204        (w.wrapping_sub(r)) as usize
205    }
206
207    /// True when no tokens are queued.
208    #[inline]
209    pub fn is_empty(&self) -> bool {
210        self.len() == 0
211    }
212
213    /// Enqueue a token. Returns false (drops the token) when the ring is
214    /// full — producers must tolerate loss. Producer-side only (SPSC).
215    pub fn try_push(&self, token: SonicToken) -> bool {
216        let w = self.write_seq.load(Ordering::Relaxed);
217        let r = self.read_seq.load(Ordering::Acquire);
218        if w.wrapping_sub(r) >= SONIC_RING_CAP as u32 {
219            return false;
220        }
221        let slot = (w % SONIC_RING_CAP as u32) as usize;
222        unsafe {
223            (*self.slots.get())[slot] = token.raw;
224        }
225        self.write_seq.store(w.wrapping_add(1), Ordering::Release);
226        true
227    }
228
229    /// Dequeue the oldest token, or `None` when empty. Consumer-side only
230    /// (SPSC).
231    pub fn try_pop(&self) -> Option<SonicToken> {
232        let r = self.read_seq.load(Ordering::Relaxed);
233        let w = self.write_seq.load(Ordering::Acquire);
234        if r == w {
235            return None;
236        }
237        let slot = (r % SONIC_RING_CAP as u32) as usize;
238        let raw = unsafe { (*self.slots.get())[slot] };
239        self.read_seq.store(r.wrapping_add(1), Ordering::Release);
240        Some(SonicToken { raw })
241    }
242}
243
244static SONIC_TOKEN_RING: SonicTokenRing = SonicTokenRing::new();
245
246/// The process-global U3 sonic token ring.
247#[inline]
248pub fn sonic_token_ring() -> &'static SonicTokenRing {
249    &SONIC_TOKEN_RING
250}
251
252/// Push a token onto the global ring; false when full (token dropped).
253#[inline]
254pub fn push_sonic_token(token: SonicToken) -> bool {
255    sonic_token_ring().try_push(token)
256}
257
258/// Pop the oldest token from the global ring, if any.
259#[inline]
260pub fn pop_sonic_token() -> Option<SonicToken> {
261    sonic_token_ring().try_pop()
262}
263
264/// Drain up to `out.len()` tokens; returns count written.
265pub fn drain_sonic_tokens(out: &mut [u64]) -> usize {
266    let mut n = 0usize;
267    while n < out.len() {
268        match pop_sonic_token() {
269            Some(t) => {
270                out[n] = t.raw;
271                n += 1;
272            }
273            None => break,
274        }
275    }
276    n
277}
278
279/// Emit parametric pulse + optional NoteOn from a tensor node (U1 → U3).
280pub fn sonify_tensor_node(tensor_index: u32, t: &Tensor10D, note_on: bool) -> usize {
281    let mut pushed = 0usize;
282    let pitch = SonicToken::pitch_from_tensor(t.w, t.q, t.sigma);
283    let velocity = (t.alpha.clamp(0.0, 1.0) * 127.0) as u8;
284    if push_sonic_token(SonicToken::parametric_pulse(tensor_index, velocity)) {
285        pushed += 1;
286    }
287    if note_on {
288        if push_sonic_token(SonicToken::note_on(tensor_index, pitch, velocity, 0)) {
289            pushed += 1;
290        }
291    }
292    pushed
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::sonic_token::{SonicEventType, SONIC_MAGIC};
299
300    fn fresh_ring() -> SonicTokenRing {
301        SonicTokenRing::new()
302    }
303
304    #[test]
305    fn sonic_ring_push_pop() {
306        let ring = fresh_ring();
307        let t = SonicToken::note_on(1, 60, 100, 0);
308        assert!(ring.try_push(t));
309        let popped = ring.try_pop().expect("token");
310        assert_eq!(popped.tensor_index(), 1);
311        assert_eq!(popped.note(), 60);
312    }
313
314    #[test]
315    fn sonic_ring_full_returns_false() {
316        let ring = fresh_ring();
317        for i in 0..SONIC_RING_CAP {
318            assert!(
319                ring.try_push(SonicToken::note_on(i as u32, 60, 100, 0)),
320                "push {i}"
321            );
322        }
323        assert!(!ring.try_push(SonicToken::note_on(999, 60, 100, 0)));
324    }
325
326    #[test]
327    fn drain_respects_capacity() {
328        let ring = fresh_ring();
329        for i in 0..4 {
330            ring.try_push(SonicToken::note_on(i, 60, 100, 0));
331        }
332        let mut local = [0u64; 2];
333        let mut n = 0usize;
334        while n < local.len() {
335            if let Some(t) = ring.try_pop() {
336                local[n] = t.raw;
337                n += 1;
338            } else {
339                break;
340            }
341        }
342        assert_eq!(n, 2);
343        assert_eq!(ring.len(), 2);
344    }
345
346    #[test]
347    fn acoustic_uniform_size_stable() {
348        assert_eq!(std::mem::size_of::<AcousticUniform>() % 4, 0);
349        let t = Tensor10D::default();
350        let u = AcousticParams::from_tensor(&t).to_uniform(true);
351        assert_eq!(u.enabled, 1);
352    }
353
354    #[test]
355    fn acoustic_disabled_in_reserve() {
356        assert!(!acoustic_enabled_for_mode(OperationalMode::Reserve));
357        assert!(acoustic_enabled_for_mode(OperationalMode::Full));
358    }
359
360    #[test]
361    fn sonify_pushes_tokens() {
362        let ring = fresh_ring();
363        let t = Tensor10D::new(0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.8, 0.1, 2.5);
364        // sonify uses global ring — test logic via local push pattern
365        let pitch = SonicToken::pitch_from_tensor(t.w, t.q, t.sigma);
366        assert!(ring.try_push(SonicToken::parametric_pulse(7, 100)));
367        assert!(ring.try_push(SonicToken::note_on(7, pitch, 100, 0)));
368        assert_eq!(ring.len(), 2);
369        let first = ring.try_pop().unwrap();
370        assert_eq!(first.event_type(), SonicEventType::Parametric);
371        let second = ring.try_pop().unwrap();
372        assert_eq!(second.event_type(), SonicEventType::NoteOn);
373        assert_eq!(second.flags() & 0xff, SONIC_MAGIC as u16);
374    }
375}