DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Oversampling.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
53#include "AudioBuffer.h"
54#include "AudioSpec.h"
55#include "DenormalGuard.h"
56#include "FIRFilter.h"
57#include "SimdOps.h"
58
59#include <algorithm>
60#include <array>
61#include <cassert>
62#include <cmath>
63#include <complex>
64#include <cstring>
65#include <memory>
66#include <vector>
67
68namespace dspark {
69
99template <typename T, int MaxChannels = 16>
101{
102public:
114 enum class Quality
115 {
116 Low,
117 Medium,
118 High,
119 Maximum
120 };
121
123 enum class Mode
124 {
127 };
128
146 enum class Depth
147 {
148 Preset,
149 Deep
150 };
151
190 enum class Band
191 {
192 Preset,
193 Audible
194 };
195
209 explicit Oversampling(int factor = 2, Quality quality = Quality::High,
211 Band band = Band::Preset)
212 : quality_(quality), mode_(mode), depth_(depth), band_(band),
213 firstStage_(firStageDesign(quality, depth, 0)), firstTransition_(firTransition(quality))
214 {
215 assert(factor >= 1 && (factor & (factor - 1)) == 0 && "Factor must be a power of 2");
216 assert(factor <= (1 << kMaxStages) && "Factor must be <= 16 (kMaxStages stages)");
217 // Release-safe normalisation: clamp into [1, 2^kMaxStages], then derive
218 // the stage count and re-derive factor_ = 2^numStages_ so the pair stays
219 // coherent even for a non-power-of-two request. An incoherent pair
220 // (e.g. factor_ = 3 driving one 2x stage) would make downsample() emit
221 // factor_/2 samples per base sample -- overrunning the caller's output
222 // buffer -- and overflow the per-stage histories sized for 2^numStages_.
223 factor = std::clamp(factor, 1, 1 << kMaxStages);
224 numStages_ = 0;
225 while ((1 << (numStages_ + 1)) <= factor)
226 ++numStages_;
227 factor_ = 1 << numStages_;
228
229 if (mode_ == Mode::PolyphaseIir)
230 {
231 for (int s = 0; s < numStages_; ++s)
232 iir_[static_cast<size_t>(s)].design(iirCoefficientCount(quality_, depth_, s),
233 iirTransition(quality_, s));
234 }
235 computeDelays();
236 }
237
250 void prepare(const AudioSpec& spec)
251 {
252 baseSpec_ = spec;
253 upBuffer_.resize(spec.numChannels, spec.maxBlockSize * factor_);
254 fitFirstStage(spec.sampleRate);
255
256 for (int stage = 0; stage < numStages_; ++stage)
257 {
258 // The max block size entering a stage is baseSize * 2^stage
259 const int stageMaxSamples = spec.maxBlockSize * (1 << stage);
260 if (mode_ == Mode::PolyphaseIir)
261 {
262 iir_[static_cast<size_t>(stage)].allocate(spec.numChannels, stageMaxSamples);
263 }
264 else
265 {
266 const StageDesign d = stageDesign(stage);
267 filters_[static_cast<size_t>(stage)].design(d.taps, static_cast<T>(d.beta),
268 spec.numChannels, stageMaxSamples);
269 }
270 }
271
272 reset();
273 }
274
279 void reset() noexcept
280 {
281 upBuffer_.clear();
282 for (int i = 0; i < numStages_; ++i)
283 {
284 filters_[static_cast<size_t>(i)].reset();
285 iir_[static_cast<size_t>(i)].reset();
286 }
287 }
288
303 [[nodiscard]] static constexpr int factorForRate(double sampleRate,
304 double minimumInternalRate = 176400.0,
305 int maxFactor = 1 << kMaxStages) noexcept
306 {
307 if (!(sampleRate > 0.0) || !(sampleRate < 1e12)) return 1;
308 const int limit = maxFactor < 1 ? 1 : (maxFactor > (1 << kMaxStages) ? (1 << kMaxStages) : maxFactor);
309 int factor = 1;
310 // A rate a rounding error short of an exact multiple still counts.
311 while (factor * 2 <= limit && sampleRate * factor < minimumInternalRate * (1.0 - 1e-9))
312 factor *= 2;
313 return factor;
314 }
315
317 [[nodiscard]] int getFactor() const noexcept { return factor_; }
318
320 [[nodiscard]] Quality getQuality() const noexcept { return quality_; }
321
323 [[nodiscard]] Mode getMode() const noexcept { return mode_; }
324
326 [[nodiscard]] Depth getDepth() const noexcept { return depth_; }
327
329 [[nodiscard]] Band getBand() const noexcept { return band_; }
330
342 [[nodiscard]] int getStageLength(int stage) const noexcept
343 {
344 if (mode_ != Mode::LinearPhaseFir || stage < 0 || stage >= numStages_) return 0;
345 return stageDesign(stage).taps;
346 }
347
355 [[nodiscard]] double getFirstStageTransition() const noexcept { return firstTransition_; }
356
370 [[nodiscard]] int getLatency() const noexcept { return latency_; }
371
384 [[nodiscard]] double getRoundTripDelay(double frequencyHz) const noexcept
385 {
386 if (mode_ != Mode::PolyphaseIir || numStages_ == 0)
387 return static_cast<double>(latency_);
388 const double fs = baseSpec_.sampleRate > 0.0 ? baseSpec_.sampleRate : 48000.0;
389 const double w = 2.0 * 3.14159265358979323846 * std::clamp(frequencyHz / fs, 1e-6, 0.4999);
390 return iirDelay(w, true);
391 }
392
405 [[nodiscard]] int getDecimationDelay() const noexcept { return decimationDelay_; }
406
421 [[nodiscard]] AudioBufferView<T> getHighRateBlock(int numSamples) noexcept
422 {
423 const int nS = std::clamp(numSamples, 0, baseSpec_.maxBlockSize);
424 return upBuffer_.toView().getSubView(0, nS * factor_);
425 }
426
438 {
439 const int nCh = std::min(input.getNumChannels(), upBuffer_.getNumChannels());
440 // Release-safe clamp: a block larger than prepare()'s maxBlockSize would
441 // overflow the per-stage histories and the internal high-rate buffer.
442 const int nS = std::min(input.getNumSamples(), baseSpec_.maxBlockSize);
443
444 if (numStages_ == 0)
445 {
446 for (int ch = 0; ch < nCh; ++ch)
447 std::memcpy(upBuffer_.getChannel(ch), input.getChannel(ch), static_cast<std::size_t>(nS) * sizeof(T));
448 return upBuffer_.toView().getSubView(0, nS);
449 }
450
451 if (mode_ == Mode::PolyphaseIir)
452 {
453 DenormalGuard guard; // recursive state: keep decaying tails out of the denormal range
454 int len = nS;
455 for (int stage = 0; stage < numStages_; ++stage)
456 {
457 for (int ch = 0; ch < nCh; ++ch)
458 iir_[static_cast<size_t>(stage)].upsampleChannel(
459 stage == 0 ? input.getChannel(ch) : upBuffer_.getChannel(ch),
460 upBuffer_.getChannel(ch), ch, len);
461 len *= 2;
462 }
463 return upBuffer_.toView().getSubView(0, nS * factor_);
464 }
465
466 // Stage 0: Read directly from input view
467 filters_[0].processUpsample(input, upBuffer_.toView(), nCh, nS);
468
469 // Subsequent stages: in-place upsampling inside upBuffer_
470 int currentLen = nS * 2;
471 for (int stage = 1; stage < numStages_; ++stage)
472 {
473 filters_[static_cast<size_t>(stage)].processUpsampleInPlace(upBuffer_.toView(), nCh, currentLen);
474 currentLen *= 2;
475 }
476
477 return upBuffer_.toView().getSubView(0, nS * factor_);
478 }
479
490 void downsample(AudioBufferView<T> output) noexcept
491 {
492 const int nCh = std::min(output.getNumChannels(), upBuffer_.getNumChannels());
493 const int nS = std::min(output.getNumSamples(), baseSpec_.maxBlockSize);
494
495 if (numStages_ == 0)
496 {
497 for (int ch = 0; ch < nCh; ++ch)
498 std::memcpy(output.getChannel(ch), upBuffer_.getChannel(ch), static_cast<std::size_t>(nS) * sizeof(T));
499 return;
500 }
501
502 if (mode_ == Mode::PolyphaseIir)
503 {
504 DenormalGuard guard;
505 int len = nS * factor_;
506 for (int stage = numStages_ - 1; stage >= 0; --stage)
507 {
508 for (int ch = 0; ch < nCh; ++ch)
509 iir_[static_cast<size_t>(stage)].downsampleChannel(
510 upBuffer_.getChannel(ch),
511 stage == 0 ? output.getChannel(ch) : upBuffer_.getChannel(ch), ch, len);
512 len /= 2;
513 }
514 return;
515 }
516
517 int currentLen = nS * factor_;
518
519 for (int stage = numStages_ - 1; stage > 0; --stage)
520 {
521 filters_[static_cast<size_t>(stage)].processDownsampleInPlace(upBuffer_.toView(), nCh, currentLen);
522 currentLen /= 2;
523 }
524
525 // Stage 0: Write directly to final output
526 filters_[0].processDownsample(upBuffer_.toView(), output, nCh, currentLen);
527
528 // Level transparency note: no gain compensation is applied (or needed).
529 // An impulse round-trip peaks slightly below 1.0 only because the
530 // impulse contains supra-Nyquist energy the anti-alias filters must
531 // remove; in-band sine-wave gain is already ~1.000 (verified to better
532 // than 0.01 dB across all quality presets).
533 }
534
535private:
536 static constexpr int kMaxStages = 4;
537
538 // ========================================================================
539 // Polyphase Block Half-Band FIR
540 // ========================================================================
545 struct PolyphaseHalfBand
546 {
547 std::vector<T> evenTaps;
548 T centerTap = T(0);
549 int halfOrder = 0;
550 int delaySamples = 0;
551
556 std::vector<T> history;
557 std::vector<T> evenHist;
558 std::vector<T> oddHist;
559 };
560 std::vector<ChannelState> upChannels;
561 std::vector<ChannelState> downChannels;
562 std::vector<T> scratch;
563
571 void design(int taps, T beta, int numChannels, int maxBlockSamples)
572 {
573 halfOrder = (taps - 1) / 2;
574 // INVARIANT: the polyphase split below collects the array-even taps,
575 // which coincide with the non-zero (odd-from-centre) half-band taps
576 // ONLY when halfOrder is odd. Every stage design satisfies this
577 // (firStageDesign); keep (taps-1)/2 odd or the filter degenerates.
578 assert((halfOrder & 1) == 1 && "half-band polyphase requires odd halfOrder");
579 // Pure-delay alignment for the centre-tap (odd) phase. With the full
580 // even branch (halfOrder+1 taps, group delay (halfOrder)/2 = numTaps/2
581 // base samples) the centre sample must sit numTaps/2 = (halfOrder+1)/2
582 // samples into the window to stay phase-aligned with the even phase.
583 delaySamples = (halfOrder + 1) / 2;
584
585 auto fullCoeffs = FIRDesign<T>::lowPass(1.0, 0.25, taps, beta);
586 centerTap = fullCoeffs[static_cast<std::size_t>(halfOrder)];
587
588 // The non-zero taps: all even array indices (the centre sits at the
589 // odd index halfOrder, and the other odd indices are the half-band
590 // zeros).
591 evenTaps.clear();
592 for (int i = 0; i < taps; i += 2)
593 evenTaps.push_back(fullCoeffs[static_cast<std::size_t>(i)]);
594
595 // Up history: base-rate (numTaps + block). Down histories: halfOrder
596 // samples of prefix plus up to maxBlockSamples new samples per phase
597 // (a stage's decimator input is 2 * maxBlockSamples long).
598 const int upHistorySize = static_cast<int>(evenTaps.size()) + maxBlockSamples;
599 const int downHistorySize = halfOrder + maxBlockSamples;
600
601 upChannels.resize(static_cast<std::size_t>(numChannels));
602 downChannels.resize(static_cast<std::size_t>(numChannels));
603
604 for (int ch = 0; ch < numChannels; ++ch)
605 {
606 upChannels[ch].history.assign(static_cast<std::size_t>(upHistorySize), T(0));
607 downChannels[ch].evenHist.assign(static_cast<std::size_t>(downHistorySize), T(0));
608 downChannels[ch].oddHist.assign(static_cast<std::size_t>(downHistorySize), T(0));
609 }
610 scratch.assign(static_cast<std::size_t>(maxBlockSamples), T(0));
611 }
612
616 void reset() noexcept
617 {
618 for (auto& ch : upChannels)
619 std::fill(ch.history.begin(), ch.history.end(), T(0));
620 for (auto& ch : downChannels)
621 {
622 std::fill(ch.evenHist.begin(), ch.evenHist.end(), T(0));
623 std::fill(ch.oddHist.begin(), ch.oddHist.end(), T(0));
624 }
625 }
626
632 void upsampleChannel(const T* src, T* dst, ChannelState& state, int n) noexcept
633 {
634 constexpr int W = simd::kVecWidth<T>;
635 using O = simd::Vec<T, W>;
636 const int numTaps = static_cast<int>(evenTaps.size());
637 auto& hist = state.history;
638
639 // Append the new block after the fixed numTaps-sample history prefix.
640 std::memmove(hist.data() + numTaps, src, static_cast<std::size_t>(n) * sizeof(T));
641
642 simd::firCorrelate(hist.data(), evenTaps.data(), numTaps, scratch.data(), n, T(2));
643
644 const T* centre = hist.data() + numTaps - delaySamples;
645 const T centre2 = centerTap * T(2);
646 const auto c2 = O::set1(centre2);
647 int i = 0;
648 for (; i + W <= n; i += W)
649 O::storeInterleave2(dst + 2 * i, O::load(scratch.data() + i),
650 O::mul(O::load(centre + i), c2));
651 for (; i < n; ++i)
652 {
653 dst[2 * i] = scratch[static_cast<std::size_t>(i)];
654 dst[2 * i + 1] = centre[i] * centre2;
655 }
656
657 // Save the trailing numTaps input samples for the next block. Using
658 // the current n keeps this correct under variable block sizes.
659 std::memmove(hist.data(), hist.data() + n, static_cast<std::size_t>(numTaps) * sizeof(T));
660 }
661
668 void downsampleChannel(const T* src, T* dst, ChannelState& state, int len) noexcept
669 {
670 constexpr int W = simd::kVecWidth<T>;
671 using O = simd::Vec<T, W>;
672 const int outLen = len / 2;
673 const int numTaps = static_cast<int>(evenTaps.size());
674 T* even = state.evenHist.data();
675 T* odd = state.oddHist.data();
676
677 // Split the new samples after the halfOrder-sample prefixes.
678 int m = 0;
679 for (; m + W <= outLen; m += W)
680 {
681 typename O::V e, o;
682 O::loadDeinterleave(src + 2 * m, e, o);
683 O::store(even + halfOrder + m, e);
684 O::store(odd + halfOrder + m, o);
685 }
686 for (; m < outLen; ++m)
687 {
688 even[halfOrder + m] = src[2 * m];
689 odd[halfOrder + m] = src[2 * m + 1];
690 }
691
692 simd::firCorrelate(even, evenTaps.data(), numTaps, dst, outLen, T(1));
693
694 // The centre tap meets x[2k + halfOrder] = odd[k + (halfOrder - 1) / 2].
695 const T* centre = odd + (halfOrder - 1) / 2;
696 const auto c = O::set1(centerTap);
697 int k = 0;
698 for (; k + W <= outLen; k += W)
699 O::store(dst + k, O::madd(c, O::load(centre + k), O::load(dst + k)));
700 for (; k < outLen; ++k)
701 {
702 // Keep the vector multiply-add rounding at block tails too.
703 T lanes[W];
704 O::store(lanes, O::madd(c, O::set1(centre[k]), O::set1(dst[k])));
705 dst[k] = lanes[0];
706 }
707
708 std::memmove(even, even + outLen, static_cast<std::size_t>(halfOrder) * sizeof(T));
709 std::memmove(odd, odd + outLen, static_cast<std::size_t>(halfOrder) * sizeof(T));
710 }
711
712 void processUpsample(AudioBufferView<const T> input, AudioBufferView<T> output, int nCh, int nS) noexcept
713 {
714 for (int ch = 0; ch < nCh; ++ch)
715 upsampleChannel(input.getChannel(ch), output.getChannel(ch),
716 upChannels[static_cast<std::size_t>(ch)], nS);
717 }
718
719 void processUpsampleInPlace(AudioBufferView<T> buffer, int nCh, int currentLen) noexcept
720 {
721 for (int ch = 0; ch < nCh; ++ch)
722 upsampleChannel(buffer.getChannel(ch), buffer.getChannel(ch),
723 upChannels[static_cast<std::size_t>(ch)], currentLen);
724 }
725
726 void processDownsample(AudioBufferView<const T> input, AudioBufferView<T> output, int nCh, int currentLen) noexcept
727 {
728 for (int ch = 0; ch < nCh; ++ch)
729 downsampleChannel(input.getChannel(ch), output.getChannel(ch),
730 downChannels[static_cast<std::size_t>(ch)], currentLen);
731 }
732
733 void processDownsampleInPlace(AudioBufferView<T> buffer, int nCh, int currentLen) noexcept
734 {
735 for (int ch = 0; ch < nCh; ++ch)
736 downsampleChannel(buffer.getChannel(ch), buffer.getChannel(ch),
737 downChannels[static_cast<std::size_t>(ch)], currentLen);
738 }
739 };
740
741 // ========================================================================
742 // Polyphase IIR half-band (elliptic allpass pair)
743 // ========================================================================
744
748 template <int W, typename D = double> struct BranchPair
749 {
750 struct V { D a, b; };
751 static V set(D a, D b) noexcept { return { a, b }; }
752 static V load(const D* p) noexcept { return { p[0], p[1] }; }
753 static void store(D* p, V v) noexcept { p[0] = v.a; p[1] = v.b; }
754 static V step(V c, V x, V x1, V y1) noexcept
755 {
756 return { c.a * (x.a - y1.a) + x1.a, c.b * (x.b - y1.b) + x1.b };
757 }
758 static D first(V v) noexcept { return v.a; }
759 static D second(V v) noexcept { return v.b; }
760 };
761 template <typename D> struct BranchPair<2, D>
762 {
763 using O = simd::Vec<D, 2>;
764 using V = typename O::V;
765 static V set(D a, D b) noexcept { return O::set2(a, b); }
766 static V load(const D* p) noexcept { return O::load(p); }
767 static void store(D* p, V v) noexcept { O::store(p, v); }
768 static V step(V c, V x, V x1, V y1) noexcept
769 {
770 return O::add(O::mul(c, O::sub(x, y1)), x1);
771 }
772 static D first(V v) noexcept { return O::lane0(v); }
773 static D second(V v) noexcept { return O::lane1(v); }
774 };
775 using Pair = BranchPair<simd::kVecDoubleNarrow>;
776
789 struct PolyphaseIirHalfBand
790 {
791 static constexpr int kMaxPairs = 8;
792
793 int numPairs = 0;
794 alignas(16) std::array<double, 2 * kMaxPairs> coef {};
795
800 {
801 alignas(16) std::array<double, 2 * (kMaxPairs + 1)> s {};
802 };
803 std::vector<ChannelState> up, down;
804 std::vector<T> scratch;
805
826 void design(int numCoefs, double transition) noexcept
827 {
828 constexpr double kPi = 3.14159265358979323846;
829 numCoefs = std::clamp(numCoefs & ~1, 2, 2 * kMaxPairs);
830 numPairs = numCoefs / 2;
831 const double fp = 0.25 - 0.5 * std::clamp(transition, 1e-4, 0.4999);
832 const double k = std::tan(kPi * fp) * std::tan(kPi * fp);
833 const double q = nome(k);
834 const int order = 2 * numCoefs + 1;
835 std::array<double, 2 * kMaxPairs> a {};
836 for (int i = 1; i <= numCoefs; ++i)
837 {
838 double num = 0.0, den = 0.0;
839 for (int m = 0; m < 20; ++m)
840 {
841 const double sign = (m & 1) ? -1.0 : 1.0;
842 num += sign * std::pow(q, m * (m + 1.0)) * std::sin((2 * m + 1) * kPi * i / order);
843 if (m > 0) den += sign * std::pow(q, static_cast<double>(m) * m) * std::cos(2 * m * kPi * i / order);
844 }
845 const double w = 2.0 * std::pow(q, 0.25) * num / (1.0 + 2.0 * den);
846 const double w2 = w * w;
847 const double sigma = std::sqrt(std::max(0.0, (1.0 - k * w2) * (1.0 - w2 / k))) / (1.0 + w2);
848 a[static_cast<size_t>(i - 1)] = (1.0 - sigma) / (1.0 + sigma);
849 }
850 std::sort(a.begin(), a.begin() + numCoefs);
851 for (int i = 0; i < numCoefs; ++i)
852 coef[static_cast<size_t>(i)] = a[static_cast<size_t>(i)]; // even -> A0, odd -> A1
853 }
854
856 static double nome(double k) noexcept
857 {
858 const double kp = std::sqrt(1.0 - k * k);
859 const double e = 0.5 * (1.0 - std::sqrt(kp)) / (1.0 + std::sqrt(kp));
860 const double e4 = e * e * e * e;
861 return e * (1.0 + e4 * (2.0 + e4 * (15.0 + 150.0 * e4)));
862 }
863
865 static double attenuationDb(int numCoefs, double transition) noexcept
866 {
867 constexpr double kPi = 3.14159265358979323846;
868 const double fp = 0.25 - 0.5 * transition;
869 const double q = nome(std::tan(kPi * fp) * std::tan(kPi * fp));
870 return 10.0 * std::log10(1.0 + std::pow(q, -(2.0 * numCoefs + 1.0) / 2.0) / 4.0);
871 }
872
874 std::complex<double> response(double w) const noexcept
875 {
876 const std::complex<double> z2 = std::polar(1.0, -2.0 * w);
877 std::complex<double> a0 = 1.0, a1 = 1.0;
878 for (int k = 0; k < numPairs; ++k)
879 {
880 const double c0 = coef[static_cast<size_t>(2 * k)];
881 const double c1 = coef[static_cast<size_t>(2 * k + 1)];
882 a0 *= (c0 + z2) / (1.0 + c0 * z2);
883 a1 *= (c1 + z2) / (1.0 + c1 * z2);
884 }
885 return 0.5 * (a0 + std::polar(1.0, -w) * a1);
886 }
887
888 void allocate(int numChannels, int maxInputSamples)
889 {
890 const auto n = static_cast<size_t>(std::max(0, numChannels));
891 up.assign(n, ChannelState {});
892 down.assign(n, ChannelState {});
893 scratch.assign(static_cast<size_t>(std::max(0, maxInputSamples)), T(0));
894 }
895
896 void reset() noexcept
897 {
898 for (auto& s : up) s = ChannelState {};
899 for (auto& s : down) s = ChannelState {};
900 }
901
908 template <int P, bool Up>
909 static void runBlock(const double* coefs, ChannelState& st, const T* src, T* dst, int n) noexcept
910 {
911 using V = typename Pair::V;
912 V prev = Pair::load(st.s.data());
913 V y1[P];
914 V c[P];
915 for (int k = 0; k < P; ++k)
916 {
917 y1[k] = Pair::load(st.s.data() + 2 * (k + 1));
918 c[k] = Pair::load(coefs + 2 * k);
919 }
920 for (int i = 0; i < n; ++i)
921 {
922 V in;
923 if constexpr (Up)
924 {
925 const double x = static_cast<double>(src[i]);
926 in = Pair::set(x, x);
927 }
928 else
929 {
930 in = Pair::set(static_cast<double>(src[2 * i + 1]), static_cast<double>(src[2 * i]));
931 }
932 V xPrev = prev;
933 prev = in;
934 for (int k = 0; k < P; ++k)
935 {
936 const V yOld = y1[k];
937 const V y = Pair::step(c[k], in, xPrev, yOld);
938 xPrev = yOld;
939 y1[k] = y;
940 in = y;
941 }
942 if constexpr (Up)
943 {
944 dst[2 * i] = static_cast<T>(Pair::first(in));
945 dst[2 * i + 1] = static_cast<T>(Pair::second(in));
946 }
947 else
948 {
949 dst[i] = static_cast<T>(0.5 * (Pair::first(in) + Pair::second(in)));
950 }
951 }
952 Pair::store(st.s.data(), prev);
953 double sum = Pair::first(prev) + Pair::second(prev);
954 for (int k = 0; k < P; ++k)
955 {
956 Pair::store(st.s.data() + 2 * (k + 1), y1[k]);
957 sum += Pair::first(y1[k]) + Pair::second(y1[k]);
958 }
959 if (!std::isfinite(sum)) st = ChannelState {};
960 }
961
962 template <bool Up>
963 void dispatch(ChannelState& st, const T* src, T* dst, int n) noexcept
964 {
965 const double* c = coef.data();
966 switch (numPairs)
967 {
968 case 1: runBlock<1, Up>(c, st, src, dst, n); break;
969 case 2: runBlock<2, Up>(c, st, src, dst, n); break;
970 case 3: runBlock<3, Up>(c, st, src, dst, n); break;
971 case 4: runBlock<4, Up>(c, st, src, dst, n); break;
972 case 5: runBlock<5, Up>(c, st, src, dst, n); break;
973 case 6: runBlock<6, Up>(c, st, src, dst, n); break;
974 case 7: runBlock<7, Up>(c, st, src, dst, n); break;
975 default: runBlock<8, Up>(c, st, src, dst, n); break;
976 }
977 }
978
980 void upsampleChannel(const T* src, T* dst, int ch, int n) noexcept
981 {
982 if (static_cast<size_t>(ch) >= up.size()) return;
983 if (src == dst)
984 {
985 std::memcpy(scratch.data(), src, static_cast<size_t>(n) * sizeof(T));
986 src = scratch.data();
987 }
988 dispatch<true>(up[static_cast<size_t>(ch)], src, dst, n);
989 }
990
992 void downsampleChannel(const T* src, T* dst, int ch, int len) noexcept
993 {
994 if (static_cast<size_t>(ch) >= down.size()) return;
995 dispatch<false>(down[static_cast<size_t>(ch)], src, dst, len / 2);
996 }
997 };
998
999 struct StageDesign { int taps; double beta; };
1000
1015 static constexpr StageDesign firStageDesign(Quality q, Depth depth, int stage) noexcept
1016 {
1017 constexpr StageDesign kLow[kMaxStages] = { { 31, 3.395 }, { 11, 2.90 }, { 7, 2.35 }, { 15, 9.45 } };
1018 constexpr StageDesign kMed[kMaxStages] = { { 63, 5.653 }, { 19, 6.25 }, { 15, 7.90 }, { 15, 9.50 } };
1019 constexpr StageDesign kHigh[kMaxStages] = { { 127, 7.857 }, { 23, 7.95 }, { 23, 12.55 }, { 15, 9.50 } };
1020 constexpr StageDesign kMax[kMaxStages] = { { 255, 10.056 },{ 31, 11.20 }, { 23, 12.70 }, { 31, 15.65 } };
1021 constexpr StageDesign kLowDeep[kMaxStages] = { { 91, 10.45 }, { 35, 11.35 }, { 23, 12.30 }, { 31, 15.65 } };
1022 constexpr StageDesign kMedDeep[kMaxStages] = { { 115, 10.45 }, { 31, 10.40 }, { 23, 12.40 }, { 31, 15.65 } };
1023 constexpr StageDesign kHighDeep[kMaxStages] = { { 163, 10.10 }, { 31, 10.85 }, { 23, 12.55 }, { 31, 15.65 } };
1024 const int s = std::clamp(stage, 0, kMaxStages - 1);
1025 const bool deep = depth == Depth::Deep;
1026 switch (q)
1027 {
1028 case Quality::Low: return deep ? kLowDeep[s] : kLow[s];
1029 case Quality::Medium: return deep ? kMedDeep[s] : kMed[s];
1030 case Quality::High: return deep ? kHighDeep[s] : kHigh[s];
1031 case Quality::Maximum: return kMax[s];
1032 }
1033 return kHigh[s];
1034 }
1035
1038 [[nodiscard]] StageDesign stageDesign(int stage) const noexcept
1039 {
1040 return stage == 0 ? firstStage_ : firStageDesign(quality_, depth_, stage);
1041 }
1042
1044 static constexpr double firstStageDepthDb(Quality q, Depth depth) noexcept
1045 {
1046 if (depth == Depth::Deep) return 100.1;
1047 switch (q)
1048 {
1049 case Quality::Low: return 38.9;
1050 case Quality::Medium: return 59.5;
1051 case Quality::High: return 79.2;
1052 case Quality::Maximum: return 100.1;
1053 }
1054 return 79.2;
1055 }
1056
1058 static constexpr double kAudibleEdgeHz = 20000.0;
1060 static constexpr int kShortestFit = 7;
1061
1063 static double kaiserBeta(double depthDb) noexcept
1064 {
1065 if (depthDb > 50.0) return 0.1102 * (depthDb - 8.7);
1066 if (depthDb > 21.0) return 0.5842 * std::pow(depthDb - 21.0, 0.4) + 0.07886 * (depthDb - 21.0);
1067 return 0.0;
1068 }
1069
1079 static double halfBandStopPeakDb(int taps, double beta, double edge)
1080 {
1081 const std::vector<double> full = FIRDesign<double>::lowPass(1.0, 0.25, taps, beta);
1082 const int half = (taps - 1) / 2;
1083 const int points = std::max(64, 4 * taps);
1084 double peak = 0.0;
1085 for (int p = 0; p <= points; ++p)
1086 {
1087 const double f = edge + (0.5 - edge) * static_cast<double>(p) / static_cast<double>(points);
1088 const double theta = 2.0 * 3.14159265358979323846 * f;
1089 const double twice = 2.0 * std::cos(2.0 * theta);
1090 double before = std::cos(theta), now = before; // cos(-theta), cos(theta)
1091 double sum = full[static_cast<size_t>(half)];
1092 for (int k = 1; k <= half; k += 2)
1093 {
1094 sum += (full[static_cast<size_t>(half + k)] + full[static_cast<size_t>(half - k)]) * now;
1095 const double next = twice * now - before; // cos((k + 2) theta)
1096 before = now;
1097 now = next;
1098 }
1099 peak = std::max(peak, std::abs(sum));
1100 }
1101 return 20.0 * std::log10(std::max(peak, 1e-12));
1102 }
1103
1112 static StageDesign fitHalfBand(double transition, double depthDb, StageDesign otherwise)
1113 {
1114 const double edge = 0.25 + 0.5 * transition;
1115 const double estimate = (depthDb - 7.95) / (14.36 * transition) + 1.0;
1116 int taps = 4 * static_cast<int>(estimate / 4.0) + 3 - 8;
1117 if (taps < kShortestFit) taps = kShortestFit;
1118 const double centre = kaiserBeta(depthDb);
1119 for (; taps < otherwise.taps; taps += 4)
1120 {
1121 double bestBeta = centre, bestPeak = halfBandStopPeakDb(taps, centre, edge);
1122 for (int i = -8; i <= 16; ++i)
1123 {
1124 const double beta = centre + 0.25 * static_cast<double>(i);
1125 if (i == 0 || beta < 0.5) continue;
1126 const double peak = halfBandStopPeakDb(taps, beta, edge);
1127 if (peak < bestPeak) { bestPeak = peak; bestBeta = beta; }
1128 }
1129 const double around = bestBeta;
1130 for (int i = -4; i <= 4; ++i)
1131 {
1132 const double beta = around + 0.05 * static_cast<double>(i);
1133 if (i == 0 || beta < 0.5) continue;
1134 const double peak = halfBandStopPeakDb(taps, beta, edge);
1135 if (peak < bestPeak) { bestPeak = peak; bestBeta = beta; }
1136 }
1137 if (bestPeak <= -depthDb) return { taps, bestBeta };
1138 }
1139 return otherwise;
1140 }
1141
1149 void fitFirstStage(double sampleRate)
1150 {
1151 firstStage_ = firStageDesign(quality_, depth_, 0);
1152 firstTransition_ = firTransition(quality_);
1153 if (band_ != Band::Audible || numStages_ == 0) return;
1154
1155 if (sampleRate > 2.0 * kAudibleEdgeHz && sampleRate < 1e12)
1156 {
1157 const double wide = 0.5 - kAudibleEdgeHz / sampleRate;
1158 if (wide > firstTransition_)
1159 {
1160 firstTransition_ = wide;
1161 if (mode_ == Mode::LinearPhaseFir)
1162 firstStage_ = fitHalfBand(wide, firstStageDepthDb(quality_, depth_), firstStage_);
1163 }
1164 }
1165 if (mode_ == Mode::PolyphaseIir)
1166 iir_[0].design(iirCoefficientCountOver(firstStageDepthDb(quality_, depth_), firstTransition_),
1167 firstTransition_);
1168 computeDelays();
1169 }
1170
1173 static constexpr double firTransition(Quality q) noexcept
1174 {
1175 switch (q)
1176 {
1177 case Quality::Low: return (40.0 - 7.95) / (14.36 * 30.0);
1178 case Quality::Medium: return (60.0 - 7.95) / (14.36 * 62.0);
1179 case Quality::High: return (80.0 - 7.95) / (14.36 * 126.0);
1180 case Quality::Maximum: return (100.0 - 7.95) / (14.36 * 254.0);
1181 }
1182 return (80.0 - 7.95) / (14.36 * 126.0);
1183 }
1184
1187 static double iirTransition(Quality q, int stage) noexcept
1188 {
1189 const double t0 = firTransition(q);
1190 return stage == 0 ? t0 : 0.5 - (1.0 + 2.0 * t0) / static_cast<double>(1 << (stage + 1));
1191 }
1192
1196 static int iirCoefficientCount(Quality q, Depth depth, int stage) noexcept
1197 {
1198 return iirCoefficientCountOver(firstStageDepthDb(q, depth), iirTransition(q, stage));
1199 }
1200
1202 static int iirCoefficientCountOver(double depthDb, double transition) noexcept
1203 {
1204 int n = 2;
1205 while (n < 2 * PolyphaseIirHalfBand::kMaxPairs
1206 && PolyphaseIirHalfBand::attenuationDb(n, transition) < depthDb)
1207 n += 2;
1208 return n;
1209 }
1210
1213 double iirDelay(double w, bool roundTrip) const noexcept
1214 {
1215 constexpr int kSteps = 512;
1216 double total = 0.0;
1217 for (int s = 0; s < numStages_; ++s)
1218 {
1219 const double scale = 1.0 / static_cast<double>(1 << (s + 1));
1220 double prev = 0.0, unwrapped = 0.0;
1221 for (int i = 1; i <= kSteps; ++i)
1222 {
1223 const double wi = w * scale * static_cast<double>(i) / kSteps;
1224 const double ph = std::arg(iir_[static_cast<size_t>(s)].response(wi));
1225 double d = ph - prev;
1226 while (d > 3.14159265358979323846) d -= 2.0 * 3.14159265358979323846;
1227 while (d < -3.14159265358979323846) d += 2.0 * 3.14159265358979323846;
1228 unwrapped += d;
1229 prev = ph;
1230 }
1231 // Down path keeps the odd instant: one high-rate sample of advance.
1232 const double down = unwrapped + w * scale;
1233 total += roundTrip ? (unwrapped + down) : down;
1234 }
1235 return -total / w;
1236 }
1237
1238 void computeDelays() noexcept
1239 {
1240 if (numStages_ == 0) { latency_ = 0; decimationDelay_ = 0; return; }
1241 if (mode_ == Mode::PolyphaseIir)
1242 {
1243 const double w = 1e-4;
1244 latency_ = static_cast<int>(std::lround(iirDelay(w, true)));
1245 decimationDelay_ = static_cast<int>(std::lround(iirDelay(w, false) * factor_));
1246 return;
1247 }
1248 int latency = 0, decimation = 0;
1249 for (int s = 0; s < numStages_; ++s)
1250 {
1251 const int halfOrder = (stageDesign(s).taps - 1) / 2;
1252 latency += (halfOrder + 1) / (1 << s); // exact by design
1253 decimation += halfOrder * (factor_ >> (s + 1));
1254 }
1255 latency_ = latency;
1256 decimationDelay_ = decimation;
1257 }
1258
1259 int factor_;
1260 int numStages_;
1261 Quality quality_;
1262 Mode mode_;
1263 Depth depth_;
1264 Band band_;
1265 StageDesign firstStage_;
1266 double firstTransition_;
1267 int latency_ = 0;
1268 int decimationDelay_ = 0;
1269 AudioSpec baseSpec_ {};
1270 AudioBuffer<T, MaxChannels> upBuffer_;
1271
1272 std::array<PolyphaseHalfBand, kMaxStages> filters_;
1273 std::array<PolyphaseIirHalfBand, kMaxStages> iir_;
1274};
1275
1300template <typename T, int MaxChannels = 16>
1302{
1303public:
1305
1314 void prepare(const AudioSpec& spec, const Engine& engine)
1315 {
1316 twin_.reset();
1317 delay_.clear();
1318 delaySamples_ = 0;
1319 writePos_ = 0;
1320 numChannels_ = std::clamp(spec.numChannels, 0, MaxChannels);
1321 if (engine.getFactor() <= 1 || numChannels_ == 0 || spec.maxBlockSize <= 0)
1322 return;
1323
1324 if (engine.getMode() == Engine::Mode::PolyphaseIir)
1325 {
1326 twin_ = std::make_unique<Engine>(engine.getFactor(), engine.getQuality(),
1327 engine.getMode(), engine.getDepth(), engine.getBand());
1328 twin_->prepare(spec);
1329 }
1330 else
1331 {
1332 delaySamples_ = engine.getLatency();
1333 delay_.assign(static_cast<size_t>(numChannels_) * static_cast<size_t>(std::max(delaySamples_, 1)), T(0));
1334 }
1335 }
1336
1338 void reset() noexcept
1339 {
1340 if (twin_) twin_->reset();
1341 std::fill(delay_.begin(), delay_.end(), T(0));
1342 writePos_ = 0;
1343 }
1344
1346 [[nodiscard]] int getLatency() const noexcept { return twin_ ? twin_->getLatency() : delaySamples_; }
1347
1354 void process(AudioBufferView<T> dry) noexcept
1355 {
1356 if (twin_)
1357 {
1358 [[maybe_unused]] const auto high = twin_->upsample(dry);
1359 twin_->downsample(dry);
1360 return;
1361 }
1362 if (delaySamples_ <= 0) return;
1363
1364 const int nCh = std::min(dry.getNumChannels(), numChannels_);
1365 const int nS = dry.getNumSamples();
1366 if (nS <= 0) return;
1367 const size_t length = static_cast<size_t>(delaySamples_);
1368 for (int ch = 0; ch < nCh; ++ch)
1369 {
1370 T* x = dry.getChannel(ch);
1371 T* line = delay_.data() + static_cast<size_t>(ch) * length;
1372 size_t pos = writePos_;
1373 for (int i = 0; i < nS; ++i)
1374 {
1375 const T out = line[pos];
1376 line[pos] = x[i];
1377 x[i] = out;
1378 if (++pos == length) pos = 0;
1379 }
1380 }
1381 // Every channel advanced by the same count from the same position.
1382 writePos_ = (writePos_ + static_cast<size_t>(nS)) % length;
1383 }
1384
1385private:
1386 std::unique_ptr<Engine> twin_;
1387 std::vector<T> delay_;
1388 int delaySamples_ = 0;
1389 int numChannels_ = 0;
1390 size_t writePos_ = 0;
1391};
1392
1393} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
AudioBufferView< T, MaxChannels > toView() noexcept
Returns a non-owning mutable view of this buffer. The view's channel capacity is propagated from MaxC...
int getNumChannels() const noexcept
Returns the number of active channels.
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
void resize(int numChannels, int numSamples)
Allocates the buffer for the given dimensions.
void clear() noexcept
Clears all channels, including SIMD alignment padding. Ensures any SIMD over-read will consume pure z...
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
static std::vector< T > lowPass(double sampleRate, double cutoffHz, int numTaps, T beta=T(5))
Designs a low-pass FIR filter.
Definition FIRFilter.h:89
Carries a dry signal through the same round trip as an Oversampling engine, so that a dry/wet mix add...
void process(AudioBufferView< T > dry) noexcept
Passes a block of the dry signal through the path, in place.
void prepare(const AudioSpec &spec, const Engine &engine)
Sizes the path for an engine.
void reset() noexcept
Clears the path's memory.
int getLatency() const noexcept
The delay of the path in base-rate samples, as the engine reports its own.
Power-of-two oversampling processor with polyphase anti-aliasing.
AudioBufferView< T > getHighRateBlock(int numSamples) noexcept
Writable high-rate block for a source that renders directly at the oversampled rate (a synthesizer,...
Mode getMode() const noexcept
Returns the half-band filter family.
double getFirstStageTransition() const noexcept
Transition band of the first stage, as a fraction of the 2x rate.
Depth getDepth() const noexcept
Returns the stopband depth (Depth::Preset or Depth::Deep).
void downsample(AudioBufferView< T > output) noexcept
Downsamples the internal high-rate buffer back to base-rate.
Band
The band the first stage keeps (see the constructor).
@ Audible
The first stage keeps 20 kHz and stops its image, by the host rate.
@ Preset
The preset's transition band (default).
int getStageLength(int stage) const noexcept
Length of a linear-phase stage's kernel, in taps at its high rate.
void reset() noexcept
Flushes all internal delay lines and history buffers. Call this when resetting the transport or to cl...
Oversampling(int factor=2, Quality quality=Quality::High, Mode mode=Mode::LinearPhaseFir, Depth depth=Depth::Preset, Band band=Band::Preset)
Constructs the oversampling engine.
int getFactor() const noexcept
Returns the current oversampling factor.
Quality getQuality() const noexcept
Returns the current quality preset.
AudioBufferView< T > upsample(AudioBufferView< const T > input) noexcept
Upsamples the input base-rate signal into the internal high-rate buffer.
Mode
Half-band filter family (see the file notes).
@ PolyphaseIir
Elliptic allpass pairs: a few samples of nonlinear-phase delay.
@ LinearPhaseFir
Exact integer delay at every frequency (default).
Band getBand() const noexcept
Returns the band of the first stage (Band::Preset or Band::Audible).
Depth
Stopband depth of the cascade (see the constructor).
@ Deep
At least 100 dB in every stage, with the preset's band.
@ Preset
The quality preset's depth (default).
int getDecimationDelay() const noexcept
Group delay of the decimation path alone, in HIGH-RATE samples.
int getLatency() const noexcept
Round-trip (upsample + downsample) delay at the BASE rate, in samples.
Quality
Quality presets defining the steepness and rejection of the anti-aliasing filter.
@ Low
~-40 dB stopband. For fast previewing.
@ High
~-80 dB stopband. Professional standard.
@ Maximum
~-100 dB stopband. Mastering grade.
@ Medium
~-60 dB stopband. General purpose.
double getRoundTripDelay(double frequencyHz) const noexcept
Exact round-trip delay at a frequency, in base-rate samples.
void prepare(const AudioSpec &spec)
Pre-allocates buffers and computes FIR filter coefficients.
static constexpr int factorForRate(double sampleRate, double minimumInternalRate=176400.0, int maxFactor=1<< kMaxStages) noexcept
The smallest factor that brings a host rate up to an internal rate.
void firCorrelate(const T *x, const T *h, int taps, T *DSPARK_RESTRICT y, int n, T gain) noexcept
Block FIR as a valid correlation: y[i] = gain * sum_j h[j] * x[i + j] for i in [0,...
Definition SimdOps.h:1496
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
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
std::vector< T > oddHist
Decimator: odd high-rate samples with prefix.
std::vector< T > evenHist
Decimator: even high-rate samples with prefix.
std::vector< T > history
Upsampler: base-rate input with its FIR prefix.