#[cfg_attr(
not(any(
feature = "whisper-onnx",
feature = "distil-whisper",
feature = "moonshine",
all(feature = "mlx", target_os = "macos", target_arch = "aarch64")
)),
allow(dead_code)
)]
const TARGET_SAMPLE_RATE: u32 = 16_000;
#[cfg_attr(
not(all(feature = "mlx", target_os = "macos", target_arch = "aarch64")),
allow(dead_code)
)]
pub(crate) fn pcm16_to_f32_mono_into(data: &[u8], channels: u8, out: &mut Vec<f32>) {
out.clear();
if channels == 0 {
return;
}
let ch = channels as usize;
let frame_bytes = 2 * ch;
let n_frames = data.len() / frame_bytes;
if n_frames == 0 {
return;
}
out.reserve(n_frames);
out.extend(data.chunks_exact(frame_bytes).map(|frame| {
let mut sum: i32 = 0;
for sample_bytes in frame.chunks_exact(2) {
sum += i16::from_le_bytes([sample_bytes[0], sample_bytes[1]]) as i32;
}
(sum as f32 / ch as f32) * (1.0 / 32768.0)
}));
}
#[cfg_attr(
not(any(
feature = "whisper-onnx",
feature = "distil-whisper",
feature = "moonshine",
all(feature = "mlx", target_os = "macos", target_arch = "aarch64")
)),
allow(dead_code)
)]
pub(crate) fn resample_to_16khz_into(input: &[f32], source_rate: u32, out: &mut Vec<f32>) {
out.clear();
if source_rate == TARGET_SAMPLE_RATE {
out.extend_from_slice(input);
return;
}
if input.is_empty() || source_rate == 0 {
return;
}
let ratio = source_rate as f64 / TARGET_SAMPLE_RATE as f64;
let output_len = ((input.len() as f64) / ratio).round() as usize;
if output_len == 0 {
return;
}
out.reserve(output_len);
out.extend((0..output_len).map(|i| {
let src_pos = i as f64 * ratio;
let idx = src_pos as usize;
let frac = (src_pos - idx as f64) as f32;
if idx + 1 < input.len() {
input[idx] * (1.0 - frac) + input[idx + 1] * frac
} else if idx < input.len() {
input[idx]
} else {
0.0
}
}));
}
#[cfg_attr(
not(any(feature = "whisper-onnx", feature = "distil-whisper", feature = "moonshine")),
allow(dead_code)
)]
pub(crate) fn downmix_to_mono(samples: &[i16], channels: u8) -> Vec<i16> {
if channels <= 1 {
return samples.to_vec();
}
let ch = channels as usize;
let n_frames = samples.len() / ch;
let mut mono = Vec::with_capacity(n_frames);
for i in 0..n_frames {
let mut sum: i32 = 0;
for c in 0..ch {
sum += samples[i * ch + c] as i32;
}
mono.push((sum / ch as i32) as i16);
}
mono
}
#[cfg_attr(
not(any(feature = "whisper-onnx", feature = "distil-whisper", feature = "moonshine")),
allow(dead_code)
)]
pub(crate) fn resample_to_16khz(samples: &[f32], source_rate: u32) -> Vec<f32> {
let mut out = Vec::new();
resample_to_16khz_into(samples, source_rate, &mut out);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn legacy_resample_to_16khz(samples: &[f32], source_rate: u32) -> Vec<f32> {
if source_rate == TARGET_SAMPLE_RATE {
return samples.to_vec();
}
if samples.is_empty() || source_rate == 0 {
return Vec::new();
}
let ratio = source_rate as f64 / TARGET_SAMPLE_RATE as f64;
let output_len = ((samples.len() as f64) / ratio).round() as usize;
if output_len == 0 {
return Vec::new();
}
let mut output = Vec::with_capacity(output_len);
for i in 0..output_len {
let src_pos = i as f64 * ratio;
let idx = src_pos as usize;
let frac = (src_pos - idx as f64) as f32;
let sample = if idx + 1 < samples.len() {
samples[idx] * (1.0 - frac) + samples[idx + 1] * frac
} else if idx < samples.len() {
samples[idx]
} else {
0.0
};
output.push(sample);
}
output
}
#[test]
fn mono_conversion_matches_samples() {
let samples: [i16; 4] = [1000, -1000, 32767, 32767];
let bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
let mut out = Vec::new();
pcm16_to_f32_mono_into(&bytes, 2, &mut out);
assert_eq!(out, vec![0.0_f32, 32767.0_f32 / 32768.0_f32]);
}
#[test]
fn pcm16_channels_zero_clears_out() {
let mut out = vec![42.0_f32, -1.0];
pcm16_to_f32_mono_into(&[1, 2, 3, 4], 0, &mut out);
assert!(out.is_empty());
}
#[test]
fn pcm16_mono_single_channel() {
let samples: [i16; 3] = [-32768, 0, 16384];
let bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
let mut out = vec![99.0_f32];
pcm16_to_f32_mono_into(&bytes, 1, &mut out);
assert_eq!(out, vec![-1.0_f32, 0.0_f32, 0.5_f32]);
}
#[test]
fn pcm16_odd_trailing_bytes_dropped() {
let samples: [i16; 2] = [16384, -16384];
let mut mono_bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
mono_bytes.push(0x7f); let mut out = vec![9.0_f32];
pcm16_to_f32_mono_into(&mono_bytes, 1, &mut out);
assert_eq!(out, vec![0.5_f32, -0.5_f32]);
let mut stereo_bytes = mono_bytes[..4].to_vec();
stereo_bytes.extend_from_slice(&8192_i16.to_le_bytes());
pcm16_to_f32_mono_into(&stereo_bytes, 2, &mut out);
assert_eq!(out, vec![0.0_f32]);
pcm16_to_f32_mono_into(&[0xff], 1, &mut out);
assert!(out.is_empty());
}
#[test]
fn pcm16_empty_input_clears_prefilled_out() {
let mut out = vec![1.0_f32, 2.0, 3.0];
pcm16_to_f32_mono_into(&[], 2, &mut out);
assert!(out.is_empty());
}
#[test]
fn resample_into_empty_and_zero_rate_clear_prefilled_out() {
let mut out = vec![1.0_f32, 2.0];
resample_to_16khz_into(&[], 48_000, &mut out);
assert!(out.is_empty());
out.extend_from_slice(&[3.0, 4.0]);
resample_to_16khz_into(&[], 16_000, &mut out);
assert!(out.is_empty());
out.extend_from_slice(&[5.0, 6.0]);
resample_to_16khz_into(&[0.25, 0.5, 0.75], 0, &mut out);
assert!(out.is_empty());
}
#[test]
fn resample_into_16khz_passthrough() {
let input = [0.125_f32, -0.5, 0.875];
let mut out = vec![99.0_f32];
resample_to_16khz_into(&input, 16_000, &mut out);
assert_eq!(out, input);
}
#[test]
fn resample_into_single_sample_downsample_zero_output_len() {
let mut out = vec![7.0_f32, 8.0];
resample_to_16khz_into(&[0.5_f32], 48_000, &mut out);
assert!(out.is_empty());
}
#[test]
fn resample_into_matches_legacy() {
let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
let input: Vec<f32> = (0..48_000)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
((state >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
})
.collect();
let expected = legacy_resample_to_16khz(&input, 48_000);
let mut actual = Vec::new();
resample_to_16khz_into(&input, 48_000, &mut actual);
assert_eq!(actual.len(), expected.len());
for (idx, (a, e)) in actual.iter().zip(expected.iter()).enumerate() {
assert_eq!(
a.to_bits(),
e.to_bits(),
"bit mismatch at sample {idx}: {a} ({:#010x}) != {e} ({:#010x})",
a.to_bits(),
e.to_bits()
);
}
}
#[test]
fn into_does_not_realloc() {
let samples = vec![1000_i16; 4096];
let bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
let mut mono = Vec::with_capacity(2048);
let mono_ptr = mono.as_ptr();
pcm16_to_f32_mono_into(&bytes, 2, &mut mono);
assert_eq!(mono.as_ptr(), mono_ptr);
pcm16_to_f32_mono_into(&bytes, 2, &mut mono);
assert_eq!(mono.as_ptr(), mono_ptr);
let mut resampled = Vec::with_capacity(2048);
let resampled_ptr = resampled.as_ptr();
resample_to_16khz_into(&mono, 48_000, &mut resampled);
assert_eq!(resampled.as_ptr(), resampled_ptr);
resample_to_16khz_into(&mono, 48_000, &mut resampled);
assert_eq!(resampled.as_ptr(), resampled_ptr);
}
#[test]
fn test_downmix_mono_passthrough() {
let samples = vec![100i16, 200, 300];
let result = downmix_to_mono(&samples, 1);
assert_eq!(result, samples);
}
#[test]
fn test_downmix_stereo() {
let stereo = vec![100i16, 200, 300, 400];
let mono = downmix_to_mono(&stereo, 2);
assert_eq!(mono, vec![150, 350]);
}
#[test]
fn test_resample_passthrough() {
let samples = vec![1.0f32; 16000];
let result = resample_to_16khz(&samples, 16000);
assert_eq!(result.len(), 16000);
}
#[test]
fn test_resample_48k_to_16k() {
let samples = vec![0.5f32; 48000]; let result = resample_to_16khz(&samples, 48000);
assert_eq!(result.len(), 16000);
}
}