1use super::format::{ConvertError, Quality};
47
48pub const MAX_TAPS: usize = 8192;
50pub const MAX_COEFFICIENTS: usize = 4_500_000;
52
53#[derive(Debug, Clone, Copy)]
55struct Spec {
56 attenuation_db: f64,
58 passband: f64,
60 stopband: f64,
62}
63
64fn spec(quality: Quality) -> Spec {
65 match quality {
66 Quality::High => Spec {
67 attenuation_db: 110.0,
68 passband: 0.91,
69 stopband: 1.0,
70 },
71 Quality::Fast => Spec {
72 attenuation_db: 84.0,
73 passband: 0.90,
74 stopband: 1.10,
75 },
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq)]
81pub struct FilterInfo {
82 pub l: usize,
84 pub m: usize,
86 pub taps: usize,
88 pub passband_hz: f64,
90 pub stopband_hz: f64,
92 pub design_attenuation_db: f64,
94}
95
96fn gcd(mut a: u64, mut b: u64) -> u64 {
97 while b != 0 {
98 (a, b) = (b, a % b);
99 }
100 a
101}
102
103pub(crate) fn bessel_i0(x: f64) -> f64 {
105 let quarter = x * x / 4.0;
106 let mut term = 1.0;
107 let mut sum = 1.0;
108 for k in 1..400 {
109 term *= quarter / (k * k) as f64;
110 sum += term;
111 if term < sum * 1e-18 {
112 break;
113 }
114 }
115 sum
116}
117
118pub(crate) fn kaiser_beta(attenuation_db: f64) -> f64 {
119 if attenuation_db > 50.0 {
120 0.1102 * (attenuation_db - 8.7)
121 } else if attenuation_db >= 21.0 {
122 0.5842 * (attenuation_db - 21.0).powf(0.4) + 0.07886 * (attenuation_db - 21.0)
123 } else {
124 0.0
125 }
126}
127
128fn sinc(x: f64) -> f64 {
129 if x.abs() < 1e-12 {
130 1.0
131 } else {
132 let px = std::f64::consts::PI * x;
133 px.sin() / px
134 }
135}
136
137pub fn filter_info(from_hz: u32, to_hz: u32, quality: Quality) -> Result<FilterInfo, ConvertError> {
140 if from_hz == 0 || to_hz == 0 {
141 return Err(ConvertError::InvalidArgument(
142 "rates must be positive".into(),
143 ));
144 }
145 let g = gcd(u64::from(from_hz), u64::from(to_hz));
146 let m = (u64::from(from_hz) / g) as usize;
147 let l = (u64::from(to_hz) / g) as usize;
148 let spec = spec(quality);
149
150 let fi = f64::from(from_hz);
151 let nyquist = f64::from(from_hz.min(to_hz)) / 2.0;
152 let passband_hz = spec.passband * nyquist;
153 let stopband_hz = spec.stopband * nyquist;
154 let transition = (stopband_hz - passband_hz) / fi;
155 let half_width = (spec.attenuation_db - 7.95) / (28.72 * transition);
156 let mut taps = 2 * half_width.ceil() as usize;
157 taps = taps.div_ceil(8) * 8;
158 taps = taps.max(16);
159 if taps > MAX_TAPS || l.saturating_mul(taps) > MAX_COEFFICIENTS {
160 return Err(ConvertError::Unsupported(format!(
161 "converting {from_hz} Hz to {to_hz} Hz needs a filter of {taps} taps in {l} phases, \
162 more than the {MAX_COEFFICIENTS} coefficients the converter builds"
163 )));
164 }
165 Ok(FilterInfo {
166 l,
167 m,
168 taps,
169 passband_hz,
170 stopband_hz,
171 design_attenuation_db: spec.attenuation_db,
172 })
173}
174
175fn design(
177 from_hz: u32,
178 to_hz: u32,
179 quality: Quality,
180) -> Result<(FilterInfo, Vec<f64>), ConvertError> {
181 let info = filter_info(from_hz, to_hz, quality)?;
182 let (l, taps) = (info.l, info.taps);
183 let cutoff = (info.passband_hz + info.stopband_hz) / 2.0 / f64::from(from_hz); let beta = kaiser_beta(info.design_attenuation_db);
185 let i0_beta = bessel_i0(beta);
186 let half = (taps / 2) as f64;
187 let mut coef = vec![0.0f64; l * taps];
188 for p in 0..l {
189 let row = &mut coef[p * taps..(p + 1) * taps];
190 let fraction = p as f64 / l as f64;
191 for (j, slot) in row.iter_mut().enumerate() {
192 let t = (half - 1.0) - j as f64 + fraction;
193 let r = t / half;
194 let window = if r.abs() >= 1.0 {
195 0.0
196 } else {
197 bessel_i0(beta * (1.0 - r * r).sqrt()) / i0_beta
198 };
199 *slot = 2.0 * cutoff * sinc(2.0 * cutoff * t) * window;
200 }
201 let sum: f64 = row.iter().sum();
202 for slot in row.iter_mut() {
203 *slot /= sum;
204 }
205 }
206 Ok((info, coef))
207}
208
209#[inline]
211fn dot(a: &[f64], b: &[f64]) -> f64 {
212 debug_assert_eq!(a.len(), b.len());
213 debug_assert_eq!(a.len() % 8, 0);
214 let mut acc = [0.0f64; 8];
215 for (x, y) in a.chunks_exact(8).zip(b.chunks_exact(8)) {
216 for i in 0..8 {
217 acc[i] += x[i] * y[i];
218 }
219 }
220 ((acc[0] + acc[4]) + (acc[1] + acc[5])) + ((acc[2] + acc[6]) + (acc[3] + acc[7]))
221}
222
223pub struct Resampler {
229 info: FilterInfo,
230 coef: Box<[f64]>,
231 half: usize,
232 max_block: usize,
233 history: Vec<Vec<f64>>,
234 base: i64,
236 k: i64,
238 p: usize,
240 in_total: u64,
241 out_total: u64,
242}
243
244impl Resampler {
245 pub fn new(
248 from_hz: u32,
249 to_hz: u32,
250 channels: usize,
251 quality: Quality,
252 max_block: usize,
253 ) -> Result<Self, ConvertError> {
254 if from_hz == 0 || to_hz == 0 || channels == 0 || max_block == 0 {
255 return Err(ConvertError::InvalidArgument(
256 "rates, channels and block size must be positive".into(),
257 ));
258 }
259 if from_hz == to_hz {
260 return Err(ConvertError::InvalidArgument(
261 "the rates are equal: there is nothing to resample".into(),
262 ));
263 }
264 let (info, coef) = design(from_hz, to_hz, quality)?;
265 let half = info.taps / 2;
266 let mut resampler = Self {
267 info,
268 coef: coef.into_boxed_slice(),
269 half,
270 max_block,
271 history: (0..channels)
272 .map(|_| Vec::with_capacity(info.taps + max_block))
273 .collect(),
274 base: 0,
275 k: 0,
276 p: 0,
277 in_total: 0,
278 out_total: 0,
279 };
280 resampler.reset();
281 Ok(resampler)
282 }
283
284 pub fn info(&self) -> &FilterInfo {
285 &self.info
286 }
287
288 pub fn channels(&self) -> usize {
289 self.history.len()
290 }
291
292 pub fn delay_frames(&self) -> usize {
295 self.half
296 }
297
298 pub fn pad_frames(&self) -> usize {
300 self.half
301 }
302
303 pub fn frames_in(&self) -> u64 {
305 self.in_total
306 }
307
308 pub fn frames_out(&self) -> u64 {
310 self.out_total
311 }
312
313 pub fn reset(&mut self) {
315 let lead = self.half - 1;
316 for history in &mut self.history {
317 history.clear();
318 history.resize(lead, 0.0);
319 }
320 self.base = -(lead as i64);
321 self.k = 0;
322 self.p = 0;
323 self.in_total = 0;
324 self.out_total = 0;
325 }
326
327 fn outputs_after(&self, input_total: u64) -> u64 {
329 let usable = input_total.saturating_sub(self.half as u64);
330 let numerator = u128::from(usable) * self.info.l as u128;
331 numerator.div_ceil(self.info.m as u128) as u64
332 }
333
334 pub fn output_len_for(&self, input_frames: usize) -> usize {
336 (self.outputs_after(self.in_total + input_frames as u64) - self.out_total) as usize
337 }
338
339 pub fn max_input_for_output(&self, output_frames: usize) -> usize {
341 let allowed_total = u128::from(self.out_total) + output_frames as u128;
342 let usable = allowed_total * self.info.m as u128 / self.info.l as u128;
343 let input_total = usable + self.half as u128;
344 input_total
345 .saturating_sub(u128::from(self.in_total))
346 .min(usize::MAX as u128) as usize
347 }
348
349 pub fn process(&mut self, input: &[Vec<f64>], n: usize, output: &mut [Vec<f64>]) -> usize {
353 assert_eq!(
354 input.len(),
355 self.history.len(),
356 "one input buffer per channel"
357 );
358 assert_eq!(
359 output.len(),
360 self.history.len(),
361 "one output buffer per channel"
362 );
363 assert!(
364 n <= self.max_block,
365 "a block of {n} frames exceeds the maximum of {}",
366 self.max_block
367 );
368 let taps = self.info.taps;
369 let (l, m) = (self.info.l, self.info.m);
370 let lead = self.half as i64 - 1;
371 let wanted = self.output_len_for(n);
372
373 if self.history[0].len() + n > taps + self.max_block {
377 let discard = ((self.k - lead - self.base).max(0) as usize).min(self.history[0].len());
378 for history in &mut self.history {
379 history.copy_within(discard.., 0);
380 history.truncate(history.len() - discard);
381 }
382 self.base += discard as i64;
383 }
384 let mut next_k = self.k;
385 let mut next_p = self.p;
386 for (channel, history) in self.history.iter_mut().enumerate() {
387 history.extend_from_slice(&input[channel][..n]);
388 let out = &mut output[channel];
389 assert!(
390 out.len() >= wanted,
391 "the output buffer holds {} frames, {wanted} are needed",
392 out.len()
393 );
394 let (mut k, mut p) = (self.k, self.p);
395 let mut count = 0usize;
396 loop {
397 let start = (k - lead - self.base) as usize;
398 if start + taps > history.len() {
399 break;
400 }
401 out[count] = dot(
402 &history[start..start + taps],
403 &self.coef[p * taps..(p + 1) * taps],
404 );
405 count += 1;
406 p += m;
407 k += (p / l) as i64;
408 p %= l;
409 }
410 debug_assert_eq!(count, wanted);
411 next_k = k;
412 next_p = p;
413 }
414 self.k = next_k;
415 self.p = next_p;
416 self.in_total += n as u64;
417 self.out_total += wanted as u64;
418 wanted
419 }
420}
421
422#[cfg(test)]
423pub(crate) mod tests {
424 use super::*;
425 use std::f64::consts::PI;
426
427 pub fn tone(rate: f64, hz: f64, amplitude: f64, start: usize, len: usize) -> Vec<f64> {
429 (start..start + len)
430 .map(|n| amplitude * (2.0 * PI * hz * n as f64 / rate).sin())
431 .collect()
432 }
433
434 pub fn run(resampler: &mut Resampler, input: &[f64], block: usize) -> Vec<f64> {
436 let mut result = Vec::new();
437 let mut out = vec![Vec::new()];
438 for chunk in input.chunks(block) {
439 let wanted = resampler.output_len_for(chunk.len());
440 out[0].resize(wanted, 0.0);
441 let produced = resampler.process(&[chunk.to_vec()], chunk.len(), &mut out);
442 result.extend_from_slice(&out[0][..produced]);
443 }
444 result
445 }
446
447 pub fn finish(resampler: &mut Resampler, block: usize) -> Vec<f64> {
449 run(resampler, &vec![0.0; resampler.pad_frames()], block)
450 }
451
452 fn make(from: u32, to: u32, quality: Quality) -> Resampler {
453 Resampler::new(from, to, 1, quality, 4096).unwrap()
454 }
455
456 #[test]
457 fn the_polyphase_ratio_is_the_reduced_fraction() {
458 for (from, to, l, m) in [
459 (44_100, 48_000, 160, 147),
460 (48_000, 44_100, 147, 160),
461 (44_100, 88_200, 2, 1),
462 (96_000, 44_100, 147, 320),
463 (768_000, 44_100, 147, 2560),
464 (44_100, 768_000, 2560, 147),
465 (705_600, 48_000, 10, 147),
466 ] {
467 let resampler = make(from, to, Quality::Fast);
468 assert_eq!(
469 (resampler.info().l, resampler.info().m),
470 (l, m),
471 "{from} -> {to}"
472 );
473 }
474 }
475
476 #[test]
477 fn equal_rates_and_nonsense_are_refused() {
478 assert!(Resampler::new(48_000, 48_000, 2, Quality::High, 64).is_err());
479 assert!(Resampler::new(0, 48_000, 2, Quality::High, 64).is_err());
480 assert!(Resampler::new(48_000, 44_100, 0, Quality::High, 64).is_err());
481 }
482
483 #[test]
484 fn a_ratio_that_needs_an_unreasonable_filter_is_unsupported() {
485 let error = Resampler::new(44_100, 47_993, 2, Quality::High, 64)
487 .err()
488 .unwrap();
489 assert_eq!(error.code(), "unsupported");
490 }
491
492 #[test]
493 fn every_standard_ratio_builds_within_the_limits() {
494 let rates = [
495 44_100u32, 88_200, 176_400, 352_800, 705_600, 48_000, 96_000, 192_000, 384_000, 768_000,
496 ];
497 for &from in &rates {
498 for &to in &rates {
499 if from == to {
500 continue;
501 }
502 for quality in [Quality::High, Quality::Fast] {
503 let resampler = Resampler::new(from, to, 1, quality, 64)
504 .unwrap_or_else(|error| panic!("{from} -> {to} {quality:?}: {error}"));
505 let info = resampler.info();
506 assert!(info.taps <= MAX_TAPS);
507 assert!(info.taps * info.l <= MAX_COEFFICIENTS);
508 assert_eq!(info.taps % 8, 0);
509 }
510 }
511 }
512 }
513
514 #[test]
515 fn the_gain_at_dc_is_exactly_one_in_every_phase() {
516 for (from, to) in [
517 (44_100, 48_000),
518 (48_000, 44_100),
519 (96_000, 44_100),
520 (44_100, 192_000),
521 ] {
522 let mut resampler = make(from, to, Quality::High);
523 let input = vec![0.3; 20_000];
524 let mut output = run(&mut resampler, &input, 777);
525 output.extend(finish(&mut resampler, 777));
526 let info = *resampler.info();
528 let margin = info.taps * info.l / info.m + 8;
529 let settled = &output[margin..output.len() - margin];
530 let worst = settled.iter().map(|y| (y - 0.3).abs()).fold(0.0, f64::max);
531 assert!(worst < 1e-13, "{from} -> {to}: DC gain off by {worst}");
532 }
533 }
534
535 #[test]
536 fn the_output_length_is_ceil_of_the_input_length_times_l_over_m() {
537 for (from, to, frames) in [
538 (44_100u32, 48_000u32, 10_000usize),
539 (48_000, 44_100, 9_999),
540 (96_000, 44_100, 12_345),
541 (44_100, 88_200, 777),
542 ] {
543 let mut resampler = make(from, to, Quality::Fast);
544 let mut produced = run(&mut resampler, &vec![0.1; frames], 513).len();
545 produced += finish(&mut resampler, 513).len();
546 let info = *resampler.info();
547 let expected = (frames * info.l).div_ceil(info.m);
548 assert_eq!(produced, expected, "{from} -> {to}");
549 assert_eq!(resampler.frames_out(), expected as u64);
550 }
551 }
552
553 #[test]
554 fn output_len_for_and_max_input_for_output_are_exact_and_agree() {
555 let mut resampler = make(48_000, 44_100, Quality::Fast);
556 let mut fed = 0usize;
557 let mut made = 0usize;
558 for step in [1usize, 7, 160, 3, 1000, 2, 4095] {
559 let predicted = resampler.output_len_for(step);
560 let produced = run(&mut resampler, &vec![0.0; step], 4096).len();
561 assert_eq!(predicted, produced);
562 fed += step;
563 made += produced;
564 for cap in [0usize, 1, 5, 100] {
566 let allowed = resampler.max_input_for_output(cap);
567 assert!(resampler.output_len_for(allowed) <= cap, "cap {cap}");
568 assert!(resampler.output_len_for(allowed + 1) > cap, "cap {cap}");
569 }
570 }
571 assert_eq!(resampler.frames_in(), fed as u64);
572 assert_eq!(resampler.frames_out(), made as u64);
573 }
574
575 #[test]
576 fn chunking_does_not_change_a_single_bit() {
577 let input = tone(44_100.0, 1_234.5, 0.7, 0, 30_000);
578 let mut reference = make(44_100, 48_000, Quality::High);
579 let mut expected = run(&mut reference, &input, 4096);
580 expected.extend(finish(&mut reference, 4096));
581 for block in [1usize, 3, 100, 147, 1000, 4096] {
582 let mut resampler = make(44_100, 48_000, Quality::High);
583 let mut got = run(&mut resampler, &input, block);
584 got.extend(finish(&mut resampler, block));
585 assert_eq!(got.len(), expected.len(), "block {block}");
586 assert!(
587 got.iter()
588 .zip(&expected)
589 .all(|(a, b)| a.to_bits() == b.to_bits()),
590 "block {block}"
591 );
592 }
593 }
594
595 #[test]
596 fn a_reset_forgets_the_past() {
597 let input = tone(48_000.0, 997.0, 0.5, 0, 9_000);
598 let mut resampler = make(48_000, 96_000, Quality::Fast);
599 let first = run(&mut resampler, &input, 1000);
600 run(
601 &mut resampler,
602 &tone(48_000.0, 5_000.0, 0.9, 0, 3_000),
603 1000,
604 );
605 resampler.reset();
606 assert_eq!(resampler.frames_in(), 0);
607 let again = run(&mut resampler, &input, 1000);
608 assert_eq!(first.len(), again.len());
609 assert!(first
610 .iter()
611 .zip(&again)
612 .all(|(a, b)| a.to_bits() == b.to_bits()));
613 }
614
615 #[test]
616 fn an_impulse_comes_back_where_it_went_in() {
617 for (from, to, n0) in [
619 (48_000u32, 96_000u32, 500usize),
620 (96_000, 48_000, 800),
621 (44_100, 48_000, 640),
622 ] {
623 let mut resampler = make(from, to, Quality::High);
624 let mut input = vec![0.0; 4_000];
625 input[n0] = 1.0;
626 let mut output = run(&mut resampler, &input, 512);
627 output.extend(finish(&mut resampler, 512));
628 let (peak, _) = output
629 .iter()
630 .enumerate()
631 .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
632 .unwrap();
633 let expected = n0 as f64 * f64::from(to) / f64::from(from);
634 assert!(
635 (peak as f64 - expected).abs() <= 1.0,
636 "{from} -> {to}: peak at {peak}, expected {expected}"
637 );
638 if (expected - expected.round()).abs() < 1e-9 {
640 let around = |d: usize| (output[peak - d] - output[peak + d]).abs();
641 assert!(around(1) < 1e-9 && around(5) < 1e-9, "{from} -> {to}");
642 }
643 }
644 }
645
646 #[test]
647 fn channels_are_independent_and_advance_together() {
648 let left = tone(44_100.0, 440.0, 0.5, 0, 8_000);
649 let right = tone(44_100.0, 3_000.0, 0.25, 0, 8_000);
650 let mut stereo = Resampler::new(44_100, 48_000, 2, Quality::Fast, 1_000).unwrap();
651 let mut mono_left = Resampler::new(44_100, 48_000, 1, Quality::Fast, 1_000).unwrap();
652 let mut mono_right = Resampler::new(44_100, 48_000, 1, Quality::Fast, 1_000).unwrap();
653 let mut out = vec![Vec::new(), Vec::new()];
654 let mut got_left = Vec::new();
655 let mut got_right = Vec::new();
656 for (l, r) in left.chunks(1_000).zip(right.chunks(1_000)) {
657 let wanted = stereo.output_len_for(l.len());
658 out[0].resize(wanted, 0.0);
659 out[1].resize(wanted, 0.0);
660 let produced = stereo.process(&[l.to_vec(), r.to_vec()], l.len(), &mut out);
661 got_left.extend_from_slice(&out[0][..produced]);
662 got_right.extend_from_slice(&out[1][..produced]);
663 }
664 let want_left = run(&mut mono_left, &left, 1_000);
665 let want_right = run(&mut mono_right, &right, 1_000);
666 assert!(got_left
667 .iter()
668 .zip(&want_left)
669 .all(|(a, b)| a.to_bits() == b.to_bits()));
670 assert!(got_right
671 .iter()
672 .zip(&want_right)
673 .all(|(a, b)| a.to_bits() == b.to_bits()));
674 }
675}