bbx_dsp 0.4.3

Block-based audio DSP graph system with oscillators, effects, modulators, and realtime-safe processing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Binaural decoder block for converting multi-channel audio to stereo headphone output.
//!
//! Supports both ambisonic (FOA/SOA/TOA) and surround (5.1, 7.1) inputs.
//! Two decoding strategies are available:
//!
//! - [`BinauralStrategy::Matrix`] - Lightweight ILD-based approximation (low CPU)
//! - [`BinauralStrategy::Hrtf`] - Full HRTF convolution for accurate binaural rendering (default)

mod hrir_data;
mod hrtf;
mod matrix;
mod virtual_speaker;

use std::marker::PhantomData;

use hrtf::HrtfConvolver;

use crate::{
    block::Block, channel::ChannelConfig, context::DspContext, graph::MAX_BLOCK_INPUTS, parameter::ModulationOutput,
    sample::Sample,
};

/// Binaural decoding strategy.
///
/// Determines how multi-channel audio is converted to binaural stereo.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinauralStrategy {
    /// Lightweight matrix-based decoder using ILD (Interaural Level Difference).
    ///
    /// Uses psychoacoustically-informed coefficients to approximate binaural cues.
    /// Low CPU usage but limited spatial accuracy.
    Matrix,

    /// Full HRTF (Head-Related Transfer Function) convolution.
    ///
    /// Uses measured impulse responses to accurately model how sounds arrive
    /// at each ear from different directions. Higher CPU usage but superior
    /// spatial rendering with proper externalization.
    Hrtf,
}

impl Default for BinauralStrategy {
    fn default() -> Self {
        Self::Hrtf
    }
}

/// Decodes multi-channel audio to stereo for headphone listening.
///
/// Supports ambisonic B-format (1st, 2nd, 3rd order) and can be configured
/// to use either lightweight matrix decoding or full HRTF convolution.
///
/// # Supported Input Formats
/// - **Ambisonics**: FOA (4 ch), SOA (9 ch), TOA (16 ch)
/// - **Surround**: 5.1 (6 ch), 7.1 (8 ch)
///
/// # Output
/// Always stereo (2 channels): Left, Right
///
/// # Example
/// ```ignore
/// use bbx_dsp::blocks::effectors::binaural_decoder::{BinauralDecoderBlock, BinauralStrategy};
///
/// // Create HRTF decoder (default)
/// let hrtf_decoder = BinauralDecoderBlock::<f32>::new(1);
///
/// // Create lightweight matrix decoder
/// let matrix_decoder = BinauralDecoderBlock::<f32>::with_strategy(1, BinauralStrategy::Matrix);
/// ```
pub struct BinauralDecoderBlock<S: Sample> {
    input_count: usize,
    strategy: BinauralStrategy,
    decoder_matrix: [[f64; MAX_BLOCK_INPUTS]; 2],
    hrtf_convolver: Option<Box<HrtfConvolver>>,
    _phantom: PhantomData<S>,
}

impl<S: Sample> BinauralDecoderBlock<S> {
    /// Create a new binaural decoder for ambisonics with the default strategy (HRTF).
    ///
    /// # Arguments
    /// * `order` - Ambisonic order (1, 2, or 3)
    ///
    /// # Panics
    /// Panics if order is not 1, 2, or 3.
    pub fn new(order: usize) -> Self {
        Self::with_strategy(order, BinauralStrategy::default())
    }

    /// Create a new binaural decoder for ambisonics with a specific strategy.
    ///
    /// # Arguments
    /// * `order` - Ambisonic order (1, 2, or 3)
    /// * `strategy` - The decoding strategy to use
    ///
    /// # Panics
    /// Panics if order is not 1, 2, or 3.
    pub fn with_strategy(order: usize, strategy: BinauralStrategy) -> Self {
        assert!((1..=3).contains(&order), "Ambisonic order must be 1, 2, or 3");

        let input_count = (order + 1) * (order + 1);
        let decoder_matrix = matrix::compute_matrix(order);

        let hrtf_convolver = match strategy {
            BinauralStrategy::Matrix => None,
            BinauralStrategy::Hrtf => Some(Box::new(HrtfConvolver::new_ambisonic(order))),
        };

        Self {
            input_count,
            strategy,
            decoder_matrix,
            hrtf_convolver,
            _phantom: PhantomData,
        }
    }

    /// Create a new binaural decoder for surround sound.
    ///
    /// # Arguments
    /// * `channel_count` - Number of input channels (6 for 5.1, 8 for 7.1)
    /// * `strategy` - The decoding strategy to use
    ///
    /// # Panics
    /// Panics if channel_count is not 6 or 8.
    pub fn new_surround(channel_count: usize, strategy: BinauralStrategy) -> Self {
        assert!(
            channel_count == 6 || channel_count == 8,
            "Surround channel count must be 6 (5.1) or 8 (7.1)"
        );

        let decoder_matrix = [[0.0; MAX_BLOCK_INPUTS]; 2];

        let hrtf_convolver = match strategy {
            BinauralStrategy::Matrix => None,
            BinauralStrategy::Hrtf => Some(Box::new(HrtfConvolver::new_surround(channel_count))),
        };

        Self {
            input_count: channel_count,
            strategy,
            decoder_matrix,
            hrtf_convolver,
            _phantom: PhantomData,
        }
    }

    /// Returns the ambisonic order (for ambisonic inputs).
    ///
    /// Returns 0 for surround inputs.
    pub fn order(&self) -> usize {
        match self.input_count {
            4 => 1,
            9 => 2,
            16 => 3,
            _ => 0,
        }
    }

    /// Returns the current decoding strategy.
    pub fn strategy(&self) -> BinauralStrategy {
        self.strategy
    }

    /// Reset the HRTF convolver state (clears convolution buffers).
    pub fn reset(&mut self) {
        if let Some(ref mut convolver) = self.hrtf_convolver {
            convolver.reset();
        }
    }

    fn process_matrix(&self, inputs: &[&[S]], outputs: &mut [&mut [S]]) {
        let num_inputs = self.input_count.min(inputs.len());
        let num_outputs = 2.min(outputs.len());

        if num_inputs == 0 || num_outputs == 0 || inputs[0].is_empty() {
            return;
        }

        let num_samples = inputs[0].len().min(outputs[0].len());

        for (out_ch, output) in outputs.iter_mut().enumerate().take(num_outputs) {
            for i in 0..num_samples {
                let mut sum = 0.0f64;
                for (in_ch, input) in inputs.iter().enumerate().take(num_inputs) {
                    sum += input[i].to_f64() * self.decoder_matrix[out_ch][in_ch];
                }
                output[i] = S::from_f64(sum);
            }
        }
    }

    fn process_hrtf(&mut self, inputs: &[&[S]], outputs: &mut [&mut [S]]) {
        if outputs.len() < 2 {
            return;
        }

        let num_inputs = self.input_count.min(inputs.len());

        if let Some(ref mut convolver) = self.hrtf_convolver {
            let (left_output, rest) = outputs.split_at_mut(1);
            let right_output = &mut rest[0];
            convolver.process(inputs, left_output[0], right_output, num_inputs);
        }
    }
}

impl<S: Sample> Block<S> for BinauralDecoderBlock<S> {
    fn process(&mut self, inputs: &[&[S]], outputs: &mut [&mut [S]], _modulation_values: &[S], _context: &DspContext) {
        match self.strategy {
            BinauralStrategy::Matrix => self.process_matrix(inputs, outputs),
            BinauralStrategy::Hrtf => self.process_hrtf(inputs, outputs),
        }
    }

    #[inline]
    fn input_count(&self) -> usize {
        self.input_count
    }

    #[inline]
    fn output_count(&self) -> usize {
        2
    }

    #[inline]
    fn modulation_outputs(&self) -> &[ModulationOutput] {
        &[]
    }

    #[inline]
    fn channel_config(&self) -> ChannelConfig {
        ChannelConfig::Explicit
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::channel::ChannelLayout;

    fn test_context() -> DspContext {
        DspContext {
            sample_rate: 44100.0,
            num_channels: 2,
            buffer_size: 4,
            current_sample: 0,
            channel_layout: ChannelLayout::Stereo,
        }
    }

    #[test]
    fn test_default_strategy_is_hrtf() {
        assert_eq!(BinauralStrategy::default(), BinauralStrategy::Hrtf);
    }

    #[test]
    fn test_new_uses_default_strategy() {
        let decoder = BinauralDecoderBlock::<f32>::new(1);
        assert_eq!(decoder.strategy(), BinauralStrategy::Hrtf);
    }

    #[test]
    fn test_with_strategy_matrix() {
        let decoder = BinauralDecoderBlock::<f32>::with_strategy(1, BinauralStrategy::Matrix);
        assert_eq!(decoder.strategy(), BinauralStrategy::Matrix);
    }

    #[test]
    fn test_binaural_foa_channel_counts() {
        let decoder = BinauralDecoderBlock::<f32>::new(1);
        assert_eq!(decoder.input_count(), 4);
        assert_eq!(decoder.output_count(), 2);
        assert_eq!(decoder.channel_config(), ChannelConfig::Explicit);
    }

    #[test]
    fn test_binaural_soa_channel_counts() {
        let decoder = BinauralDecoderBlock::<f32>::new(2);
        assert_eq!(decoder.input_count(), 9);
        assert_eq!(decoder.output_count(), 2);
    }

    #[test]
    fn test_binaural_toa_channel_counts() {
        let decoder = BinauralDecoderBlock::<f32>::new(3);
        assert_eq!(decoder.input_count(), 16);
        assert_eq!(decoder.output_count(), 2);
    }

    #[test]
    fn test_binaural_front_signal_balanced() {
        let mut decoder = BinauralDecoderBlock::<f32>::with_strategy(1, BinauralStrategy::Matrix);
        let context = test_context();

        // Front signal: W=1, Y=0, Z=0, X=1
        let w = [1.0f32; 4];
        let y = [0.0f32; 4];
        let z = [0.0f32; 4];
        let x = [1.0f32; 4];
        let mut left_out = [0.0f32; 4];
        let mut right_out = [0.0f32; 4];

        let inputs: [&[f32]; 4] = [&w, &y, &z, &x];
        let mut outputs: [&mut [f32]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        let diff = (left_out[0] - right_out[0]).abs();
        assert!(diff < 0.01, "Front signal should be balanced, diff={}", diff);
    }

    #[test]
    fn test_binaural_left_signal_louder_in_left() {
        let mut decoder = BinauralDecoderBlock::<f32>::with_strategy(1, BinauralStrategy::Matrix);
        let context = test_context();

        // Left signal: W=1, Y=1, Z=0, X=0
        let w = [1.0f32; 4];
        let y = [1.0f32; 4];
        let z = [0.0f32; 4];
        let x = [0.0f32; 4];
        let mut left_out = [0.0f32; 4];
        let mut right_out = [0.0f32; 4];

        let inputs: [&[f32]; 4] = [&w, &y, &z, &x];
        let mut outputs: [&mut [f32]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        assert!(
            left_out[0] > right_out[0],
            "Left signal should be louder in left channel: L={}, R={}",
            left_out[0],
            right_out[0]
        );
    }

    #[test]
    fn test_binaural_right_signal_louder_in_right() {
        let mut decoder = BinauralDecoderBlock::<f32>::with_strategy(1, BinauralStrategy::Matrix);
        let context = test_context();

        // Right signal: W=1, Y=-1, Z=0, X=0
        let w = [1.0f32; 4];
        let y = [-1.0f32; 4];
        let z = [0.0f32; 4];
        let x = [0.0f32; 4];
        let mut left_out = [0.0f32; 4];
        let mut right_out = [0.0f32; 4];

        let inputs: [&[f32]; 4] = [&w, &y, &z, &x];
        let mut outputs: [&mut [f32]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        assert!(
            right_out[0] > left_out[0],
            "Right signal should be louder in right channel: L={}, R={}",
            left_out[0],
            right_out[0]
        );
    }

    #[test]
    fn test_binaural_rear_signal_balanced() {
        let mut decoder = BinauralDecoderBlock::<f32>::with_strategy(1, BinauralStrategy::Matrix);
        let context = test_context();

        // Rear signal: W=1, Y=0, Z=0, X=-1
        let w = [1.0f32; 4];
        let y = [0.0f32; 4];
        let z = [0.0f32; 4];
        let x = [-1.0f32; 4];
        let mut left_out = [0.0f32; 4];
        let mut right_out = [0.0f32; 4];

        let inputs: [&[f32]; 4] = [&w, &y, &z, &x];
        let mut outputs: [&mut [f32]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        let diff = (left_out[0] - right_out[0]).abs();
        assert!(diff < 0.01, "Rear signal should be balanced, diff={}", diff);
    }

    #[test]
    fn test_binaural_silence_produces_silence() {
        let mut decoder = BinauralDecoderBlock::<f32>::with_strategy(1, BinauralStrategy::Matrix);
        let context = test_context();

        let w = [0.0f32; 4];
        let y = [0.0f32; 4];
        let z = [0.0f32; 4];
        let x = [0.0f32; 4];
        let mut left_out = [1.0f32; 4];
        let mut right_out = [1.0f32; 4];

        let inputs: [&[f32]; 4] = [&w, &y, &z, &x];
        let mut outputs: [&mut [f32]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        for i in 0..4 {
            assert!(left_out[i].abs() < 1e-10, "Left output should be silence");
            assert!(right_out[i].abs() < 1e-10, "Right output should be silence");
        }
    }

    #[test]
    fn test_binaural_order_accessor() {
        assert_eq!(BinauralDecoderBlock::<f32>::new(1).order(), 1);
        assert_eq!(BinauralDecoderBlock::<f32>::new(2).order(), 2);
        assert_eq!(BinauralDecoderBlock::<f32>::new(3).order(), 3);
    }

    #[test]
    #[should_panic]
    fn test_binaural_invalid_order_zero_panics() {
        let _ = BinauralDecoderBlock::<f32>::new(0);
    }

    #[test]
    #[should_panic]
    fn test_binaural_invalid_order_four_panics() {
        let _ = BinauralDecoderBlock::<f32>::new(4);
    }

    #[test]
    fn test_binaural_soa_lateral_differentiation() {
        let mut decoder = BinauralDecoderBlock::<f32>::with_strategy(2, BinauralStrategy::Matrix);
        let context = test_context();

        // Only V channel active (ACN index 4)
        let mut inputs_data: [[f32; 4]; 9] = [[0.0; 4]; 9];
        inputs_data[4] = [1.0; 4];

        let inputs: Vec<&[f32]> = inputs_data.iter().map(|a| a.as_slice()).collect();
        let mut left_out = [0.0f32; 4];
        let mut right_out = [0.0f32; 4];
        let mut outputs: [&mut [f32]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        // V channel should create opposite signs for L/R
        assert!(
            left_out[0] * right_out[0] < 0.0,
            "V channel should create opposite polarity: L={}, R={}",
            left_out[0],
            right_out[0]
        );
    }

    // f64 variant tests

    #[test]
    fn test_binaural_foa_channel_counts_f64() {
        let decoder = BinauralDecoderBlock::<f64>::new(1);
        assert_eq!(decoder.input_count(), 4);
        assert_eq!(decoder.output_count(), 2);
        assert_eq!(decoder.channel_config(), ChannelConfig::Explicit);
    }

    #[test]
    fn test_binaural_soa_channel_counts_f64() {
        let decoder = BinauralDecoderBlock::<f64>::new(2);
        assert_eq!(decoder.input_count(), 9);
        assert_eq!(decoder.output_count(), 2);
    }

    #[test]
    fn test_binaural_toa_channel_counts_f64() {
        let decoder = BinauralDecoderBlock::<f64>::new(3);
        assert_eq!(decoder.input_count(), 16);
        assert_eq!(decoder.output_count(), 2);
    }

    #[test]
    fn test_binaural_front_signal_balanced_f64() {
        let mut decoder = BinauralDecoderBlock::<f64>::with_strategy(1, BinauralStrategy::Matrix);
        let context = test_context();

        let w = [1.0f64; 4];
        let y = [0.0f64; 4];
        let z = [0.0f64; 4];
        let x = [1.0f64; 4];
        let mut left_out = [0.0f64; 4];
        let mut right_out = [0.0f64; 4];

        let inputs: [&[f64]; 4] = [&w, &y, &z, &x];
        let mut outputs: [&mut [f64]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        let diff = (left_out[0] - right_out[0]).abs();
        assert!(diff < 0.01, "Front signal should be balanced, diff={}", diff);
    }

    #[test]
    fn test_binaural_left_signal_louder_in_left_f64() {
        let mut decoder = BinauralDecoderBlock::<f64>::with_strategy(1, BinauralStrategy::Matrix);
        let context = test_context();

        let w = [1.0f64; 4];
        let y = [1.0f64; 4];
        let z = [0.0f64; 4];
        let x = [0.0f64; 4];
        let mut left_out = [0.0f64; 4];
        let mut right_out = [0.0f64; 4];

        let inputs: [&[f64]; 4] = [&w, &y, &z, &x];
        let mut outputs: [&mut [f64]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        assert!(
            left_out[0] > right_out[0],
            "Left signal should be louder in left channel: L={}, R={}",
            left_out[0],
            right_out[0]
        );
    }

    #[test]
    fn test_binaural_silence_produces_silence_f64() {
        let mut decoder = BinauralDecoderBlock::<f64>::with_strategy(1, BinauralStrategy::Matrix);
        let context = test_context();

        let w = [0.0f64; 4];
        let y = [0.0f64; 4];
        let z = [0.0f64; 4];
        let x = [0.0f64; 4];
        let mut left_out = [1.0f64; 4];
        let mut right_out = [1.0f64; 4];

        let inputs: [&[f64]; 4] = [&w, &y, &z, &x];
        let mut outputs: [&mut [f64]; 2] = [&mut left_out, &mut right_out];

        decoder.process(&inputs, &mut outputs, &[], &context);

        for i in 0..4 {
            assert!(left_out[i].abs() < 1e-14, "Left output should be silence");
            assert!(right_out[i].abs() < 1e-14, "Right output should be silence");
        }
    }

    #[test]
    fn test_binaural_order_accessor_f64() {
        assert_eq!(BinauralDecoderBlock::<f64>::new(1).order(), 1);
        assert_eq!(BinauralDecoderBlock::<f64>::new(2).order(), 2);
        assert_eq!(BinauralDecoderBlock::<f64>::new(3).order(), 3);
    }
}