Skip to main content

qualia_core_db/audio/
acoustic_sab.rs

1//! SharedArrayBuffer layout for zero-copy U3 uniform + sonic token mirror (Phase 7.4).
2//!
3//! Layout: `[header 32][uniform 352][tokens 128][float mirror 328]` = 840 B (padded to 1024).
4
5use bytemuck::{Pod, Zeroable};
6
7use super::acoustic_plane::AcousticUniform;
8use crate::sonic_token::SonicToken;
9
10pub const ACOUSTIC_SAB_MAGIC: u32 = 0x5133_4153; // "Q3AS"
11pub const ACOUSTIC_SAB_VERSION: u16 = 1;
12pub const ACOUSTIC_SAB_HEADER_BYTES: usize = 32;
13pub const ACOUSTIC_SAB_UNIFORM_OFFSET: usize = 32;
14pub const ACOUSTIC_SAB_UNIFORM_PADDED: usize = 352;
15pub const ACOUSTIC_SAB_TOKEN_OFFSET: usize =
16    ACOUSTIC_SAB_UNIFORM_OFFSET + ACOUSTIC_SAB_UNIFORM_PADDED;
17pub const ACOUSTIC_SAB_TOKEN_BYTES: usize = 128;
18pub const ACOUSTIC_SAB_FLOAT_MIRROR_OFFSET: usize =
19    ACOUSTIC_SAB_TOKEN_OFFSET + ACOUSTIC_SAB_TOKEN_BYTES;
20pub const ACOUSTIC_SAB_FLOAT_MIRROR_BYTES: usize = 328;
21pub const ACOUSTIC_SAB_BYTES: usize = 1024;
22
23/// SAB header — worklet polls `uniform_seq` / `token_seq` (Release/Acquire).
24#[repr(C)]
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable)]
26pub struct AcousticSabHeader {
27    /// Format magic `"Q3AS"` (`ACOUSTIC_SAB_MAGIC`).
28    pub magic: u32,
29    /// Layout version (`ACOUSTIC_SAB_VERSION`).
30    pub version: u16,
31    /// Bumped on every uniform write; the worklet polls for changes.
32    pub uniform_seq: u16,
33    /// Producer sequence counter for the SAB token ring.
34    pub token_write: u32,
35    /// Consumer sequence counter for the SAB token ring.
36    pub token_read: u32,
37    /// STFT frame index currently being rendered.
38    pub stft_frame: u32,
39    /// Worklet sample rate (default 48,000).
40    pub sample_rate: u32,
41    pub _pad: u32,
42}
43
44impl AcousticSabHeader {
45    /// Header initialised to defaults: 48 kHz, all sequence counters at 0.
46    #[inline]
47    pub const fn new() -> Self {
48        Self {
49            magic: ACOUSTIC_SAB_MAGIC,
50            version: ACOUSTIC_SAB_VERSION,
51            uniform_seq: 0,
52            token_write: 0,
53            token_read: 0,
54            stft_frame: 0,
55            sample_rate: 48_000,
56            _pad: 0,
57        }
58    }
59
60    /// Parse and validate a header from raw bytes (magic + version); `None`
61    /// on a short buffer or a magic/version mismatch.
62    #[inline]
63    pub fn parse(bytes: &[u8]) -> Option<Self> {
64        let hlen = std::mem::size_of::<Self>();
65        if bytes.len() < hlen {
66            return None;
67        }
68        let h = bytemuck::pod_read_unaligned::<AcousticSabHeader>(&bytes[..hlen]);
69        (h.magic == ACOUSTIC_SAB_MAGIC && h.version == ACOUSTIC_SAB_VERSION).then_some(h)
70    }
71}
72
73/// Initialise a SAB region: writes the header and zeroes the remaining
74/// layout. Returns false when `out` is smaller than `ACOUSTIC_SAB_BYTES`.
75#[inline]
76pub fn init_acoustic_sab(out: &mut [u8]) -> bool {
77    if out.len() < ACOUSTIC_SAB_BYTES {
78        return false;
79    }
80    let header = AcousticSabHeader::new();
81    out[..ACOUSTIC_SAB_HEADER_BYTES].fill(0);
82    let hlen = std::mem::size_of::<AcousticSabHeader>();
83    out[..hlen].copy_from_slice(bytemuck::bytes_of(&header));
84    out[ACOUSTIC_SAB_UNIFORM_OFFSET..].fill(0);
85    true
86}
87
88/// Write pod uniform + optional f32 mirror for worklet `Float32Array` view.
89#[inline]
90pub fn write_uniform_to_sab(out: &mut [u8], uniform: &AcousticUniform) -> bool {
91    write_uniform_to_sab_with_mirror(out, uniform, None)
92}
93
94/// Write the uniform plus an optional `f32` mirror region for a worklet
95/// `Float32Array` view, then bump `uniform_seq`. Returns false when `out` is
96/// too small or the uniform would overlap the token region.
97#[inline]
98pub fn write_uniform_to_sab_with_mirror(
99    out: &mut [u8],
100    uniform: &AcousticUniform,
101    float_mirror: Option<&[f32]>,
102) -> bool {
103    if out.len() < ACOUSTIC_SAB_FLOAT_MIRROR_OFFSET + ACOUSTIC_SAB_FLOAT_MIRROR_BYTES {
104        return false;
105    }
106    let bytes = bytemuck::bytes_of(uniform);
107    let end = ACOUSTIC_SAB_UNIFORM_OFFSET + bytes.len();
108    if end > ACOUSTIC_SAB_TOKEN_OFFSET {
109        return false;
110    }
111    out[ACOUSTIC_SAB_UNIFORM_OFFSET..end].copy_from_slice(bytes);
112    if let Some(mirror) = float_mirror {
113        let n = mirror.len().min(ACOUSTIC_SAB_FLOAT_MIRROR_BYTES / 4);
114        out[ACOUSTIC_SAB_FLOAT_MIRROR_OFFSET..ACOUSTIC_SAB_FLOAT_MIRROR_OFFSET + n * 4]
115            .copy_from_slice(bytemuck::cast_slice(&mirror[..n]));
116    }
117    let header = AcousticSabHeader::parse(out).unwrap_or(AcousticSabHeader::new());
118    let mut h = header;
119    h.uniform_seq = h.uniform_seq.wrapping_add(1);
120    let hlen = std::mem::size_of::<AcousticSabHeader>();
121    out[..hlen].copy_from_slice(bytemuck::bytes_of(&h));
122    true
123}
124
125#[inline]
126fn write_sab_header(out: &mut [u8], h: &AcousticSabHeader) {
127    let hlen = std::mem::size_of::<AcousticSabHeader>();
128    out[..hlen].copy_from_slice(bytemuck::bytes_of(h));
129}
130
131/// Read the `AcousticUniform` payload out of the SAB region; `None` when the
132/// slice is too short to contain it.
133#[inline]
134pub fn read_uniform_from_sab(bytes: &[u8]) -> Option<AcousticUniform> {
135    if bytes.len() < ACOUSTIC_SAB_UNIFORM_OFFSET + std::mem::size_of::<AcousticUniform>() {
136        return None;
137    }
138    let u_size = std::mem::size_of::<AcousticUniform>();
139    Some(bytemuck::pod_read_unaligned::<AcousticUniform>(
140        &bytes[ACOUSTIC_SAB_UNIFORM_OFFSET..ACOUSTIC_SAB_UNIFORM_OFFSET + u_size],
141    ))
142}
143
144/// Push one token into SAB ring (16 slots × 8 B).
145#[inline]
146pub fn push_token_to_sab(out: &mut [u8], token: SonicToken) -> bool {
147    if out.len() < ACOUSTIC_SAB_BYTES {
148        return false;
149    }
150    let mut h = AcousticSabHeader::parse(out).unwrap_or(AcousticSabHeader::new());
151    let w = h.token_write;
152    let r = h.token_read;
153    if w.wrapping_sub(r) >= 16 {
154        return false;
155    }
156    let slot = (w % 16) as usize;
157    let off = ACOUSTIC_SAB_TOKEN_OFFSET + slot * 8;
158    out[off..off + 8].copy_from_slice(bytemuck::bytes_of(&token.raw));
159    h.token_write = w.wrapping_add(1);
160    write_sab_header(out, &h);
161    true
162}
163
164// ───────────────────────────────────────────────────────────────────────────
165//  Double-Buffered 64-Voice SeqLock Table & Perceptual Salience Culling
166// ───────────────────────────────────────────────────────────────────────────
167
168pub const VOICE_DESCRIPTOR_SLOT_SIZE: usize = 64;
169pub const MAX_ACOUSTIC_VOICE_SLOTS: usize = 64;
170
171/// 64-byte cache-line-aligned voice descriptor slot with monotonic SeqLock synchronization.
172#[repr(C, align(64))]
173#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
174pub struct VoiceDescriptorSlot {
175    /// Monotonic sequence counter: odd = write in progress, even = valid consistent state.
176    pub sequence_number: u32,
177    /// Entity emitting this voice.
178    pub entity_id: u32,
179    /// Voice amplitude (linear).
180    pub amplitude: f32,
181    /// Stereo pan / room-send blend for the voice.
182    pub pan_room_send: f32,
183    /// Emitter position in world space.
184    pub world_position: [f32; 3],
185    /// Jakob-Hanika dual polynomial coefficients (c0, c1, c2) for spectral
186    /// material response.
187    pub acoustic_coeffs: [f32; 3],
188    pub padding: [u32; 6],
189}
190
191impl VoiceDescriptorSlot {
192    /// Zeroed slot (`sequence_number = 0`, no voice assigned).
193    #[inline]
194    pub const fn empty() -> Self {
195        Self {
196            sequence_number: 0,
197            entity_id: 0,
198            amplitude: 0.0,
199            pan_room_send: 0.0,
200            world_position: [0.0; 3],
201            acoustic_coeffs: [0.0; 3],
202            padding: [0; 6],
203        }
204    }
205}
206
207/// Decoded voice snapshot returned when a SeqLock read succeeds without tear.
208#[derive(Debug, Clone, Copy, PartialEq)]
209pub struct VoiceSnapshot {
210    /// Entity emitting this voice.
211    pub entity_id: u32,
212    /// Voice amplitude (linear).
213    pub amplitude: f32,
214    /// Stereo pan / room-send blend.
215    pub pan_room_send: f32,
216    /// Emitter position in world space.
217    pub world_position: [f32; 3],
218    /// Jakob-Hanika dual polynomial coefficients (c0, c1, c2).
219    pub acoustic_coeffs: [f32; 3],
220}
221
222/// Calculate acoustic salience score $S_i = \frac{A_i \cdot \mathcal{D}}{1.0 + \|\vec{P}_i - \vec{P}_{\text{listener}}\|^2}$.
223///
224/// Emitters falling below $S_i < 10^{-4}$ are culled by the producer before writing to the SAB.
225#[inline]
226pub fn calculate_acoustic_salience(
227    amplitude: f32,
228    diffraction_scalar: f32,
229    emitter_pos: [f32; 3],
230    listener_pos: [f32; 3],
231) -> f32 {
232    let dx = emitter_pos[0] - listener_pos[0];
233    let dy = emitter_pos[1] - listener_pos[1];
234    let dz = emitter_pos[2] - listener_pos[2];
235    let dist_sq = dx * dx + dy * dy + dz * dz;
236
237    let diff = diffraction_scalar.clamp(0.1, 1.0);
238    (amplitude.max(0.0) * diff) / (1.0 + dist_sq)
239}
240
241/// Producer update: writes parameters into a voice slot using odd-even SeqLock signaling.
242#[inline]
243pub fn update_voice_slot(
244    slot: &mut VoiceDescriptorSlot,
245    entity_id: u32,
246    amplitude: f32,
247    pan_room_send: f32,
248    world_pos: [f32; 3],
249    coeffs: [f32; 3],
250) {
251    let seq = slot.sequence_number;
252    // Step 1: Mark odd (write in progress)
253    slot.sequence_number = seq.wrapping_add(1) | 1;
254
255    // Step 2: Store payload fields
256    slot.entity_id = entity_id;
257    slot.amplitude = amplitude;
258    slot.pan_room_send = pan_room_send;
259    slot.world_position = world_pos;
260    slot.acoustic_coeffs = coeffs;
261
262    // Step 3: Mark even (write complete)
263    slot.sequence_number = seq.wrapping_add(2) & !1;
264}
265
266/// Consumer read: reads parameters from a voice slot; returns `None` if producer was writing or torn read occurred.
267#[inline]
268pub fn read_voice_slot(slot: &VoiceDescriptorSlot) -> Option<VoiceSnapshot> {
269    let seq1 = slot.sequence_number;
270    // Odd sequence means producer is currently writing
271    if (seq1 & 1) != 0 {
272        return None;
273    }
274
275    let snapshot = VoiceSnapshot {
276        entity_id: slot.entity_id,
277        amplitude: slot.amplitude,
278        pan_room_send: slot.pan_room_send,
279        world_position: slot.world_position,
280        acoustic_coeffs: slot.acoustic_coeffs,
281    };
282
283    let seq2 = slot.sequence_number;
284    // If sequence changed during read, a torn read occurred
285    if seq1 != seq2 {
286        None
287    } else {
288        Some(snapshot)
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    #[test]
297    fn sab_header_pod_fits_slot() {
298        let hlen = std::mem::size_of::<AcousticSabHeader>();
299        assert!(hlen <= ACOUSTIC_SAB_HEADER_BYTES);
300        assert_eq!(hlen, 28);
301    }
302
303    #[test]
304    fn sab_roundtrip_uniform() {
305        let mut sab = [0u8; ACOUSTIC_SAB_BYTES];
306        assert!(init_acoustic_sab(&mut sab));
307        let u = AcousticUniform::default();
308        assert!(write_uniform_to_sab(&mut sab, &u));
309        let h = AcousticSabHeader::parse(&sab).unwrap();
310        assert_eq!(h.uniform_seq, 1);
311        let read = read_uniform_from_sab(&sab).unwrap();
312        assert_eq!(read.frequency_hz, u.frequency_hz);
313    }
314
315    #[test]
316    fn sab_token_push() {
317        let mut sab = [0u8; ACOUSTIC_SAB_BYTES];
318        init_acoustic_sab(&mut sab);
319        let t = SonicToken::note_on(1, 60, 100, 0);
320        assert!(push_token_to_sab(&mut sab, t));
321        let h = AcousticSabHeader::parse(&sab).unwrap();
322        assert_eq!(h.token_write, 1);
323    }
324
325    #[test]
326    fn voice_descriptor_slot_layout_and_seqlock() {
327        assert_eq!(std::mem::size_of::<VoiceDescriptorSlot>(), 64);
328        assert_eq!(std::mem::align_of::<VoiceDescriptorSlot>(), 64);
329
330        let mut slot = VoiceDescriptorSlot::empty();
331        assert_eq!(read_voice_slot(&slot).unwrap().amplitude, 0.0);
332
333        // Update slot
334        update_voice_slot(
335            &mut slot,
336            42,
337            0.85,
338            0.5,
339            [10.0, 2.0, -5.0],
340            [0.1, -0.4, 0.9],
341        );
342
343        // Successful read
344        let snap = read_voice_slot(&slot).expect("valid read");
345        assert_eq!(snap.entity_id, 42);
346        assert_eq!(snap.amplitude, 0.85);
347        assert_eq!(snap.world_position, [10.0, 2.0, -5.0]);
348        assert_eq!(snap.acoustic_coeffs, [0.1, -0.4, 0.9]);
349
350        // Simulating write in progress (odd sequence number)
351        slot.sequence_number = 3;
352        assert!(read_voice_slot(&slot).is_none());
353    }
354
355    #[test]
356    fn test_acoustic_salience_culling() {
357        let listener = [0.0, 0.0, 0.0];
358        let near_emitter = [1.0, 0.0, 0.0]; // dist = 1m
359        let far_emitter = [100.0, 0.0, 0.0]; // dist = 100m
360
361        let s_near = calculate_acoustic_salience(1.0, 1.0, near_emitter, listener);
362        let s_far = calculate_acoustic_salience(1.0, 1.0, far_emitter, listener);
363
364        assert!(s_near > 0.4);
365        assert!(s_far < 1e-4); // Below audibility threshold!
366    }
367}