Skip to main content

qualia_core_db/audio/
holosonic.rs

1//! Holosonic Engine — Volumetric Acoustic Wavefield Synthesis & Semantic Sonification.
2//!
3//! Companion to the Holographic 3D Visual Engine (`docs/Holographic 3D Engine for Semantic Graphs.md`):
4//! - Replaces rigid pre-recorded audio triggers with continuous spatial wavefield synthesis.
5//! - Evaluates acoustic wave interference: constructive interference generates crisp resonant
6//!   harmonics where logical assertions align; destructive interference creates acoustic voids.
7//! - Emits sound from volumetric SDF fields (water bodies, wind through canopies, vector corridor).
8//! - Evaluates in the Tier-1 zero-heap hot path with caller-supplied buffers.
9
10use crate::audio::hrtf::binaural_from_position;
11use crate::sonic_token::{SonicEventType, SonicToken, SONIC_MAGIC};
12use bytemuck::{Pod, Zeroable};
13use std::f32::consts::TAU;
14
15/// 48-byte Pod telemetry token emitted by the Holosonic wavefield engine (`Q42` U3 telemetry).
16#[repr(C)]
17#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
18pub struct HolosonicSonicToken48 {
19    /// 64-bit origin NQuin hash or semantic entity identifier (offset 0..8).
20    pub origin_quin_hash: u64,
21    /// `HolosonicModality` archetype (0..=4) (offset 8).
22    pub archetype: u8,
23    /// Deontic permit state (`0 = Permitted`, `1 = Obligatory`, `2 = Forbidden/Escrow`) (offset 9).
24    pub deontic_permit: u8,
25    /// Magic and status flags (`SONIC_MAGIC`) (offset 10..12).
26    pub flags: u16,
27    /// Associated 10D tensor node index in `NodePool` (offset 12..16).
28    pub tensor_index: u32,
29    /// Base fundamental frequency in Hz (offset 16..20).
30    pub fundamental_hz: f32,
31    /// Instantaneous wavefield phase at the listener in radians (offset 20..24).
32    pub phase_rad: f32,
33    /// Epistemic certainty `q` in `[0.0, 1.0]` (offset 24..28).
34    pub epistemic_q: f32,
35    /// Constructive/destructive wave interference gain ratio (offset 28..32).
36    pub interference_gain: f32,
37    /// Direct-path acoustic occlusion transmission gain `[0.0, 1.0]` (offset 32..36).
38    pub occlusion_gain: f32,
39    /// World-space emitter position `[x, y, z]` (offset 36..48).
40    pub position: [f32; 3],
41}
42
43const _: [(); 48] = [(); core::mem::size_of::<HolosonicSonicToken48>()];
44
45impl Default for HolosonicSonicToken48 {
46    fn default() -> Self {
47        Self::zeroed()
48    }
49}
50
51
52/// Maximum number of active acoustic hologram emitters evaluated simultaneously (zero-heap stack array).
53pub const MAX_HOLOSONIC_EMITTERS: usize = 32;
54
55/// Speed of sound in ambient air at 20°C (m/s).
56pub const SPEED_OF_SOUND_MPS: f32 = 343.0;
57
58/// Semantic modality archetype for holosonic emission.
59#[repr(u8)]
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum HolosonicModality {
62    /// Vector transit corridor (propulsion whine, pavement friction, electromagnetic hum).
63    VectorCorridor = 0,
64    /// Hydrodynamic fluid resonance (streams, lake shorelines, waterfalls).
65    WaterResonance = 1,
66    /// Volumetric flora canopy (wind through leaves, pine needle sibilance).
67    FloraWind = 2,
68    /// Wildlife bioacoustic vocalization (fauna call signatures, movement rustle).
69    Bioacoustic = 3,
70    /// High-epistemic landmark beacon (resonant singing bowl, crystalline focal harmonic).
71    LandmarkBeacon = 4,
72}
73
74/// An acoustic emitter contributing to the spatial holosonic field.
75#[repr(C)]
76#[derive(Debug, Clone, Copy, PartialEq)]
77pub struct HolosonicEmitter {
78    /// World position [x, y, z] in meters.
79    pub position: [f32; 3],
80    /// Base fundamental frequency in Hz.
81    pub base_freq_hz: f32,
82    /// Acoustic pressure amplitude in `[0.0, 1.0]`.
83    pub amplitude: f32,
84    /// Initial phase offset in radians.
85    pub phase_rad: f32,
86    /// Epistemic certainty `q` in `[0.0, 1.0]` (controls harmonic purity and constructive focus).
87    pub epistemic_q: f32,
88    /// Maximum spatial coherence radius in meters.
89    pub coherence_radius: f32,
90    /// Modality archetype.
91    pub modality: HolosonicModality,
92}
93
94impl Default for HolosonicEmitter {
95    fn default() -> Self {
96        Self {
97            position: [0.0; 3],
98            base_freq_hz: 440.0,
99            amplitude: 0.0,
100            phase_rad: 0.0,
101            epistemic_q: 1.0,
102            coherence_radius: 25.0,
103            modality: HolosonicModality::VectorCorridor,
104        }
105    }
106}
107
108impl HolosonicEmitter {
109    /// Constructs a holosonic emitter in the hot path.
110    #[inline]
111    pub const fn new(
112        position: [f32; 3],
113        base_freq_hz: f32,
114        amplitude: f32,
115        phase_rad: f32,
116        epistemic_q: f32,
117        coherence_radius: f32,
118        modality: HolosonicModality,
119    ) -> Self {
120        Self {
121            position,
122            base_freq_hz,
123            amplitude,
124            phase_rad,
125            epistemic_q,
126            coherence_radius,
127            modality,
128        }
129    }
130}
131
132/// Instantaneous binaural field sample at a listener standpoint.
133#[derive(Debug, Clone, Copy, PartialEq)]
134pub struct HolosonicPointSample {
135    /// Instantaneous acoustic pressure for left ear.
136    pub pressure_l: f32,
137    /// Instantaneous acoustic pressure for right ear.
138    pub pressure_r: f32,
139    /// Net wave interference magnitude (constructive gain ratio).
140    pub interference_gain: f32,
141    /// Number of active acoustic emitters within audible horizon.
142    pub active_emitter_count: usize,
143}
144
145/// Fixed-capacity holosonic wavefield manager (Tier-1 zero-heap).
146pub struct HolosonicWavefield {
147    emitters: [HolosonicEmitter; MAX_HOLOSONIC_EMITTERS],
148    count: usize,
149}
150
151impl Default for HolosonicWavefield {
152    fn default() -> Self {
153        Self::new()
154    }
155}
156
157impl HolosonicWavefield {
158    /// Creates an empty holosonic wavefield.
159    #[inline]
160    pub const fn new() -> Self {
161        Self {
162            emitters: [HolosonicEmitter {
163                position: [0.0; 3],
164                base_freq_hz: 440.0,
165                amplitude: 0.0,
166                phase_rad: 0.0,
167                epistemic_q: 1.0,
168                coherence_radius: 25.0,
169                modality: HolosonicModality::VectorCorridor,
170            }; MAX_HOLOSONIC_EMITTERS],
171            count: 0,
172        }
173    }
174
175    /// Clears all emitters.
176    #[inline]
177    pub fn clear(&mut self) {
178        self.count = 0;
179    }
180
181    /// Current number of registered emitters.
182    #[inline]
183    pub const fn len(&self) -> usize {
184        self.count
185    }
186
187    /// True if no emitters are active.
188    #[inline]
189    pub const fn is_empty(&self) -> bool {
190        self.count == 0
191    }
192
193    /// Adds an emitter to the spatial wavefield. Returns false if capacity exceeded.
194    #[inline]
195    pub fn push(&mut self, emitter: HolosonicEmitter) -> bool {
196        if self.count >= MAX_HOLOSONIC_EMITTERS {
197            return false;
198        }
199        self.emitters[self.count] = emitter;
200        self.count += 1;
201        true
202    }
203
204    /// Returns a slice of the currently active emitters.
205    #[inline]
206    pub fn as_slice(&self) -> &[HolosonicEmitter] {
207        &self.emitters[..self.count]
208    }
209
210    /// Emits a 48-byte `HolosonicSonicToken48` telemetry record for an active emitter and sample,
211    /// and also packs a 64-bit `SonicToken` for the `Q42` U3 `SonicTokenRing`.
212    #[inline]
213    pub fn emit_sonic_token(
214        &self,
215        emitter_idx: usize,
216        origin_quin_hash: u64,
217        tensor_index: u32,
218        deontic_permit: u8,
219        occlusion_gain: f32,
220        sample: HolosonicPointSample,
221        listener_pos: [f32; 3],
222        time_s: f32,
223    ) -> (HolosonicSonicToken48, SonicToken) {
224        let e = if emitter_idx < self.count {
225            self.emitters[emitter_idx]
226        } else {
227            HolosonicEmitter::default()
228        };
229        let dx = e.position[0] - listener_pos[0];
230        let dy = e.position[1] - listener_pos[1];
231        let dz = e.position[2] - listener_pos[2];
232        let dist = (dx * dx + dy * dy + dz * dz).sqrt();
233        let omega = TAU * e.base_freq_hz;
234        let phase_rad = e.phase_rad + omega * time_s - (omega / SPEED_OF_SOUND_MPS) * dist;
235        let tok48 = HolosonicSonicToken48 {
236            origin_quin_hash,
237            archetype: e.modality as u8,
238            deontic_permit,
239            flags: SONIC_MAGIC as u16,
240            tensor_index,
241            fundamental_hz: e.base_freq_hz,
242            phase_rad,
243            epistemic_q: e.epistemic_q,
244            interference_gain: sample.interference_gain,
245            occlusion_gain: (e.amplitude * occlusion_gain).clamp(0.0, 1.0),
246            position: e.position,
247        };
248        let midi_note = (69.0 + 12.0 * (e.base_freq_hz.max(20.0) / 440.0).log2())
249            .round()
250            .clamp(0.0, 127.0) as u8;
251        let velocity = ((e.amplitude * occlusion_gain * sample.interference_gain * 96.0)
252            .clamp(1.0, 127.0)) as u8;
253        let packed = SonicToken::pack(
254            0,
255            SonicEventType::Parametric,
256            e.modality as u8 & 0x0f,
257            midi_note,
258            velocity,
259            tensor_index,
260            (SONIC_MAGIC as u16) | ((deontic_permit as u16) << 8),
261        );
262        (tok48, packed)
263    }
264
265    /// Evaluates the instantaneous spatial acoustic wavefield at the listener standpoint.
266    ///
267    /// Computes spherical wave propagation, phase delays ($\Delta \phi = k \cdot d$),
268    /// wave superposition, and HRTF binaural panning.
269    pub fn evaluate_point(
270        &self,
271        listener_pos: [f32; 3],
272        listener_yaw: f32,
273        time_s: f32,
274    ) -> HolosonicPointSample {
275        let mut sum_l = 0.0_f32;
276        let mut sum_r = 0.0_f32;
277        let mut raw_energy = 0.0_f32;
278        let mut active = 0usize;
279
280        for i in 0..self.count {
281            let e = &self.emitters[i];
282            if e.amplitude <= 0.0 {
283                continue;
284            }
285
286            let dx = e.position[0] - listener_pos[0];
287            let dy = e.position[1] - listener_pos[1];
288            let dz = e.position[2] - listener_pos[2];
289            let dist = (dx * dx + dy * dy + dz * dz).sqrt();
290
291            if dist > e.coherence_radius || dist < 0.001 {
292                continue;
293            }
294            active += 1;
295
296            // Distance attenuation (spherical spreading with smooth rolloff)
297            let falloff = (1.0 - (dist / e.coherence_radius)).clamp(0.0, 1.0);
298            let atten = (1.0 / (1.0 + dist * 0.45)) * falloff * e.amplitude;
299
300            // Wave phase delay: propagation time tau = dist / c, phase_shift = omega * tau
301            let omega = TAU * e.base_freq_hz;
302            let wave_number = omega / SPEED_OF_SOUND_MPS;
303            let phase = e.phase_rad + omega * time_s - wave_number * dist;
304
305            // Harmonic content modulated by epistemic certainty q
306            // High q -> pure fundamental tone; low q -> complex multi-frequency dissonant phase
307            let q = e.epistemic_q.clamp(0.0, 1.0);
308
309            // HRTF binaural spatialization (ITD + ILD); pass unit direction so distance
310            // attenuation is governed once by the Holosonic spherical spreading formula above.
311            let unit_dir = [dx / dist, dy / dist, dz / dist];
312            let gains = binaural_from_position(unit_dir, listener_yaw);
313
314            // Left/right ear pressure with interaural phase delay and epistemic harmonics
315            let ear_delay_phase = wave_number * gains.itd_seconds * SPEED_OF_SOUND_MPS;
316            let phase_l = phase + ear_delay_phase * 0.5;
317            let phase_r = phase - ear_delay_phase * 0.5;
318            let harmonic_l = (phase_l * 2.0 + 0.5).sin() * (1.0 - q) * 0.35;
319            let harmonic_r = (phase_r * 2.0 + 0.5).sin() * (1.0 - q) * 0.35;
320            let sample_l = (phase_l.sin() + harmonic_l) * atten * gains.gain_l;
321            let sample_r = (phase_r.sin() + harmonic_r) * atten * gains.gain_r;
322
323            sum_l += sample_l;
324            sum_r += sample_r;
325            raw_energy += atten;
326        }
327
328        let net_amplitude = (sum_l * sum_l + sum_r * sum_r).sqrt();
329        let interference_gain = if raw_energy > 0.001 {
330            net_amplitude / raw_energy
331        } else {
332            1.0
333        };
334
335        HolosonicPointSample {
336            pressure_l: sum_l.clamp(-2.0, 2.0),
337            pressure_r: sum_r.clamp(-2.0, 2.0),
338            interference_gain,
339            active_emitter_count: active,
340        }
341    }
342
343    /// Renders a discrete buffer block of stereo audio samples (zero heap).
344    ///
345    /// Fills caller-supplied `out_l` and `out_r` slices.
346    pub fn render_block(
347        &self,
348        listener_pos: [f32; 3],
349        listener_yaw: f32,
350        start_time_s: f32,
351        sample_rate: f32,
352        out_l: &mut [f32],
353        out_r: &mut [f32],
354    ) {
355        let n = out_l.len().min(out_r.len());
356        let dt = 1.0 / sample_rate.max(1.0);
357
358        for i in 0..n {
359            let t = start_time_s + i as f32 * dt;
360            let sample = self.evaluate_point(listener_pos, listener_yaw, t);
361            out_l[i] = sample.pressure_l;
362            out_r[i] = sample.pressure_r;
363        }
364    }
365
366    /// Translates constructive interference peaks into 64-bit `SonicToken` events.
367    ///
368    /// Fills `out_tokens` without heap allocation; returns number of tokens emitted.
369    pub fn emit_tokens_from_sample(
370        &self,
371        sample: HolosonicPointSample,
372        out_tokens: &mut [SonicToken],
373    ) -> usize {
374        if out_tokens.is_empty() {
375            return 0;
376        }
377
378        // If constructive interference peaks above threshold, trigger symbolic sonic resonance token
379        if sample.interference_gain > 1.25 && sample.active_emitter_count > 0 {
380            let midi_note = 60u8; // Middle C base
381            let velocity = (sample.interference_gain * 40.0).clamp(20.0, 127.0) as u8;
382            out_tokens[0] =
383                SonicToken::pack(0, SonicEventType::NoteOn, 0, midi_note, velocity, 0, 0);
384            1
385        } else {
386            0
387        }
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    #[test]
396    fn empty_wavefield_produces_silence() {
397        let wf = HolosonicWavefield::new();
398        let sample = wf.evaluate_point([0.0, 0.0, 0.0], 0.0, 0.0);
399        assert_eq!(sample.pressure_l, 0.0);
400        assert_eq!(sample.pressure_r, 0.0);
401        assert_eq!(sample.active_emitter_count, 0);
402    }
403
404    #[test]
405    fn distance_attenuation_is_monotonic() {
406        let mut wf = HolosonicWavefield::new();
407        wf.push(HolosonicEmitter::new(
408            [0.0, 0.0, 10.0],
409            220.0,
410            1.0,
411            0.0,
412            1.0,
413            50.0,
414            HolosonicModality::LandmarkBeacon,
415        ));
416
417        let near = wf.evaluate_point([0.0, 0.0, 8.0], 0.0, 0.0);
418        let far = wf.evaluate_point([0.0, 0.0, 0.0], 0.0, 0.0);
419
420        let near_mag = (near.pressure_l.powi(2) + near.pressure_r.powi(2)).sqrt();
421        let far_mag = (far.pressure_l.powi(2) + far.pressure_r.powi(2)).sqrt();
422        assert!(
423            near_mag > far_mag,
424            "Near ({near_mag}) should exceed Far ({far_mag})"
425        );
426    }
427
428    #[test]
429    fn constructive_interference_amplifies_signal() {
430        let mut wf = HolosonicWavefield::new();
431        // Two coherent in-phase emitters equidistant from the listener
432        wf.push(HolosonicEmitter::new(
433            [2.0, 0.0, 5.0],
434            440.0,
435            0.5,
436            0.0,
437            1.0,
438            20.0,
439            HolosonicModality::LandmarkBeacon,
440        ));
441        wf.push(HolosonicEmitter::new(
442            [-2.0, 0.0, 5.0],
443            440.0,
444            0.5,
445            0.0,
446            1.0,
447            20.0,
448            HolosonicModality::LandmarkBeacon,
449        ));
450
451        // Evaluate sample block
452        let mut buf_l = [0.0_f32; 64];
453        let mut buf_r = [0.0_f32; 64];
454        wf.render_block([0.0, 0.0, 0.0], 0.0, 0.0, 48_000.0, &mut buf_l, &mut buf_r);
455
456        let max_val = buf_l
457            .iter()
458            .chain(buf_r.iter())
459            .fold(0.0_f32, |m, &x| m.max(x.abs()));
460        assert!(
461            max_val > 0.05,
462            "Constructive interference should yield audible peak"
463        );
464    }
465}