Skip to main content

qualia_core_db/audio/
hrtf.rs

1//! HRTF — analytic + KemarLite embedded tables (zero-heap hot path).
2//!
3//! Full measured KEMAR datasets are optional cold assets; default hot path uses KemarLite
4//! (8-azimuth ITD/ILD samples) with analytic Woodworth/Rayleigh fallback delegated to
5//! `etalon_signal::audio`.
6
7use core::f32::consts::PI;
8use std::sync::atomic::{AtomicU8, Ordering};
9
10pub use etalon_signal::audio::{
11    pinna_elevation_notch_hz, spherical_ild_db, woodworth_itd_seconds, DEFAULT_HEAD_RADIUS_M,
12    DEFAULT_SPEED_OF_SOUND_M_S,
13};
14use etalon_signal::audio::{
15    convolve_fir_into, head_relative_position as etalon_head_relative_position,
16    synthesize_hrir_into,
17};
18
19/// HRTF synthesis profile (hot path).
20#[repr(u8)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum HrtfProfile {
23    Analytic = 0,
24    KemarLite = 1,
25}
26
27static HRTF_PROFILE: AtomicU8 = AtomicU8::new(HrtfProfile::KemarLite as u8);
28
29/// Select the process-global HRTF profile used by the hot path
30/// (`Analytic` or `KemarLite`; default `KemarLite`).
31#[inline]
32pub fn set_hrtf_profile(profile: HrtfProfile) {
33    HRTF_PROFILE.store(profile as u8, Ordering::Relaxed);
34}
35
36/// The currently selected process-global HRTF profile.
37#[inline]
38pub fn hrtf_profile() -> HrtfProfile {
39    match HRTF_PROFILE.load(Ordering::Relaxed) {
40        0 => HrtfProfile::Analytic,
41        _ => HrtfProfile::KemarLite,
42    }
43}
44
45/// KemarLite: 8 azimuth samples (pan -1..1) — ITD µs and ILD dB-ish scalars (embedded cold asset).
46const KEMAR_LITE_ITD_US: [f32; 8] = [-650.0, -480.0, -280.0, -80.0, 0.0, 80.0, 280.0, 480.0];
47const KEMAR_LITE_ILD_DB: [f32; 8] = [6.0, 4.5, 2.5, 0.8, 0.0, -0.8, -2.5, -4.5];
48
49/// Binaural staging gains + ITD for stereo worklet.
50#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct BinauralGains {
52    pub gain_l: f32,
53    pub gain_r: f32,
54    pub itd_seconds: f32,
55    pub azimuth_rad: f32,
56    pub elevation_rad: f32,
57    pub distance: f32,
58}
59
60impl Default for BinauralGains {
61    fn default() -> Self {
62        Self {
63            gain_l: 0.707,
64            gain_r: 0.707,
65            itd_seconds: 0.0,
66            azimuth_rad: 0.0,
67            elevation_rad: 0.0,
68            distance: 1.0,
69        }
70    }
71}
72
73/// Rotate source position into head frame (listener at origin, yaw around Y),
74/// delegated to [`etalon_signal::audio::head_relative_position`].
75#[inline]
76pub fn head_relative_position(source: [f32; 3], listener_yaw: f32) -> [f32; 3] {
77    etalon_head_relative_position(source, listener_yaw)
78}
79
80#[inline]
81fn lerp_table(pan: f32, table: &[f32; 8]) -> f32 {
82    let t = ((pan + 1.0) * 0.5 * 7.0).clamp(0.0, 7.0);
83    let i = t.floor() as usize;
84    let f = t - i as f32;
85    let a = table[i.min(7)];
86    let b = table[(i + 1).min(7)];
87    a + (b - a) * f
88}
89
90/// KemarLite binaural — interpolated embedded ITD/ILD tables.
91#[inline]
92pub fn binaural_kemar_lite(source: [f32; 3], listener_yaw: f32) -> BinauralGains {
93    let mut g = binaural_analytic(source, listener_yaw);
94    let pan = (g.azimuth_rad / (PI * 0.5)).clamp(-1.0, 1.0);
95    let itd_us = lerp_table(pan, &KEMAR_LITE_ITD_US);
96    let ild_db = lerp_table(pan, &KEMAR_LITE_ILD_DB);
97    let ild = (ild_db / 20.0).clamp(-0.45, 0.45);
98    g.itd_seconds = itd_us * 1e-6;
99    g.gain_l = (g.gain_l * (1.0 - ild)).clamp(0.05, 1.0);
100    g.gain_r = (g.gain_r * (1.0 + ild)).clamp(0.05, 1.0);
101    g
102}
103
104/// Analytic binaural gains — azimuth ∈ [-π, π], elevation ∈ [-π/2, π/2].
105#[inline]
106pub fn binaural_analytic(source: [f32; 3], listener_yaw: f32) -> BinauralGains {
107    let rel = head_relative_position(source, listener_yaw);
108    let x = rel[0];
109    let y = rel[1];
110    let z = (-rel[2]).max(0.05);
111    let horiz = (x * x + z * z).sqrt();
112    let dist = (x * x + y * y + rel[2] * rel[2]).sqrt().max(0.15);
113    let azimuth = x.atan2(z);
114    let elevation = y.atan2(horiz.max(1e-4));
115
116    let pan = (azimuth / (PI * 0.5)).clamp(-1.0, 1.0);
117    let ild = pan * 0.42;
118    let gain_l = (0.707 * (1.0 - ild)).clamp(0.05, 1.0);
119    let gain_r = (0.707 * (1.0 + ild)).clamp(0.05, 1.0);
120    // Spherical-head Woodworth ITD via etalon_signal::audio (head radius 0.078 m => ~584 us max).
121    let itd_seconds =
122        woodworth_itd_seconds(azimuth, 0.078, DEFAULT_SPEED_OF_SOUND_M_S).unwrap_or(pan * 0.0006);
123    let atten = (1.0 / dist).min(1.0);
124
125    BinauralGains {
126        gain_l: gain_l * atten,
127        gain_r: gain_r * atten,
128        itd_seconds,
129        azimuth_rad: azimuth,
130        elevation_rad: elevation,
131        distance: dist,
132    }
133}
134
135/// Dispatch binaural model from active `HrtfProfile`.
136#[inline]
137pub fn binaural_from_position(source: [f32; 3], listener_yaw: f32) -> BinauralGains {
138    match hrtf_profile() {
139        HrtfProfile::Analytic => binaural_analytic(source, listener_yaw),
140        HrtfProfile::KemarLite => binaural_kemar_lite(source, listener_yaw),
141    }
142}
143
144/// Manifold `w` biases room absorption (higher w → softer highs).
145#[inline]
146pub fn room_damp_from_manifold(manifold_w: f32) -> f32 {
147    (1.0 - manifold_w * 0.08).clamp(0.55, 1.0)
148}
149
150// ---------------------------------------------------------------------------
151// Real HRTF convolution (cold path; heap OK).
152//
153// Full measured KEMAR HRIRs remain an optional cold asset. The functions below
154// SYNTHESIZE a physically-plausible HRIR directly from the ITD/ILD model in
155// `BinauralGains` (interaural time difference as a fractional sample delay,
156// interaural level difference as per-ear gain, and a one-pole head-shadow
157// low-pass on the farther/contralateral ear), delegated to `etalon_signal::audio`.
158// ---------------------------------------------------------------------------
159
160/// Direct linear (FIR) convolution: `y[i] = Σ_j signal[j]·h[i-j]`.
161///
162/// Output length is `signal.len() + h.len() - 1`. Either operand empty → empty.
163pub fn convolve_fir(signal: &[f32], h: &[f32]) -> Vec<f32> {
164    if signal.is_empty() || h.is_empty() {
165        return Vec::new();
166    }
167    let out_len = signal.len() + h.len() - 1;
168    let mut out = vec![0.0_f32; out_len];
169    if convolve_fir_into(signal, h, &mut out).is_err() {
170        out.fill(0.0);
171        for (j, &s) in signal.iter().enumerate() {
172            if s == 0.0 {
173                continue;
174            }
175            for (m, &hm) in h.iter().enumerate() {
176                out[j + m] += s * hm;
177            }
178        }
179    }
180    out
181}
182
183/// Synthesize left/right HRIRs from `gains`, delegated to
184/// [`etalon_signal::audio::synthesize_hrir_into`].
185///
186/// Each ear is a unit impulse scaled by `gain_l`/`gain_r`, delayed by its ear
187/// delay: the nearer ear sits at ~0, the farther ear is delayed by
188/// `|itd_seconds|·sample_rate` samples (placed with linear-interpolated
189/// fractional delay). A gentle one-pole low-pass (head shadow) is applied ONLY
190/// to the contralateral (farther, quieter) ear so its highs are attenuated.
191///
192/// `itd_seconds < 0` ⇒ source to the left ⇒ right ear is the farther/contralateral
193/// one; `itd_seconds > 0` ⇒ left ear is farther. Returns `(left_ir, right_ir)`,
194/// both length `taps` (min 1).
195pub fn synthesize_hrir(
196    gains: &BinauralGains,
197    sample_rate: f32,
198    taps: usize,
199) -> (Vec<f32>, Vec<f32>) {
200    let n = taps.max(1);
201    let mut left = vec![0.0_f32; n];
202    let mut right = vec![0.0_f32; n];
203    // Head-shadow low-pass coefficient for the contralateral ear (gentle).
204    const SHADOW_A: f32 = 0.35;
205
206    let _ = synthesize_hrir_into(
207        gains.gain_l,
208        gains.gain_r,
209        gains.itd_seconds,
210        sample_rate.max(1.0),
211        SHADOW_A,
212        &mut left,
213        &mut right,
214    );
215
216    (left, right)
217}
218
219/// Render a `mono` source at `source` (world space) into a binaural pair.
220///
221/// Pipeline: `binaural_from_position` (active `HrtfProfile`) →
222/// `synthesize_hrir` → `convolve_fir` the mono signal with each ear's HRIR.
223/// Returns `(left, right)`, each of length `mono.len() + taps - 1` (taps = 64).
224pub fn binaural_render(
225    mono: &[f32],
226    source: [f32; 3],
227    listener_yaw: f32,
228    sample_rate: f32,
229) -> (Vec<f32>, Vec<f32>) {
230    const TAPS: usize = 64;
231    let gains = binaural_from_position(source, listener_yaw);
232    let (hl, hr) = synthesize_hrir(&gains, sample_rate, TAPS);
233    let left = convolve_fir(mono, &hl);
234    let right = convolve_fir(mono, &hr);
235    (left, right)
236}
237
238/// First index where the running energy of `x` crosses `frac` of its total
239/// energy (onset proxy for ITD comparison). Returns `x.len()` if all-zero.
240#[cfg(test)]
241fn energy_onset(x: &[f32], frac: f32) -> usize {
242    let total: f32 = x.iter().map(|&v| v * v).sum();
243    if total <= 0.0 {
244        return x.len();
245    }
246    let threshold = total * frac;
247    let mut acc = 0.0_f32;
248    for (i, &v) in x.iter().enumerate() {
249        acc += v * v;
250        if acc >= threshold {
251            return i;
252        }
253    }
254    x.len()
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn center_source_balanced() {
263        let g = binaural_from_position([0.0, 0.0, 1.0], 0.0);
264        assert!((g.gain_l - g.gain_r).abs() < 0.15);
265        assert!(g.itd_seconds.abs() < 1e-4);
266    }
267
268    #[test]
269    fn left_source_favors_left_ear() {
270        let g = binaural_from_position([-1.0, 0.0, -1.0], 0.0);
271        assert!(g.gain_l > g.gain_r);
272        assert!(g.itd_seconds < 0.0);
273    }
274
275    #[test]
276    fn right_source_favors_right_ear() {
277        let g = binaural_from_position([1.0, 0.0, -1.0], 0.0);
278        assert!(g.gain_r > g.gain_l);
279        assert!(g.itd_seconds > 0.0);
280    }
281
282    #[test]
283    fn kemar_lite_stronger_itd_than_analytic_at_side() {
284        set_hrtf_profile(HrtfProfile::KemarLite);
285        let k = binaural_from_position([-1.0, 0.0, 0.5], 0.0);
286        set_hrtf_profile(HrtfProfile::Analytic);
287        let a = binaural_from_position([-1.0, 0.0, 0.5], 0.0);
288        assert!(k.itd_seconds.abs() >= a.itd_seconds.abs());
289        set_hrtf_profile(HrtfProfile::KemarLite);
290    }
291
292    #[test]
293    fn yaw_rotates_pan() {
294        let g0 = binaural_from_position([1.0, 0.0, 1.0], 0.0);
295        let g1 = binaural_from_position([1.0, 0.0, 1.0], PI * 0.5);
296        assert!(g0.gain_r > g0.gain_l, "right-front source favors right ear");
297        assert!(g1.gain_l > g1.gain_r, "90° yaw inverts pan to left ear");
298        assert!(
299            (g0.gain_r - g1.gain_l).abs() < 0.12,
300            "yaw swap: g0.gain_r≈g1.gain_l"
301        );
302        assert!(
303            (g0.gain_l - g1.gain_r).abs() < 0.12,
304            "yaw swap: g0.gain_l≈g1.gain_r"
305        );
306    }
307
308    #[test]
309    fn convolve_identity_kernel_returns_input() {
310        let x = [0.1_f32, -0.4, 0.7, 0.2, -0.9];
311        let y = convolve_fir(&x, &[1.0]);
312        assert_eq!(y.len(), x.len());
313        for (a, b) in y.iter().zip(x.iter()) {
314            assert!((a - b).abs() < 1e-6, "identity convolution");
315        }
316    }
317
318    #[test]
319    fn convolve_output_length() {
320        let x = vec![0.5_f32; 17];
321        let h = vec![0.25_f32; 9];
322        let y = convolve_fir(&x, &h);
323        assert_eq!(y.len(), x.len() + h.len() - 1);
324    }
325
326    #[test]
327    fn convolve_known_result() {
328        // [1,2,3] * [1,1] = [1, 3, 5, 3]
329        let y = convolve_fir(&[1.0, 2.0, 3.0], &[1.0, 1.0]);
330        assert_eq!(y.len(), 4);
331        let expect = [1.0, 3.0, 5.0, 3.0];
332        for (a, b) in y.iter().zip(expect.iter()) {
333            assert!((a - b).abs() < 1e-6, "got {y:?}");
334        }
335    }
336
337    #[test]
338    fn hard_left_source_earlier_and_louder_on_left() {
339        set_hrtf_profile(HrtfProfile::KemarLite);
340        let sample_rate = 48_000.0_f32;
341        // A unit click followed by silence.
342        let mut click = vec![0.0_f32; 128];
343        click[0] = 1.0;
344        // Hard-left source (−X, in front).
345        let (left, right) = binaural_render(&click, [-1.0, 0.0, -1.0], 0.0, sample_rate);
346
347        // ITD: the left (nearer) ear's energy onset is EARLIER than the right.
348        let onset_l = energy_onset(&left, 0.5);
349        let onset_r = energy_onset(&right, 0.5);
350        assert!(
351            onset_l < onset_r,
352            "left onset {onset_l} should precede right onset {onset_r} (ITD)"
353        );
354
355        // ILD: left energy >= right energy (nearer/louder ear).
356        let energy_l: f32 = left.iter().map(|&v| v * v).sum();
357        let energy_r: f32 = right.iter().map(|&v| v * v).sum();
358        assert!(
359            energy_l >= energy_r,
360            "left energy {energy_l} should be >= right energy {energy_r} (ILD)"
361        );
362    }
363
364    #[test]
365    fn synthesize_hrir_delays_contralateral_ear() {
366        let sample_rate = 48_000.0_f32;
367        // itd < 0 ⇒ source left ⇒ right ear delayed.
368        let g = BinauralGains {
369            gain_l: 0.8,
370            gain_r: 0.6,
371            itd_seconds: -0.0006,
372            ..Default::default()
373        };
374        let (left, right) = synthesize_hrir(&g, sample_rate, 64);
375        assert_eq!(left.len(), 64);
376        assert_eq!(right.len(), 64);
377        // Left ear (near) has its first tap energetic; right ear's peak is later.
378        let left_peak = left
379            .iter()
380            .enumerate()
381            .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap())
382            .unwrap()
383            .0;
384        let right_peak = right
385            .iter()
386            .enumerate()
387            .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap())
388            .unwrap()
389            .0;
390        assert_eq!(left_peak, 0, "near (left) ear impulse at tap 0");
391        assert!(
392            right_peak > 0,
393            "contralateral (right) ear delayed, peak at {right_peak}"
394        );
395    }
396
397    #[test]
398    fn binaural_render_output_length() {
399        let mono = vec![0.3_f32; 100];
400        let (l, r) = binaural_render(&mono, [1.0, 0.0, -1.0], 0.0, 48_000.0);
401        assert_eq!(l.len(), 100 + 64 - 1);
402        assert_eq!(r.len(), 100 + 64 - 1);
403    }
404}