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
//! Reconstruction of impulse responses from simulation data.

use crate::context::Context;
use crate::energy_field::EnergyField;
use crate::error::{to_option_error, SteamAudioError};
use crate::impulse_response::ImpulseResponse;

/// An object that can convert energy fields to impulse responses.
///
/// Energy fields are typically much smaller in size than impulse responses, and therefore are used when storing baked reflections or reverb in a probe batch, but impulse responses are what is needed at runtime for convolution.
#[derive(Debug)]
pub struct Reconstructor {
    inner: audionimbus_sys::IPLReconstructor,

    /// The largest possible duration (in seconds) of any impulse response that will be reconstructed.
    /// Used for validation when calling [`Self::reconstruct`].
    max_duration: f32,

    /// The largest possible Ambisonic order of any impulse response that will be reconstructed.
    /// Used for validation when calling [`Self::reconstruct`].
    max_order: u32,
}

impl Reconstructor {
    /// Creates a new reconstructor.
    ///
    /// # Errors
    ///
    /// Returns [`SteamAudioError`] if creation fails.
    pub fn try_new(
        context: &Context,
        reconstructor_settings: &ReconstructorSettings,
    ) -> Result<Self, SteamAudioError> {
        let mut reconstructor = Self {
            inner: std::ptr::null_mut(),
            max_duration: reconstructor_settings.max_duration,
            max_order: reconstructor_settings.max_order,
        };

        let status = unsafe {
            audionimbus_sys::iplReconstructorCreate(
                context.raw_ptr(),
                &mut audionimbus_sys::IPLReconstructorSettings::from(reconstructor_settings),
                reconstructor.raw_ptr_mut(),
            )
        };

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

        Ok(reconstructor)
    }

    /// Reconstructs one or more impulse responses as a single batch of work.
    ///
    /// # Errors
    ///
    /// Returns:
    /// - [`ReconstructorError::DurationExceedsMax`] if `shared_inputs.duration` exceeds the max duration.
    /// - [`ReconstructorError::OrderExceedsMax`] if `shared_inputs.order` exceeds the max order.
    /// - [`ReconstructorError::InputOutputLengthMismatch`] if `inputs` and `outputs` have different lengths.
    pub fn reconstruct(
        &self,
        inputs: &[ReconstructorInputs],
        shared_inputs: &ReconstructorSharedInputs,
        outputs: &[ReconstructorOutputs],
    ) -> Result<(), ReconstructorError> {
        if shared_inputs.duration > self.max_duration {
            return Err(ReconstructorError::DurationExceedsMax {
                duration: shared_inputs.duration,
                max_duration: self.max_duration,
            });
        }

        if shared_inputs.order > self.max_order {
            return Err(ReconstructorError::OrderExceedsMax {
                order: shared_inputs.order,
                max_order: self.max_order,
            });
        }

        if inputs.len() != outputs.len() {
            return Err(ReconstructorError::InputOutputLengthMismatch {
                inputs_len: inputs.len(),
                outputs_len: outputs.len(),
            });
        }

        let c_inputs: Vec<audionimbus_sys::IPLReconstructorInputs> = inputs
            .iter()
            .map(audionimbus_sys::IPLReconstructorInputs::from)
            .collect();

        let c_outputs: Vec<audionimbus_sys::IPLReconstructorOutputs> = outputs
            .iter()
            .map(audionimbus_sys::IPLReconstructorOutputs::from)
            .collect();

        let c_shared_inputs = audionimbus_sys::IPLReconstructorSharedInputs::from(shared_inputs);

        unsafe {
            audionimbus_sys::iplReconstructorReconstruct(
                self.raw_ptr(),
                inputs.len() as i32,
                c_inputs.as_ptr().cast_mut(),
                &c_shared_inputs as *const audionimbus_sys::IPLReconstructorSharedInputs
                    as *mut audionimbus_sys::IPLReconstructorSharedInputs,
                c_outputs.as_ptr().cast_mut(),
            );
        }

        Ok(())
    }

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

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

unsafe impl Send for Reconstructor {}
unsafe impl Sync for Reconstructor {}

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

/// Settings used to create a reconstructor.
#[derive(Debug)]
pub struct ReconstructorSettings {
    /// The largest possible duration (in seconds) of any impulse response that will be reconstructed using this reconstructor.
    pub max_duration: f32,

    /// The largest possible Ambisonic order of any impulse response that will be reconstructed using this reconstructor.
    pub max_order: u32,

    /// The sampling rate of impulse responses reconstructed using this reconstructor.
    pub sampling_rate: u32,
}

impl From<&ReconstructorSettings> for audionimbus_sys::IPLReconstructorSettings {
    fn from(settings: &ReconstructorSettings) -> Self {
        Self {
            maxDuration: settings.max_duration,
            maxOrder: settings.max_order as i32,
            samplingRate: settings.sampling_rate as i32,
        }
    }
}

/// Inputs common to all reconstruction operations specified in a single call to
/// [`Reconstructor::reconstruct`].
#[derive(Debug)]
pub struct ReconstructorSharedInputs {
    /// Duration of impulse responses to reconstruct.
    ///
    /// Must be less than or equal to maxDuration specified in [`ReconstructorSettings`].
    pub duration: f32,

    /// Ambisonic order of impulse responses to reconstruct.
    ///
    /// Must be less than or equal to maxOrder specified in [`ReconstructorSettings`].
    pub order: u32,
}

impl From<&ReconstructorSharedInputs> for audionimbus_sys::IPLReconstructorSharedInputs {
    fn from(reconstructor_shared_inputs: &ReconstructorSharedInputs) -> Self {
        Self {
            duration: reconstructor_shared_inputs.duration,
            order: reconstructor_shared_inputs.order as i32,
        }
    }
}

/// The inputs for a single reconstruction operation.
#[derive(Debug)]
pub struct ReconstructorInputs<'a> {
    /// The energy field from which to reconstruct an impulse response.
    pub energy_field: &'a EnergyField,
}

impl From<&ReconstructorInputs<'_>> for audionimbus_sys::IPLReconstructorInputs {
    fn from(reconstructor_inputs: &ReconstructorInputs) -> Self {
        Self {
            energyField: reconstructor_inputs.energy_field.raw_ptr(),
        }
    }
}

/// The outputs for a single reconstruction operation.
#[derive(Debug)]
pub struct ReconstructorOutputs<'a> {
    pub impulse_response: &'a mut ImpulseResponse,
}

impl From<&ReconstructorOutputs<'_>> for audionimbus_sys::IPLReconstructorOutputs {
    fn from(reconstructor_outputs: &ReconstructorOutputs) -> Self {
        Self {
            impulseResponse: reconstructor_outputs.impulse_response.raw_ptr(),
        }
    }
}

/// [`Reconstructor`] errors.
#[derive(Debug, PartialEq)]
pub enum ReconstructorError {
    /// Duration exceeds the maximum duration specified in the reconstructor's settings.
    DurationExceedsMax { duration: f32, max_duration: f32 },
    /// Order exceeds the maximum order specified in the reconstructor's settings.
    OrderExceedsMax { order: u32, max_order: u32 },
    /// Input and output arrays have mismatched lengths.
    InputOutputLengthMismatch {
        inputs_len: usize,
        outputs_len: usize,
    },
}

impl std::error::Error for ReconstructorError {}

impl std::fmt::Display for ReconstructorError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::DurationExceedsMax {
                duration,
                max_duration,
            } => write!(
                f,
                "duration {duration} exceeds max duration {max_duration}"
            ),
            Self::OrderExceedsMax { order, max_order } => {
                write!(f, "order {order} exceeds max order {max_order}")
            }
            Self::InputOutputLengthMismatch {
                inputs_len,
                outputs_len,
            } => write!(
                f,
                "inputs and outputs length mismatch: inputs_len={inputs_len}, outputs_len={outputs_len}"
            ),
        }
    }
}

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

    mod reconstructor {
        use super::*;

        const SAMPLING_RATE: u32 = 48_000;
        const MAX_DURATION: f32 = 2.0;
        const MAX_ORDER: u32 = 2;
        const VALID_DURATION: f32 = 1.0;
        const VALID_ORDER: u32 = 1;

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

            let reconstructor_settings = ReconstructorSettings {
                max_duration: MAX_DURATION,
                max_order: MAX_ORDER,
                sampling_rate: SAMPLING_RATE,
            };

            let reconstructor = Reconstructor::try_new(&context, &reconstructor_settings).unwrap();

            let shared_inputs = ReconstructorSharedInputs {
                duration: VALID_DURATION,
                order: VALID_ORDER,
            };

            let energy_field = EnergyField::try_new(
                &context,
                &EnergyFieldSettings {
                    duration: VALID_DURATION,
                    order: VALID_ORDER,
                },
            )
            .unwrap();
            let inputs = vec![ReconstructorInputs {
                energy_field: &energy_field,
            }];

            let mut impulse_response = ImpulseResponse::try_new(
                &context,
                &ImpulseResponseSettings {
                    duration: VALID_DURATION,
                    order: VALID_ORDER,
                    sampling_rate: SAMPLING_RATE,
                },
            )
            .unwrap();
            let outputs = vec![ReconstructorOutputs {
                impulse_response: &mut impulse_response,
            }];

            let result = reconstructor.reconstruct(&inputs, &shared_inputs, &outputs);

            assert!(result.is_ok());
        }

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

            let reconstructor_settings = ReconstructorSettings {
                max_duration: MAX_DURATION,
                max_order: MAX_ORDER,
                sampling_rate: SAMPLING_RATE,
            };

            let reconstructor = Reconstructor::try_new(&context, &reconstructor_settings).unwrap();

            let invalid_duration = MAX_DURATION + 1.0;

            let shared_inputs = ReconstructorSharedInputs {
                duration: invalid_duration,
                order: VALID_ORDER,
            };

            let energy_field = EnergyField::try_new(
                &context,
                &EnergyFieldSettings {
                    duration: VALID_DURATION,
                    order: VALID_ORDER,
                },
            )
            .unwrap();
            let inputs = vec![ReconstructorInputs {
                energy_field: &energy_field,
            }];

            let mut impulse_response = ImpulseResponse::try_new(
                &context,
                &ImpulseResponseSettings {
                    duration: VALID_DURATION,
                    order: VALID_ORDER,
                    sampling_rate: SAMPLING_RATE,
                },
            )
            .unwrap();
            let outputs = vec![ReconstructorOutputs {
                impulse_response: &mut impulse_response,
            }];

            assert_eq!(
                reconstructor.reconstruct(&inputs, &shared_inputs, &outputs),
                Err(ReconstructorError::DurationExceedsMax {
                    duration: invalid_duration,
                    max_duration: MAX_DURATION,
                }),
            );
        }

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

            let reconstructor_settings = ReconstructorSettings {
                max_duration: MAX_DURATION,
                max_order: MAX_ORDER,
                sampling_rate: SAMPLING_RATE,
            };

            let reconstructor = Reconstructor::try_new(&context, &reconstructor_settings).unwrap();

            let invalid_order = MAX_ORDER + 1;

            let shared_inputs = ReconstructorSharedInputs {
                duration: MAX_DURATION,
                order: invalid_order,
            };

            let energy_field = EnergyField::try_new(
                &context,
                &EnergyFieldSettings {
                    duration: VALID_DURATION,
                    order: VALID_ORDER,
                },
            )
            .unwrap();
            let inputs = vec![ReconstructorInputs {
                energy_field: &energy_field,
            }];

            let mut impulse_response = ImpulseResponse::try_new(
                &context,
                &ImpulseResponseSettings {
                    duration: VALID_DURATION,
                    order: VALID_ORDER,
                    sampling_rate: SAMPLING_RATE,
                },
            )
            .unwrap();
            let outputs = vec![ReconstructorOutputs {
                impulse_response: &mut impulse_response,
            }];

            assert_eq!(
                reconstructor.reconstruct(&inputs, &shared_inputs, &outputs),
                Err(ReconstructorError::OrderExceedsMax {
                    order: invalid_order,
                    max_order: MAX_ORDER,
                }),
            );
        }

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

            let reconstructor_settings = ReconstructorSettings {
                max_duration: MAX_DURATION,
                max_order: MAX_ORDER,
                sampling_rate: SAMPLING_RATE,
            };

            let reconstructor = Reconstructor::try_new(&context, &reconstructor_settings).unwrap();

            let shared_inputs = ReconstructorSharedInputs {
                duration: VALID_DURATION,
                order: VALID_ORDER,
            };

            let energy_field = EnergyField::try_new(
                &context,
                &EnergyFieldSettings {
                    duration: VALID_DURATION,
                    order: VALID_ORDER,
                },
            )
            .unwrap();
            let inputs = vec![
                ReconstructorInputs {
                    energy_field: &energy_field,
                },
                ReconstructorInputs {
                    energy_field: &energy_field,
                },
            ];

            let mut impulse_response = ImpulseResponse::try_new(
                &context,
                &ImpulseResponseSettings {
                    duration: VALID_DURATION,
                    order: VALID_ORDER,
                    sampling_rate: SAMPLING_RATE,
                },
            )
            .unwrap();
            let outputs = vec![ReconstructorOutputs {
                impulse_response: &mut impulse_response,
            }];

            assert_eq!(
                reconstructor.reconstruct(&inputs, &shared_inputs, &outputs),
                Err(ReconstructorError::InputOutputLengthMismatch {
                    inputs_len: 2,
                    outputs_len: 1,
                }),
            );
        }

        #[test]
        fn test_clone() {
            let context = Context::default();
            let reconstructor_settings = ReconstructorSettings {
                max_duration: MAX_DURATION,
                max_order: MAX_ORDER,
                sampling_rate: SAMPLING_RATE,
            };
            let reconstructor = Reconstructor::try_new(&context, &reconstructor_settings).unwrap();
            let clone = reconstructor.clone();
            assert_eq!(reconstructor.raw_ptr(), clone.raw_ptr());
            drop(reconstructor);
            assert!(!clone.raw_ptr().is_null());
        }
    }
}