audio/
utils.rs

1use core::ptr;
2
3/// Utility functions to copy a channel in-place in a sequential audio buffer
4/// from one place to another.
5///
6/// # Safety
7///
8/// Caller has to ensure that the `data` pointer points to sequential memory
9/// with the correct topology and initialized frame count.
10pub(crate) unsafe fn copy_channels_sequential<T>(
11    data: ptr::NonNull<T>,
12    channels: usize,
13    frames: usize,
14    from: usize,
15    to: usize,
16) where
17    T: Copy,
18{
19    assert! {
20        from < channels,
21        "copy from channel {} is out of bounds 0-{}",
22        from,
23        channels
24    };
25    assert! {
26        to < channels,
27        "copy to channel {} which is out of bounds 0-{}",
28        to,
29        channels
30    };
31
32    if from != to {
33        let from = data.as_ptr().add(from * frames);
34        let to = data.as_ptr().add(to * frames);
35        ptr::copy_nonoverlapping(from, to, frames);
36    }
37}
38
39/// Utility functions to copy a channel in-place in an interleaved audio buffer
40/// from one place to another.
41///
42/// # Safety
43///
44/// Caller has to ensure that the `data` pointer points to interleaved memory
45/// with the correct topology and initialized frame count.
46pub(crate) unsafe fn copy_channels_interleaved<T>(
47    data: ptr::NonNull<T>,
48    channels: usize,
49    frames: usize,
50    from: usize,
51    to: usize,
52) where
53    T: Copy,
54{
55    assert! {
56        from < channels,
57        "copy from channel {} is out of bounds 0-{}",
58        from,
59        channels
60    };
61    assert! {
62        to < channels,
63        "copy to channel {} which is out of bounds 0-{}",
64        to,
65        channels
66    };
67
68    if from != to {
69        // Safety: We're making sure not to access any mutable buffers which
70        // are not initialized.
71        for n in 0..frames {
72            let from = data.as_ptr().add(from + channels * n) as *const _;
73            let to = data.as_ptr().add(to + channels * n);
74            let f = ptr::read(from);
75            ptr::write(to, f);
76        }
77    }
78}