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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
//! Types and utilities for working with audio buffers.

use crate::context::Context;
use crate::effect::ambisonics::AmbisonicsType;
use crate::ffi_wrapper::FFIWrapper;

/// Trait for types that can provide access to channel pointers.
///
/// This trait abstracts over different storage backends for channel pointers,
/// allowing [`AudioBuffer`] to work with both owned (`Vec<*mut Sample>`) and
/// borrowed (`&[*mut Sample]`, `&mut [*mut Sample]`) pointer storage.
pub trait ChannelPointers {
    /// Returns an immutable slice of channel pointers.
    ///
    /// Each pointer in the slice points to the sample data for one audio channel.
    fn as_slice(&self) -> &[*mut Sample];

    /// Returns a mutable slice of channel pointers.
    ///
    /// Each pointer in the slice points to the sample data for one audio channel.
    fn as_mut_slice(&mut self) -> &mut [*mut Sample];
}

impl<T> ChannelPointers for T
where
    T: AsRef<[*mut Sample]> + AsMut<[*mut Sample]>,
{
    fn as_slice(&self) -> &[*mut Sample] {
        self.as_ref()
    }
    fn as_mut_slice(&mut self) -> &mut [*mut Sample] {
        self.as_mut()
    }
}

/// An audio buffer descriptor.
///
/// This struct does not hold the actual sample data, but instead contains pointers to samples stored elsewhere.
/// The generic parameter `T` is used to ensure that these pointers remain valid for the lifetime of the underlying data.
/// The generic parameter `P` allows for different storage backends (owned Vec or borrowed slice of
/// channel pointers).
///
/// # Examples
///
/// ```
/// use audionimbus::{AudioBuffer, AudioBufferSettings};
///
/// // Mono buffer
/// let samples = vec![0.0; 1024];
/// let buffer = AudioBuffer::try_with_data(&samples)?;
///
/// // Stereo buffer
/// let stereo_samples = vec![0.0; 2048];
/// let buffer = AudioBuffer::try_with_data_and_settings(
///     &stereo_samples,
///     AudioBufferSettings::with_num_channels(2),
/// )?;
/// # Ok::<(), audionimbus::AudioBufferError>(())
/// ```
#[derive(Debug)]
pub struct AudioBuffer<T, P: ChannelPointers = Vec<*mut Sample>> {
    /// Number of samples per channel.
    num_samples: u32,

    /// Pointers to sample data for each channel.
    channel_ptrs: P,

    /// Marker to enforce the lifetime of the channel pointers.
    _marker: std::marker::PhantomData<T>,
}

impl<T, P: ChannelPointers> AudioBuffer<T, P> {
    /// Constructs a new `AudioBuffer` from raw pointers to mutable channel samples and the number
    /// of samples.
    ///
    /// This function is designed to provide maximum flexibility for advanced users who need
    /// fine-grained control over the memory layout of audio data.
    /// However, for most use cases, the safe constructors [`Self::try_with_data`] and
    /// [`Self::try_with_data_and_settings`] should be preferred, because they enforce invariants
    /// using lifetimes.
    ///
    /// The generic parameter `T` can be used to enforce a lifetime and ensure the pointers remain
    /// valid.
    ///
    /// # Errors
    ///
    /// - [`AudioBufferError::InvalidNumChannels`] if `channel_ptrs` is empty.
    /// - [`AudioBufferError::InvalidNumSamples`] if `num_samples` is 0.
    ///
    /// # Safety
    ///
    /// - `channel_ptrs` must contain valid pointers for the duration of the `AudioBuffer`.
    /// - Each pointer in `channel_ptrs` must point to a region of memory containing at least `num_samples` valid samples.
    /// - The lifetime of the `AudioBuffer` must not exceed the lifetime of the memory referenced by `channel_ptrs`.
    ///
    /// Any violations of the above invariants will result in undefined behavior.
    pub unsafe fn try_new(channel_ptrs: P, num_samples: u32) -> Result<Self, AudioBufferError> {
        if channel_ptrs.as_slice().is_empty() {
            return Err(AudioBufferError::InvalidNumChannels { num_channels: 0 });
        }

        if num_samples == 0 {
            return Err(AudioBufferError::InvalidNumSamples { num_samples });
        }

        debug_assert!(
            channel_ptrs.as_slice().iter().all(|&ptr| !ptr.is_null()),
            "some channel pointers are null"
        );

        Ok(Self {
            num_samples,
            channel_ptrs,
            _marker: std::marker::PhantomData,
        })
    }

    /// Returns the number of channels of the audio buffer.
    pub fn num_channels(&self) -> u32 {
        self.channel_ptrs.as_slice().len() as u32
    }

    /// Returns the number of samples per channel in the audio buffer.
    pub const fn num_samples(&self) -> u32 {
        self.num_samples
    }

    /// Reads samples from the audio buffer and interleaves them into `dst`.
    ///
    /// # Errors
    ///
    /// Returns [`AudioBufferOperationError::InterleaveLengthMismatch`] if the destination slice length
    /// does not match the audio buffer's total sample count.
    pub fn interleave(
        &self,
        context: &Context,
        dst: &mut [Sample],
    ) -> Result<(), AudioBufferOperationError> {
        let expected_len = self.num_channels() * self.num_samples();
        if dst.len() as u32 != expected_len {
            return Err(AudioBufferOperationError::InterleaveLengthMismatch {
                dst_len: dst.len(),
                expected_len,
            });
        }

        let mut audio_buffer_ffi = self.as_ffi();

        unsafe {
            audionimbus_sys::iplAudioBufferInterleave(
                context.raw_ptr(),
                &raw mut *audio_buffer_ffi,
                dst.as_mut_ptr(),
            );
        }

        Ok(())
    }

    /// Deinterleaves the `src` sample data into `Self`.
    ///
    /// # Errors
    ///
    /// Returns [`AudioBufferOperationError::DeinterleaveLengthMismatch`] if the source slice length
    /// does not match the audio buffer's total sample count.
    pub fn deinterleave(
        &mut self,
        context: &Context,
        src: &[Sample],
    ) -> Result<(), AudioBufferOperationError> {
        let expected_len = self.num_channels() * self.num_samples();
        if src.len() as u32 != expected_len {
            return Err(AudioBufferOperationError::DeinterleaveLengthMismatch {
                src_len: src.len(),
                expected_len,
            });
        }

        let mut audio_buffer_ffi = self.as_ffi();

        unsafe {
            audionimbus_sys::iplAudioBufferDeinterleave(
                context.raw_ptr(),
                src.as_ptr().cast_mut(),
                &raw mut *audio_buffer_ffi,
            );
        };

        Ok(())
    }

    /// Mixes `source` into `self`.
    ///
    /// Both audio buffers must have the same number of channels and samples.
    ///
    /// # Errors
    ///
    /// Returns:
    /// - [`AudioBufferOperationError::ChannelCountMismatch`] if the audio buffers have different numbers of channels.
    /// - [`AudioBufferOperationError::SampleCountMismatch`] if the audio buffers have different numbers of samples per channel.
    pub fn mix<T2, P2: ChannelPointers>(
        &mut self,
        context: &Context,
        source: &AudioBuffer<T2, P2>,
    ) -> Result<(), AudioBufferOperationError> {
        let self_num_channels = self.num_channels();
        let other_num_channels = source.num_channels();
        if self_num_channels != other_num_channels {
            return Err(AudioBufferOperationError::ChannelCountMismatch {
                self_num_channels,
                other_num_channels,
            });
        }

        let self_num_samples = self.num_samples();
        let other_num_samples = source.num_samples();
        if self_num_samples != other_num_samples {
            return Err(AudioBufferOperationError::SampleCountMismatch {
                self_num_samples,
                other_num_samples,
            });
        }

        unsafe {
            audionimbus_sys::iplAudioBufferMix(
                context.raw_ptr(),
                &raw mut *source.as_ffi(),
                &raw mut *self.as_ffi(),
            );
        }

        Ok(())
    }

    /// Downmixes the multi-channel `source` audio buffer into a mono `self` audio buffer.
    ///
    /// Both audio buffers must have the same number of samples per channel.
    ///
    /// Downmixing is performed by summing up the source channels and dividing the result by the number of source channels.
    /// If this is not the desired downmixing behavior, we recommend that downmixing be performed manually.
    ///
    /// # Errors
    ///
    /// Returns [`AudioBufferOperationError::SampleCountMismatch`] if the audio buffers have different numbers of samples per channel.
    pub fn downmix<T2, P2: ChannelPointers>(
        &mut self,
        context: &Context,
        source: &AudioBuffer<T2, P2>,
    ) -> Result<(), AudioBufferOperationError> {
        let self_num_samples = self.num_samples();
        let other_num_samples = source.num_samples();
        if self_num_samples != other_num_samples {
            return Err(AudioBufferOperationError::SampleCountMismatch {
                self_num_samples,
                other_num_samples,
            });
        }

        unsafe {
            audionimbus_sys::iplAudioBufferDownmix(
                context.raw_ptr(),
                &raw mut *source.as_ffi(),
                &raw mut *self.as_ffi(),
            );
        }

        Ok(())
    }

    /// Returns an iterator over channels.
    pub fn channels(&self) -> impl Iterator<Item = &[Sample]> + '_ {
        self.channel_ptrs.as_slice().iter().map(|&ptr|
            // SAFETY: pointers are guaranteed to be valid by the lifetime.
            unsafe { std::slice::from_raw_parts(ptr, self.num_samples() as usize) })
    }

    /// Returns an iterator over mutable channels.
    pub fn channels_mut(&mut self) -> impl Iterator<Item = &mut [Sample]> + '_ {
        let num_samples = self.num_samples as usize;
        self.channel_ptrs.as_mut_slice().iter_mut().map(move |ptr|
            // SAFETY: pointers are guaranteed to be valid by the lifetime.
            unsafe { std::slice::from_raw_parts_mut(*ptr, num_samples) })
    }

    /// Converts an Ambisonic audio buffer from one Ambisonic format to another.
    ///
    /// Steam Audio’s "native" Ambisonic format is [`AmbisonicsType::N3D`], so for best performance, keep all Ambisonic data in N3D format except when exchanging data with your audio engine.
    pub fn convert_ambisonics(
        &mut self,
        context: &Context,
        in_type: AmbisonicsType,
        out_type: AmbisonicsType,
    ) {
        unsafe {
            audionimbus_sys::iplAudioBufferConvertAmbisonics(
                context.raw_ptr(),
                in_type.into(),
                out_type.into(),
                &raw mut *self.as_ffi(),
                &raw mut *self.as_ffi(),
            );
        }
    }

    /// Converts an Ambisonic audio buffer from one Ambisonic format to another.
    ///
    /// Both audio buffers must have the same number of samples.
    ///
    /// Steam Audio’s "native" Ambisonic format is [`AmbisonicsType::N3D`], so for best performance, keep all Ambisonic data in N3D format except when exchanging data with your audio engine.
    ///
    /// # Errors
    ///
    /// Returns [`AudioBufferOperationError::TotalSampleMismatch`] if the audio buffers have different total sample counts.
    pub fn convert_ambisonics_into<T2, P2: ChannelPointers>(
        &mut self,
        context: &Context,
        in_type: AmbisonicsType,
        out_type: AmbisonicsType,
        out: &mut AudioBuffer<T2, P2>,
    ) -> Result<(), AudioBufferOperationError> {
        let self_count = self.num_channels() * self.num_samples();
        let other_count = out.num_channels() * out.num_samples();
        if self_count != other_count {
            return Err(AudioBufferOperationError::TotalSampleMismatch {
                self_count,
                other_count,
            });
        }

        unsafe {
            audionimbus_sys::iplAudioBufferConvertAmbisonics(
                context.raw_ptr(),
                in_type.into(),
                out_type.into(),
                &raw mut *self.as_ffi(),
                &raw mut *out.as_ffi(),
            );
        }

        Ok(())
    }

    pub(crate) fn as_ffi(&self) -> FFIWrapper<'_, audionimbus_sys::IPLAudioBuffer, Self> {
        let audio_buffer = audionimbus_sys::IPLAudioBuffer {
            numChannels: self.num_channels() as i32,
            numSamples: self.num_samples() as i32,
            data: self.channel_ptrs.as_slice().as_ptr().cast_mut(),
        };

        FFIWrapper::new(audio_buffer)
    }
}

impl<T: AsRef<[Sample]>> AudioBuffer<T, Vec<*mut Sample>> {
    /// Constructs an `AudioBuffer` over `data` with one channel spanning the entire data provided.
    ///
    /// # Errors
    ///
    /// - [`AudioBufferError::EmptyData`] if the `data` slice is empty.
    /// - [`AudioBufferError::InvalidNumSamples`] if `num_samples` is 0 or the data length is not divisible by `num_samples`.
    /// - [`AudioBufferError::InvalidNumChannels`] if `num_channels` is 0 or the data length is not divisible by `num_channels`.
    /// - [`AudioBufferError::FrameOutOfBounds`] if the frame is out of channel bounds.
    pub fn try_with_data(data: T) -> Result<Self, AudioBufferError> {
        Self::try_with_data_and_settings(data, AudioBufferSettings::default())
    }

    /// Constructs an `AudioBuffer` over `data` given the provided [`AudioBufferSettings`].
    ///
    /// # Errors
    ///
    /// - [`AudioBufferError::EmptyData`] if the `data` slice is empty.
    /// - [`AudioBufferError::InvalidNumSamples`] if `num_samples` is 0 or the data length is not divisible by `num_samples`.
    /// - [`AudioBufferError::InvalidNumChannels`] if `num_channels` is 0 or the data length is not divisible by `num_channels`.
    /// - [`AudioBufferError::FrameOutOfBounds`] if the frame is out of channel bounds.
    pub fn try_with_data_and_settings(
        data: T,
        settings: AudioBufferSettings,
    ) -> Result<Self, AudioBufferError> {
        let data = data.as_ref();

        if data.is_empty() {
            return Err(AudioBufferError::EmptyData);
        }

        let (num_channels, num_samples) = settings.num_channels_and_samples(data)?;
        let frame_size = settings.frame_size.unwrap_or(num_samples);
        let frame_index = settings.frame_index;

        if (frame_index + 1) * frame_size > num_samples {
            return Err(AudioBufferError::FrameOutOfBounds {
                frame_size,
                frame_index,
            });
        }

        let channel_ptrs = (0..num_channels)
            .map(|channel| {
                let index = (channel * num_samples + frame_index * frame_size) as usize;
                data[index..].as_ptr().cast_mut()
            })
            .collect();

        Ok(Self {
            num_samples: frame_size,
            channel_ptrs,
            _marker: std::marker::PhantomData,
        })
    }
}

impl<'a, T: AsRef<[Sample]>> AudioBuffer<T, &'a mut [*mut Sample]> {
    /// Constructs an `AudioBuffer` over `data` with one channel spanning the entire data provided.
    /// The `null_channel_ptrs` argument will be filled with actual channel pointers.
    ///
    /// # Errors
    ///
    /// - [`AudioBufferError::EmptyData`] if the `data` slice is empty.
    /// - [`AudioBufferError::InvalidNumSamples`] if the number of samples is 0 or the data length is not divisible by the number of samples.
    /// - [`AudioBufferError::InvalidNumChannels`] if the number of channels is 0 or the data length is not divisible by the number of channels.
    /// - [`AudioBufferError::FrameOutOfBounds`] if the frame is out of channel bounds.
    /// - [`AudioBufferError::InvalidChannelPtrs`] if the length of `null_channel_ptrs` is not equal to the number of channels.
    pub fn try_borrowed_with_data(
        data: T,
        null_channel_ptrs: &'a mut [*mut Sample],
    ) -> Result<Self, AudioBufferError> {
        Self::try_borrowed_with_data_and_settings(
            data,
            null_channel_ptrs,
            AudioBufferSettings::default(),
        )
    }

    /// Constructs an `AudioBuffer` over `data` given the provided [`AudioBufferSettings`].
    /// The `null_channel_ptrs` argument will be filled with actual channel pointers.
    ///
    /// # Errors
    ///
    /// - [`AudioBufferError::EmptyData`] if `data` is empty.
    /// - [`AudioBufferError::InvalidNumSamples`] if the number of samples is 0 or the data length is not divisible by the number of samples.
    /// - [`AudioBufferError::InvalidNumChannels`] if the number of channels is 0 or the data length is not divisible by the number of channels.
    /// - [`AudioBufferError::FrameOutOfBounds`] if the frame is out of channel bounds.
    /// - [`AudioBufferError::InvalidChannelPtrs`] if the length of `null_channel_ptrs` is not equal to the number of channels.
    pub fn try_borrowed_with_data_and_settings(
        data: T,
        null_channel_ptrs: &'a mut [*mut Sample],
        settings: AudioBufferSettings,
    ) -> Result<Self, AudioBufferError> {
        let data = data.as_ref();

        if data.is_empty() {
            return Err(AudioBufferError::EmptyData);
        }

        let (num_channels, num_samples) = settings.num_channels_and_samples(data)?;
        let frame_size = settings.frame_size.unwrap_or(num_samples);
        let frame_index = settings.frame_index;

        if (frame_index + 1) * frame_size > num_samples {
            return Err(AudioBufferError::FrameOutOfBounds {
                frame_size,
                frame_index,
            });
        }

        if null_channel_ptrs.len() as u32 != num_channels {
            return Err(AudioBufferError::InvalidChannelPtrs {
                actual: null_channel_ptrs.len() as u32,
                expected: num_channels,
            });
        }

        null_channel_ptrs
            .iter_mut()
            .enumerate()
            .for_each(|(i, channel)| {
                let index = i as u32 * num_samples + frame_index * frame_size;
                *channel = data[index as usize..].as_ptr().cast_mut();
            });

        let channel_ptrs = null_channel_ptrs;

        Ok(AudioBuffer {
            num_samples: frame_size,
            channel_ptrs,
            _marker: std::marker::PhantomData,
        })
    }
}

impl<'a> AudioBuffer<(), &'a mut [*mut Sample]> {
    /// Constructs an `AudioBuffer` from channel data `channels` and null channel pointers to be
    /// initialized.
    /// The `null_channel_ptrs` argument will be filled with actual channel pointers.
    ///
    /// # Errors
    ///
    /// - [`AudioBufferError::InvalidNumSamples`] if `channels` is empty.
    /// - [`AudioBufferError::InvalidNumChannels`] if channels contain no samples.
    /// - [`AudioBufferError::InvalidChannelPtrs`] if the length of `null_channel_ptrs` is not equal to the length of `channels`.
    pub fn try_from_slices(
        channels: &[&'a [Sample]],
        null_channel_ptrs: &'a mut [*mut Sample],
    ) -> Result<Self, AudioBufferError> {
        if channels.is_empty() {
            return Err(AudioBufferError::InvalidNumChannels { num_channels: 0 });
        }

        let num_samples = channels[0].len();
        if num_samples == 0 {
            return Err(AudioBufferError::InvalidNumSamples { num_samples: 0 });
        }

        if null_channel_ptrs.len() != channels.len() {
            return Err(AudioBufferError::InvalidChannelPtrs {
                actual: null_channel_ptrs.len() as u32,
                expected: channels.len() as u32,
            });
        }

        for (ptr, channel) in null_channel_ptrs.iter_mut().zip(channels.iter()) {
            *ptr = channel.as_ptr().cast_mut();
        }

        Ok(AudioBuffer {
            num_samples: num_samples as u32,
            channel_ptrs: null_channel_ptrs,
            _marker: std::marker::PhantomData,
        })
    }
}

/// An audio sample.
pub type Sample = f32;

/// Settings used to construct an [`AudioBuffer`].
#[derive(Default, Copy, Clone, Debug)]
pub struct AudioBufferSettings {
    /// The number of channels.
    ///
    /// If `None`, the number of channels is:
    /// - 1 if [`Self::num_samples`] is `None`.
    /// - The length of the data divided by the number of samples per channel if [`Self::num_samples`] is `Some`.
    pub num_channels: Option<u32>,

    /// The number of samples per channel.
    ///
    /// If `None`, the number of samples per channel is:
    /// - The length of the data if [`Self::num_channels`] is `None`.
    /// - The length of the data divided by the number of channels if [`Self::num_channels`] is `Some`.
    pub num_samples: Option<u32>,

    /// The size of a frame.
    ///
    /// If `None`, the frame size is the number of samples per channel.
    pub frame_size: Option<u32>,

    /// Zero-based index of the frame.
    pub frame_index: u32,
}

impl AudioBufferSettings {
    /// Creates a new [`AudioBufferSettings`] with the specified number of channels.
    /// The number of samples per channel will be inferred.
    pub fn with_num_channels(num_channels: u32) -> Self {
        Self {
            num_channels: Some(num_channels),
            ..Default::default()
        }
    }

    /// Creates a new [`AudioBufferSettings`] with the specified number of samples per channel.
    /// The number of channels will be inferred.
    pub fn with_num_samples(num_samples: u32) -> Self {
        Self {
            num_samples: Some(num_samples),
            ..Default::default()
        }
    }

    /// Creates a new [`AudioBufferSettings`] with the specified number of samples per channel and
    /// channels.
    pub fn with_num_channels_and_num_samples(num_channels: u32, num_samples: u32) -> Self {
        Self {
            num_channels: Some(num_channels),
            num_samples: Some(num_samples),
            ..Default::default()
        }
    }

    /// Returns the number of channels and the number of samples derived from these
    /// [`AudioBufferSettings`].
    ///
    /// # Errors
    ///
    /// - [`AudioBufferError::InvalidNumSamples`] if [`Self::num_samples`] is 0 or the data length is not divisible by [`Self::num_samples`].
    /// - [`AudioBufferError::InvalidNumChannels`] if [`Self::num_channels`] is 0 or the data length is not divisible by [`Self::num_channels`].
    pub fn num_channels_and_samples<T: AsRef<[Sample]>>(
        &self,
        data: T,
    ) -> Result<(u32, u32), AudioBufferError> {
        let data = data.as_ref();

        let (num_channels, num_samples) = match (self.num_channels, self.num_samples) {
            (None, None) => (1, data.len() as u32),
            (Some(num_channels), Some(num_samples)) => {
                if num_channels == 0 {
                    return Err(AudioBufferError::InvalidNumChannels { num_channels });
                }

                if num_samples == 0 || num_channels * num_samples != data.len() as u32 {
                    return Err(AudioBufferError::InvalidNumSamples { num_samples });
                }

                (num_channels, num_samples)
            }
            (Some(num_channels), None) => {
                if num_channels == 0 || !(data.len() as u32).is_multiple_of(num_channels) {
                    return Err(AudioBufferError::InvalidNumChannels { num_channels });
                }

                let num_samples = data.len() as u32 / num_channels;

                (num_channels, num_samples)
            }
            (None, Some(num_samples)) => {
                if num_samples == 0 || !(data.len() as u32).is_multiple_of(num_samples) {
                    return Err(AudioBufferError::InvalidNumSamples { num_samples });
                }

                let num_channels = data.len() as u32 / num_samples;

                (num_channels, num_samples)
            }
        };

        Ok((num_channels, num_samples))
    }
}

/// Allocates a vector of mutable pointers to later store channel pointers of an audio buffer.
///
/// # Errors
///
/// - [`AudioBufferError::InvalidNumSamples`] if `num_samples` in `settings` is 0 or the data length is not divisible by `num_samples` in `settings`.
/// - [`AudioBufferError::InvalidNumChannels`] if `num_channels` in `settings` is 0 or the data length is not divisible by `num_channels` in `settings`.
pub fn allocate_channel_ptrs<T: AsRef<[Sample]>>(
    data: T,
    settings: AudioBufferSettings,
) -> Result<Vec<*mut Sample>, AudioBufferError> {
    let (num_channels, _) = settings.num_channels_and_samples(data)?;
    let channel_ptrs = vec![std::ptr::null_mut(); num_channels as usize];
    Ok(channel_ptrs)
}

/// [`AudioBuffer`] construction errors.
#[derive(Debug, PartialEq, Eq)]
pub enum AudioBufferError {
    /// Error when trying to construct an [`AudioBuffer`] with empty data.
    EmptyData,

    /// Error when trying to construct an [`AudioBuffer`] with an invalid number of samples per
    /// channel.
    InvalidNumSamples { num_samples: u32 },

    /// Error when trying to construct an [`AudioBuffer`] with an invalid number of channels.
    InvalidNumChannels { num_channels: u32 },

    /// Error when trying to construct an [`AudioBuffer`] with an invalid length of channel pointers.
    InvalidChannelPtrs { actual: u32, expected: u32 },

    /// Error when trying to construct an [`AudioBuffer`] with a frame out of channel bounds.
    FrameOutOfBounds { frame_size: u32, frame_index: u32 },
}

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

impl std::fmt::Display for AudioBufferError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match &self {
            Self::EmptyData => write!(f, "empty audio buffer data",),
            Self::InvalidNumSamples { num_samples } => {
                write!(f, "invalid number of samples per channel: {num_samples}")
            }
            Self::InvalidNumChannels { num_channels } => {
                write!(f, "invalid number of channels: {num_channels}")
            }
            Self::InvalidChannelPtrs { actual, expected } => {
                write!(
                    f,
                    "invalid length of channel pointers: expected {expected}, got {actual}"
                )
            }
            Self::FrameOutOfBounds {
                frame_size,
                frame_index,
            } => {
                write!(
                    f,
                    "frame with index {frame_index} of size {frame_size} out of channel bounds"
                )
            }
        }
    }
}

/// [`AudioBuffer`] operation errors.
#[derive(Debug, PartialEq, Eq)]
pub enum AudioBufferOperationError {
    /// Destination slice length does not match audio buffer length.
    InterleaveLengthMismatch { dst_len: usize, expected_len: u32 },

    /// Source slice length does not match audio buffer length.
    DeinterleaveLengthMismatch { src_len: usize, expected_len: u32 },

    /// Audio buffers have mismatched number of channels.
    ChannelCountMismatch {
        self_num_channels: u32,
        other_num_channels: u32,
    },

    /// Audio buffers have mismatched number of samples.
    SampleCountMismatch {
        self_num_samples: u32,
        other_num_samples: u32,
    },

    /// Audio buffers have mismatched total sample count for conversion.
    TotalSampleMismatch { self_count: u32, other_count: u32 },
}

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

impl std::fmt::Display for AudioBufferOperationError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::InterleaveLengthMismatch {
                dst_len,
                expected_len,
            } => write!(
                f,
                "destination slice length {dst_len} does not match expected length {expected_len}"
            ),
            Self::DeinterleaveLengthMismatch {
                src_len,
                expected_len,
            } => write!(
                f,
                "source slice length {src_len} does not match expected length {expected_len}"
            ),
            Self::ChannelCountMismatch {
                self_num_channels,
                other_num_channels,
            } => write!(
                f,
                "channel count mismatch: buffer has {self_num_channels} channels, other has {other_num_channels}"
            ),
            Self::SampleCountMismatch {
                self_num_samples,
                other_num_samples,
            } => write!(
                f,
                "sample count mismatch: buffer has {self_num_samples} samples, other has {other_num_samples}"
            ),
            Self::TotalSampleMismatch {
                self_count,
                other_count,
            } => write!(
                f,
                "total sample count mismatch: buffer has {self_count} samples, other has {other_count}"
            ),
        }
    }
}

/// Returns the number of channels required for a given ambisonics order.
///
/// The channel count is given by:
///
/// ```text
/// (order + 1)²
/// ```
///
/// # Examples
///
/// ```
/// # use audionimbus::*;
/// const FOA: u32 = num_ambisonics_channels(1);
/// assert_eq!(FOA, 4);
///
/// const HOA3: u32 = num_ambisonics_channels(3);
/// assert_eq!(HOA3, 16);
/// ```
pub const fn num_ambisonics_channels(order: u32) -> u32 {
    (order + 1) * (order + 1)
}

/// Describes the channel count requirement for an audio buffer.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum ChannelRequirement {
    /// The buffer must have exactly this many channels.
    Exactly(u32),

    /// The buffer must have at least this many channels.
    AtLeast(u32),

    /// The buffer must have a channel count within the given inclusive range.
    Range { min: u32, max: u32 },
}

impl ChannelRequirement {
    /// Returns whether a number of channels satisfies this requirement.
    pub fn is_satisfied_by(&self, actual: u32) -> bool {
        match *self {
            Self::Exactly(num_channels) => actual == num_channels,
            Self::AtLeast(num_channels) => actual >= num_channels,
            Self::Range { min, max } => (min..=max).contains(&actual),
        }
    }
}

impl std::fmt::Display for ChannelRequirement {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Exactly(num_channels) => {
                write!(f, "exactly {num_channels}")
            }
            Self::AtLeast(num_channels) => {
                write!(f, "at least {num_channels}")
            }
            Self::Range { min, max } => {
                write!(f, "between {min} and {max} (inclusive)")
            }
        }
    }
}

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

    mod try_new {
        use super::*;

        #[test]
        fn test_valid() {
            let mut data = vec![0.5f32; 2048];
            let (left, right) = data.split_at_mut(1024);
            let mut channel_ptrs: Vec<*mut f32> = vec![left.as_mut_ptr(), right.as_mut_ptr()];
            let result =
                unsafe { AudioBuffer::<f32, &mut Vec<*mut f32>>::try_new(&mut channel_ptrs, 1024) };
            assert!(result.is_ok());
        }

        #[test]
        fn test_invalid_num_samples() {
            let channel_ptrs = vec![std::ptr::null_mut(); 2];
            let result = unsafe { AudioBuffer::<(), _>::try_new(channel_ptrs, 0) };
            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumSamples { num_samples: 0 }),
            ));
        }

        #[test]
        fn test_invalid_num_channels() {
            let channel_ptrs: Vec<*mut f32> = vec![];
            let result = unsafe { AudioBuffer::<(), _>::try_new(channel_ptrs, 1024) };
            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumChannels { num_channels: 0 }),
            ));
        }
    }

    mod try_with_data {
        use super::*;

        #[test]
        fn test_valid() {
            let empty_data: Vec<f32> = vec![0.5; 1024];
            assert!(AudioBuffer::try_with_data(&empty_data).is_ok());
        }

        #[test]
        fn test_empty_data() {
            let empty_data: Vec<f32> = vec![];
            assert!(matches!(
                AudioBuffer::try_with_data(&empty_data),
                Err(AudioBufferError::EmptyData),
            ));
        }
    }

    mod try_with_data_and_settings {
        use super::*;

        #[test]
        fn test_valid_default_settings() {
            let data: Vec<Sample> = vec![0.0; 10];
            let settings = AudioBufferSettings::default();

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(result.is_ok());
        }

        #[test]
        fn test_valid_settings() {
            let data: Vec<Sample> = vec![0.0; 6];
            let settings = AudioBufferSettings {
                num_channels: Some(2),
                num_samples: Some(3),
                ..Default::default()
            };

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(result.is_ok());
        }

        #[test]
        fn test_valid_settings_with_frame_size() {
            let data: Vec<Sample> = vec![0.0; 10];
            let settings = AudioBufferSettings {
                num_channels: Some(2),
                num_samples: Some(5),
                frame_size: Some(3),
                frame_index: 0,
            };

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(result.is_ok());
        }

        #[test]
        fn test_valid_multiple_channels_and_samples() {
            let data: Vec<Sample> = vec![0.0; 12];
            let settings = AudioBufferSettings {
                num_channels: Some(3),
                num_samples: Some(4),
                ..Default::default()
            };

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(result.is_ok());
        }

        #[test]
        fn test_empty_data() {
            let data: Vec<Sample> = vec![];
            let settings = AudioBufferSettings::default();

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(matches!(result, Err(AudioBufferError::EmptyData)));
        }

        #[test]
        fn test_invalid_num_channels_zero() {
            let data: Vec<Sample> = vec![0.0; 10];
            let settings = AudioBufferSettings {
                num_channels: Some(0),
                num_samples: Some(5),
                frame_size: None,
                frame_index: 0,
            };

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumChannels { num_channels: 0 })
            ));
        }

        #[test]
        fn test_invalid_num_samples_zero() {
            let data: Vec<Sample> = vec![0.0; 10];
            let settings = AudioBufferSettings {
                num_channels: Some(2),
                num_samples: Some(0),
                frame_size: None,
                frame_index: 0,
            };

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumSamples { num_samples: 0 })
            ));
        }

        #[test]
        fn test_invalid_num_samples_not_divisible() {
            let data: Vec<Sample> = vec![0.0; 10];
            let settings = AudioBufferSettings {
                num_channels: Some(3),
                num_samples: Some(3),
                frame_size: None,
                frame_index: 0,
            };

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumSamples { num_samples: 3 })
            ));
        }

        #[test]
        fn test_frame_out_of_bounds() {
            let data: Vec<Sample> = vec![0.0; 10];
            let settings = AudioBufferSettings {
                num_channels: Some(2),
                num_samples: Some(5),
                frame_size: Some(3),
                frame_index: 1,
            };

            let result = AudioBuffer::try_with_data_and_settings(&data, settings);
            assert!(matches!(
                result,
                Err(AudioBufferError::FrameOutOfBounds {
                    frame_size: 3,
                    frame_index: 1
                })
            ));
        }
    }

    mod try_new_borrowed {
        use super::*;

        #[test]
        fn test_valid_construction() {
            let mut channel1 = vec![1.0, 2.0, 3.0];
            let mut channel2 = vec![4.0, 5.0, 6.0];
            let mut ptrs = vec![channel1.as_mut_ptr(), channel2.as_mut_ptr()];

            let buffer = unsafe { AudioBuffer::<&[Sample], _>::try_new(&mut ptrs, 3) }.unwrap();
            assert_eq!(buffer.num_channels(), 2);
            assert_eq!(buffer.num_samples(), 3);

            let channels: Vec<&[Sample]> = buffer.channels().collect();
            assert_eq!(channels[0], &[1.0, 2.0, 3.0]);
            assert_eq!(channels[1], &[4.0, 5.0, 6.0]);
        }

        #[test]
        fn test_empty_channel_ptrs() {
            let mut ptrs: Vec<*mut Sample> = vec![];

            let result = unsafe { AudioBuffer::<&[Sample], _>::try_new(&mut ptrs, 100) };

            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumChannels { num_channels: 0 })
            ));
        }

        #[test]
        fn test_zero_num_samples() {
            let mut data = vec![1.0, 2.0, 3.0];
            let mut ptrs = vec![data.as_mut_ptr()];

            let result = unsafe { AudioBuffer::<&[Sample], _>::try_new(&mut ptrs, 0) };

            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumSamples { num_samples: 0 })
            ));
        }
    }

    mod try_borrowed_with_data_and_settings {
        use super::*;

        #[test]
        fn test_valid_construction() {
            let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
            let settings = AudioBufferSettings::with_num_channels(2);
            let mut channel_ptrs = allocate_channel_ptrs(&data, settings).unwrap();

            let buffer = AudioBuffer::try_borrowed_with_data_and_settings(
                &data,
                &mut channel_ptrs,
                settings,
            )
            .unwrap();
            assert_eq!(buffer.num_channels(), 2);
            assert_eq!(buffer.num_samples(), 3);

            let channels: Vec<&[Sample]> = buffer.channels().collect();
            assert_eq!(channels[0], &[1.0, 2.0, 3.0]);
            assert_eq!(channels[1], &[4.0, 5.0, 6.0]);
        }

        #[test]
        fn test_invalid_channel_ptrs() {
            let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
            let settings = AudioBufferSettings::with_num_channels(2);
            let mut channel_ptrs = [std::ptr::null_mut(); 3];

            let result = AudioBuffer::try_borrowed_with_data_and_settings(
                &data,
                &mut channel_ptrs,
                settings,
            );

            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidChannelPtrs {
                    actual: 3,
                    expected: 2
                })
            ));
        }
    }

    mod try_from_slices {
        use super::*;

        #[test]
        fn test_valid_construction() {
            let channel_0 = vec![1.0, 2.0, 3.0, 4.0];
            let channel_1 = vec![5.0, 6.0, 7.0, 8.0];

            let channels: &[&[Sample]] = &[&channel_0, &channel_1];
            let mut channel_ptrs = vec![std::ptr::null_mut(); 2];

            let audio_buffer = AudioBuffer::try_from_slices(channels, &mut channel_ptrs).unwrap();

            assert_eq!(audio_buffer.num_channels(), 2);
            assert_eq!(audio_buffer.num_samples(), 4);

            let mut iter = audio_buffer.channels();
            assert_eq!(iter.next().unwrap(), &[1.0, 2.0, 3.0, 4.0]);
            assert_eq!(iter.next().unwrap(), &[5.0, 6.0, 7.0, 8.0]);
            assert!(iter.next().is_none());
        }

        #[test]
        fn test_empty_channels() {
            let empty_channels: &[&[Sample]] = &[];
            let mut channel_ptrs = vec![];
            let result = AudioBuffer::try_from_slices(empty_channels, &mut channel_ptrs);
            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumChannels { num_channels: 0 })
            ));
        }

        #[test]
        fn test_mismatched_channel_ptrs_length() {
            let channel_0 = vec![1.0, 2.0, 3.0];
            let channel_1 = vec![4.0, 5.0, 6.0];
            let channels: &[&[Sample]] = &[&channel_0, &channel_1];

            let mut channel_ptrs_wrong_size = vec![std::ptr::null_mut(); 1];
            let result = AudioBuffer::try_from_slices(channels, &mut channel_ptrs_wrong_size);
            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidChannelPtrs {
                    actual: 1,
                    expected: 2
                })
            ));
        }

        #[test]
        fn test_empty_channel_data() {
            let empty_channel = vec![];
            let channels_with_empty: &[&[Sample]] = &[&empty_channel];
            let mut channel_ptrs = vec![std::ptr::null_mut(); 1];
            let result = AudioBuffer::try_from_slices(channels_with_empty, &mut channel_ptrs);
            assert!(matches!(
                result,
                Err(AudioBufferError::InvalidNumSamples { num_samples: 0 })
            ));
        }
    }

    mod channels_iteration {
        use super::*;

        #[test]
        fn test_channels_iter() {
            let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
            let buffer = AudioBuffer::try_with_data_and_settings(
                &data,
                AudioBufferSettings::with_num_channels(2),
            )
            .unwrap();

            let channels: Vec<&[Sample]> = buffer.channels().collect();
            assert_eq!(channels.len(), 2);
            assert_eq!(channels[0], &[1.0, 2.0, 3.0]);
            assert_eq!(channels[1], &[4.0, 5.0, 6.0]);
        }

        #[test]
        fn test_channels_mut_iter() {
            let mut data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
            let mut buffer = AudioBuffer::try_with_data_and_settings(
                &mut data,
                AudioBufferSettings::with_num_channels(2),
            )
            .unwrap();

            for channel in buffer.channels_mut() {
                for sample in channel.iter_mut() {
                    *sample *= 2.0;
                }
            }

            assert_eq!(data, vec![2.0, 4.0, 6.0, 8.0, 10.0, 12.0]);
        }
    }

    mod audio_buffer_settings {
        use super::*;

        #[test]
        fn test_with_num_channels() {
            let settings = AudioBufferSettings::with_num_channels(4);
            assert_eq!(settings.num_channels, Some(4));
            assert_eq!(settings.num_samples, None);
        }

        #[test]
        fn test_with_num_samples() {
            let settings = AudioBufferSettings::with_num_samples(1024);
            assert_eq!(settings.num_channels, None);
            assert_eq!(settings.num_samples, Some(1024));
        }

        #[test]
        fn test_with_num_channels_and_num_samples() {
            let settings = AudioBufferSettings::with_num_channels_and_num_samples(2, 512);
            assert_eq!(settings.num_channels, Some(2));
            assert_eq!(settings.num_samples, Some(512));
        }

        #[test]
        fn test_num_channels_and_samples_inference() {
            let data = vec![0.0; 12];

            // Infer both from data length
            let settings = AudioBufferSettings::default();
            let (channels, samples) = settings.num_channels_and_samples(&data).unwrap();
            assert_eq!(channels, 1);
            assert_eq!(samples, 12);

            // Infer samples from channels
            let settings = AudioBufferSettings::with_num_channels(3);
            let (channels, samples) = settings.num_channels_and_samples(&data).unwrap();
            assert_eq!(channels, 3);
            assert_eq!(samples, 4);

            // Infer channels from samples
            let settings = AudioBufferSettings::with_num_samples(4);
            let (channels, samples) = settings.num_channels_and_samples(&data).unwrap();
            assert_eq!(channels, 3);
            assert_eq!(samples, 4);
        }
    }

    mod allocate_channel_ptrs {
        use super::*;

        #[test]
        fn test_valid() {
            let data = vec![0.0; 12];
            let settings = AudioBufferSettings::with_num_channels(3);
            let ptrs = allocate_channel_ptrs(&data, settings).unwrap();

            assert_eq!(ptrs.len(), 3);
            assert!(ptrs.iter().all(|&ptr| ptr.is_null()));
        }

        #[test]
        fn test_invalid() {
            let data = vec![0.0; 10];
            let settings = AudioBufferSettings {
                num_channels: Some(3),
                num_samples: Some(3),
                ..Default::default()
            };

            let result = allocate_channel_ptrs(&data, settings);
            assert!(result.is_err());
        }
    }

    mod channel_requirement {
        use super::*;

        #[test]
        fn test_is_satisfied_by() {
            assert!(ChannelRequirement::Exactly(2).is_satisfied_by(2));
            assert!(!ChannelRequirement::Exactly(2).is_satisfied_by(1));
            assert!(ChannelRequirement::AtLeast(2).is_satisfied_by(3));
            assert!(!ChannelRequirement::AtLeast(2).is_satisfied_by(1));
            assert!(ChannelRequirement::Range { min: 1, max: 4 }.is_satisfied_by(3));
            assert!(!ChannelRequirement::Range { min: 1, max: 4 }.is_satisfied_by(5));
        }
    }

    mod mix {
        use super::*;

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

            let source = vec![0.5; 100];
            let source_buffer = AudioBuffer::try_with_data(&source).unwrap();

            let mut mix = vec![0.5; 100];
            let mut mix_buffer = AudioBuffer::try_with_data(&mut mix).unwrap();

            assert!(mix_buffer.mix(&context, &source_buffer).is_ok());
        }

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

            let source = vec![0.5; 100];
            let source_buffer = AudioBuffer::try_with_data(&source).unwrap();

            let mut mix = vec![0.5; 200];
            let mut mix_buffer = AudioBuffer::try_with_data_and_settings(
                &mut mix,
                AudioBufferSettings::with_num_channels(2),
            )
            .unwrap();

            assert_eq!(
                mix_buffer.mix(&context, &source_buffer),
                Err(AudioBufferOperationError::ChannelCountMismatch {
                    self_num_channels: 2,
                    other_num_channels: 1
                }),
            );
        }

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

            let source = vec![0.0; 512];
            let source_buffer = AudioBuffer::try_with_data(&source).unwrap();

            let mix = vec![0.0; 1024];
            let mut mix_buffer = AudioBuffer::try_with_data(&mix).unwrap();

            assert_eq!(
                mix_buffer.mix(&context, &source_buffer),
                Err(AudioBufferOperationError::SampleCountMismatch {
                    self_num_samples: 1024,
                    other_num_samples: 512,
                }),
            );
        }
    }

    mod downmix {
        use super::*;

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

            let input = vec![0.5; 200];
            let input_buffer = AudioBuffer::try_with_data(&input).unwrap();

            let mut output = vec![0.5; 200];
            let mut output_buffer = AudioBuffer::try_with_data(&mut output).unwrap();

            assert!(output_buffer.downmix(&context, &input_buffer).is_ok());
        }

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

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

            let mut output = vec![0.5; 50];
            let mut output_buffer = AudioBuffer::try_with_data(&mut output).unwrap();

            assert_eq!(
                output_buffer.downmix(&context, &input_buffer),
                Err(AudioBufferOperationError::SampleCountMismatch {
                    self_num_samples: 50,
                    other_num_samples: 100
                }),
            );
        }
    }

    mod interleave {
        use super::*;

        #[test]
        fn test_valid() {
            let context = Context::default();
            let samples = vec![0.0; 1024];
            let buffer = AudioBuffer::try_with_data(&samples).unwrap();

            let mut dst = vec![0.0; 1024];
            assert!(buffer.interleave(&context, &mut dst).is_ok());
        }

        #[test]
        fn test_length_mismatch() {
            let context = Context::default();
            let samples = vec![0.0; 1024];
            let buffer = AudioBuffer::try_with_data(&samples).unwrap();

            let mut dst = vec![0.0; 512];
            assert_eq!(
                buffer.interleave(&context, &mut dst),
                Err(AudioBufferOperationError::InterleaveLengthMismatch {
                    dst_len: 512,
                    expected_len: 1024,
                }),
            );
        }
    }

    mod deinterleave {
        use super::*;

        #[test]
        fn test_valid() {
            let context = Context::default();
            let samples = vec![0.0; 1024];
            let mut buffer = AudioBuffer::try_with_data(&samples).unwrap();

            let src = vec![0.0; 1024];
            assert!(buffer.deinterleave(&context, &src).is_ok());
        }

        #[test]
        fn test_length_mismatch() {
            let context = Context::default();
            let samples = vec![0.0; 1024];
            let mut buffer = AudioBuffer::try_with_data(&samples).unwrap();

            let src = vec![0.0; 2048];
            assert_eq!(
                buffer.deinterleave(&context, &src),
                Err(AudioBufferOperationError::DeinterleaveLengthMismatch {
                    src_len: 2048,
                    expected_len: 1024,
                }),
            );
        }
    }

    mod convert_ambisonics {
        use super::*;

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

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

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

            assert!(buffer1
                .convert_ambisonics_into(
                    &context,
                    AmbisonicsType::N3D,
                    AmbisonicsType::FuMa,
                    &mut buffer2,
                )
                .is_ok());
        }

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

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

            let samples2 = vec![0.0; 512];
            let mut buffer2 = AudioBuffer::try_with_data_and_settings(
                &samples2,
                AudioBufferSettings::with_num_channels(4),
            )
            .unwrap();

            assert_eq!(
                buffer1.convert_ambisonics_into(
                    &context,
                    AmbisonicsType::N3D,
                    AmbisonicsType::FuMa,
                    &mut buffer2,
                ),
                Err(AudioBufferOperationError::TotalSampleMismatch {
                    self_count: 1024,
                    other_count: 512,
                }),
            );
        }
    }
}