DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Resampler.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
55#include "AudioBuffer.h"
56#include "AudioSpec.h"
57#include "FFT.h"
58#include "SimdOps.h"
59
60#include <algorithm>
61#include <array>
62#include <cassert>
63#include <cmath>
64#include <cstddef>
65#include <cstdint>
66#include <limits>
67#include <numbers>
68#include <optional>
69#include <type_traits>
70#include <utility>
71#include <vector>
72
73namespace dspark {
74
98template <typename T>
100{
101public:
102 enum class Quality
103 {
104 Draft,
105 Normal,
106 High,
107 Ultra
108 };
109
111 static constexpr int kMaxTaps = 8192;
112
115 static constexpr double kMaxRatio = 16777216.0;
116
119 static constexpr int kMaxTwoStageOrder = 1 << 16;
120
122 enum class OfflineEngine
123 {
124 Direct,
125 TwoStage
126 };
127
176 void setOfflineEngine(OfflineEngine engine) noexcept { offlineEngine_ = engine; }
177
179 [[nodiscard]] OfflineEngine getOfflineEngine() const noexcept { return offlineEngine_; }
180
192 void prepare(double sourceRate, double targetRate,
193 Quality quality = Quality::Normal)
194 {
195 prepareTransactional(sourceRate, targetRate, quality,
196 channelStates_.size());
197 }
198
208 void prepare(const AudioSpec& spec, double targetRate,
209 Quality quality = Quality::Normal)
210 {
211 const size_t requestedChannels = spec.numChannels > 0
212 ? static_cast<size_t>(spec.numChannels)
213 : size_t(0);
214 prepareTransactional(spec.sampleRate, targetRate, quality,
215 std::max(channelStates_.size(), requestedChannels));
216 }
217
224 void reset() noexcept
225 {
226 resetChannelState(mono_);
227 for (auto& cs : channelStates_)
228 resetChannelState(cs);
229 }
230
244 [[nodiscard]] std::vector<T> process(const T* input, int inputLength)
245 {
246 if (table_.empty() || input == nullptr || inputLength <= 0) return {};
247 std::vector<T> output(static_cast<size_t>(outputLengthFor(inputLength)));
248 (void)process(input, inputLength, output.data(), static_cast<int64_t>(output.size()));
249 return output;
250 }
251
268 int64_t process(const T* input, int inputLength, T* output, int64_t outputCapacity)
269 {
270 if (table_.empty() || input == nullptr || inputLength <= 0
271 || output == nullptr || outputCapacity <= 0)
272 return 0;
273 const int64_t outputLength = std::min<int64_t>(outputLengthFor(inputLength), outputCapacity);
274 // A prepared ratio is positive, so this only states it: the zero fill
275 // of the tail below then spans a count that cannot be negative.
276 if (outputLength <= 0)
277 return 0;
278 if (useTwoStage())
279 {
280 runTwoStage(input, inputLength, 0, outputLength, output);
281 return outputLength;
282 }
283 int64_t outIdx = 0;
284 for (; outIdx < outputLength; ++outIdx)
285 {
286 int64_t intPos;
287 int64_t phase = 0;
288 double frac = 0.0;
289 if (exact_)
290 {
291 // Integer position arithmetic: output k reads input k*M/L.
292 const int64_t num = outIdx * stepM_;
293 intPos = num / phasesL_;
294 phase = num % phasesL_;
295 }
296 else
297 {
298 const double srcPos = static_cast<double>(outIdx) / ratio_;
299 intPos = static_cast<int64_t>(srcPos);
300 frac = srcPos - static_cast<double>(intPos);
301 }
302 if (intPos >= inputLength) break;
303 output[outIdx] = interpolateOffline(input, inputLength, static_cast<int>(intPos), phase, frac);
304 }
305 std::fill(output + outIdx, output + outputLength, T(0));
306 return outputLength;
307 }
308
322 [[nodiscard]] std::vector<T> processRange(const T* input, int inputLength,
323 int64_t firstOutput, int64_t count)
324 {
325 if (table_.empty() || input == nullptr || inputLength <= 0 || count <= 0) return {};
326 std::vector<T> output(static_cast<size_t>(count));
327 if (useTwoStage())
328 {
329 runTwoStage(input, inputLength, firstOutput, count, output.data());
330 return output;
331 }
332 for (int64_t i = 0; i < count; ++i)
333 {
334 const int64_t outIdx = firstOutput + i;
335 int64_t intPos;
336 int64_t phase = 0;
337 double frac = 0.0;
338 if (exact_)
339 {
340 // Floor division: negative positions are ordinary here.
341 const int64_t num = outIdx * stepM_;
342 intPos = num / phasesL_;
343 if (num % phasesL_ != 0 && num < 0) --intPos;
344 phase = num - intPos * phasesL_;
345 }
346 else
347 {
348 const double srcPos = static_cast<double>(outIdx) / ratio_;
349 const double fl = std::floor(srcPos);
350 intPos = static_cast<int64_t>(fl);
351 frac = srcPos - fl;
352 }
353 // A window that misses the input entirely is exactly zero.
354 const int64_t firstTap = intPos - halfTaps_ + 1;
355 if (firstTap + taps_ <= 0 || firstTap >= inputLength) continue;
356 output[static_cast<size_t>(i)] =
357 interpolateOffline(input, inputLength, static_cast<int>(intPos), phase, frac);
358 }
359 return output;
360 }
361
369 [[nodiscard]] int64_t getReach() const noexcept
370 {
371 if (offlineEngine_ == OfflineEngine::TwoStage && !table_.empty() && ratio_ != 1.0)
372 {
373 const TwoStageShape s = twoStageShape(sourceRate_, targetRate_, ratio_, quality_);
374 // Input sample i drives mid samples up*i -/+ half1; a mid sample
375 // reaches outputs whose interpolation window holds it.
376 return static_cast<int64_t>(std::ceil(static_cast<double>(s.half1 + s.stage2.taps / 2 + 1)
377 * ratio_ / static_cast<double>(s.up))) + 1;
378 }
379 return static_cast<int64_t>(std::ceil((taps_ - halfTaps_ + 1) * ratio_)) + 1;
380 }
381
390 int processBlock(const T* input, int inputLength, T* output) noexcept
391 {
392 return processChannel(input, inputLength, output, mono_);
393 }
394
405 {
406 int numCh = std::min(input.getNumChannels(), output.getNumChannels());
407 int inLen = input.getNumSamples();
408
409 assert(static_cast<int>(channelStates_.size()) >= numCh &&
410 "Resampler channels not allocated! Call prepare(spec...) first.");
411 // Release-safe: never index channelStates_ past what prepare() allocated
412 // (the assert above flags the missing prepare(spec) in debug builds).
413 numCh = std::min(numCh, static_cast<int>(channelStates_.size()));
414
415 int outCount = 0;
416 for (int ch = 0; ch < numCh; ++ch)
417 {
418 outCount = processChannel(input.getChannel(ch), inLen,
419 output.getChannel(ch),
420 channelStates_[static_cast<size_t>(ch)]);
421 }
422
423 return outCount;
424 }
425
431 [[nodiscard]] int getMaxOutputSamples(int inputLength) const noexcept
432 {
433 const double maxOut =
434 std::ceil(static_cast<double>(inputLength) * ratio_) + 2.0;
435 return static_cast<int>(
436 std::min(maxOut, static_cast<double>(std::numeric_limits<int>::max())));
437 }
438
440 [[nodiscard]] double getRatio() const noexcept { return ratio_; }
441
443 [[nodiscard]] int getFilterLength() const noexcept { return taps_; }
444
453 [[nodiscard]] int getLatency() const noexcept
454 {
455 return static_cast<int>(std::round(static_cast<double>(halfTaps_) * ratio_));
456 }
457
458private:
461 [[nodiscard]] int outputLengthFor(int inputLength) const noexcept
462 {
463 const double n = std::ceil(static_cast<double>(inputLength) * ratio_);
464 return static_cast<int>(std::min(n, static_cast<double>(std::numeric_limits<int>::max())));
465 }
466
468 static constexpr int kTablePhases = 512;
471 static constexpr int64_t kMaxExactPhases = 4096;
472 static constexpr int64_t kMaxExactCoefficients = int64_t(1) << 21;
473
474 struct ChannelState
475 {
476 std::vector<T> history;
477 int writePos = 0;
478 double fractionalPos = 0.0;
479 int64_t phase = 0;
480 };
481
482 struct Spec { double passband; double attenuationDb; };
483
484 static_assert(std::is_nothrow_copy_assignable_v<T>,
485 "Resampler sample storage must be reset without throwing");
486 static_assert(std::is_nothrow_swappable_v<ChannelState>,
487 "Resampler state commit must be no-throw");
488 static_assert(std::is_nothrow_swappable_v<std::vector<T>>,
489 "Resampler table commit must be no-throw");
490 static_assert(std::is_nothrow_swappable_v<std::vector<ChannelState>>,
491 "Resampler channel commit must be no-throw");
492
493 static Spec qualitySpec(Quality q) noexcept
494 {
495 switch (q)
496 {
497 case Quality::Draft: return { 0.80, 60.0 };
498 case Quality::Normal: return { 0.90, 100.0 };
499 case Quality::High: return { 0.91, 140.0 };
500 case Quality::Ultra: return { 0.915, 210.0 };
501 }
502 return { 0.90, 100.0 };
503 }
504
506 [[nodiscard]] static double kaiserBeta(double a) noexcept
507 {
508 if (a > 50.0) return 0.1102 * (a - 8.7);
509 if (a >= 21.0) return 0.5842 * std::pow(a - 21.0, 0.4) + 0.07886 * (a - 21.0);
510 return 0.0;
511 }
512
514 [[nodiscard]] static double besselI0(double x) noexcept
515 {
516 // sum_k (x^2 / 4)^k / (k!)^2: each term is the previous one times
517 // (x^2 / 4) / k^2, the reciprocal squares coming from a table, so the
518 // series has no division in its loop.
519 static constexpr std::array<double, 201> kInvSquares = [] {
520 std::array<double, 201> a {};
521 for (int k = 1; k <= 200; ++k) a[static_cast<size_t>(k)] = 1.0 / (static_cast<double>(k) * static_cast<double>(k));
522 return a;
523 }();
524 const double y = 0.25 * x * x;
525 double sum = 1.0, term = 1.0;
526 for (int k = 1; k <= 200; ++k)
527 {
528 term *= y * kInvSquares[static_cast<size_t>(k)];
529 sum += term;
530 if (term < 1e-17 * sum) break;
531 }
532 return sum;
533 }
534
536 struct Design
537 {
538 int taps = 2;
539 double cutoff = 1.0;
540 double beta = 0.0;
541 bool identity = false;
542 };
543
544 [[nodiscard]] static Design design(double ratio, Quality quality) noexcept
545 {
546 Design d;
547 if (ratio == 1.0)
548 {
549 d.identity = true;
550 return d;
551 }
552 const Spec spec = qualitySpec(quality);
553 const double scale = std::min(1.0, ratio); // lower Nyquist / input Nyquist
554 // Band edges in cycles per input sample: the passband ends at
555 // passband * lower Nyquist, the stopband begins at the lower Nyquist.
556 const double transition = 0.5 * scale * (1.0 - spec.passband);
557 d.cutoff = scale * 0.5 * (1.0 + spec.passband);
558 d.beta = kaiserBeta(spec.attenuationDb);
559 // Kaiser's length estimate, N = (A - 7.95) / (14.36 * df).
560 const double n = (spec.attenuationDb - 7.95) / (14.36 * transition);
561 const double capped = std::min(n, static_cast<double>(kMaxTaps));
562 d.taps = 2 * static_cast<int>(std::ceil(0.5 * capped));
563 d.taps = std::max(d.taps, 4);
564 return d;
565 }
566
576 template <typename D>
577 static void buildPhase(D* dst, const Design& d, double frac)
578 {
579 const int half = d.taps / 2;
580 if (d.identity)
581 {
582 for (int j = 0; j < d.taps; ++j)
583 dst[j] = (j == half - 1) ? D(1) : D(0);
584 return;
585 }
586 constexpr double kPi = std::numbers::pi;
587 const double i0Beta = besselI0(d.beta);
588 double sum = 0.0;
589 // Accumulate in double; the table stores T.
590 for (int j = 0; j < d.taps; ++j)
591 {
592 const double t = static_cast<double>(j - half + 1) - frac;
593 const double x = t * d.cutoff;
594 const double sincVal = (std::abs(x) < 1e-12)
595 ? d.cutoff
596 : d.cutoff * std::sin(kPi * x) / (kPi * x);
597 const double wx = t / static_cast<double>(half);
598 const double win = (std::abs(wx) >= 1.0)
599 ? 0.0
600 : besselI0(d.beta * std::sqrt(1.0 - wx * wx)) / i0Beta;
601 dst[j] = static_cast<D>(sincVal * win);
602 sum += sincVal * win;
603 }
604 if (std::abs(sum) > 1e-12)
605 {
606 const double inv = 1.0 / sum;
607 for (int j = 0; j < d.taps; ++j)
608 dst[j] = static_cast<D>(static_cast<double>(dst[j]) * inv);
609 }
610 }
611
621 template <typename D>
622 static void buildTable(D* dst, const Design& d, int64_t L, int64_t offset, int64_t numPhases)
623 {
624 const auto taps = static_cast<size_t>(d.taps);
625 if (d.identity)
626 {
627 for (int64_t p = 0; p < numPhases; ++p)
628 buildPhase(dst + static_cast<size_t>(p) * taps, d,
629 static_cast<double>(p + offset) / static_cast<double>(L));
630 return;
631 }
632 constexpr double kPi = std::numbers::pi;
633 const int half = d.taps / 2;
634 const double i0Beta = besselI0(d.beta);
635 const double scale = 1.0 / static_cast<double>(L);
636 // |k| = |(j - half + 1) L - (p + offset)| stays below this bound.
637 const int64_t kMax = static_cast<int64_t>(half + 1) * L + numPhases + 2;
638 std::vector<double> grid(static_cast<size_t>(kMax) + 1, 0.0);
639 const int64_t kWindow = static_cast<int64_t>(half) * L; // the window is 0 from here
640 for (int64_t k = 0; k < std::min(kWindow, kMax + 1); ++k)
641 {
642 const double t = static_cast<double>(k) * scale;
643 const double x = t * d.cutoff;
644 const double sincVal = (x < 1e-12) ? d.cutoff : d.cutoff * std::sin(kPi * x) / (kPi * x);
645 const double wx = t / static_cast<double>(half);
646 grid[static_cast<size_t>(k)] = sincVal * besselI0(d.beta * std::sqrt(1.0 - wx * wx)) / i0Beta;
647 }
648 for (int64_t p = 0; p < numPhases; ++p)
649 {
650 D* row = dst + static_cast<size_t>(p) * taps;
651 double sum = 0.0;
652 int64_t k = static_cast<int64_t>(1 - half) * L - (p + offset);
653 for (size_t j = 0; j < taps; ++j, k += L)
654 {
655 const double v = grid[static_cast<size_t>(k < 0 ? -k : k)];
656 row[j] = static_cast<D>(v);
657 sum += v;
658 }
659 if (std::abs(sum) > 1e-12)
660 {
661 const double inv = 1.0 / sum;
662 for (size_t j = 0; j < taps; ++j)
663 row[j] = static_cast<D>(static_cast<double>(row[j]) * inv);
664 }
665 }
666 }
667
672 [[nodiscard]] static std::pair<int64_t, int64_t> rationalRatio(
673 double sourceRate, double targetRate) noexcept
674 {
675 // Integer rates (every standard one) reduce exactly.
676 const double rs = std::round(sourceRate), rt = std::round(targetRate);
677 if (std::abs(rs - sourceRate) < 1e-9 && std::abs(rt - targetRate) < 1e-9
678 && rs < 1e12 && rt < 1e12)
679 {
680 int64_t a = static_cast<int64_t>(rt), b = static_cast<int64_t>(rs);
681 int64_t x = a, y = b;
682 while (y != 0) { const int64_t r = x % y; x = y; y = r; }
683 if (x > 0) return { a / x, b / x };
684 }
685 // Otherwise a continued-fraction approximation that is exact to
686 // double precision.
687 const double r = targetRate / sourceRate;
688 int64_t h0 = 0, h1 = 1, k0 = 1, k1 = 0;
689 double v = r;
690 for (int it = 0; it < 64; ++it)
691 {
692 const double fl = std::floor(v);
693 if (fl > 1e12) break;
694 const auto an = static_cast<int64_t>(fl);
695 const int64_t h2 = an * h1 + h0, k2 = an * k1 + k0;
696 if (k2 > (int64_t(1) << 32) || h2 > (int64_t(1) << 32)) break;
697 h0 = h1; h1 = h2; k0 = k1; k1 = k2;
698 if (std::abs(static_cast<double>(h1) / static_cast<double>(k1) - r) <= 1e-15 * r)
699 return { h1, k1 };
700 const double rem = v - fl;
701 if (rem < 1e-15) break;
702 v = 1.0 / rem;
703 }
704 return { 0, 0 };
705 }
706
707 static void initialiseChannelState(ChannelState& state, int taps)
708 {
709 state.history.assign(static_cast<size_t>(taps * 2), T(0));
710 state.writePos = 0;
711 state.fractionalPos = 0.0;
712 state.phase = 0;
713 }
714
715 void prepareTransactional(double sourceRate, double targetRate,
716 Quality quality, size_t channelCount)
717 {
718 if (!std::isfinite(sourceRate) || !std::isfinite(targetRate)) return;
719
720 // Derive the complete candidate configuration without touching the
721 // live object. The std::max behavior intentionally preserves the
722 // established treatment of non-positive rates.
723 const double stagedSourceRate = std::max(sourceRate, 1.0);
724 const double stagedTargetRate = std::max(targetRate, 1.0);
725 const double stagedRatio = stagedTargetRate / stagedSourceRate;
726 if (stagedRatio > kMaxRatio) return;
727 const Design d = design(stagedRatio, quality);
728
729 auto [l, m] = rationalRatio(stagedSourceRate, stagedTargetRate);
730 const bool exact = d.identity
731 || (l > 0 && l <= kMaxExactPhases
732 && l * static_cast<int64_t>(d.taps) <= kMaxExactCoefficients);
733 if (d.identity) { l = 1; m = 1; }
734
735 // Every potentially throwing allocation belongs to local state. A
736 // failure therefore destroys only the candidate and leaves the live
737 // conversion, histories and streaming positions untouched.
738 std::vector<T> stagedTable;
739 if (exact)
740 {
741 // Phase p is the kernel for fractional position p / L.
742 stagedTable.resize(static_cast<size_t>(l * d.taps));
743 buildTable(stagedTable.data(), d, l, 0, l);
744 }
745 else
746 {
747 // kTablePhases + 3 phases: one guard phase before position 0 and
748 // two after the last, so cubic interpolation across phases never
749 // reads outside the table.
750 stagedTable.resize(static_cast<size_t>((kTablePhases + 3) * d.taps));
751 buildTable(stagedTable.data(), d, kTablePhases, -1, kTablePhases + 3);
752 }
753 ChannelState stagedMono;
754 initialiseChannelState(stagedMono, d.taps);
755 std::vector<ChannelState> stagedChannels(channelCount);
756 for (auto& state : stagedChannels)
757 initialiseChannelState(state, d.taps);
758
759 // Scalar assignment and the mechanically checked swaps below cannot
760 // throw. Once commit starts, observers can only see the complete new
761 // state (prepare itself remains a setup-thread operation).
762 sourceRate_ = stagedSourceRate;
763 targetRate_ = stagedTargetRate;
764 quality_ = quality;
765 ratio_ = stagedRatio;
766 srcStep_ = 1.0 / stagedRatio;
767 taps_ = d.taps;
768 halfTaps_ = d.taps / 2;
769 exact_ = exact;
770 phasesL_ = exact ? l : 0;
771 stepM_ = exact ? m : 0;
772 table_.swap(stagedTable);
773 using std::swap;
774 swap(mono_, stagedMono);
775 channelStates_.swap(stagedChannels);
776 }
777
779 T interpolateContiguous(const T* src, int64_t phase, double frac) const noexcept
780 {
781 if (exact_)
782 return simd::dotProduct(table_.data() + phase * taps_, src, taps_);
783
784 // Cubic (Lagrange) interpolation across the four phases around the
785 // position: error ~ (pi / (2 * kTablePhases))^4, below every stopband.
786 const double exactPhase = frac * static_cast<double>(kTablePhases);
787 int p0 = static_cast<int>(exactPhase);
788 if (p0 > kTablePhases - 1) p0 = kTablePhases - 1; // frac is < 1 by contract
789 const double u = exactPhase - static_cast<double>(p0);
790 const T* k = table_.data() + static_cast<size_t>(p0) * static_cast<size_t>(taps_);
791 // Table phase index p0 + 1 holds position p0 / P (one guard phase first).
792 const T sm = simd::dotProduct(k, src, taps_);
793 const T s0 = simd::dotProduct(k + taps_, src, taps_);
794 const T s1 = simd::dotProduct(k + 2 * taps_, src, taps_);
795 const T s2 = simd::dotProduct(k + 3 * taps_, src, taps_);
796 const double wm = -u * (u - 1.0) * (u - 2.0) / 6.0;
797 const double w0 = (u + 1.0) * (u - 1.0) * (u - 2.0) / 2.0;
798 const double w1 = -(u + 1.0) * u * (u - 2.0) / 2.0;
799 const double w2 = (u + 1.0) * u * (u - 1.0) / 6.0;
800 return static_cast<T>(wm * sm + w0 * s0 + w1 * s1 + w2 * s2);
801 }
802
804 T interpolateOffline(const T* data, int length, int intPos,
805 int64_t phase, double frac)
806 {
807 // Tap j weighs data[intPos - halfTaps + 1 + j] (see buildPhase).
808 const int firstSrc = intPos - halfTaps_ + 1;
809 if (firstSrc >= 0 && firstSrc + taps_ <= length)
810 return interpolateContiguous(data + firstSrc, phase, frac);
811
812 // Edge path: gather into a zero-padded window. The kernel is read
813 // exactly as in the fast path, so both agree bit for bit.
814 std::vector<T>& w = edgeScratch_;
815 w.assign(static_cast<size_t>(taps_), T(0));
816 for (int j = 0; j < taps_; ++j)
817 {
818 const int srcIdx = firstSrc + j;
819 if (srcIdx >= 0 && srcIdx < length)
820 w[static_cast<size_t>(j)] = data[srcIdx];
821 }
822 return interpolateContiguous(w.data(), phase, frac);
823 }
824
825 // -- Two-stage offline engine ------------------------------------------------
826
828 static constexpr int kTwoStagePhases = 2048;
829
831 struct TwoStageShape
832 {
833 int up = 1;
834 int half1 = 1;
835 double cutoff1 = 1.0;
836 double beta1 = 0.0;
837 Design stage2;
838 int64_t phases2 = 0;
839 int64_t step2 = 0;
840 bool pick = false;
841 };
842
849 static constexpr double kStage1MarginDb = 12.0;
850 static constexpr double kStage2MarginDb = 40.0;
851
852 [[nodiscard]] static TwoStageShape twoStageShape(double sourceRate, double targetRate,
853 double ratio, Quality quality) noexcept
854 {
855 TwoStageShape s;
856 const Spec spec = qualitySpec(quality);
857 const double atten1 = spec.attenuationDb + kStage1MarginDb;
858 const double atten2 = spec.attenuationDb + kStage2MarginDb;
859 const double band = 0.5 * std::min(1.0, ratio); // lower Nyquist, cycles per input sample
860 // The mid rate doubles the input's when the band is too close to the
861 // input Nyquist to leave stage 2 a transition of half the mid rate.
862 s.up = ((1.0 + spec.passband) * band <= 0.5) ? 1 : 2;
863 const double b = band / static_cast<double>(s.up); // cycles per mid sample
864 // Stage 1: flat to passband * b, stopband from b (the tier's edges).
865 const double order1 = std::min((atten1 - 7.95) / (14.36 * (1.0 - spec.passband) * b),
866 static_cast<double>(kMaxTwoStageOrder));
867 s.half1 = std::max(1, static_cast<int>(std::ceil(0.5 * order1)));
868 s.cutoff1 = (1.0 + spec.passband) * b;
869 s.beta1 = kaiserBeta(atten1);
870 // Stage 2: flat to passband * b; the mid signal holds nothing above b
871 // until its first image at 1 - b, where the stopband starts.
872 const double order2 = (atten2 - 7.95) / (14.36 * (1.0 - (1.0 + spec.passband) * b));
873 s.stage2.taps = std::max(4, 4 * static_cast<int>(std::ceil(0.25 * order2)));
874 s.stage2.cutoff = spec.passband * b + 1.0 - b;
875 s.stage2.beta = kaiserBeta(atten2);
876 const auto [l, m] = rationalRatio(sourceRate * static_cast<double>(s.up), targetRate);
877 s.phases2 = l;
878 s.step2 = m;
879 // An integer ratio between the mid and output rates (48 <-> 96 kHz)
880 // reads the band-limited mid signal at its own samples: no stage 2.
881 // Two taps, {1, 0}, keep the window arithmetic of the general case.
882 if (l == 1)
883 {
884 s.pick = true;
885 s.stage2.taps = 2;
886 }
887 return s;
888 }
889
891 struct TwoStagePlan
892 {
893 bool ready = false;
894 double sourceRate = 0.0;
895 double targetRate = 0.0;
896 Quality quality = Quality::Normal;
897 TwoStageShape shape;
898 int fftSize = 0;
899 int block = 0;
900 bool exact2 = true;
901 int64_t phases2 = 1;
902 int64_t step2 = 1;
903 double midStep = 1.0;
904 std::vector<double> gain1;
905 std::vector<double> table2;
906 std::vector<int64_t> advance2;
907 std::vector<int32_t> cycleOf2;
908 std::optional<detail::fft::SplitFFT<double>> engine;
909 std::optional<detail::fft::SplitFFT<double>> engineHalf;
910 std::optional<detail::fft::SplitFFT<double>> engineDecim;
911 std::vector<double> mid;
912 };
913
915 [[nodiscard]] bool useTwoStage()
916 {
917 if (offlineEngine_ != OfflineEngine::TwoStage || ratio_ == 1.0) return false;
918 if (!plan_.ready || plan_.sourceRate != sourceRate_ || plan_.targetRate != targetRate_
919 || plan_.quality != quality_)
920 {
921 // Built aside: a failed allocation leaves the previous plan intact.
922 TwoStagePlan fresh = buildTwoStagePlan(sourceRate_, targetRate_, ratio_, quality_);
923 plan_ = std::move(fresh);
924 }
925 return true;
926 }
927
928 [[nodiscard]] static TwoStagePlan buildTwoStagePlan(double sourceRate, double targetRate,
929 double ratio, Quality quality)
930 {
931 constexpr double kPi = std::numbers::pi;
932 TwoStagePlan p;
933 p.sourceRate = sourceRate;
934 p.targetRate = targetRate;
935 p.quality = quality;
936 p.shape = twoStageShape(sourceRate, targetRate, ratio, quality);
937 const TwoStageShape& s = p.shape;
938 const int order1 = 2 * s.half1;
939 const int taps2 = s.stage2.taps;
940
941 // At least 75% of every transform is output.
942 int n = 256;
943 while (n < 4 * order1 || n < 4 * taps2 + 16) n *= 2;
944 p.fftSize = n;
945 p.block = n - order1;
946
947 // Stage 1: Kaiser-windowed sinc at the mid rate, DC gain `up` (the
948 // zero-stuffing keeps one sample in `up`), stored centred on sample
949 // 0 of the circular frame: its spectrum is then real, and the
950 // filtering a multiplication of every (re, im) pair by one number.
951 std::vector<double> h(static_cast<size_t>(n), 0.0);
952 const double i0Beta = besselI0(s.beta1);
953 double sum = 0.0;
954 for (int t = -s.half1; t <= s.half1; ++t)
955 {
956 const double x = static_cast<double>(t) * s.cutoff1;
957 const double sincVal = (std::abs(x) < 1e-12)
958 ? s.cutoff1
959 : s.cutoff1 * std::sin(kPi * x) / (kPi * x);
960 const double wx = static_cast<double>(t) / static_cast<double>(s.half1);
961 const double win = besselI0(s.beta1 * std::sqrt(std::max(0.0, 1.0 - wx * wx))) / i0Beta;
962 h[static_cast<size_t>(t >= 0 ? t : n + t)] = sincVal * win;
963 sum += sincVal * win;
964 }
965 // The inverse transform's 1/n is folded into the gain.
966 const double gain = static_cast<double>(s.up) / (sum * static_cast<double>(n));
967 for (auto& v : h) v *= gain;
968 {
969 FFTReal<double> fft(static_cast<size_t>(n));
970 std::vector<double> spec(static_cast<size_t>(n) + 2, 0.0);
971 fft.forward(h.data(), spec.data());
972 // The imaginary parts are rounding; the spectrum is even.
973 p.gain1.assign(static_cast<size_t>(n), 0.0);
974 for (int k = 0; k <= n / 2; ++k)
975 {
976 p.gain1[static_cast<size_t>(k)] = spec[static_cast<size_t>(2 * k)];
977 p.gain1[static_cast<size_t>((n - k) % n)] = spec[static_cast<size_t>(2 * k)];
978 }
979 }
980 // Two frames per transform: one as the real part, the next as the
981 // imaginary part. The kernel is real, so the filtered frames come
982 // back as the real and imaginary parts of one inverse.
983 p.engine.emplace(static_cast<size_t>(n));
984 if (s.up == 2) p.engineHalf.emplace(static_cast<size_t>(n / 2));
985 // A 2:1 pick reads every second mid sample only: the inverse is taken
986 // at half the length on the folded spectrum (the kernel's stopband
987 // starts at the output Nyquist, so the fold aliases nothing).
988 if (s.pick && s.up == 1 && s.step2 == 2) p.engineDecim.emplace(static_cast<size_t>(n / 2));
989
990 // Stage 2: exact phases when fs_out / fs_mid is a manageable fraction.
991 const int64_t l = s.phases2, m = s.step2;
992 p.exact2 = l > 0 && l <= kMaxExactPhases
993 && l * static_cast<int64_t>(taps2) <= kMaxExactCoefficients;
994 p.midStep = static_cast<double>(s.up) / ratio;
995 if (s.pick)
996 {
997 p.phases2 = 1;
998 p.step2 = m;
999 p.table2 = { 1.0, 0.0 };
1000 }
1001 else if (p.exact2)
1002 {
1003 p.phases2 = l;
1004 p.step2 = m;
1005 // The rows follow the outputs: output k of a cycle of l outputs has
1006 // phase (k * m) mod l, so the stage-2 loop reads the table front to
1007 // back and steps its window by a precomputed advance (no division
1008 // and no data-dependent branch per output).
1009 p.table2.resize(static_cast<size_t>(l * taps2));
1010 p.advance2.resize(static_cast<size_t>(l));
1011 p.cycleOf2.resize(static_cast<size_t>(l));
1012 for (int64_t k = 0; k < l; ++k)
1013 {
1014 const int64_t ph = (k * (m % l)) % l;
1015 buildPhase(p.table2.data() + k * taps2, s.stage2,
1016 static_cast<double>(ph) / static_cast<double>(l));
1017 p.advance2[static_cast<size_t>(k)] = m / l + (ph + m % l >= l ? 1 : 0);
1018 p.cycleOf2[static_cast<size_t>(ph)] = static_cast<int32_t>(k);
1019 }
1020 }
1021 else
1022 {
1023 // One guard phase before position 0 and two after the last.
1024 p.table2.resize(static_cast<size_t>(kTwoStagePhases + 3) * static_cast<size_t>(taps2));
1025 for (int ph = 0; ph < kTwoStagePhases + 3; ++ph)
1026 buildPhase(p.table2.data() + static_cast<size_t>(ph) * static_cast<size_t>(taps2), s.stage2,
1027 static_cast<double>(ph - 1) / static_cast<double>(kTwoStagePhases));
1028 }
1029 // Room for the carried window, then the two frames of one transform
1030 // (see runTwoStage()).
1031 p.mid.assign(static_cast<size_t>(taps2 + s.up + 2 * p.block), 0.0);
1032 p.ready = true;
1033 return p;
1034 }
1035
1049 void twoStagePair(const T* input, int inputLength, int64_t s, double* dst) noexcept
1050 {
1051 TwoStagePlan& p = plan_;
1052 const int n = p.fftSize, up = p.shape.up, half1 = p.shape.half1, block = p.block;
1053 const int frameInputs = n / up;
1054 const int64_t q0 = (s - half1) / up; // the first frame's first input (exact)
1055 const int64_t q1 = q0 + block / up; // and the second frame's
1056 if (std::max<int64_t>(q0, 0) >= std::min<int64_t>(q1 + frameInputs, inputLength))
1057 {
1058 std::fill(dst, dst + 2 * block, 0.0);
1059 return;
1060 }
1061 detail::fft::SplitFFT<double>& first = (up == 1) ? *p.engine : *p.engineHalf;
1062 const double* zr = nullptr;
1063 const double* zi = nullptr;
1064 bool direct = false;
1065 if constexpr (std::is_same_v<T, double>)
1066 {
1067 // Both frames inside the input: the transform reads them there.
1068 if (q0 >= 0 && q1 + frameInputs <= inputLength)
1069 {
1070 first.runFromSplit(input + q0, input + q1, zr, zi);
1071 direct = true;
1072 }
1073 }
1074 if (!direct)
1075 {
1076 const auto load = [&](double* frame, int64_t q) noexcept {
1077 const int64_t a = std::clamp<int64_t>(-q, 0, frameInputs);
1078 const int64_t b = std::clamp<int64_t>(inputLength - q, a, frameInputs);
1079 std::fill(frame, frame + a, 0.0);
1080 for (int64_t t = a; t < b; ++t) frame[t] = static_cast<double>(input[q + t]);
1081 std::fill(frame + b, frame + frameInputs, 0.0);
1082 };
1083 load(first.inRe(), q0);
1084 load(first.inIm(), q1);
1085 first.run(zr, zi);
1086 }
1087
1088 // The filter's product and inverse in one transform. The zero-stuffed
1089 // frames' spectrum is the half-length one repeated, Z[k] = Zh[k mod
1090 // n/2].
1091 const double* wr = nullptr;
1092 const double* wi = nullptr;
1093 if (p.engineDecim)
1094 {
1095 // Decimated sample u is frame sample 2u, mid sample s - half1 + 2u
1096 // of the first frame (s + block - half1 + 2u of the second): the
1097 // even mid samples, the only ones the pick reads.
1098 p.engineDecim->runScaledSwapFolded(zr, zi, p.gain1.data(), 2, wr, wi);
1099 for (int i = half1 & 1; i < block; i += 2)
1100 {
1101 dst[i] = wi[(i + half1) / 2];
1102 dst[block + i] = wr[(i + half1) / 2];
1103 }
1104 return;
1105 }
1106 p.engine->runScaledSwap(zr, zi, p.gain1.data(), static_cast<size_t>(n / up - 1), wr, wi);
1107 std::copy(wi + half1, wi + half1 + block, dst);
1108 std::copy(wr + half1, wr + half1 + block, dst + block);
1109 }
1110
1112 [[nodiscard]] double twoStageTable(const double* src, double frac) const noexcept
1113 {
1114 const int taps2 = plan_.shape.stage2.taps;
1115 const double exactPhase = frac * static_cast<double>(kTwoStagePhases);
1116 int p0 = static_cast<int>(exactPhase);
1117 if (p0 > kTwoStagePhases - 1) p0 = kTwoStagePhases - 1;
1118 const double u = exactPhase - static_cast<double>(p0);
1119 const double* k = plan_.table2.data() + static_cast<size_t>(p0) * static_cast<size_t>(taps2);
1120 const double* const rows[4] = { k, k + taps2, k + 2 * taps2, k + 3 * taps2 };
1121 double y[4];
1122 simd::dotProduct4(src, rows, taps2, y);
1123 const double sm = y[0], s0 = y[1], s1 = y[2], s2 = y[3];
1124 const double wm = -u * (u - 1.0) * (u - 2.0) / 6.0;
1125 const double w0 = (u + 1.0) * (u - 1.0) * (u - 2.0) / 2.0;
1126 const double w1 = -(u + 1.0) * u * (u - 2.0) / 2.0;
1127 const double w2 = (u + 1.0) * u * (u - 1.0) / 6.0;
1128 return wm * sm + w0 * s0 + w1 * s1 + w2 * s2;
1129 }
1130
1138 void runTwoStage(const T* input, int inputLength, int64_t firstOutput, int64_t count, T* out)
1139 {
1140 if (plan_.shape.pick) runTwoStageAs<true, true>(input, inputLength, firstOutput, count, out);
1141 else if (plan_.exact2) runTwoStageAs<true, false>(input, inputLength, firstOutput, count, out);
1142 else runTwoStageAs<false, false>(input, inputLength, firstOutput, count, out);
1143 }
1144
1145 template <bool Exact, bool Pick>
1146 void runTwoStageAs(const T* input, int inputLength, int64_t firstOutput, int64_t count, T* out)
1147 {
1148 // Everything the loop reads lives in locals: the output stores
1149 // cannot then force reloads of the plan.
1150 TwoStagePlan& p = plan_;
1151 const int up = p.shape.up, half1 = p.shape.half1, block = p.block;
1152 const int taps2 = p.shape.stage2.taps, half2 = taps2 / 2;
1153 const int carry = taps2 + up; // room before the transform
1154 const int64_t pairBlock = 2 * static_cast<int64_t>(block); // mid samples per transform
1155 const int64_t l = p.phases2;
1156 const double midStep = p.midStep;
1157 // Mid samples that can differ from zero.
1158 const int64_t nzLo = -static_cast<int64_t>(half1);
1159 const int64_t nzHi = static_cast<int64_t>(up) * (inputLength - 1) + half1;
1160 double* const mid = p.mid.data();
1161 int64_t origin = 0, bufStart = 0, bufEnd = 0;
1162 bool haveBuf = false;
1163
1164 // Exact: output k sits at mid position k * step2 / l; the anchor
1165 // (its floor) and the phase (the remainder) advance exactly.
1166 // Table: the position is k * midStep.
1167 int64_t anchor = 0, phase = 0, wholeStep = 0, remStep = 0;
1168 double frac = 0.0;
1169 if constexpr (Exact)
1170 {
1171 wholeStep = p.step2 / l;
1172 remStep = p.step2 % l;
1173 // floor(k * step2 / l) without forming k * step2.
1174 const int64_t r = firstOutput * remStep;
1175 int64_t q = r / l, rem = r % l;
1176 if (rem < 0) { rem += l; --q; }
1177 anchor = firstOutput * wholeStep + q;
1178 phase = rem;
1179 }
1180
1181 int64_t i = 0;
1182 while (i < count)
1183 {
1184 if constexpr (!Exact)
1185 {
1186 const double pos = static_cast<double>(firstOutput + i) * midStep;
1187 const double fl = std::floor(pos);
1188 anchor = static_cast<int64_t>(fl);
1189 frac = pos - fl;
1190 }
1191 // Tap j weighs mid sample anchor - half2 + 1 + j (as buildPhase).
1192 int64_t w0 = anchor - half2 + 1;
1193 if (w0 + taps2 <= nzLo || w0 > nzHi)
1194 {
1195 out[i++] = T(0);
1196 if constexpr (Exact)
1197 {
1198 anchor += wholeStep;
1199 phase += remStep;
1200 if (phase >= l) { phase -= l; ++anchor; }
1201 }
1202 continue;
1203 }
1204 if (!haveBuf || w0 >= bufEnd)
1205 {
1206 // (Re)start on the fixed grid of transforms, half1 + j * 2 *
1207 // block for any integer j: every call computes a mid sample
1208 // with the same transform, so spans agree bit for bit. The
1209 // grid puts an input sample on each frame's first slot (block
1210 // is even).
1211 const int64_t d = w0 - half1;
1212 const int64_t j = d / pairBlock - ((d % pairBlock) < 0 ? 1 : 0);
1213 bufStart = bufEnd = half1 + j * pairBlock;
1214 haveBuf = true;
1215 }
1216 while (bufEnd < w0 + taps2)
1217 {
1218 // Move the part of the window already computed (fewer than
1219 // taps2 samples) in front of the new transform's samples.
1220 const int64_t keep = std::max(w0, bufStart);
1221 const int r = static_cast<int>(bufEnd - keep);
1222 if (r > 0) std::copy(mid + (keep - origin), mid + (bufEnd - origin), mid + (carry - r));
1223 twoStagePair(input, inputLength, bufEnd, mid + carry);
1224 origin = bufEnd - carry;
1225 bufStart = keep;
1226 bufEnd += pairBlock;
1227 }
1228 // Every output whose window is now in the buffer.
1229 const int64_t last = std::min(bufEnd - taps2, nzHi); // largest w0 served here
1230 if constexpr (Exact)
1231 {
1232 const double* src = mid + (w0 - origin);
1233 if constexpr (Pick)
1234 {
1235 do
1236 {
1237 out[i++] = static_cast<T>(*src);
1238 src += wholeStep;
1239 w0 += wholeStep;
1240 phase += remStep;
1241 if (phase >= l) { phase -= l; ++src; ++w0; }
1242 } while (i < count && w0 <= last);
1243 }
1244 else
1245 {
1246 // The table rows follow the outputs (see buildTwoStagePlan()),
1247 // so the loop walks them in order and steps the window by the
1248 // cycle's precomputed advances.
1249 const double* const rows = p.table2.data();
1250 const int64_t* const advance = p.advance2.data();
1251 int64_t k = p.cycleOf2[static_cast<size_t>(phase)];
1252 const double* row = rows + k * taps2;
1253 // Outputs j and j + l share a kernel row, and their windows
1254 // lie step2 mid samples apart. The batch runs in groups of
1255 // at most eight cycles, of nearly equal sizes (the group's
1256 // windows stay in the first-level cache while every row
1257 // meets them); in a group, each position of the cycle runs
1258 // its outputs as one strided set of products, the row
1259 // loaded once for all of them. A result has the same bits
1260 // however its set is split, so spans agree. Output j from
1261 // here sits at w0 + floor((phase + j step2) / l), so those
1262 // up to `last` are the first ((last - w0 + 1) l - phase -
1263 // 1) / step2 + 1.
1264 const int64_t cycleStep = p.step2;
1265 const int64_t batch = std::min<int64_t>(
1266 count - i, ((last - w0 + 1) * l - phase - 1) / cycleStep + 1);
1267 const int64_t cycles = batch / l, rest = batch % l;
1268 const int64_t spanned = cycles + (rest > 0 ? 1 : 0);
1269 const int64_t groups = (spanned + 7) / 8;
1270 for (int64_t g = 0, c0 = 0; g < groups; ++g)
1271 {
1272 const int64_t size = (spanned - c0 + (groups - g) - 1) / (groups - g);
1273 const double* s = src + c0 * cycleStep;
1274 const double* r = row;
1275 int64_t kk = k;
1276 const int64_t positions = std::min(l, batch - c0 * l);
1277 for (int64_t t = 0; t < positions; ++t)
1278 {
1279 const int m = static_cast<int>(std::min(size, cycles + (t < rest ? 1 : 0) - c0));
1280 double y[8];
1281 simd::dotProductStrided(r, s, static_cast<std::ptrdiff_t>(cycleStep), taps2, m, y);
1282 T* const o = out + i + c0 * l + t;
1283 for (int x = 0; x < m; ++x) o[x * l] = static_cast<T>(y[x]);
1284 s += advance[kk];
1285 r += taps2;
1286 if (++kk == l) { kk = 0; r = rows; }
1287 }
1288 c0 += size;
1289 }
1290 // On to output i + batch: position `rest` of cycle `cycles`.
1291 for (int64_t t = 0; t < rest; ++t)
1292 {
1293 src += advance[k];
1294 if (++k == l) k = 0;
1295 }
1296 src += cycles * cycleStep;
1297 w0 = origin + (src - mid);
1298 i += batch;
1299 phase = (k * remStep) % l;
1300 }
1301 anchor = w0 + half2 - 1;
1302 }
1303 else
1304 {
1305 do
1306 {
1307 out[i++] = static_cast<T>(twoStageTable(mid + (w0 - origin), frac));
1308 if (i == count) break;
1309 const double pos = static_cast<double>(firstOutput + i) * midStep;
1310 const double fl = std::floor(pos);
1311 anchor = static_cast<int64_t>(fl);
1312 frac = pos - fl;
1313 w0 = anchor - half2 + 1;
1314 } while (w0 <= last);
1315 // The loop head recomputes the same position.
1316 }
1317 }
1318 }
1319
1320 static void resetChannelState(ChannelState& cs) noexcept
1321 {
1322 std::fill(cs.history.begin(), cs.history.end(), T(0));
1323 cs.writePos = 0;
1324 cs.fractionalPos = 0.0;
1325 cs.phase = 0;
1326 }
1327
1328 int processChannel(const T* input, int inputLength, T* output,
1329 ChannelState& state) noexcept
1330 {
1331 if (state.history.empty()) return 0; // not prepared
1332
1333 // Hot state lives in locals for the duration of the block: this both
1334 // tells the compiler the fields cannot alias the output writes (no
1335 // per-sample reloads) and keeps them in registers. The window
1336 // [writePos, writePos + n) holds the last n inputs, oldest first; the
1337 // kernel peaks at tap halfTaps-1+frac, so the output stream is
1338 // delayed by exactly halfTaps input samples (see getLatency()).
1339 T* const hist = state.history.data();
1340 const int n = taps_;
1341 int writePos = state.writePos;
1342 int outIdx = 0;
1343
1344 if (exact_)
1345 {
1346 const int64_t l = phasesL_, m = stepM_;
1347 int64_t phase = state.phase;
1348 for (int i = 0; i < inputLength; ++i)
1349 {
1350 // Double-buffered push: the mirror write keeps the read
1351 // window contiguous (no modulo).
1352 const T x = input[i];
1353 hist[writePos] = x;
1354 hist[writePos + n] = x;
1355 if (++writePos >= n)
1356 writePos = 0;
1357
1358 while (phase < l)
1359 {
1360 output[outIdx++] = interpolateContiguous(hist + writePos, phase, 0.0);
1361 phase += m;
1362 }
1363 phase -= l;
1364 }
1365 state.phase = phase;
1366 }
1367 else
1368 {
1369 const double step = srcStep_;
1370 double frac = state.fractionalPos;
1371 for (int i = 0; i < inputLength; ++i)
1372 {
1373 const T x = input[i];
1374 hist[writePos] = x;
1375 hist[writePos + n] = x;
1376 if (++writePos >= n)
1377 writePos = 0;
1378
1379 while (frac < 1.0)
1380 {
1381 output[outIdx++] = interpolateContiguous(hist + writePos, 0, frac);
1382 frac += step;
1383 }
1384 frac -= 1.0;
1385 }
1386 state.fractionalPos = frac;
1387 }
1388
1389 state.writePos = writePos;
1390 return outIdx;
1391 }
1392
1393 double sourceRate_ = 44100.0;
1394 double targetRate_ = 48000.0;
1395 double ratio_ = 1.0;
1396 double srcStep_ = 1.0;
1397
1398 int taps_ = 2;
1399 int halfTaps_ = 1;
1400 bool exact_ = true;
1401 int64_t phasesL_ = 0;
1402 int64_t stepM_ = 0;
1403
1404 Quality quality_ = Quality::Normal;
1405 OfflineEngine offlineEngine_ = OfflineEngine::Direct;
1406
1407 std::vector<T> table_;
1408 std::vector<T> edgeScratch_;
1409 ChannelState mono_;
1410 std::vector<ChannelState> channelStates_;
1411 TwoStagePlan plan_;
1412};
1413
1414} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Windowed-sinc sample rate converter optimized for real-time DSP.
Definition Resampler.h:100
int processBlock(AudioBufferView< T > input, AudioBufferView< T > output) noexcept
Resamples multi-channel audio using AudioBufferView (streaming).
Definition Resampler.h:404
@ High
Passband 0.91 of Nyquist (20 kHz at 44.1), 140 dB stopband.
@ Ultra
Passband 0.915 of Nyquist, 210 dB stopband: mastering.
@ Normal
Passband 0.90 of Nyquist, 100 dB stopband.
@ Draft
Passband 0.80 of Nyquist, 60 dB stopband: previews.
int64_t getReach() const noexcept
How far, in output samples, the kernel reaches before an input sample and after it: processRange() ov...
Definition Resampler.h:369
OfflineEngine getOfflineEngine() const noexcept
The offline engine in force (Direct by default).
Definition Resampler.h:179
int getLatency() const noexcept
Returns the streaming latency in output samples.
Definition Resampler.h:453
static constexpr int kMaxTaps
Longest kernel, in input samples (see the class note).
Definition Resampler.h:111
double getRatio() const noexcept
Returns the conversion ratio (targetRate / sourceRate).
Definition Resampler.h:440
static constexpr double kMaxRatio
Largest target/source ratio prepare() accepts. Output per input sample follows the ratio,...
Definition Resampler.h:115
int getFilterLength() const noexcept
Kernel length in input samples (1 at a ratio of exactly 1).
Definition Resampler.h:443
std::vector< T > processRange(const T *input, int inputLength, int64_t firstOutput, int64_t count)
Offline, time-aligned conversion of any span of output samples.
Definition Resampler.h:322
int64_t process(const T *input, int inputLength, T *output, int64_t outputCapacity)
process() into caller storage.
Definition Resampler.h:268
OfflineEngine
How process() and processRange() compute (setOfflineEngine()).
Definition Resampler.h:123
@ TwoStage
FFT band-limiting, then a short interpolator: the same tier specification, cheaper.
@ Direct
The streaming kernels: process() is processBlock() shifted by getLatency(), bit for bit.
void reset() noexcept
Resets the internal state (delay lines, all channels) to zero.
Definition Resampler.h:224
void setOfflineEngine(OfflineEngine engine) noexcept
Chooses the offline engine (the streaming path is unaffected).
Definition Resampler.h:176
std::vector< T > process(const T *input, int inputLength)
Resamples an entire buffer (offline batch processing).
Definition Resampler.h:244
int processBlock(const T *input, int inputLength, T *output) noexcept
Resamples a block of audio in single-channel streaming mode.
Definition Resampler.h:390
void prepare(const AudioSpec &spec, double targetRate, Quality quality=Quality::Normal)
Prepares the resampler using AudioSpec (unified API).
Definition Resampler.h:208
void prepare(double sourceRate, double targetRate, Quality quality=Quality::Normal)
Prepares the resampler for a given rate conversion.
Definition Resampler.h:192
static constexpr int kMaxTwoStageOrder
Longest stage-1 kernel order of the TwoStage offline engine (see setOfflineEngine()).
Definition Resampler.h:119
int getMaxOutputSamples(int inputLength) const noexcept
Returns the maximum number of output samples for a given input length.
Definition Resampler.h:431
void dotProduct4(const double *shared, const double *const *other, int count, double *out) noexcept
dotProduct() of one array with four others: out[x] equals dotProduct(shared, other[x],...
Definition SimdOps.h:773
void dotProductStrided(const double *shared, const double *first, std::ptrdiff_t stride, int count, int outputs, double *out) noexcept
Dot products of one array with outputs arrays stride elements apart: out[x] = sum_i shared[i] * first...
Definition SimdOps.h:809
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
Definition SimdOps.h:644
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45