lewton/
samples.rs
1pub trait Samples {
15 fn num_samples(&self) -> usize;
16 fn truncate(&mut self, limit :usize);
17 fn from_floats(floats :Vec<Vec<f32>>) -> Self;
18}
19
20impl<S :Sample> Samples for Vec<Vec<S>> {
21 fn num_samples(&self) -> usize {
22 self[0].len()
23 }
24 fn truncate(&mut self, limit :usize) {
25 for ch in self.iter_mut() {
26 if limit < ch.len() {
27 ch.truncate(limit);
28 }
29 }
30 }
31
32 fn from_floats(floats :Vec<Vec<f32>>) -> Self {
33 floats.into_iter()
34 .map(|samples| {
35 samples.into_iter()
36 .map(S::from_float)
37 .collect()
38 }).collect()
39 }
40}
41
42pub struct InterleavedSamples<S :Sample> {
44 pub samples :Vec<S>,
45 pub channel_count :usize,
46}
47
48impl<S :Sample> Samples for InterleavedSamples<S> {
49 fn num_samples(&self) -> usize {
50 self.samples.len() / self.channel_count
51 }
52 fn truncate(&mut self, limit :usize) {
53 self.samples.truncate(limit * self.channel_count);
54 }
55 fn from_floats(floats :Vec<Vec<f32>>) -> Self {
56 let channel_count = floats.len();
57 assert!(floats.len() > 0);
61 let samples_interleaved = if channel_count == 1 {
62 <Vec<Vec<S>> as Samples>::from_floats(floats).into_iter().next().unwrap()
64 } else {
65 let len = floats[0].len();
66 let mut samples = Vec::with_capacity(len * channel_count);
67 for i in 0 .. len {
68 for ref chan in floats.iter() {
69 samples.push(S::from_float(chan[i]));
70 }
71 }
72 samples
73 };
74 Self {
75 samples : samples_interleaved,
76 channel_count,
77 }
78 }
79}
80
81pub trait Sample {
83 fn from_float(fl :f32) -> Self;
84}
85
86impl Sample for f32 {
87 fn from_float(fl :f32) -> Self {
88 fl
89 }
90}
91
92impl Sample for i16 {
93 fn from_float(fl :f32) -> Self {
94 let fl = fl * 32768.0;
95 if fl > 32767. {
96 32767
97 } else if fl < -32768. {
98 -32768
99 } else {
100 fl as i16
101 }
102 }
103}