Skip to main content

qualia_audio/
qac_spatial.rs

1//! QAC Spatial Audio, Higher-Order Ambisonics (HOA) Bus, Wigner-D Rotation,
2//! Binaural HRIR/RIR Rendering, ITU-R BS.1770-5 Loudness & Modal Resonance Adapters
3//! (`qac_spatial.rs`).
4//!
5//! Bridges `etalon_signal::{hoa, bs1770, modal}` into `qualia-audio` with caller-buffered,
6//! zero-heap scene buses and loudness/modal sessions.
7
8pub use etalon_signal::bs1770::{
9    calibrated_rms_db_spl, gate_block_energies_bs1770, measure_bs1770_integrated_loudness,
10    measure_true_peak_4x_f32, new_k_weighting_cascade, Bs1770ChannelRole, Bs1770LoudnessReading,
11    CalibratedSplReading, QualityStatus, TruePeakReading, AIR_REF_PRESSURE_PA,
12    BS1770_ABSOLUTE_GATE_LUFS, BS1770_RELATIVE_GATE_OFFSET_LU, MAX_BS1770_CHANNELS,
13    UNDERWATER_REF_PRESSURE_PA,
14};
15pub use etalon_signal::hoa::{
16    acn_degree_order, acn_index, admit_and_derive_unit_quaternion_f64,
17    convert_hoa_normalization_in_place_f64, convert_hoa_stream_normalization_in_place_f32,
18    decode_hoa_frame_to_direction_f64, decode_hoa_stream_to_speakers_into,
19    encode_mono_to_hoa_accum_into, evaluate_hoa_basis_f32, evaluate_hoa_basis_f64,
20    hamilton_product_xyzw, hoa_decode_matrix_apply_into, max_re_degree_weight_f64,
21    n3d_over_sn3d_factor_f64, quaternion_conjugate_xyzw, quaternion_ordered_norm_sq_f64,
22    rotate_symmetric_tensor_active_f64, rotate_vector_active_f64,
23    rotation_matrix_from_quaternion_f64, sn3d_over_n3d_factor_f64,
24    spherical_to_unit_cartesian_f64, HoaDecodeShape, HoaNormalization, HoaOrder,
25    HoaWignerRotation, MAX_HOA_CHANNELS, MAX_HOA_ORDER, QUATERNION_NORM_SQ_TOLERANCE,
26};
27pub use etalon_signal::modal::{
28    apply_linear_fir_filter_into, convolve_hrir_with_additional_delay_into,
29    convolve_stereo_hrir_with_additional_delays_into, estimate_pitch_yin_with_status,
30    evaluate_modal_bank_at_time_f64, extract_mel_mfcc_frame_into, fir_dc_and_nyquist_gain_f64,
31    impulse_first_moment_tap_f64, modal_t60_seconds, normal_incidence_fluid_interface_f64,
32    place_cubic_lagrange_fractional_impulse, ray_arrival_delay_taps_f64,
33    render_hoa_stream_binaural_into, FluidImpedanceInterface, IdealAcousticBoundary,
34    ModalOscillatorState, ModalResonanceRecord, PitchReading, LN_1000,
35    MODAL_RESONANCE_RECORD_BYTES, OCTAHEDRAL_VIRTUAL_SPEAKERS_XYZ,
36};
37pub use etalon_signal::SignalError;
38
39/// Zero-heap Higher-Order Ambisonics (HOA) scene bus for `qualia-audio` sessions.
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct QacHoaSceneBus {
42    pub order: HoaOrder,
43    pub normalization: HoaNormalization,
44    pub listener_rotation: HoaWignerRotation,
45    pub reference_freq_hz: f32,
46}
47
48impl QacHoaSceneBus {
49    /// Construct a new HOA scene bus with identity listener orientation.
50    pub fn new(
51        order: HoaOrder,
52        normalization: HoaNormalization,
53        reference_freq_hz: f32,
54    ) -> Result<Self, SignalError> {
55        if !reference_freq_hz.is_finite() || reference_freq_hz <= 0.0 {
56            return Err(SignalError::InvalidParameter);
57        }
58        let listener_rotation =
59            HoaWignerRotation::from_quaternion_xyzw([0.0, 0.0, 0.0, 1.0])?;
60        Ok(Self {
61            order,
62            normalization,
63            listener_rotation,
64            reference_freq_hz,
65        })
66    }
67
68    /// Update the active scene rotation from an admitted Hamilton quaternion `xyzw`.
69    pub fn set_rotation_quaternion_xyzw(&mut self, xyzw: [f64; 4]) -> Result<(), SignalError> {
70        self.listener_rotation = HoaWignerRotation::from_quaternion_xyzw(xyzw)?;
71        Ok(())
72    }
73
74    /// Encode a mono source at `direction_xyz` into `hoa_bus_interleaved`, rotate by
75    /// `self.listener_rotation` into `rotated_hoa_scratch`, and render stereo binaural output
76    /// into `out_stereo`.
77    pub fn encode_rotate_and_render_binaural_into(
78        &self,
79        mono_samples: &[f32],
80        direction_xyz: [f32; 3],
81        gain: f32,
82        hoa_bus_interleaved: &mut [f32],
83        rotated_hoa_scratch: &mut [f32],
84        out_stereo: &mut [[f32; 2]],
85    ) -> Result<usize, SignalError> {
86        let ch = self.order.channel_count();
87        let needed = mono_samples
88            .len()
89            .checked_mul(ch)
90            .ok_or(SignalError::NumericRange)?;
91        if hoa_bus_interleaved.len() < needed || rotated_hoa_scratch.len() < needed {
92            return Err(SignalError::LengthMismatch);
93        }
94        hoa_bus_interleaved[..needed].fill(0.0);
95        encode_mono_to_hoa_accum_into(
96            mono_samples,
97            self.order,
98            self.normalization,
99            direction_xyz,
100            gain,
101            &mut hoa_bus_interleaved[..needed],
102        )?;
103        self.listener_rotation.apply_stream_into_f32(
104            self.order,
105            &hoa_bus_interleaved[..needed],
106            &mut rotated_hoa_scratch[..needed],
107        )?;
108        render_hoa_stream_binaural_into(
109            self.order,
110            self.normalization,
111            &rotated_hoa_scratch[..needed],
112            self.reference_freq_hz,
113            out_stereo,
114        )
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn qac_hoa_scene_bus_rotates_and_renders_stereo() {
124        let mut bus = QacHoaSceneBus::new(HoaOrder::Order1, HoaNormalization::Sn3d, 1000.0).unwrap();
125        let s = core::f64::consts::FRAC_1_SQRT_2;
126        // Rotate +90 deg around +Z so a +X source moves to +Y (left ear)
127        bus.set_rotation_quaternion_xyzw([0.0, 0.0, s, s]).unwrap();
128
129        let mono = [1.0f32; 16];
130        let mut hoa_buf = [0.0f32; 64];
131        let mut rot_buf = [0.0f32; 64];
132        let mut stereo = [[0.0f32; 2]; 16];
133        let frames = bus
134            .encode_rotate_and_render_binaural_into(
135                &mono,
136                [1.0, 0.0, 0.0],
137                1.0,
138                &mut hoa_buf,
139                &mut rot_buf,
140                &mut stereo,
141            )
142            .unwrap();
143        assert_eq!(frames, 16);
144        assert!(stereo[0][0] > stereo[0][1]);
145    }
146}