use std::sync::LazyLock;
use crate::kaiser;
const HALF: usize = 64;
const KAISER_BETA: f64 = 12.0;
pub(crate) struct Resampler {
pub(crate) up: usize,
pub(crate) down: usize,
reach: usize,
phases: Vec<Vec<f64>>,
}
impl Resampler {
pub(crate) fn to_48000() -> &'static Self {
static FILTER: LazyLock<Resampler> = LazyLock::new(|| Resampler::new(44_100, 48_000));
&FILTER
}
pub(crate) fn to_44100() -> &'static Self {
static FILTER: LazyLock<Resampler> = LazyLock::new(|| Resampler::new(48_000, 44_100));
&FILTER
}
fn new(from: usize, to: usize) -> Self {
let common = gcd(from, to);
let (up, down) = (to / common, from / common);
let lower = up.max(down);
let reach = HALF * lower;
let taps = kaiser::lowpass(2 * reach + 1, 0.5 / lower as f64, KAISER_BETA);
let phases = (0..up)
.map(|phase| {
let mut taps: Vec<f64> = (0..=2 * reach / up)
.map(|k| taps.get(phase + k * up).copied().unwrap_or(0.0))
.collect();
let gain = 1.0 / taps.iter().sum::<f64>();
for tap in &mut taps {
*tap *= gain;
}
taps.reverse();
taps
})
.collect();
Self {
up,
down,
reach,
phases,
}
}
fn edge(&self) -> usize {
self.reach.div_ceil(self.down)
}
fn run(&self, input: &[f64]) -> Vec<f64> {
let (up, down) = (self.up, self.down);
let before = 2 * self.reach / up;
let mut padded = vec![0.0; input.len() + 2 * before];
padded[before..before + input.len()].copy_from_slice(input);
(0..input.len() * up / down)
.map(|j| {
let at = j * down + self.reach;
let (newest, phase) = (at / up, at % up);
dot(&self.phases[phase], &padded[newest..=newest + before])
})
.collect()
}
pub(crate) fn brought(&self, channels: &[&[f64]], first: u64) -> Option<(Vec<Vec<f64>>, u64)> {
let down = self.down as u64;
let skip = ((down - first % down) % down) as usize;
let edge = self.edge();
let mut resampled: Vec<Vec<f64>> = channels
.iter()
.map(|c| self.run(c.get(skip..).unwrap_or(&[])))
.collect();
let length = resampled.first()?.len();
if length <= 2 * edge {
return None;
}
for channel in &mut resampled {
channel.truncate(length - edge);
channel.drain(..edge);
}
let start = (first + skip as u64) / down * self.up as u64 + edge as u64;
Some((resampled, start))
}
}
const SIDE_BY_SIDE: usize = 8;
fn dot(a: &[f64], b: &[f64]) -> f64 {
let (a_runs, a_rest) = a.as_chunks::<SIDE_BY_SIDE>();
let (b_runs, b_rest) = b.as_chunks::<SIDE_BY_SIDE>();
let mut totals = [0.0; SIDE_BY_SIDE];
for (a, b) in a_runs.iter().zip(b_runs) {
for ((total, a), b) in totals.iter_mut().zip(a).zip(b) {
*total += a * b;
}
}
let rest: f64 = a_rest.iter().zip(b_rest).map(|(a, b)| a * b).sum();
totals.iter().sum::<f64>() + rest
}
fn gcd(a: usize, b: usize) -> usize {
if b == 0 { a } else { gcd(b, a % b) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resampling_keeps_a_tone_and_its_place_in_time() {
let tone = |n: usize, rate: f64| (2.0 * std::f64::consts::PI * 1000.0 * n as f64 / rate).sin();
for (resampler, from, to) in [
(Resampler::to_48000(), 44_100, 48_000),
(Resampler::to_44100(), 48_000, 44_100),
] {
let input: Vec<f64> = (0..from / 10).map(|n| tone(n, from as f64)).collect();
let output = resampler.run(&input);
assert_eq!(output.len(), to / 10);
let edge = resampler.edge();
for (j, sample) in output.iter().enumerate().take(to / 10 - edge).skip(edge) {
assert!((sample - tone(j, to as f64)).abs() < 1e-5, "{j}: {sample}");
}
}
}
#[test]
fn a_constant_stays_that_constant() {
for resampler in [Resampler::to_48000(), Resampler::to_44100()] {
let output = resampler.run(&[-1.0; 4096]);
let edge = resampler.edge();
let inside = &output[edge..output.len() - edge];
assert!(inside.iter().all(|sample| *sample as f32 == -1.0));
}
}
#[test]
fn a_stretch_starts_at_a_time_both_rates_share() {
let silence = vec![0.0; 44_100];
let (channels, start) = Resampler::to_48000()
.brought(&[&silence], 1000)
.expect("a second leaves samples");
assert_eq!(start, 1120 + 70);
assert_eq!(channels[0].len(), (44_100 - 29) * 160 / 147 - 140);
assert!(
Resampler::to_48000()
.brought(&[&silence[..100]], 0)
.is_none()
);
}
}