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
use std::iter::{Zip, IntoIterator};
use std::vec::IntoIter;
use std::slice;
use num_traits::Float;
pub struct AudioBuffer<'a, T: 'a + Float> {
inputs: Vec<&'a mut [T]>,
outputs: Vec<&'a mut [T]>,
}
pub type ChannelBufferIter<'a, T> = IntoIter<&'a mut [T]>;
impl<'a, T: 'a + Float> AudioBuffer<'a, T> {
pub fn new(inputs: Vec<&'a mut [T]>, outputs: Vec<&'a mut [T]>) -> AudioBuffer<'a, T> {
AudioBuffer {
inputs: inputs,
outputs: outputs,
}
}
pub unsafe fn from_raw(inputs_raw: *mut *mut T, outputs_raw: *mut *mut T, num_inputs: usize, num_outputs: usize, samples: usize) -> AudioBuffer<'a, T> {
let inputs =
slice::from_raw_parts_mut(inputs_raw, num_inputs).iter()
.map(|input| slice::from_raw_parts_mut(*input, samples))
.collect();
let outputs =
slice::from_raw_parts_mut(outputs_raw, num_outputs).iter()
.map(|output| slice::from_raw_parts_mut(*output, samples))
.collect();
AudioBuffer::new(inputs, outputs)
}
pub fn inputs(&'a mut self) -> &'a mut Vec<&'a mut [T]> {
&mut self.inputs
}
pub fn outputs(&'a mut self) -> &'a mut Vec<&'a mut [T]> {
&mut self.outputs
}
pub fn split(self) -> (Vec<&'a mut [T]>, Vec<&'a mut [T]>) {
(self.inputs, self.outputs)
}
pub fn zip(self) -> Zip<ChannelBufferIter<'a, T>, ChannelBufferIter<'a, T>> {
self.inputs.into_iter().zip(self.outputs.into_iter())
}
}
#[cfg(test)]
mod tests {
use buffer::AudioBuffer;
const SIZE: usize = 1024;
#[test]
fn buffer_zip() {
let mut in1: Vec<f32> = (0..SIZE).map(|x| x as f32).collect();
let mut in2 = in1.clone();
let mut out1 = vec![0.0; SIZE];
let mut out2 = out1.clone();
let buffer = AudioBuffer::new(vec![&mut in1, &mut in2],
vec![&mut out1, &mut out2]);
for (input, output) in buffer.zip() {
input.into_iter().zip(output.into_iter())
.fold(0, |acc, (input, output)| {
assert_eq!(*input - acc as f32, 0.0);
assert_eq!(*output, 0.0);
acc + 1
});
}
}
#[test]
fn from_raw() {
let mut in1: Vec<f32> = (0..SIZE).map(|x| x as f32).collect();
let mut in2 = in1.clone();
let mut out1 = vec![0.0; SIZE];
let mut out2 = out1.clone();
let buffer = unsafe {
AudioBuffer::from_raw(vec![in1.as_mut_ptr(), in2.as_mut_ptr()].as_mut_ptr(),
vec![out1.as_mut_ptr(), out2.as_mut_ptr()].as_mut_ptr(),
2, 2, SIZE)
};
for (input, output) in buffer.zip() {
input.into_iter().zip(output.into_iter())
.fold(0, |acc, (input, output)| {
assert_eq!(*input - acc as f32, 0.0);
assert_eq!(*output, 0.0);
acc + 1
});
}
}
}