qualia_audio/io/resample/
polyphase.rs1use crate::types::AudioError;
6
7pub fn resample_polyphase(
10 src: &[f32],
11 src_rate: u32,
12 dst_rate: u32,
13 out: &mut [f32],
14 half_taps: usize,
15) -> Result<usize, AudioError> {
16 if src_rate == 0 || dst_rate == 0 || half_taps == 0 {
17 return Err(AudioError::InvalidParameter);
18 }
19 if src.is_empty() {
20 return Err(AudioError::MalformedAudio);
21 }
22 Ok(etalon_signal::resample::resample_polyphase_into(
23 src, src_rate, dst_rate, half_taps, out,
24 ))
25}
26
27#[cfg(test)]
28mod tests {
29 use super::*;
30 use core::f64::consts::TAU;
31
32 #[test]
33 fn rational_ratio_output_length() {
34 let s = vec![0.0f32; 1470];
36 let mut o = vec![0.0f32; 2000];
37 let n = resample_polyphase(&s, 44100, 48000, &mut o, 16).unwrap();
38 assert_eq!(n, 1470 * 160 / 147);
39 }
40
41 #[test]
42 fn dc_is_preserved() {
43 let s = vec![0.25f32; 512];
44 let mut o = vec![0.0f32; 600];
45 let n = resample_polyphase(&s, 44100, 48000, &mut o, 16).unwrap();
46 assert!(n > 0);
47 for &v in &o[64..n - 64] {
49 assert!((v - 0.25).abs() < 1e-3, "DC not preserved: {v}");
50 }
51 }
52
53 #[test]
54 fn identity_rate_returns_input() {
55 let s = [0.1f32, -0.2, 0.3];
56 let mut o = [0.0f32; 3];
57 let n = resample_polyphase(&s, 8000, 8000, &mut o, 8).unwrap();
58 assert_eq!(n, 3);
59 assert_eq!(o, s);
60 }
61
62 #[test]
63 fn anti_aliasing_downsample_rejects_out_of_band() {
64 let n_in = 4800usize;
65 let amp = 0.8;
66 let out_band: Vec<f32> = (0..n_in)
67 .map(|i| (amp * (TAU * 12000.0 * i as f64 / 48000.0).sin()) as f32)
68 .collect();
69 let mut out = vec![0.0f32; 1700];
70 let n = resample_polyphase(&out_band, 48000, 16000, &mut out, 32).unwrap();
71
72 let mid = &out[100..n - 100];
73 let w = TAU * 4000.0 / 16000.0;
74 let coeff = 2.0 * w.cos();
75 let (mut s1, mut s2) = (0.0f64, 0.0f64);
76 for &x in mid {
77 let s0 = x as f64 + coeff * s1 - s2;
78 s2 = s1;
79 s1 = s0;
80 }
81 let power = (s1 * s1 + s2 * s2 - coeff * s1 * s2).max(0.0);
82 let alias = power.sqrt() * 2.0 / mid.len() as f64;
83 assert!(alias < 0.1, "alias tone should be suppressed, got {alias}");
84 }
85}