audionimbus 0.13.0

A safe wrapper around Steam Audio that provides spatial audio capabilities with realistic occlusion, reverb, and HRTF effects, accounting for physical attributes and scene geometry.
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! Sound propagation path effects for navigating around obstacles.

use super::audio_effect_state::AudioEffectState;
use super::{EffectError, SpeakerLayout};
use crate::audio_buffer::{AudioBuffer, Sample};
use crate::audio_settings::AudioSettings;
use crate::context::Context;
use crate::error::{to_option_error, SteamAudioError};
use crate::ffi_wrapper::FFIWrapper;
use crate::geometry::CoordinateSystem;
use crate::hrtf::Hrtf;
use crate::num_ambisonics_channels;
use crate::{ChannelPointers, ChannelRequirement};

#[cfg(doc)]
use crate::baking::PathBaker;
#[cfg(doc)]
use crate::geometry::Scene;
#[cfg(doc)]
use crate::probe::ProbeBatch;
#[cfg(doc)]
use crate::simulation::{SimulationOutputs, Simulator, Source};

/// Applies the result of simulating sound paths from the source to the listener.
///
/// Multiple paths that sound can take as it propagates from the source to the listener are combined into an Ambisonic sound field.
///
/// # Examples
///
/// Applying pathing involves:
/// 1. Baking path data between probes using [`PathBaker::bake`]
/// 2. Setting up a [`Simulator`] with a [`Scene`] and [`ProbeBatch`]
/// 3. Adding [`Source`]s with pathing enabled (don't forget to commit using [`Simulator::commit`]!)
/// 4. Running the simulation ([`Simulator::run_pathing`]) and retrieving the output for the source ([`Source::get_outputs`])
/// 5. Applying the path effect using the simulation output ([`SimulationOutputs::pathing`]) as params
///
/// ```
/// use audionimbus::*;
///
/// let context = Context::default();
///
/// const SAMPLING_RATE: u32 = 48_000;
/// const FRAME_SIZE: u32 = 1024;
/// const MAX_ORDER: u32 = 1;
///
/// let simulation_settings = SimulationSettings::new(SAMPLING_RATE, FRAME_SIZE, MAX_ORDER)
///     .with_direct(DirectSimulationSettings {
///         max_num_occlusion_samples: 4,
///     })
///     .with_reflections(ReflectionsSimulationSettings::Convolution {
///         max_num_rays: 4096,
///         num_diffuse_samples: 32,
///         max_duration: 2.0,
///         max_num_sources: 8,
///         num_threads: 2,
///     })
///     .with_pathing(PathingSimulationSettings {
///         num_visibility_samples: 4,
///     });
/// let mut simulator = Simulator::try_new(&context, &simulation_settings)?;
///
/// let mut scene = Scene::try_new(&context)?;
/// let vertices = vec![
///     Point::new(-50.0, 0.0, -50.0),
///     Point::new(50.0, 0.0, -50.0),
///     Point::new(50.0, 0.0, 50.0),
///     Point::new(-50.0, 0.0, 50.0),
/// ];
/// let triangles = vec![Triangle::new(0, 1, 2), Triangle::new(0, 2, 3)];
/// let materials = vec![Material::default()];
/// let material_indices = vec![0, 0];
/// let static_mesh = StaticMesh::try_new(
///     &scene,
///     &StaticMeshSettings {
///         vertices: &vertices,
///         triangles: &triangles,
///         material_indices: &material_indices,
///         materials: &materials,
///     },
/// )?;
/// scene.add_static_mesh(static_mesh);
/// scene.commit();
/// simulator.set_scene(&scene);
///
/// let identifier = BakedDataIdentifier::Pathing {
///     variation: BakedDataVariation::Dynamic,
/// };
///
/// let mut probe_array = ProbeArray::try_new(&context)?;
/// let box_transform = Matrix::new([
///     [100.0, 0.0, 0.0, 0.0],
///     [0.0, 100.0, 0.0, 0.0],
///     [0.0, 0.0, 100.0, 0.0],
///     [0.0, 0.0, 0.0, 1.0],
/// ]);
/// probe_array.generate_probes(
///     &scene,
///     &ProbeGenerationParams::UniformFloor {
///         spacing: 2.0,
///         height: 1.5,
///         transform: box_transform,
///     },
/// );
///
/// let mut probe_batch = ProbeBatch::try_new(&context)?;
/// probe_batch.add_probe_array(&probe_array);
/// probe_batch.commit();
/// simulator.add_probe_batch(&probe_batch);
///
/// let path_bake_params = PathBakeParams {
///     identifier,
///     num_samples: 1, // Trace a single ray to test if one probe can see another probe.
///     visibility_range: 50.0, // Don't check visibility between probes that are > 50m apart.
///     path_range: 100.0, // Don't store paths between probes that are > 100m apart.
///     num_threads: 8,
///     radius: 1.0,
///     threshold: 0.5,
/// };
/// PathBaker::new()
///     .bake(&context, &mut probe_batch, &scene, path_bake_params)
///     .unwrap();
///
/// let source_settings = SourceSettings {
///     flags: SimulationFlags::PATHING,
/// };
/// let mut source = Source::try_new(&simulator, &source_settings)?;
/// let simulation_inputs = SimulationInputs::new(CoordinateSystem::default())
///     .with_direct(
///         DirectSimulationParameters::new()
///             .with_distance_attenuation(DistanceAttenuationModel::default())
///             .with_air_absorption(AirAbsorptionModel::default())
///             .with_directivity(Directivity::default())
///             .with_occlusion(
///                 Occlusion::new(OcclusionAlgorithm::Raycast).with_transmission(
///                     TransmissionParameters {
///                         num_transmission_rays: 1,
///                     },
///                 ),
///             ),
///     )
///     .with_reflections(ReflectionsSimulationParameters::Convolution {
///         baked_data_identifier: None,
///     })
///     .with_pathing(PathingSimulationParameters {
///         pathing_probes: &probe_batch,
///         visibility_radius: 1.0,
///         visibility_threshold: 10.0,
///         visibility_range: 10.0,
///         pathing_order: 1,
///         enable_validation: true,
///         find_alternate_paths: true,
///         deviation: DeviationModel::default(),
///     });
/// source.set_inputs(SimulationFlags::PATHING, simulation_inputs);
/// simulator.add_source(&source);
///
/// simulator.commit();
/// simulator.run_pathing();
///
/// let audio_settings = AudioSettings::default();
/// let path_effect_settings = PathEffectSettings {
///     max_order: MAX_ORDER,
///     spatialization: None,
/// };
/// let mut path_effect = PathEffect::try_new(&context, &audio_settings, &path_effect_settings)?;
///
/// let input = vec![0.5; FRAME_SIZE as usize];
/// let input_buffer = AudioBuffer::try_with_data(&input)?;
///
/// // Must have 4 channels (1st order Ambisonics) for this example.
/// const NUM_CHANNELS: u32 = num_ambisonics_channels(1);
/// let mut output_container = vec![0.0; (NUM_CHANNELS * input_buffer.num_samples()) as usize];
/// let output_buffer = AudioBuffer::try_with_data_and_settings(
///     &mut output_container,
///     AudioBufferSettings::with_num_channels(NUM_CHANNELS),
/// )?;
///
/// let simulation_outputs = source.get_outputs(SimulationFlags::PATHING)?;
/// let path_effect_params = simulation_outputs.pathing();
/// let _ = path_effect.apply(&path_effect_params, &input_buffer, &output_buffer);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct PathEffect {
    inner: audionimbus_sys::IPLPathEffect,

    /// Number of output channels needed for the ambisonics order specified when creating the
    /// effect.
    num_output_channels: u32,
}

impl PathEffect {
    /// Creates a new path effect.
    ///
    /// # Errors
    ///
    /// Returns [`SteamAudioError`] if effect creation fails.
    pub fn try_new(
        context: &Context,
        audio_settings: &AudioSettings,
        path_effect_settings: &PathEffectSettings,
    ) -> Result<Self, SteamAudioError> {
        let mut inner = std::ptr::null_mut();

        let status = unsafe {
            audionimbus_sys::iplPathEffectCreate(
                context.raw_ptr(),
                &mut audionimbus_sys::IPLAudioSettings::from(audio_settings),
                &mut audionimbus_sys::IPLPathEffectSettings::from(path_effect_settings),
                &raw mut inner,
            )
        };

        if let Some(error) = to_option_error(status) {
            return Err(error);
        }

        let path_effect = Self {
            inner,
            num_output_channels: num_ambisonics_channels(path_effect_settings.max_order),
        };

        Ok(path_effect)
    }

    /// Applies a path effect to an audio buffer.
    ///
    /// This effect CANNOT be applied in-place.
    ///
    /// The input audio buffer must have one channel, and the output audio buffer must have as many
    /// channels as needed for the ambisonics order specified when creating the effect (see
    /// [`num_ambisonics_channels`]).
    ///
    /// # Errors
    ///
    /// Returns [`EffectError`] if:
    /// - The input buffer has more than one channel
    /// - The output buffer has a number of channels different from that needed for the ambisonics
    ///   order specified when creating the effect
    pub fn apply<I, O, PI: ChannelPointers, PO: ChannelPointers>(
        &mut self,
        path_effect_params: &PathEffectParams,
        input_buffer: &AudioBuffer<I, PI>,
        output_buffer: &AudioBuffer<O, PO>,
    ) -> Result<AudioEffectState, EffectError>
    where
        I: AsRef<[Sample]>,
        O: AsRef<[Sample]> + AsMut<[Sample]>,
    {
        let num_input_channels = input_buffer.num_channels();
        if num_input_channels != 1 {
            return Err(EffectError::InvalidInputChannels {
                expected: ChannelRequirement::Exactly(1),
                actual: num_input_channels,
            });
        }

        let num_output_channels = output_buffer.num_channels();
        if num_output_channels != self.num_output_channels {
            return Err(EffectError::InvalidOutputChannels {
                expected: ChannelRequirement::Exactly(self.num_output_channels),
                actual: num_output_channels,
            });
        }

        let state = unsafe {
            audionimbus_sys::iplPathEffectApply(
                self.raw_ptr(),
                &raw mut *path_effect_params.as_ffi(),
                &raw mut *input_buffer.as_ffi(),
                &raw mut *output_buffer.as_ffi(),
            )
        }
        .into();

        Ok(state)
    }

    /// Retrieves a single frame of tail samples from a path effect’s internal buffers.
    ///
    /// After the input to the path effect has stopped, this function must be called instead of [`Self::apply`] until the return value indicates that no more tail samples remain.
    ///
    /// The output audio buffer must have as many channels as needed for the Ambisonics order specified when creating the effect.
    ///
    /// # Errors
    ///
    /// Returns [`EffectError`] if the output buffer has a number of channels different from that
    /// needed for the ambisonics order specified when creating the effect.
    pub fn tail<O>(&self, output_buffer: &AudioBuffer<O>) -> Result<AudioEffectState, EffectError>
    where
        O: AsRef<[Sample]> + AsMut<[Sample]>,
    {
        let num_output_channels = output_buffer.num_channels();
        if num_output_channels != self.num_output_channels {
            return Err(EffectError::InvalidOutputChannels {
                expected: ChannelRequirement::Exactly(self.num_output_channels),
                actual: num_output_channels,
            });
        }

        let state = unsafe {
            audionimbus_sys::iplPathEffectGetTail(self.raw_ptr(), &raw mut *output_buffer.as_ffi())
        }
        .into();

        Ok(state)
    }

    /// Returns the number of tail samples remaining in a path effect’s internal buffers.
    ///
    /// Tail samples are audio samples that should be played even after the input to the effect has stopped playing and no further input samples are available.
    pub fn tail_size(&self) -> usize {
        unsafe { audionimbus_sys::iplPathEffectGetTailSize(self.raw_ptr()) as usize }
    }

    /// Resets the internal processing state of a path effect.
    pub fn reset(&mut self) {
        unsafe { audionimbus_sys::iplPathEffectReset(self.raw_ptr()) };
    }

    /// Returns the raw FFI pointer to the underlying path effect.
    ///
    /// This is intended for internal use and advanced scenarios.
    pub const fn raw_ptr(&self) -> audionimbus_sys::IPLPathEffect {
        self.inner
    }

    /// Returns a mutable reference to the raw FFI pointer.
    ///
    /// This is intended for internal use and advanced scenarios.
    pub const fn raw_ptr_mut(&mut self) -> &mut audionimbus_sys::IPLPathEffect {
        &mut self.inner
    }
}

impl Drop for PathEffect {
    fn drop(&mut self) {
        unsafe { audionimbus_sys::iplPathEffectRelease(&raw mut self.inner) }
    }
}

unsafe impl Send for PathEffect {}
unsafe impl Sync for PathEffect {}

impl Clone for PathEffect {
    /// Retains an additional reference to the path effect.
    ///
    /// The returned [`PathEffect`] shares the same underlying Steam Audio object.
    fn clone(&self) -> Self {
        // SAFETY: The path effect will not be destroyed until all references are released.
        Self {
            inner: unsafe { audionimbus_sys::iplPathEffectRetain(self.inner) },
            num_output_channels: self.num_output_channels,
        }
    }
}

/// Settings used to create a path effect.
#[derive(Debug)]
pub struct PathEffectSettings<'a> {
    /// The maximum ambisonics order that will be used by output audio buffers.
    pub max_order: u32,

    /// If `Some`, then this effect will render spatialized audio into the output buffer.
    ///
    /// If `None`, this effect will render un-spatialized (and un-rotated) Ambisonic audio.
    /// Setting this to `None` is mainly useful only if you plan to mix multiple Ambisonic buffers and/or apply additional processing to the Ambisonic audio before spatialization.
    /// If you plan to immediately spatialize the output of the path effect, setting this value to `Some` can result in significant performance improvements.
    pub spatialization: Option<Spatialization<'a>>,
}

impl From<&PathEffectSettings<'_>> for audionimbus_sys::IPLPathEffectSettings {
    fn from(settings: &PathEffectSettings) -> Self {
        let (spatialize, speaker_layout, hrtf) = if let Some(Spatialization {
            speaker_layout,
            hrtf,
        }) = &settings.spatialization
        {
            (
                audionimbus_sys::IPLbool::IPL_TRUE,
                speaker_layout.clone(),
                hrtf.raw_ptr(),
            )
        } else {
            (
                audionimbus_sys::IPLbool::IPL_FALSE,
                SpeakerLayout::Mono,
                std::ptr::null_mut(),
            )
        };

        Self {
            maxOrder: settings.max_order as i32,
            spatialize,
            speakerLayout: (&speaker_layout).into(),
            hrtf,
        }
    }
}

/// Spatialization settings.
#[derive(Debug)]
pub struct Spatialization<'a> {
    /// The speaker layout to use when spatializing.
    pub speaker_layout: SpeakerLayout,

    /// The HRTF to use when spatializing.
    pub hrtf: &'a Hrtf,
}

/// Parameters for applying a path effect to an audio buffer.
#[derive(Debug)]
pub struct PathEffectParams {
    /// 3-band EQ coefficients for modeling frequency-dependent attenuation caused by paths bending around obstacles.
    pub eq_coeffs: [f32; 3],

    /// Ambisonic coefficients for modeling the directional distribution of sound reaching the listener.
    /// The coefficients are specified in world-space, and must be rotated to match the listener’s orientation separately.
    pub sh_coeffs: ShCoeffs,

    /// Ambisonic order of the output buffer.
    /// May be less than the maximum order specified when creating the effect, in which case higher-order [`Self::sh_coeffs`] will be ignored, and CPU usage will be reduced.
    pub order: u32,

    /// If `true`, spatialize using HRTF-based binaural rendering.
    /// Only used if [`PathEffectSettings::spatialization`] is `Some`.
    pub binaural: bool,

    /// The HRTF to use when spatializing.
    /// Only used if [`PathEffectSettings::spatialization`] is `Some` and [`Self::binaural`] is set to `true`.
    pub hrtf: Hrtf,

    /// The position and orientation of the listener.
    /// Only used if [`PathEffectSettings::spatialization`] is `Some` and [`Self::binaural`] is set to `true`.
    pub listener: CoordinateSystem,

    /// If `true`, the values in [`Self::eq_coeffs`] will be normalized before being used, i.e., each value in [`Self::eq_coeffs`] will be divided by the largest value in [`Self::eq_coeffs`].
    /// This can help counteract overly-aggressive filtering due to a physics-based deviation model.
    /// If `false`, the values in [`Self::eq_coeffs`] will be used as-is.
    pub normalize_eq: bool,
}

/// The spherical harmonic coefficients used in [`PathEffectParams`].
/// Do not access these pointers after applying the effect.
#[derive(Debug)]
pub struct ShCoeffs(pub *mut f32);

unsafe impl Send for ShCoeffs {}

impl ShCoeffs {
    pub const fn raw_ptr(&self) -> *mut f32 {
        self.0
    }
}
impl From<audionimbus_sys::IPLPathEffectParams> for PathEffectParams {
    fn from(params: audionimbus_sys::IPLPathEffectParams) -> Self {
        Self {
            eq_coeffs: params.eqCoeffs,
            sh_coeffs: ShCoeffs(params.shCoeffs),
            order: params.order as u32,
            binaural: params.binaural == audionimbus_sys::IPLbool::IPL_TRUE,
            hrtf: params.hrtf.into(),
            listener: params.listener.into(),
            normalize_eq: params.normalizeEQ == audionimbus_sys::IPLbool::IPL_TRUE,
        }
    }
}

impl PathEffectParams {
    pub(crate) fn as_ffi(&self) -> FFIWrapper<'_, audionimbus_sys::IPLPathEffectParams, Self> {
        let path_effect_params = audionimbus_sys::IPLPathEffectParams {
            eqCoeffs: self.eq_coeffs,
            shCoeffs: self.sh_coeffs.raw_ptr(),
            order: self.order as i32,
            binaural: if self.binaural {
                audionimbus_sys::IPLbool::IPL_TRUE
            } else {
                audionimbus_sys::IPLbool::IPL_FALSE
            },
            hrtf: self.hrtf.raw_ptr(),
            listener: self.listener.into(),
            normalizeEQ: if self.normalize_eq {
                audionimbus_sys::IPLbool::IPL_TRUE
            } else {
                audionimbus_sys::IPLbool::IPL_FALSE
            },
        };

        FFIWrapper::new(path_effect_params)
    }
}

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

    mod apply {
        use super::*;

        #[test]
        fn test_valid() {
            let context = Context::default();

            const FRAME_SIZE: u32 = 1024;
            const MAX_ORDER: u32 = 1;
            const NUM_SH_COEFFS: usize = (MAX_ORDER as usize + 1).pow(2);

            let audio_settings = AudioSettings::default();
            let path_effect_settings = PathEffectSettings {
                max_order: MAX_ORDER,
                spatialization: None,
            };
            let mut path_effect =
                PathEffect::try_new(&context, &audio_settings, &path_effect_settings).unwrap();

            let input_container = vec![0.5; FRAME_SIZE as usize];
            let input_buffer = AudioBuffer::try_with_data(&input_container).unwrap();

            // Must have 4 channels (1st order Ambisonics) for this example.
            let mut output_container = vec![0.0; 4 * input_buffer.num_samples() as usize];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output_container,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

            let hrtf_settings = HrtfSettings::default();
            let hrtf = Hrtf::try_new(&context, &audio_settings, &hrtf_settings).unwrap();

            let mut sh_storage = vec![0.0f32; NUM_SH_COEFFS];
            sh_storage[0] = 1.0;

            let sh_coeffs = ShCoeffs(sh_storage.as_mut_ptr());

            let path_effect_params = PathEffectParams {
                eq_coeffs: [1.0, 1.0, 1.0],
                sh_coeffs,
                order: MAX_ORDER,
                binaural: false,
                hrtf,
                listener: CoordinateSystem::default(),
                normalize_eq: false,
            };

            assert!(path_effect
                .apply(&path_effect_params, &input_buffer, &output_buffer)
                .is_ok());
        }

        #[test]
        fn test_invalid_input_num_channels() {
            let context = Context::default();

            const FRAME_SIZE: u32 = 1024;
            const MAX_ORDER: u32 = 1;
            const NUM_SH_COEFFS: usize = (MAX_ORDER as usize + 1).pow(2);

            let audio_settings = AudioSettings::default();
            let path_effect_settings = PathEffectSettings {
                max_order: MAX_ORDER,
                spatialization: None,
            };
            let mut path_effect =
                PathEffect::try_new(&context, &audio_settings, &path_effect_settings).unwrap();

            let input_container = vec![0.5; 2 * FRAME_SIZE as usize];
            let input_buffer = AudioBuffer::try_with_data_and_settings(
                &input_container,
                AudioBufferSettings::with_num_channels(2),
            )
            .unwrap();

            // Must have 4 channels (1st order Ambisonics) for this example.
            let mut output_container = vec![0.0; 4 * input_buffer.num_samples() as usize];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output_container,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

            let hrtf_settings = HrtfSettings::default();
            let hrtf = Hrtf::try_new(&context, &audio_settings, &hrtf_settings).unwrap();

            let mut sh_storage = vec![0.0f32; NUM_SH_COEFFS];
            sh_storage[0] = 1.0;

            let sh_coeffs = ShCoeffs(sh_storage.as_mut_ptr());

            let path_effect_params = PathEffectParams {
                eq_coeffs: [1.0, 1.0, 1.0],
                sh_coeffs,
                order: MAX_ORDER,
                binaural: false,
                hrtf,
                listener: CoordinateSystem::default(),
                normalize_eq: false,
            };

            assert_eq!(
                path_effect.apply(&path_effect_params, &input_buffer, &output_buffer),
                Err(EffectError::InvalidInputChannels {
                    expected: ChannelRequirement::Exactly(1),
                    actual: 2
                })
            );
        }

        #[test]
        fn test_invalid_output_num_channels() {
            let context = Context::default();

            const FRAME_SIZE: u32 = 1024;
            const MAX_ORDER: u32 = 1;
            const NUM_SH_COEFFS: usize = (MAX_ORDER as usize + 1).pow(2);

            let audio_settings = AudioSettings::default();
            let path_effect_settings = PathEffectSettings {
                max_order: MAX_ORDER,
                spatialization: None,
            };
            let mut path_effect =
                PathEffect::try_new(&context, &audio_settings, &path_effect_settings).unwrap();

            let input_container = vec![0.5; FRAME_SIZE as usize];
            let input_buffer = AudioBuffer::try_with_data(&input_container).unwrap();

            let mut output_container = vec![0.0; 2 * input_buffer.num_samples() as usize];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output_container,
                AudioBufferSettings::with_num_channels(2),
            )
            .unwrap();

            let hrtf_settings = HrtfSettings::default();
            let hrtf = Hrtf::try_new(&context, &audio_settings, &hrtf_settings).unwrap();

            let mut sh_storage = vec![0.0f32; NUM_SH_COEFFS];
            sh_storage[0] = 1.0;

            let sh_coeffs = ShCoeffs(sh_storage.as_mut_ptr());

            let path_effect_params = PathEffectParams {
                eq_coeffs: [1.0, 1.0, 1.0],
                sh_coeffs,
                order: MAX_ORDER,
                binaural: false,
                hrtf,
                listener: CoordinateSystem::default(),
                normalize_eq: false,
            };

            assert_eq!(
                path_effect.apply(&path_effect_params, &input_buffer, &output_buffer),
                Err(EffectError::InvalidOutputChannels {
                    expected: ChannelRequirement::Exactly(4),
                    actual: 2
                })
            );
        }
    }

    mod tail {
        use super::*;

        #[test]
        fn test_valid() {
            let context = Context::default();

            const FRAME_SIZE: usize = 1024;
            const MAX_ORDER: u32 = 1;

            let audio_settings = AudioSettings::default();
            let path_effect_settings = PathEffectSettings {
                max_order: MAX_ORDER,
                spatialization: None,
            };
            let path_effect =
                PathEffect::try_new(&context, &audio_settings, &path_effect_settings).unwrap();

            // Must have 4 channels (1st order Ambisonics) for this example.
            let mut output_container = vec![0.0; 4 * FRAME_SIZE];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output_container,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

            assert!(path_effect.tail(&output_buffer).is_ok());
        }

        #[test]
        fn test_invalid_output_num_channels() {
            let context = Context::default();

            const FRAME_SIZE: usize = 1024;
            const MAX_ORDER: u32 = 1;

            let audio_settings = AudioSettings::default();
            let path_effect_settings = PathEffectSettings {
                max_order: MAX_ORDER,
                spatialization: None,
            };
            let path_effect =
                PathEffect::try_new(&context, &audio_settings, &path_effect_settings).unwrap();

            // Must have 4 channels (1st order Ambisonics) for this example.
            let mut output_container = vec![0.0; 2 * FRAME_SIZE];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output_container,
                AudioBufferSettings::with_num_channels(2),
            )
            .unwrap();

            assert_eq!(
                path_effect.tail(&output_buffer),
                Err(EffectError::InvalidOutputChannels {
                    expected: ChannelRequirement::Exactly(4),
                    actual: 2
                })
            );
        }
    }

    mod clone {
        use super::*;

        #[test]
        fn test_clone() {
            let context = Context::default();
            let audio_settings = AudioSettings::default();

            let effect = PathEffect::try_new(
                &context,
                &audio_settings,
                &PathEffectSettings {
                    max_order: 1,
                    spatialization: None,
                },
            )
            .unwrap();
            let clone = effect.clone();
            assert_eq!(effect.raw_ptr(), clone.raw_ptr());
            drop(effect);
            assert!(!clone.raw_ptr().is_null());
        }
    }
}