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
//! Rotation of Ambisonics sound fields to match listener orientation.

use super::super::{AudioEffectState, EffectError};
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::num_ambisonics_channels;
use crate::{ChannelPointers, ChannelRequirement};

/// Applies a rotation to an ambisonics audio buffer.
///
/// The input buffer is assumed to describe a sound field in "world space".
/// The output buffer is then the same sound field, but expressed relative to the listener’s orientation.
///
/// # Examples
///
/// ```
/// use audionimbus::*;
///
/// let context = Context::default();
/// let audio_settings = AudioSettings::default();
/// let hrtf = Hrtf::try_new(&context, &audio_settings, &HrtfSettings::default())?;
///
/// let mut effect = AmbisonicsRotationEffect::try_new(
///     &context,
///     &audio_settings,
///     &AmbisonicsRotationEffectSettings { max_order: 1 },
/// )?;
///
/// let params = AmbisonicsRotationEffectParams {
///     orientation: CoordinateSystem::default(), // Identity orientation
///     order: 1,
/// };
///
/// const FRAME_SIZE: usize = 1024;
/// let input = vec![0.5; 4 * FRAME_SIZE]; // 4 channels
/// let input_buffer =
///     AudioBuffer::try_with_data_and_settings(&input, AudioBufferSettings::with_num_channels(4))?;
/// let mut output = vec![0.0; 4 * FRAME_SIZE];
/// let output_buffer = AudioBuffer::try_with_data_and_settings(
///     &mut output,
///     AudioBufferSettings::with_num_channels(4),
/// )?;
///
/// let _ = effect.apply(&params, &input_buffer, &output_buffer);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct AmbisonicsRotationEffect {
    inner: audionimbus_sys::IPLAmbisonicsRotationEffect,

    /// The number of input and output channels needed for the ambisonics order used when creating
    /// the effect.
    num_channels: u32,
}

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

        let status = unsafe {
            audionimbus_sys::iplAmbisonicsRotationEffectCreate(
                context.raw_ptr(),
                &mut audionimbus_sys::IPLAudioSettings::from(audio_settings),
                &mut audionimbus_sys::IPLAmbisonicsRotationEffectSettings::from(
                    ambisonics_rotation_effect_settings,
                ),
                &raw mut inner,
            )
        };

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

        let num_channels = num_ambisonics_channels(ambisonics_rotation_effect_settings.max_order);
        let ambisonics_rotation_effect = Self {
            inner,
            num_channels,
        };

        Ok(ambisonics_rotation_effect)
    }

    /// Applies an ambisonics rotation effect to an audio buffer.
    ///
    /// This effect CANNOT be applied in-place.
    ///
    /// Both input and output audio buffers must have as many channels as needed for the
    /// Ambisonics order used (see [`crate::num_ambisonics_channels`]).
    ///
    /// # Errors
    ///
    /// Returns [`EffectError`] if:
    /// - The input buffer does not have the correct number of channels for the Ambisonics order
    /// - The output buffer does not have the correct number of channels for the Ambisonics order
    pub fn apply<I, O, PI: ChannelPointers, PO: ChannelPointers>(
        &mut self,
        ambisonics_rotation_effect_params: &AmbisonicsRotationEffectParams,
        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 != self.num_channels {
            return Err(EffectError::InvalidInputChannels {
                expected: ChannelRequirement::Exactly(self.num_channels),
                actual: num_input_channels,
            });
        }

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

        let state = unsafe {
            audionimbus_sys::iplAmbisonicsRotationEffectApply(
                self.raw_ptr(),
                &raw mut *ambisonics_rotation_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 an Ambisonics rotation effect’s internal buffers.
    ///
    /// After the input to the Ambisonics rotation 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 does not have the correct number of channels
    /// for the Ambisonics order.
    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_channels {
            return Err(EffectError::InvalidOutputChannels {
                expected: ChannelRequirement::Exactly(self.num_channels),
                actual: num_output_channels,
            });
        }

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

        Ok(state)
    }

    /// Returns the number of tail samples remaining in an Ambisonics rotation 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::iplAmbisonicsRotationEffectGetTailSize(self.raw_ptr()) as usize }
    }

    /// Resets the internal processing state of an ambisonics rotation effect.
    pub fn reset(&mut self) {
        unsafe { audionimbus_sys::iplAmbisonicsRotationEffectReset(self.raw_ptr()) };
    }

    /// Returns the raw FFI pointer to the underlying ambisonics rotation effect.
    ///
    /// This is intended for internal use and advanced scenarios.
    pub const fn raw_ptr(&self) -> audionimbus_sys::IPLAmbisonicsRotationEffect {
        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::IPLAmbisonicsRotationEffect {
        &mut self.inner
    }
}

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

unsafe impl Send for AmbisonicsRotationEffect {}
unsafe impl Sync for AmbisonicsRotationEffect {}

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

/// Settings used to create an ambisonics rotation effect.
#[derive(Debug)]
pub struct AmbisonicsRotationEffectSettings {
    /// The maximum ambisonics order that will be used by input audio buffers.
    pub max_order: u32,
}

impl From<&AmbisonicsRotationEffectSettings>
    for audionimbus_sys::IPLAmbisonicsRotationEffectSettings
{
    fn from(settings: &AmbisonicsRotationEffectSettings) -> Self {
        Self {
            maxOrder: settings.max_order as i32,
        }
    }
}

/// Parameters for applying an ambisonics rotation effect to an audio buffer.
#[derive(Debug)]
pub struct AmbisonicsRotationEffectParams {
    /// The orientation of the listener.
    pub orientation: CoordinateSystem,

    /// Ambisonic order of the input and output buffers.
    ///
    /// May be less than the `max_order` specified when creating the effect, in which case the effect will process fewer channels, reducing CPU usage.
    pub order: u32,
}

impl AmbisonicsRotationEffectParams {
    pub(crate) fn as_ffi(
        &self,
    ) -> FFIWrapper<'_, audionimbus_sys::IPLAmbisonicsRotationEffectParams, Self> {
        let ambisonics_rotation_effect_params =
            audionimbus_sys::IPLAmbisonicsRotationEffectParams {
                orientation: self.orientation.into(),
                order: self.order as i32,
            };

        FFIWrapper::new(ambisonics_rotation_effect_params)
    }
}

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

    mod apply {
        use super::*;

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

            let mut effect = AmbisonicsRotationEffect::try_new(
                &context,
                &audio_settings,
                &AmbisonicsRotationEffectSettings { max_order: 1 },
            )
            .unwrap();

            let params = AmbisonicsRotationEffectParams {
                orientation: CoordinateSystem::default(),
                order: 1,
            };

            let input = vec![0.5; 4 * 1024];
            let input_buffer = AudioBuffer::try_with_data_and_settings(
                &input,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

            let mut output = vec![0.0; 4 * 1024];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

            assert!(effect.apply(&params, &input_buffer, &output_buffer).is_ok());
        }

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

            let mut effect = AmbisonicsRotationEffect::try_new(
                &context,
                &audio_settings,
                &AmbisonicsRotationEffectSettings { max_order: 1 },
            )
            .unwrap();

            let params = AmbisonicsRotationEffectParams {
                orientation: CoordinateSystem::default(),
                order: 1,
            };

            let input = vec![0.5; 2 * 1024];
            let input_buffer = AudioBuffer::try_with_data_and_settings(
                &input,
                AudioBufferSettings::with_num_channels(2),
            )
            .unwrap();

            let mut output = vec![0.0; 4 * 1024];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

            assert_eq!(
                effect.apply(&params, &input_buffer, &output_buffer),
                Err(EffectError::InvalidInputChannels {
                    expected: ChannelRequirement::Exactly(4),
                    actual: 2
                })
            );
        }

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

            let mut effect = AmbisonicsRotationEffect::try_new(
                &context,
                &audio_settings,
                &AmbisonicsRotationEffectSettings { max_order: 1 },
            )
            .unwrap();

            let params = AmbisonicsRotationEffectParams {
                orientation: CoordinateSystem::default(),
                order: 1,
            };

            let input = vec![0.5; 4 * 1024];
            let input_buffer = AudioBuffer::try_with_data_and_settings(
                &input,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

            let mut output = vec![0.0; 3 * 1024];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output,
                AudioBufferSettings::with_num_channels(3),
            )
            .unwrap();

            assert_eq!(
                effect.apply(&params, &input_buffer, &output_buffer),
                Err(EffectError::InvalidOutputChannels {
                    expected: ChannelRequirement::Exactly(4),
                    actual: 3,
                })
            );
        }
    }

    mod tail {
        use super::*;

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

            let effect = AmbisonicsRotationEffect::try_new(
                &context,
                &audio_settings,
                &AmbisonicsRotationEffectSettings { max_order: 1 },
            )
            .unwrap();

            let mut output = vec![0.0; 4 * 1024];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

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

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

            let effect = AmbisonicsRotationEffect::try_new(
                &context,
                &audio_settings,
                &AmbisonicsRotationEffectSettings { max_order: 1 },
            )
            .unwrap();

            let mut output = vec![0.0; 2 * 1024];
            let output_buffer = AudioBuffer::try_with_data_and_settings(
                &mut output,
                AudioBufferSettings::with_num_channels(2),
            )
            .unwrap();

            assert_eq!(
                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 = AmbisonicsRotationEffect::try_new(
                &context,
                &audio_settings,
                &AmbisonicsRotationEffectSettings { max_order: 1 },
            )
            .unwrap();
            let clone = effect.clone();
            assert_eq!(effect.raw_ptr(), clone.raw_ptr());
            drop(effect);
            assert!(!clone.raw_ptr().is_null());
        }
    }
}