Skip to main content

rtci_media/audio/
buffer.rs

1//! Multi-channel audio buffers.
2//!
3//! A buffer is a flat slice of samples plus a [`BufferInfo`](crate::audio::buffer::BufferInfo) recording how many channels and
4//! frames it holds. The layout is a type parameter: [`Interleaved`](crate::audio::buffer::layout::Interleaved) stores
5//! one sample per channel per frame (what most audio APIs use), while
6//! [`Deinterleaved`](crate::audio::buffer::layout::Deinterleaved) stores each channel contiguously.
7//!
8//! Encoding a layout in the type rather than a runtime flag means indexing is resolved at compile
9//! time and the two cannot be mixed up. [`FromBytes`](crate::audio::buffer::FromBytes) and [`ToByteBufferRef`](crate::audio::buffer::ToByteBufferRef) convert to and from
10//! raw bytes in a caller-chosen endianness.
11/// Channel and frame counts for a buffer.
12pub mod info;
13/// The interleaved and deinterleaved buffer layouts.
14pub mod layout;
15
16use std::mem::{ManuallyDrop, MaybeUninit};
17use std::ops::Range;
18
19use byteorder::ByteOrder;
20pub use info::BufferInfo;
21pub use layout::BufferLayout;
22use layout::{Deinterleaved, Interleaved};
23use thiserror::Error;
24
25/// Decodes a buffer from raw little- or big-endian bytes.
26///
27/// `L` is the [`BufferLayout`] the decoded samples are arranged in.
28pub trait FromBytes<L>: Sized {
29    /// The error type produced by a failed conversion.
30    type Error;
31
32    /// Decodes `channels` channels of samples from `bytes`, reading in byte order `B`.
33    ///
34    /// # Errors
35    ///
36    /// Fails if `bytes` is too short for a whole number of frames.
37    fn from_bytes<B: ByteOrder>(bytes: &[u8], channels: usize) -> Result<Self, Self::Error>;
38}
39
40/// Encodes a buffer into raw bytes in a caller-chosen endianness.
41pub trait ToByteBufferRef<L>: Sized {
42    /// The error type produced by a failed conversion.
43    type Error;
44
45    /// The number of bytes [`Self::to_bytes`] will write.
46    fn bytes_len(&self);
47    /// Encodes the buffer into `bytes` in byte order `B`, returning the bytes written.
48    ///
49    /// # Errors
50    ///
51    /// Fails if `bytes` is too short.
52    fn to_bytes<B: ByteOrder>(
53        &self,
54        bytes: &mut [u8],
55        channels: usize,
56    ) -> Result<usize, Self::Error>;
57}
58
59#[derive(Debug, Error, PartialEq, Eq)]
60/// Errors from converting between buffers and raw bytes.
61#[non_exhaustive]
62pub enum Error {
63    #[error("Unexpected end of buffer: (expected: {expected}, actual: {actual})")]
64    /// The byte slice was too short to hold the expected number of samples.
65    UnexpectedEndOfBuffer {
66        /// Bytes required.
67        expected: usize,
68        /// Bytes available.
69        actual: usize,
70    },
71}
72
73#[derive(Eq, PartialEq, Clone, Debug)]
74/// A borrowed view of multi-channel audio: samples of type `T` in layout `L`.
75pub struct BufferRef<'a, T, L> {
76    samples: &'a [T],
77    info: BufferInfo<L>,
78}
79
80impl<'a, T, L> BufferRef<'a, T, L> {
81    /// Wraps `samples` as `channels` interleaved or deinterleaved channels.
82    ///
83    /// The frame count is derived from the slice length, which must divide evenly by `channels`.
84    pub fn new(samples: &'a [T], channels: usize) -> Self {
85        debug_assert_eq!(samples.len() % channels, 0);
86        let info = {
87            let frames = samples.len() / channels;
88            BufferInfo::new(channels, frames)
89        };
90        Self { samples, info }
91    }
92}
93
94/// Buffer multi-channel interlaced Audio.
95#[derive(Eq, PartialEq, Clone, Debug)]
96pub struct Buffer<T, L> {
97    samples: Vec<T>,
98    info: BufferInfo<L>,
99}
100
101impl<T, L> Buffer<T, L> {
102    /// Takes ownership of `samples` as `channels` channels.
103    ///
104    /// The frame count is derived from the length, which must divide evenly by `channels`.
105    pub fn new(samples: Vec<T>, channels: usize) -> Self {
106        debug_assert_eq!(samples.len() % channels, 0);
107        let info = {
108            let frames = samples.len() / channels;
109            BufferInfo::new(channels, frames)
110        };
111        Self { samples, info }
112    }
113
114    /// Borrows the whole buffer as a [`BufferRef`].
115    pub fn as_ref(&'_ self) -> BufferRef<'_, T, L> {
116        BufferRef {
117            samples: &self.samples[..],
118            info: self.info,
119        }
120    }
121
122    /// Borrows a sample range of the buffer as a [`BufferRef`].
123    pub fn sub_range(&'_ self, range: Range<usize>) -> BufferRef<'_, T, L> {
124        let samples_len = range.len();
125        let samples = &self.samples[range];
126        let info = {
127            let channels = self.info.channels();
128            assert_eq!(samples_len % channels, 0);
129            let frames = samples_len / channels;
130            BufferInfo::new(channels, frames)
131        };
132        BufferRef { samples, info }
133    }
134}
135
136impl<T> From<Buffer<T, Deinterleaved>> for Buffer<T, Interleaved>
137where
138    T: Default + Copy,
139{
140    fn from(buffer: Buffer<T, Deinterleaved>) -> Self {
141        Self::from(buffer.as_ref())
142    }
143}
144
145impl<'a, T> From<BufferRef<'a, T, Deinterleaved>> for Buffer<T, Interleaved>
146where
147    T: Default + Copy,
148{
149    fn from(buffer: BufferRef<'a, T, Deinterleaved>) -> Self {
150        // Writing into a vec of uninitialized `samples` is about 10% faster than
151        // cloning it or creating a default-initialized one and over-writing it.
152        //
153        // # Safety
154        //
155        // The performance boost comes with a cost though:
156        // At the end of the block each and every single item in
157        // `samples` needs to have been initialized, or else you get UB!
158        let samples = {
159            // Create a vec of uninitialized samples.
160            let mut samples: Vec<MaybeUninit<T>> =
161                vec![MaybeUninit::uninit(); buffer.samples.len()];
162
163            // Initialize all of its values:
164            layout::interleaved_by(
165                buffer.samples,
166                &mut samples[..],
167                buffer.info.channels(),
168                |sample| MaybeUninit::new(*sample),
169            );
170
171            // Transmute the vec to the initialized type.
172            unsafe { std::mem::transmute::<Vec<MaybeUninit<T>>, Vec<T>>(samples) }
173        };
174
175        let info = buffer.info.into();
176        Self { samples, info }
177    }
178}
179
180impl<T> From<Buffer<T, Interleaved>> for Buffer<T, Deinterleaved>
181where
182    T: Default + Copy,
183{
184    fn from(buffer: Buffer<T, Interleaved>) -> Self {
185        Self::from(buffer.as_ref())
186    }
187}
188
189impl<'a, T> From<BufferRef<'a, T, Interleaved>> for Buffer<T, Deinterleaved>
190where
191    T: Default + Copy,
192{
193    fn from(buffer: BufferRef<'a, T, Interleaved>) -> Self {
194        // Writing into a vec of uninitialized `samples` is about 10% faster than
195        // cloning it or creating a default-initialized one and over-writing it.
196        //
197        // # Safety
198        //
199        // The performance boost comes with a cost though:
200        // At the end of the block each and every single item in
201        // `samples` needs to have been initialized, or else you get UB!
202        let samples = {
203            // Create a vec of uninitialized samples.
204            let mut samples: Vec<MaybeUninit<T>> =
205                vec![MaybeUninit::uninit(); buffer.samples.len()];
206
207            // Initialize the vec's values:
208            layout::deinterleaved_by(
209                buffer.samples,
210                &mut samples[..],
211                buffer.info.channels(),
212                |sample| MaybeUninit::new(*sample),
213            );
214
215            // Everything is initialized. Transmute the vec to the initialized type.
216            unsafe { std::mem::transmute::<Vec<MaybeUninit<T>>, Vec<T>>(samples) }
217        };
218
219        let info = buffer.info.into();
220        Self { samples, info }
221    }
222}
223
224impl FromBytes<Interleaved> for Buffer<i16, Interleaved> {
225    type Error = ();
226
227    fn from_bytes<B: ByteOrder>(bytes: &[u8], channels: usize) -> Result<Self, Self::Error> {
228        const STRIDE: usize = std::mem::size_of::<i16>();
229        assert_eq!(bytes.len() % STRIDE, 0);
230
231        let chunks = {
232            let chunks_ptr = bytes.as_ptr() as *const [u8; STRIDE];
233            let chunks_len = bytes.len() / STRIDE;
234            unsafe { std::slice::from_raw_parts(chunks_ptr, chunks_len) }
235        };
236
237        let samples: Vec<_> = chunks.iter().map(|chunk| B::read_i16(&chunk[..])).collect();
238
239        let info = {
240            let frames = samples.len() / channels;
241            BufferInfo::new(channels, frames)
242        };
243        Ok(Self { samples, info })
244    }
245}
246
247impl FromBytes<Deinterleaved> for Buffer<i16, Interleaved> {
248    type Error = ();
249
250    fn from_bytes<B: ByteOrder>(bytes: &[u8], channels: usize) -> Result<Self, Self::Error> {
251        const STRIDE: usize = std::mem::size_of::<i16>();
252        assert_eq!(bytes.len() % STRIDE, 0);
253
254        let chunks = {
255            let chunks_ptr = bytes.as_ptr() as *const [u8; STRIDE];
256            let chunks_len = bytes.len() / STRIDE;
257            unsafe { std::slice::from_raw_parts(chunks_ptr, chunks_len) }
258        };
259
260        // Writing into a vec of uninitialized `samples` is about 10% faster than
261        // cloning it or creating a default-initialized one and over-writing it.
262        //
263        // # Safety
264        //
265        // The performance boost comes with a cost though:
266        // At the end of the block each and every single item in
267        // `samples` needs to have been initialized, or else you get UB!
268        let samples = unsafe {
269            init_vec(chunks.len(), |samples| {
270                layout::interleaved_by(chunks, samples, channels, |chunk| {
271                    MaybeUninit::new(B::read_i16(&chunk[..]))
272                });
273            })
274        };
275
276        let info = {
277            let frames = samples.len() / channels;
278            BufferInfo::new(channels, frames)
279        };
280        Ok(Self { samples, info })
281    }
282}
283
284impl FromBytes<Deinterleaved> for Buffer<i16, Deinterleaved> {
285    type Error = ();
286
287    fn from_bytes<B: ByteOrder>(bytes: &[u8], channels: usize) -> Result<Self, Self::Error> {
288        const STRIDE: usize = std::mem::size_of::<i16>();
289        assert_eq!(bytes.len() % STRIDE, 0);
290
291        let chunks = {
292            let chunks_ptr = bytes.as_ptr() as *const [u8; STRIDE];
293            let chunks_len = bytes.len() / STRIDE;
294            unsafe { std::slice::from_raw_parts(chunks_ptr, chunks_len) }
295        };
296
297        let samples: Vec<_> = chunks.iter().map(|chunk| B::read_i16(&chunk[..])).collect();
298
299        let info = {
300            let frames = samples.len() / channels;
301            BufferInfo::new(channels, frames)
302        };
303        Ok(Self { samples, info })
304    }
305}
306
307impl FromBytes<Interleaved> for Buffer<i16, Deinterleaved> {
308    type Error = ();
309
310    fn from_bytes<B: ByteOrder>(bytes: &[u8], channels: usize) -> Result<Self, Self::Error> {
311        const STRIDE: usize = std::mem::size_of::<i16>();
312        assert_eq!(bytes.len() % STRIDE, 0);
313
314        let chunks = {
315            let chunks_ptr = bytes.as_ptr() as *const [u8; STRIDE];
316            let chunks_len = bytes.len() / STRIDE;
317            unsafe { std::slice::from_raw_parts(chunks_ptr, chunks_len) }
318        };
319
320        // Writing into a vec of uninitialized `samples` is about 10% faster than
321        // cloning it or creating a default-initialized one and over-writing it.
322        //
323        // # Safety
324        //
325        // The performance boost comes with a cost though:
326        // At the end of the block each and every single item in
327        // `samples` needs to have been initialized, or else you get UB!
328        let samples = unsafe {
329            init_vec(chunks.len(), |samples| {
330                layout::deinterleaved_by(chunks, samples, channels, |chunk| {
331                    MaybeUninit::new(B::read_i16(&chunk[..]))
332                });
333            })
334        };
335
336        let info = {
337            let frames = samples.len() / channels;
338            BufferInfo::new(channels, frames)
339        };
340        Ok(Self { samples, info })
341    }
342}
343
344/// Creates a vec with deferred initialization.
345///
346/// # Safety
347///
348/// The closure `f` MUST initialize every single item in the provided slice.
349unsafe fn init_vec<T, F>(len: usize, f: F) -> Vec<T>
350where
351    MaybeUninit<T>: Clone,
352    F: FnOnce(&mut [MaybeUninit<T>]),
353{
354    unsafe {
355        // Create a vec of uninitialized values.
356        let mut vec: Vec<MaybeUninit<T>> = vec![MaybeUninit::uninit(); len];
357
358        // Initialize values:
359        f(&mut vec[..]);
360
361        // Take owner-ship away from `vec`:
362        let mut manually_drop: ManuallyDrop<_> = ManuallyDrop::new(vec);
363
364        // Create vec of proper type from `vec`'s raw parts.
365        let ptr = manually_drop.as_mut_ptr() as *mut T;
366        let len = manually_drop.len();
367        let cap = manually_drop.capacity();
368        Vec::from_raw_parts(ptr, len, cap)
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use byteorder::NativeEndian;
375
376    use super::*;
377
378    #[test]
379    fn deinterleaved_from_interleaved() {
380        let channels = 3;
381
382        let input_samples: Vec<i32> = vec![0, 5, 10, 1, 6, 11, 2, 7, 12, 3, 8, 13, 4, 9, 14];
383        let input: Buffer<i32, Interleaved> = Buffer::new(input_samples, channels);
384
385        let output = Buffer::<i32, Deinterleaved>::from(input);
386
387        let actual = output.samples;
388        let expected = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
389
390        assert_eq!(actual, expected);
391    }
392
393    #[test]
394    fn interleaved_from_deinterleaved() {
395        let channels = 3;
396
397        let input_samples: Vec<i32> = vec![0, 3, 6, 9, 12, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14];
398        let input: Buffer<i32, Deinterleaved> = Buffer::new(input_samples, channels);
399
400        let output = Buffer::<i32, Interleaved>::from(input);
401
402        let actual = output.samples;
403        let expected = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
404
405        assert_eq!(actual, expected);
406    }
407
408    #[test]
409    fn deinterleaved_from_deinterleaved_bytes() {
410        let channels = 3;
411        let stride = 2;
412
413        let input_samples: Vec<i16> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
414        let input_bytes: &[u8] = {
415            let bytes_ptr = input_samples.as_ptr() as *const u8;
416            let bytes_len = input_samples.len() * stride;
417            unsafe { std::slice::from_raw_parts(bytes_ptr, bytes_len) }
418        };
419
420        let output: Buffer<i16, Deinterleaved> =
421            FromBytes::<Deinterleaved>::from_bytes::<NativeEndian>(input_bytes, channels).unwrap();
422
423        let actual = output.samples;
424        let expected = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
425
426        assert_eq!(actual, expected);
427    }
428
429    #[test]
430    fn deinterleaved_from_interleaved_bytes() {
431        let channels = 3;
432        let stride = 2;
433
434        let input_samples: Vec<i16> = vec![0, 5, 10, 1, 6, 11, 2, 7, 12, 3, 8, 13, 4, 9, 14];
435        let input_bytes: &[u8] = {
436            let bytes_ptr = input_samples.as_ptr() as *const u8;
437            let bytes_len = input_samples.len() * stride;
438            unsafe { std::slice::from_raw_parts(bytes_ptr, bytes_len) }
439        };
440
441        let output: Buffer<i16, Deinterleaved> =
442            FromBytes::<Interleaved>::from_bytes::<NativeEndian>(input_bytes, channels).unwrap();
443
444        let actual = output.samples;
445        let expected = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
446
447        assert_eq!(actual, expected);
448    }
449
450    #[test]
451    fn interleaved_from_interleaved_bytes() {
452        let channels = 3;
453        let stride = 2;
454
455        let input_samples: Vec<i16> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
456        let input_bytes: &[u8] = {
457            let bytes_ptr = input_samples.as_ptr() as *const u8;
458            let bytes_len = input_samples.len() * stride;
459            unsafe { std::slice::from_raw_parts(bytes_ptr, bytes_len) }
460        };
461
462        let output: Buffer<i16, Interleaved> =
463            FromBytes::<Interleaved>::from_bytes::<NativeEndian>(input_bytes, channels).unwrap();
464
465        let actual = output.samples;
466        let expected = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
467
468        assert_eq!(actual, expected);
469    }
470
471    #[test]
472    fn interleaved_from_deinterleaved_bytes() {
473        let channels = 3;
474        let stride = 2;
475
476        let input_samples: Vec<i16> = vec![0, 3, 6, 9, 12, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14];
477        let input_bytes: &[u8] = {
478            let bytes_ptr = input_samples.as_ptr() as *const u8;
479            let bytes_len = input_samples.len() * stride;
480            unsafe { std::slice::from_raw_parts(bytes_ptr, bytes_len) }
481        };
482
483        let output: Buffer<i16, Interleaved> =
484            FromBytes::<Deinterleaved>::from_bytes::<NativeEndian>(input_bytes, channels).unwrap();
485
486        let actual = output.samples;
487        let expected = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
488
489        assert_eq!(actual, expected);
490    }
491}