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
extern crate libsamplerate_sys;
pub mod converter_type;
pub mod error;
pub mod samplerate;
pub use crate::converter_type::*;
pub use crate::error::*;
pub use crate::samplerate::*;
use libsamplerate_sys::*;
use std::ffi::CStr;
use std::convert::TryInto;
#[cfg(test)]
extern crate rstest;
#[cfg(test)]
mod sanity_test;
pub fn convert(from_rate: u32, to_rate: u32, channels: usize, converter_type: ConverterType, input: &[f32]) -> Result<Vec<f32>, Error> {
let input_len = input.len();
assert_eq!(input_len % channels, 0);
let input_frames = input_len / channels;
let ratio = to_rate as f64 / from_rate as f64;
let output_frames = (input_frames * to_rate as usize + (from_rate as usize - 1)) / from_rate as usize;
let mut output = vec![0f32;output_frames * channels];
let mut src = SRC_DATA {
data_in: input.as_ptr(),
data_out: output.as_mut_ptr(),
input_frames: input_frames.try_into().unwrap(),
output_frames: output_frames.try_into().unwrap(),
src_ratio: ratio,
end_of_input: 0,
input_frames_used: 0,
output_frames_gen: 0,
..Default::default()
};
let error_int = unsafe { src_simple(&mut src as *mut SRC_DATA, converter_type as i32, channels as i32) };
let error_code = ErrorCode::from_int(error_int);
match error_code {
ErrorCode::NoError => Ok(output),
_ => Err(Error::from_code(error_code)),
}
}
pub fn version() -> &'static str {
unsafe { CStr::from_ptr(src_get_version()) }.to_str().unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correct_version() {
assert_eq!(version(), "libsamplerate-0.1.9 (c) 2002-2008 Erik de Castro Lopo");
}
}