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
103fn 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
118fn 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 let mut next_k = self.k;
374 let mut next_p = self.p;
375 let mut dropped = 0usize;
376 for (channel, history) in self.history.iter_mut().enumerate() {
377 history.extend_from_slice(&input[channel][..n]);
378 let out = &mut output[channel];
379 assert!(
380 out.len() >= wanted,
381 "the output buffer holds {} frames, {wanted} are needed",
382 out.len()
383 );
384 let (mut k, mut p) = (self.k, self.p);
385 let mut count = 0usize;
386 loop {
387 let start = (k - lead - self.base) as usize;
388 if start + taps > history.len() {
389 break;
390 }
391 out[count] = dot(
392 &history[start..start + taps],
393 &self.coef[p * taps..(p + 1) * taps],
394 );
395 count += 1;
396 p += m;
397 k += (p / l) as i64;
398 p %= l;
399 }
400 debug_assert_eq!(count, wanted);
401 let next_start = (k - lead - self.base) as usize;
403 let drop = next_start.min(history.len());
404 history.copy_within(drop.., 0);
405 let kept = history.len() - drop;
406 history.truncate(kept);
407 next_k = k;
408 next_p = p;
409 dropped = drop;
410 }
411 self.base += dropped as i64;
412 self.k = next_k;
413 self.p = next_p;
414 self.in_total += n as u64;
415 self.out_total += wanted as u64;
416 wanted
417 }
418}
419
420#[cfg(test)]
421pub(crate) mod tests {
422 use super::*;
423 use std::f64::consts::PI;
424
425 pub fn tone(rate: f64, hz: f64, amplitude: f64, start: usize, len: usize) -> Vec<f64> {
427 (start..start + len)
428 .map(|n| amplitude * (2.0 * PI * hz * n as f64 / rate).sin())
429 .collect()
430 }
431
432 pub fn run(resampler: &mut Resampler, input: &[f64], block: usize) -> Vec<f64> {
434 let mut result = Vec::new();
435 let mut out = vec![Vec::new()];
436 for chunk in input.chunks(block) {
437 let wanted = resampler.output_len_for(chunk.len());
438 out[0].resize(wanted, 0.0);
439 let produced = resampler.process(&[chunk.to_vec()], chunk.len(), &mut out);
440 result.extend_from_slice(&out[0][..produced]);
441 }
442 result
443 }
444
445 pub fn finish(resampler: &mut Resampler, block: usize) -> Vec<f64> {
447 run(resampler, &vec![0.0; resampler.pad_frames()], block)
448 }
449
450 fn make(from: u32, to: u32, quality: Quality) -> Resampler {
451 Resampler::new(from, to, 1, quality, 4096).unwrap()
452 }
453
454 #[test]
455 fn the_polyphase_ratio_is_the_reduced_fraction() {
456 for (from, to, l, m) in [
457 (44_100, 48_000, 160, 147),
458 (48_000, 44_100, 147, 160),
459 (44_100, 88_200, 2, 1),
460 (96_000, 44_100, 147, 320),
461 (768_000, 44_100, 147, 2560),
462 (44_100, 768_000, 2560, 147),
463 (705_600, 48_000, 10, 147),
464 ] {
465 let resampler = make(from, to, Quality::Fast);
466 assert_eq!(
467 (resampler.info().l, resampler.info().m),
468 (l, m),
469 "{from} -> {to}"
470 );
471 }
472 }
473
474 #[test]
475 fn equal_rates_and_nonsense_are_refused() {
476 assert!(Resampler::new(48_000, 48_000, 2, Quality::High, 64).is_err());
477 assert!(Resampler::new(0, 48_000, 2, Quality::High, 64).is_err());
478 assert!(Resampler::new(48_000, 44_100, 0, Quality::High, 64).is_err());
479 }
480
481 #[test]
482 fn a_ratio_that_needs_an_unreasonable_filter_is_unsupported() {
483 let error = Resampler::new(44_100, 47_993, 2, Quality::High, 64)
485 .err()
486 .unwrap();
487 assert_eq!(error.code(), "unsupported");
488 }
489
490 #[test]
491 fn every_standard_ratio_builds_within_the_limits() {
492 let rates = [
493 44_100u32, 88_200, 176_400, 352_800, 705_600, 48_000, 96_000, 192_000, 384_000, 768_000,
494 ];
495 for &from in &rates {
496 for &to in &rates {
497 if from == to {
498 continue;
499 }
500 for quality in [Quality::High, Quality::Fast] {
501 let resampler = Resampler::new(from, to, 1, quality, 64)
502 .unwrap_or_else(|error| panic!("{from} -> {to} {quality:?}: {error}"));
503 let info = resampler.info();
504 assert!(info.taps <= MAX_TAPS);
505 assert!(info.taps * info.l <= MAX_COEFFICIENTS);
506 assert_eq!(info.taps % 8, 0);
507 }
508 }
509 }
510 }
511
512 #[test]
513 fn the_gain_at_dc_is_exactly_one_in_every_phase() {
514 for (from, to) in [
515 (44_100, 48_000),
516 (48_000, 44_100),
517 (96_000, 44_100),
518 (44_100, 192_000),
519 ] {
520 let mut resampler = make(from, to, Quality::High);
521 let input = vec![0.3; 20_000];
522 let mut output = run(&mut resampler, &input, 777);
523 output.extend(finish(&mut resampler, 777));
524 let info = *resampler.info();
526 let margin = info.taps * info.l / info.m + 8;
527 let settled = &output[margin..output.len() - margin];
528 let worst = settled.iter().map(|y| (y - 0.3).abs()).fold(0.0, f64::max);
529 assert!(worst < 1e-13, "{from} -> {to}: DC gain off by {worst}");
530 }
531 }
532
533 #[test]
534 fn the_output_length_is_ceil_of_the_input_length_times_l_over_m() {
535 for (from, to, frames) in [
536 (44_100u32, 48_000u32, 10_000usize),
537 (48_000, 44_100, 9_999),
538 (96_000, 44_100, 12_345),
539 (44_100, 88_200, 777),
540 ] {
541 let mut resampler = make(from, to, Quality::Fast);
542 let mut produced = run(&mut resampler, &vec![0.1; frames], 513).len();
543 produced += finish(&mut resampler, 513).len();
544 let info = *resampler.info();
545 let expected = (frames * info.l).div_ceil(info.m);
546 assert_eq!(produced, expected, "{from} -> {to}");
547 assert_eq!(resampler.frames_out(), expected as u64);
548 }
549 }
550
551 #[test]
552 fn output_len_for_and_max_input_for_output_are_exact_and_agree() {
553 let mut resampler = make(48_000, 44_100, Quality::Fast);
554 let mut fed = 0usize;
555 let mut made = 0usize;
556 for step in [1usize, 7, 160, 3, 1000, 2, 4095] {
557 let predicted = resampler.output_len_for(step);
558 let produced = run(&mut resampler, &vec![0.0; step], 4096).len();
559 assert_eq!(predicted, produced);
560 fed += step;
561 made += produced;
562 for cap in [0usize, 1, 5, 100] {
564 let allowed = resampler.max_input_for_output(cap);
565 assert!(resampler.output_len_for(allowed) <= cap, "cap {cap}");
566 assert!(resampler.output_len_for(allowed + 1) > cap, "cap {cap}");
567 }
568 }
569 assert_eq!(resampler.frames_in(), fed as u64);
570 assert_eq!(resampler.frames_out(), made as u64);
571 }
572
573 #[test]
574 fn chunking_does_not_change_a_single_bit() {
575 let input = tone(44_100.0, 1_234.5, 0.7, 0, 30_000);
576 let mut reference = make(44_100, 48_000, Quality::High);
577 let mut expected = run(&mut reference, &input, 4096);
578 expected.extend(finish(&mut reference, 4096));
579 for block in [1usize, 3, 100, 147, 1000, 4096] {
580 let mut resampler = make(44_100, 48_000, Quality::High);
581 let mut got = run(&mut resampler, &input, block);
582 got.extend(finish(&mut resampler, block));
583 assert_eq!(got.len(), expected.len(), "block {block}");
584 assert!(
585 got.iter()
586 .zip(&expected)
587 .all(|(a, b)| a.to_bits() == b.to_bits()),
588 "block {block}"
589 );
590 }
591 }
592
593 #[test]
594 fn a_reset_forgets_the_past() {
595 let input = tone(48_000.0, 997.0, 0.5, 0, 9_000);
596 let mut resampler = make(48_000, 96_000, Quality::Fast);
597 let first = run(&mut resampler, &input, 1000);
598 run(
599 &mut resampler,
600 &tone(48_000.0, 5_000.0, 0.9, 0, 3_000),
601 1000,
602 );
603 resampler.reset();
604 assert_eq!(resampler.frames_in(), 0);
605 let again = run(&mut resampler, &input, 1000);
606 assert_eq!(first.len(), again.len());
607 assert!(first
608 .iter()
609 .zip(&again)
610 .all(|(a, b)| a.to_bits() == b.to_bits()));
611 }
612
613 #[test]
614 fn an_impulse_comes_back_where_it_went_in() {
615 for (from, to, n0) in [
617 (48_000u32, 96_000u32, 500usize),
618 (96_000, 48_000, 800),
619 (44_100, 48_000, 640),
620 ] {
621 let mut resampler = make(from, to, Quality::High);
622 let mut input = vec![0.0; 4_000];
623 input[n0] = 1.0;
624 let mut output = run(&mut resampler, &input, 512);
625 output.extend(finish(&mut resampler, 512));
626 let (peak, _) = output
627 .iter()
628 .enumerate()
629 .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
630 .unwrap();
631 let expected = n0 as f64 * f64::from(to) / f64::from(from);
632 assert!(
633 (peak as f64 - expected).abs() <= 1.0,
634 "{from} -> {to}: peak at {peak}, expected {expected}"
635 );
636 if (expected - expected.round()).abs() < 1e-9 {
638 let around = |d: usize| (output[peak - d] - output[peak + d]).abs();
639 assert!(around(1) < 1e-9 && around(5) < 1e-9, "{from} -> {to}");
640 }
641 }
642 }
643
644 #[test]
645 fn channels_are_independent_and_advance_together() {
646 let left = tone(44_100.0, 440.0, 0.5, 0, 8_000);
647 let right = tone(44_100.0, 3_000.0, 0.25, 0, 8_000);
648 let mut stereo = Resampler::new(44_100, 48_000, 2, Quality::Fast, 1_000).unwrap();
649 let mut mono_left = Resampler::new(44_100, 48_000, 1, Quality::Fast, 1_000).unwrap();
650 let mut mono_right = Resampler::new(44_100, 48_000, 1, Quality::Fast, 1_000).unwrap();
651 let mut out = vec![Vec::new(), Vec::new()];
652 let mut got_left = Vec::new();
653 let mut got_right = Vec::new();
654 for (l, r) in left.chunks(1_000).zip(right.chunks(1_000)) {
655 let wanted = stereo.output_len_for(l.len());
656 out[0].resize(wanted, 0.0);
657 out[1].resize(wanted, 0.0);
658 let produced = stereo.process(&[l.to_vec(), r.to_vec()], l.len(), &mut out);
659 got_left.extend_from_slice(&out[0][..produced]);
660 got_right.extend_from_slice(&out[1][..produced]);
661 }
662 let want_left = run(&mut mono_left, &left, 1_000);
663 let want_right = run(&mut mono_right, &right, 1_000);
664 assert!(got_left
665 .iter()
666 .zip(&want_left)
667 .all(|(a, b)| a.to_bits() == b.to_bits()));
668 assert!(got_right
669 .iter()
670 .zip(&want_right)
671 .all(|(a, b)| a.to_bits() == b.to_bits()));
672 }
673}