Skip to main content

max / audiofiles

2.3 KB · 76 lines History Blame Raw
1 //! DC offset removal: compute mean amplitude and subtract it from all samples.
2
3 /// Remove DC offset from interleaved audio samples.
4 ///
5 /// Computes the mean sample value (the DC component) and subtracts it,
6 /// centering the waveform around zero. Operates per-channel to handle
7 /// stereo files where channels may have different offsets.
8 pub fn apply_remove_dc_offset(samples: &mut [f32], channels: u16) {
9 if samples.is_empty() || channels == 0 {
10 return;
11 }
12 let ch = channels as usize;
13 let num_frames = samples.len() / ch;
14 if num_frames == 0 {
15 return;
16 }
17
18 // Compute per-channel mean
19 let mut sums = vec![0.0f64; ch];
20 for frame in 0..num_frames {
21 for c in 0..ch {
22 sums[c] += samples[frame * ch + c] as f64;
23 }
24 }
25 let means: Vec<f32> = sums.iter().map(|s| (*s / num_frames as f64) as f32).collect();
26
27 // Subtract per-channel mean
28 for frame in 0..num_frames {
29 for c in 0..ch {
30 samples[frame * ch + c] -= means[c];
31 }
32 }
33 }
34
35 #[cfg(test)]
36 mod tests {
37 use super::*;
38
39 #[test]
40 fn removes_dc_offset_mono() {
41 let mut samples = vec![0.5, 0.6, 0.4, 0.5]; // mean = 0.5
42 apply_remove_dc_offset(&mut samples, 1);
43 let mean: f32 = samples.iter().sum::<f32>() / samples.len() as f32;
44 assert!(mean.abs() < 1e-6, "mean should be ~0, got {mean}");
45 assert!((samples[0] - 0.0).abs() < 1e-6);
46 assert!((samples[1] - 0.1).abs() < 1e-6);
47 }
48
49 #[test]
50 fn removes_dc_offset_stereo() {
51 // L channel: mean 0.5, R channel: mean -0.5
52 let mut samples = vec![0.5, -0.5, 0.5, -0.5];
53 apply_remove_dc_offset(&mut samples, 2);
54 // After removal, both channels centered at 0
55 assert!((samples[0]).abs() < 1e-6);
56 assert!((samples[1]).abs() < 1e-6);
57 }
58
59 #[test]
60 fn noop_on_already_centered() {
61 let original = vec![0.1, -0.1, 0.2, -0.2];
62 let mut samples = original.clone();
63 apply_remove_dc_offset(&mut samples, 1);
64 for (a, b) in samples.iter().zip(original.iter()) {
65 assert!((a - b).abs() < 1e-6);
66 }
67 }
68
69 #[test]
70 fn empty_input() {
71 let mut samples: Vec<f32> = vec![];
72 apply_remove_dc_offset(&mut samples, 1);
73 assert!(samples.is_empty());
74 }
75 }
76