DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
CrossoverFilter.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
116#include "../Core/AudioBuffer.h"
117#include "../Core/AudioSpec.h"
118#include "../Core/Biquad.h"
119#include "../Core/BiquadCascade.h"
120#include "../Core/DspMath.h"
121#include "../Core/DenormalGuard.h"
122#include "../Core/FFT.h"
123#include "../Core/NormalizedLadder.h"
124#include "../Core/SimdOps.h"
125#include "../Core/SmoothedValue.h"
126#include "../Core/StateBlob.h"
127
128#include <algorithm>
129#include <array>
130#include <atomic>
131#include <cmath>
132#include <cstddef>
133#include <cstdint>
134#include <cstdio>
135#include <memory>
136#include <numbers>
137#include <vector>
138
139namespace dspark {
140
148template <FloatType T, int MaxBands = 12>
150{
151public:
153 enum class FilterMode
154 {
157 };
158
160 {
161 initDefaultFrequencies();
162 }
163
164 // -- Lifecycle -----------------------------------------------------------
165
177 void prepare(const AudioSpec& spec)
178 {
179 if (!spec.isValid()) return;
180 prepared_ = false; // basic guarantee while (re)allocating
181 spec_ = spec;
182 // Per-split filters are Biquad<T, 16>; clamp so processing more than 16
183 // channels can't index their fixed per-channel state out of bounds.
184 numChannels_ = std::min(static_cast<int>(spec.numChannels), 16);
185
186 // Allocate flat IIR work buffer (Channels * MaxBlockSize)
187 workBuf_.assign(static_cast<size_t>(spec.numChannels) * static_cast<size_t>(spec.maxBlockSize), T(0));
188
189 // Linear-phase resources. Allocated regardless of the current mode so
190 // setFilterMode(LinearPhase) after prepare() actually engages. The
191 // FIR length follows the sample rate (about 85 ms), never the host
192 // block. lpFft_ acts as the gate and is created last: if any
193 // allocation throws, the engine stays unavailable but coherent.
194 lpFft_.reset();
195 lpDesignFft_.reset();
196 firLength_ = 0;
197 lpPart_ = 0;
198 lpLatency_ = 0;
199 {
200 int firLen = 256;
201 const double wanted = spec.sampleRate * kLpFirSeconds;
202 while (firLen < wanted && firLen < kLpMaxFirLength) firLen <<= 1;
203 firLength_ = firLen;
204 lpPart_ = firLen / kLpPartitions;
205 // The kernel is centred at firLength/2; the engine delays its
206 // output by kLpLeadBlocks partitions (the scheduling slack).
207 lpLatency_ = firLength_ / 2 + kLpLeadBlocks * lpPart_;
208
209 const size_t specLen = static_cast<size_t>(2 * lpPart_ + 2);
210 const size_t chans = static_cast<size_t>(numChannels_);
211 const size_t designBins = static_cast<size_t>(firLength_ + 1); // 2L-point design grid
212
213 // Two kernel sets: one plays while the next design is built. The
214 // last band of a set is the residual and has no kernel.
215 lpKernelSpec_.assign(2 * static_cast<size_t>(kMaxSplits * kLpPartitions) * specLen, T(0));
216 lpPartOn_.assign(2 * static_cast<size_t>(kMaxSplits * kLpPartitions), uint8_t(0));
217 lpFdl_.assign(chans * static_cast<size_t>(kLpPartitions) * specLen, T(0));
218 lpRing_.assign(chans * static_cast<size_t>(kLpRingBlocks * lpPart_), T(0));
219 lpOut_.assign(chans * 2 * static_cast<size_t>(MaxBands * lpPart_), T(0));
220 lpAccum_.assign(specLen, T(0));
221 lpResult_.assign(static_cast<size_t>(2 * lpPart_), T(0));
222
223 // Cost model of the steps (units: one complex multiply-accumulate
224 // bin), used to spread a partition's work and a design's steps.
225 const double part = static_cast<double>(lpPart_);
226 lpCostFft_ = (kLpFftUnitsPerPoint + kLpCopyUnitsPerSample) * 2.0 * part;
227 lpCostCma_ = part + 1.0;
228 lpCostIfft_ = kLpFftUnitsPerPoint * 2.0 * part + kLpCopyUnitsPerSample * part;
229 lpCostResidualPerBand_ = kLpResidualUnitsPerSample * part;
230 lpCostMagChunk_ = kLpMagUnitsPerBin * static_cast<double>((designBins + kLpMagChunks - 1) / kLpMagChunks);
231 lpCostPartitionStep_ = lpCostIfft_ + kLpCopyUnitsPerSample * part;
232
233 // Design scratch, so a live crossover/order change never allocates
234 // on the audio thread (the design steps run there).
235 lpCarry_.assign(designBins, 1.0);
236 lpBinFreq_.assign(designBins, 0.0);
237 lpMag_.assign(designBins, T(0));
238 for (size_t k = 0; k < designBins; ++k)
239 lpBinFreq_[k] = spec.sampleRate * static_cast<double>(k) / static_cast<double>(2 * firLength_);
240 // Flat-top window: a cosine taper over the outer quarter on each side.
241 lpWindow_.assign(static_cast<size_t>(firLength_), T(1));
242 const int taper = firLength_ / 4;
243 for (int i = 0; i < firLength_; ++i)
244 {
245 const int edge = std::min(i, firLength_ - 1 - i);
246 if (edge < taper)
247 lpWindow_[static_cast<size_t>(i)] = static_cast<T>(
248 0.5 - 0.5 * std::cos(std::numbers::pi * (static_cast<double>(edge) + 0.5)
249 / static_cast<double>(taper)));
250 }
251 lpTimeResponse_.assign(static_cast<size_t>(2 * firLength_ + 2), T(0));
252 lpFirKernel_.assign(static_cast<size_t>(2 * firLength_), T(0));
253 lpScratch_.assign(static_cast<size_t>(2 * lpPart_), T(0));
254
255 lpDesignFft_ = std::make_unique<FFTReal<T>>(2 * firLength_);
256 lpDesignFftSteps_ = lpDesignFft_->getInverseStepCount();
257 lpCostDesignFftStep_ = kLpDesignFftUnitsPerPoint * 2.0 * static_cast<double>(firLength_)
258 / static_cast<double>(lpDesignFftSteps_);
259 lpFft_ = std::make_unique<FFTReal<T>>(2 * lpPart_);
260 }
261
262 // The two banks of sections: the correction chains [band (or tree
263 // node) * kMaxSplits + split], and the ladders of setStructure(Ladder),
264 // allocated whatever the current structure and topology so a later
265 // switch never allocates.
266 for (auto& k : banks_)
267 {
268 if (!k) k = std::make_unique<IirBank>();
269 k->allpass.resize(static_cast<size_t>(MaxBands * kMaxSplits));
270 k->ladders.assign(static_cast<size_t>(kLadderCount), NormalizedLadder<T, 16> {});
271 }
272 bank_ = 0;
273 fadeBank_ = -1;
274 ladderTmp_.assign(static_cast<size_t>(spec.maxBlockSize), 0.0);
275 ladderActive_ = false;
276
277 // A change of the band count in the minimum-phase engine: both
278 // topologies run for kFadeSeconds and the bands go from one to the
279 // other, a chunk at a time through this scratch.
280 fadeLength_ = std::max(1, static_cast<int>(std::lround(kFadeSeconds * spec.sampleRate)));
281 fadeBands_.assign(static_cast<size_t>(MaxBands * numChannels_ * kFadeChunk), T(0));
282 fadeLower_.assign(static_cast<size_t>(MaxBands * numChannels_ * kFadeChunk), T(0));
283 fadeTop_.assign(static_cast<size_t>(numChannels_ * kFadeChunk), T(0));
284 lpFadeOld_.assign(static_cast<size_t>(MaxBands) * static_cast<size_t>(lpPart_), T(0));
285
286 // Re-sync smoothers to the CURRENT targets. prepare() used to reset
287 // all split frequencies to the log-spaced defaults, silently discarding
288 // any configuration made before prepare().
289 for (int i = 0; i < kMaxSplits; ++i)
290 {
291 freqSmoothers_[i].prepare(spec.sampleRate, 5.0);
292 freqSmoothers_[i].setSmoothingType(SmoothedValue<T>::SmoothingType::Exponential);
293 T target = targetFrequencies_[i].load(std::memory_order_relaxed);
294 freqSmoothers_[i].reset(target);
295 frequencies_[i] = target;
296 }
297
298 lastMode_ = filterMode_.load(std::memory_order_relaxed);
299 dirty_.store(true, std::memory_order_relaxed);
300 // The first design is built whole here (setup thread); later changes
301 // are spread over blocks by the audio thread.
302 lpActiveSet_ = 0;
303 lpSetBands_ = { 0, 0 };
304 lpSetParts_ = { 0, 0 };
305 lpDesignActive_ = false;
306 lpDesignRedo_ = false;
307 if (lpFft_ != nullptr) designLinearPhaseNow();
308 reset();
309
310 prepared_ = true;
311 }
312
335 AudioBufferView<T>* bandOutputs, int numOutputBands) noexcept
336 {
337 if (!prepared_ || bandOutputs == nullptr) return 0;
338
339 const FilterMode mode = filterMode_.load(std::memory_order_relaxed);
340 const bool lpActive = (mode == FilterMode::LinearPhase) && lpFft_ != nullptr;
341 if (mode != lastMode_)
342 {
343 // Live mode switch: clear filter/overlap state so the incoming
344 // engine does not replay stale history (audible transient is
345 // documented behaviour of an engine switch).
346 lastMode_ = mode;
347 reset();
348 if (lpActive) syncFrequenciesToTargets();
349 }
350
351 // Check if UI requested a frequency update
352 if (freqUpdatePending_.exchange(false, std::memory_order_acquire))
353 {
354 if (lpActive)
355 {
356 // FIR kernels are rebuilt per change (per-sample smoothing
357 // cannot apply to a kernel), from the targets synced here.
358 syncFrequenciesToTargets();
359 lpMagDirty_.store(true, std::memory_order_relaxed);
360 }
361 else
362 {
363 for (int i = 0; i < kMaxSplits; ++i)
364 freqSmoothers_[i].setTargetValue(targetFrequencies_[i].load(std::memory_order_relaxed));
365 }
366 }
367
368 // A change of structure restarts the memory of the sections; the
369 // ladders take the coefficients in use.
370 const bool ladder = structure_.load(std::memory_order_relaxed) == Structure::Ladder && !bank(0).ladders.empty();
371 if (!lpActive && ladder != ladderActive_)
372 {
373 ladderActive_ = ladder;
374 resetBank(bank(0));
375 resetBank(bank(1));
376 if (ladder) updateCoefficients();
377 }
378
379 // The IIR coefficients are only rebuilt while the IIR engine runs; in
380 // linear-phase mode the flag stays set for a later switch back.
381 if (!lpActive && dirty_.load(std::memory_order_relaxed) &&
382 dirty_.exchange(false, std::memory_order_acquire))
383 {
384 updateCoefficients();
385 }
386
387 const int n = std::min(numOutputBands, numBands_.load(std::memory_order_relaxed));
388 if (n < 2) return 0;
389
390 // Defensive span clamp: never index past the prepared work buffers
391 // (fixed maxBlockSize stride) or past any output view. The channel
392 // count is clamped to the narrowest band view too: a view with fewer
393 // channels used to be written through a null channel pointer.
394 int nS = std::min(input.getNumSamples(), spec_.maxBlockSize);
395 int nCh = std::min(input.getNumChannels(), numChannels_);
396 for (int b = 0; b < n; ++b)
397 {
398 nS = std::min(nS, bandOutputs[b].getNumSamples());
399 nCh = std::min(nCh, bandOutputs[b].getNumChannels());
400 }
401 if (nS <= 0) return 0;
402
403 if (lpActive)
404 {
405 processLinearPhase(input, bandOutputs, n, nS, nCh);
406 passExtraChannels(input, bandOutputs, n, nS, nCh);
407 return n;
408 }
409
410 // The minimum-phase engine changes its band count or its topology
411 // over a fade (a change that arrives during one waits for it to end).
412 const Topology topology = topology_.load(std::memory_order_relaxed);
413 if (iirBands_ == 0)
414 {
415 iirBands_ = n;
416 iirTopo_ = topology;
417 }
418 else if (fadeLeft_ == 0 && (n != iirBands_ || topology != iirTopo_)) startBandFade(n, topology);
419 const int written = std::min(iirBands_, numOutputBands);
420 processIIR(input, bandOutputs, written, nS, nCh);
421 passExtraChannels(input, bandOutputs, written, nS, nCh);
422 return written;
423 }
424
425 // -- Configuration -------------------------------------------------------
426
443 void setNumBands(int n) noexcept
444 {
445 numBands_.store(std::clamp(n, 2, MaxBands), std::memory_order_relaxed);
446 initDefaultFrequencies();
447 dirty_.store(true, std::memory_order_release);
448 lpMagDirty_.store(true, std::memory_order_release);
449 }
450
462 void setNumBandsKeepingSplits(int n) noexcept
463 {
464 const int bands = std::clamp(n, 2, MaxBands);
465 for (int s = 1; s < bands - 1; ++s)
466 {
467 const T below = targetFrequencies_[static_cast<size_t>(s - 1)].load(std::memory_order_relaxed);
468 const T at = targetFrequencies_[static_cast<size_t>(s)].load(std::memory_order_relaxed);
469 if (!(at > below))
470 targetFrequencies_[static_cast<size_t>(s)].store(
471 std::sqrt(std::max(below, T(1)) * T(20000)), std::memory_order_relaxed);
472 }
473 numBands_.store(bands, std::memory_order_relaxed);
474 freqUpdatePending_.store(true, std::memory_order_release);
475 dirty_.store(true, std::memory_order_release);
476 lpMagDirty_.store(true, std::memory_order_release);
477 }
478
485 void setCrossoverFrequency(int index, T freqHz) noexcept
486 {
487 if (!std::isfinite(freqHz)) return;
488 if (index >= 0 && index < numBands_.load(std::memory_order_relaxed) - 1)
489 {
490 freqHz = std::max(freqHz, T(1));
491
492 // Read all current targets into a local array to sort them
493 std::array<T, kMaxSplits> localTargets;
494 for (int i = 0; i < kMaxSplits; ++i)
495 localTargets[i] = targetFrequencies_[i].load(std::memory_order_relaxed);
496
497 localTargets[static_cast<size_t>(index)] = freqHz;
498
499 // Sort on the UI thread to avoid Audio Thread priority inversion/CPU
500 // spikes. activeSplits is in [0, kMaxSplits] (numBands_ is clamped to
501 // [2, MaxBands]); an explicit insertion sort over this tiny fixed
502 // array is exact for the <=11 elements and avoids libstdc++'s generic
503 // std::sort, whose internal threshold constant trips a spurious GCC
504 // -O2 -Warray-bounds on the small std::array.
505 const int activeSplits = std::clamp(numBands_.load(std::memory_order_relaxed) - 1, 0, kMaxSplits);
506 for (int i = 1; i < activeSplits; ++i)
507 {
508 const T key = localTargets[static_cast<size_t>(i)];
509 int j = i - 1;
510 while (j >= 0 && localTargets[static_cast<size_t>(j)] > key)
511 {
512 localTargets[static_cast<size_t>(j + 1)] = localTargets[static_cast<size_t>(j)];
513 --j;
514 }
515 localTargets[static_cast<size_t>(j + 1)] = key;
516 }
517
518 for (int i = 0; i < kMaxSplits; ++i)
519 targetFrequencies_[i].store(localTargets[static_cast<size_t>(i)], std::memory_order_relaxed);
520
521 freqUpdatePending_.store(true, std::memory_order_release);
522 dirty_.store(true, std::memory_order_release);
523 lpMagDirty_.store(true, std::memory_order_release);
524 }
525 }
526
536 void setOrder(int order) noexcept
537 {
538 if (order == 6 || order == 12 || order == 24 || order == 36 || order == 48)
539 {
540 order_.store(order, std::memory_order_relaxed);
541 dirty_.store(true, std::memory_order_release);
542 lpMagDirty_.store(true, std::memory_order_release);
543 }
544 }
545
547 void setFilterMode(FilterMode mode) noexcept
548 {
549 const int m = std::clamp(static_cast<int>(mode), 0, 1);
550 filterMode_.store(static_cast<FilterMode>(m), std::memory_order_relaxed);
551 dirty_.store(true, std::memory_order_release);
552 lpMagDirty_.store(true, std::memory_order_release);
553 }
554
556 enum class Structure
557 {
558 DirectForm,
559 Ladder
560 };
561
582 void setStructure(Structure structure) noexcept
583 {
584 structure_.store(static_cast<Structure>(std::clamp(static_cast<int>(structure), 0, 1)),
585 std::memory_order_relaxed);
586 }
587
589 [[nodiscard]] Structure getStructure() const noexcept { return structure_.load(std::memory_order_relaxed); }
590
592 enum class Topology
593 {
594 Cascade,
595 Balanced
596 };
597
616 void setTopology(Topology topology) noexcept
617 {
618 topology_.store(static_cast<Topology>(std::clamp(static_cast<int>(topology), 0, 1)), std::memory_order_relaxed);
619 dirty_.store(true, std::memory_order_release);
620 }
621
623 [[nodiscard]] Topology getTopology() const noexcept { return topology_.load(std::memory_order_relaxed); }
624
625 // -- Queries -------------------------------------------------------------
626
627 [[nodiscard]] int getNumBands() const noexcept { return numBands_.load(std::memory_order_relaxed); }
628 [[nodiscard]] int getOrder() const noexcept { return order_.load(std::memory_order_relaxed); }
629 [[nodiscard]] FilterMode getFilterMode() const noexcept { return filterMode_.load(std::memory_order_relaxed); }
630
632 [[nodiscard]] T getCrossoverFrequency(int index) const noexcept
633 {
634 if (index < 0 || index >= kMaxSplits) return T(0);
635 return targetFrequencies_[static_cast<size_t>(index)].load(std::memory_order_relaxed);
636 }
637
645 [[nodiscard]] int getLatency() const noexcept
646 {
647 return (filterMode_.load(std::memory_order_relaxed) == FilterMode::LinearPhase && lpFft_ != nullptr)
648 ? lpLatency_ : 0;
649 }
650
651 void reset() noexcept
652 {
653 for (auto& k : banks_)
654 if (k) resetBank(*k);
655 fadeBank_ = -1;
656
657 std::fill(lpRing_.begin(), lpRing_.end(), T(0));
658 std::fill(lpFdl_.begin(), lpFdl_.end(), T(0));
659 std::fill(lpOut_.begin(), lpOut_.end(), T(0));
660 lpPos_ = 0;
661 lpStageBlock_ = 0;
662 lpPlay_ = 0;
663 lpOutBands_ = lpSetBands_[static_cast<size_t>(lpActiveSet_)];
664 // No partition task is in flight: the first one starts when the
665 // first partition of input is in.
666 lpTaskSet_ = -1;
667 lpTaskFdl_ = 0;
668 lpTaskUnit_ = 0;
669 lpTaskUnits_ = 0;
670 lpTaskDone_ = 0.0;
671 lpTaskTotal_ = 0.0;
672 lpLaunchedSet_ = -1;
673 lpTaskFadeSet_ = -1;
674 glideRemain_ = 0;
675 iirBands_ = 0;
676 fadeLeft_ = 0;
677 }
678
679
681 [[nodiscard]] std::vector<uint8_t> getState() const
682 {
683 StateWriter w(stateId("XOVR"), 1);
684 const int n = getNumBands();
685 w.write("numBands", n);
686 w.write("order", getOrder());
687 w.write("mode", static_cast<int32_t>(getFilterMode()));
688 w.write("structure", static_cast<int32_t>(getStructure()));
689 w.write("topology", static_cast<int32_t>(getTopology()));
690 char key[16];
691 for (int i = 0; i < n - 1; ++i)
692 {
693 std::snprintf(key, sizeof(key), "x%d", i);
694 w.write(key, static_cast<float>(getCrossoverFrequency(i)));
695 }
696 return w.blob();
697 }
698
700 bool setState(const uint8_t* data, size_t size)
701 {
702 StateReader r(data, size);
703 if (!r.isValid() || r.processorId() != stateId("XOVR")) return false;
704 setNumBands(std::clamp(r.read("numBands", 2), 2, MaxBands));
705 setOrder(r.read("order", 24));
706 setFilterMode(static_cast<FilterMode>(std::clamp(r.read("mode", 0), 0, 1)));
707 setStructure(static_cast<Structure>(std::clamp(r.read("structure", 0), 0, 1)));
708 setTopology(static_cast<Topology>(std::clamp(r.read("topology", 0), 0, 1)));
709 const int n = getNumBands();
710 char key[16];
711 for (int i = 0; i < n - 1; ++i)
712 {
713 std::snprintf(key, sizeof(key), "x%d", i);
714 const float f = r.read(key, -1.0f);
715 if (f > 0.0f) setCrossoverFrequency(i, static_cast<T>(f));
716 }
717 return true;
718 }
719
720private:
721 static constexpr int kMaxSplits = MaxBands - 1;
722 static constexpr int kMaxStagesPerFilter = 4;
723 static constexpr double kLpFirSeconds = 4096.0 / 48000.0;
724 static constexpr int kLpMaxFirLength = 1 << 16;
725 static constexpr int kLpPartitions = 8;
726 static_assert(kLpPartitions % 2 == 0, "the FIR centre must fall on a partition boundary");
730 static constexpr int kLpLeadBlocks = 2;
735 static constexpr int kLpRingBlocks = 8;
736 static_assert(kLpRingBlocks >= kLpPartitions / 2 + 2
737 && (kLpRingBlocks & (kLpRingBlocks - 1)) == 0,
738 "the input history must hold the residual delay and the staged block");
739 static constexpr int kGlideGrid = 32;
740 static constexpr double kFadeSeconds = 0.02;
741 static constexpr int kFadeChunk = 64;
742 // Linear-phase cost model, in units of one complex multiply-accumulate
743 // bin (about 0.2 ns on a desktop core with AVX2). It weighs the steps of
744 // a partition's work (spread over the partition) and of a design (paced
745 // at a share of the steady work); only the ratios matter.
746 static constexpr double kLpFftUnitsPerPoint = 2.4;
747 static constexpr double kLpDesignFftUnitsPerPoint = 2.7;
748 static constexpr double kLpMagUnitsPerBin = 3.4;
749 static constexpr double kLpCopyUnitsPerSample = 0.1;
750 static constexpr double kLpResidualUnitsPerSample = 0.35;
751 static constexpr int kLpMagChunks = 4;
754 static constexpr double kLpSkipL1 = 1e-6;
758 static constexpr double kLpDesignShare = 0.45;
759
760 struct SplitPoint
761 {
764 };
765
766 struct AllPassChain
767 {
768 BiquadCascade<T, kMaxStagesPerFilter, 16> stages;
769 };
770
780 [[nodiscard]] static BiquadCoeffs makeFirstOrderAllPass(double sampleRate, double freq) noexcept
781 {
782 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
783 const double w = std::tan(std::numbers::pi * freq / sampleRate);
784 const double a = (w - 1.0) / (w + 1.0);
785 BiquadCoeffs coeffs;
786 coeffs.b0 = a;
787 coeffs.b1 = 1.0;
788 coeffs.b2 = 0.0;
789 coeffs.a1 = a;
790 coeffs.a2 = 0.0;
791 return coeffs;
792 }
793
794 void initDefaultFrequencies() noexcept
795 {
796 int numSplits = numBands_.load(std::memory_order_relaxed) - 1;
797 const T logMin = std::log(T(100));
798 const T logMax = std::log(T(10000));
799
800 for (int s = 0; s < numSplits; ++s)
801 {
802 T t = static_cast<T>(s + 1) / static_cast<T>(numSplits + 1);
803 targetFrequencies_[s].store(std::exp(logMin + t * (logMax - logMin)), std::memory_order_relaxed);
804 }
805 freqUpdatePending_.store(true, std::memory_order_release);
806 }
807
811 void syncFrequenciesToTargets() noexcept
812 {
813 for (int i = 0; i < kMaxSplits; ++i)
814 {
815 const T t = targetFrequencies_[i].load(std::memory_order_relaxed);
816 frequencies_[i] = t;
817 freqSmoothers_[i].reset(t);
818 }
819 }
820
821 [[nodiscard]] static double clampSplitFreq(double f, double sr) noexcept
822 {
823 return std::clamp(f, 20.0, sr * 0.499);
824 }
825
826 void updateCoefficients(int ladderRamp = 0) noexcept
827 {
828 if (spec_.sampleRate <= 0 || !banks_[0]) return;
829
830 int numSplits = numBands_.load(std::memory_order_relaxed) - 1;
831 double sr = spec_.sampleRate;
832
833 // Splits (and their allpass chains) that a band count increase brings
834 // back are reset where they come into the path (startBandFade()):
835 // a split still fading out keeps playing until then.
836
837 // The phase-correction allpass per band/split must equal the allpass
838 // that the split's LP/HP branches sum to: ONE first-order section for
839 // LR12 (LP1^2 - HP1^2 = AP1 exactly), ONE second-order section for
840 // LR24 (LP2^2 + HP2^2 = AP2(Q=0.7071)), TWO sections (q1, q2) for
841 // LR48. Applying numStagesPerFilter_ sections (the old behaviour)
842 // doubled the correction phase and carved up to -3.5 dB (LR24) /
843 // -13 dB (LR48) holes into the band sum with octave-spaced splits.
844 // Note: Frequencies are already guaranteed to be sorted by the setter thread.
845 switch (order_.load(std::memory_order_relaxed))
846 {
847 case 6:
848 // A first-order low-pass and the high-pass on the same pole:
849 // they add up to the input itself (their numerators sum to
850 // the denominator), so no band needs a phase correction.
851 numStagesPerFilter_ = 1;
852 numStagesAllpass_ = 0;
853 for (int s = 0; s < numSplits; ++s)
854 {
855 double f = clampSplitFreq(static_cast<double>(frequencies_[s]), sr);
856 setSplitSection(s, 0, BiquadCoeffs::makeFirstOrderLowPass(sr, f),
857 BiquadCoeffs::makeFirstOrderHighPass(sr, f), ladderRamp);
858 }
859 break;
860
861 case 36:
862 // Two third-order Butterworth filters in series per branch:
863 // a first-order section and a second-order one of Q = 1,
864 // twice. The two branches meet half a turn apart (three
865 // times 180 degrees), as in LR12, so the high branch is
866 // inverted and the pair sums to the allpass of one
867 // third-order filter: a first-order and a second-order
868 // section.
869 numStagesPerFilter_ = 4;
870 numStagesAllpass_ = 2;
871 for (int s = 0; s < numSplits; ++s)
872 {
873 double f = clampSplitFreq(static_cast<double>(frequencies_[s]), sr);
874 const auto lp1 = BiquadCoeffs::makeFirstOrderLowPass(sr, f);
875 const auto hp1 = BiquadCoeffs::makeFirstOrderHighPass(sr, f);
876 const auto lp2 = BiquadCoeffs::makeLowPass(sr, f, 1.0);
877 const auto hp2 = BiquadCoeffs::makeHighPass(sr, f, 1.0);
878 auto hp1Inverted = hp1;
879 hp1Inverted.b0 = -hp1Inverted.b0;
880 hp1Inverted.b1 = -hp1Inverted.b1;
881 hp1Inverted.b2 = -hp1Inverted.b2;
882 setSplitSection(s, 0, lp1, hp1Inverted, ladderRamp);
883 setSplitSection(s, 1, lp2, hp2, ladderRamp);
884 setSplitSection(s, 2, lp1, hp1, ladderRamp);
885 setSplitSection(s, 3, lp2, hp2, ladderRamp);
886 const auto ap1 = makeFirstOrderAllPass(sr, f);
887 const auto ap2 = BiquadCoeffs::makeAllPass(sr, f, 1.0);
888 setCorrection(s, numSplits, 0, ap1, ladderRamp);
889 setCorrection(s, numSplits, 1, ap2, ladderRamp);
890 }
891 break;
892
893 case 12:
894 numStagesPerFilter_ = 2;
895 numStagesAllpass_ = 1;
896 for (int s = 0; s < numSplits; ++s)
897 {
898 double f = clampSplitFreq(static_cast<double>(frequencies_[s]), sr);
899 auto lpC = BiquadCoeffs::makeFirstOrderLowPass(sr, f);
900 auto hpC = BiquadCoeffs::makeFirstOrderHighPass(sr, f);
901 auto apC = makeFirstOrderAllPass(sr, f);
902
903 // LR12 sums flat only with the high branch polarity
904 // inverted (LP^2 - HP^2 = allpass; LP^2 + HP^2 notches at
905 // fc). Bake the inversion into the first HP stage: odd
906 // bands come out inverted, the sum is allpass-flat.
907 auto hpC0 = hpC;
908 hpC0.b0 = -hpC0.b0;
909 hpC0.b1 = -hpC0.b1;
910 hpC0.b2 = -hpC0.b2;
911
912 setSplitSection(s, 0, lpC, hpC0, ladderRamp);
913 setSplitSection(s, 1, lpC, hpC, ladderRamp);
914 setCorrection(s, numSplits, 0, apC, ladderRamp);
915 }
916 break;
917
918 case 24:
919 numStagesPerFilter_ = 2;
920 numStagesAllpass_ = 1;
921 for (int s = 0; s < numSplits; ++s)
922 {
923 double f = clampSplitFreq(static_cast<double>(frequencies_[s]), sr);
924 // Exact Butterworth Q: the rounded 0.7071 left the band sum
925 // 3.4e-4 dB off flat (now 1e-6).
926 constexpr double qB = 0.70710678118654752440;
927 auto lpC = BiquadCoeffs::makeLowPass(sr, f, qB);
928 auto hpC = BiquadCoeffs::makeHighPass(sr, f, qB);
929 auto apC = BiquadCoeffs::makeAllPass(sr, f, qB);
930
931 for (int st = 0; st < 2; ++st)
932 setSplitSection(s, st, lpC, hpC, ladderRamp);
933 setCorrection(s, numSplits, 0, apC, ladderRamp);
934 }
935 break;
936
937 case 48:
938 {
939 numStagesPerFilter_ = 4;
940 numStagesAllpass_ = 2;
941 // Exact 4th-order Butterworth section Qs, 1/(2 cos(pi/8)) and
942 // 1/(2 cos(3 pi/8)): the rounded values left the band sum
943 // 1.1e-3 dB off flat (now 1.5e-6).
944 constexpr double q1 = 0.54119610014619698440;
945 constexpr double q2 = 1.30656296487637652786;
946 const double qArr[4] = { q1, q2, q1, q2 };
947
948 for (int s = 0; s < numSplits; ++s)
949 {
950 double f = clampSplitFreq(static_cast<double>(frequencies_[s]), sr);
951
952 for (int st = 0; st < 4; ++st)
953 setSplitSection(s, st, BiquadCoeffs::makeLowPass(sr, f, qArr[st]),
954 BiquadCoeffs::makeHighPass(sr, f, qArr[st]), ladderRamp);
955 const auto ap1 = BiquadCoeffs::makeAllPass(sr, f, q1);
956 const auto ap2 = BiquadCoeffs::makeAllPass(sr, f, q2);
957 setCorrection(s, numSplits, 0, ap1, ladderRamp);
958 setCorrection(s, numSplits, 1, ap2, ladderRamp);
959 }
960 break;
961 }
962
963 default: break;
964 }
965
966 const bool tree = treeInUse();
967 for (int i = 0; i < 2; ++i)
968 {
969 if (i != bank_ && i != fadeBank_) continue;
970 IirBank& k = bank(i);
971 for (int s = 0; s < numSplits; ++s)
972 {
973 k.splits[static_cast<size_t>(s)].lp.setNumSections(numStagesPerFilter_);
974 k.splits[static_cast<size_t>(s)].hp.setNumSections(numStagesPerFilter_);
975 for (int b = 0; b < (tree ? numSplits : s); ++b)
976 if (b != s) k.allpass[static_cast<size_t>(b * kMaxSplits + s)].stages.setNumSections(numStagesAllpass_);
977 }
978 }
979 }
980
981 static constexpr int kLadderSplitStride = 2 * kMaxStagesPerFilter;
982 static constexpr int kLadderAllpassBase = kMaxSplits * kLadderSplitStride;
983 static constexpr int kLadderCount = kLadderAllpassBase + MaxBands * kMaxSplits * 2;
984
986 [[nodiscard]] static constexpr int ladderLow(int s, int st) noexcept { return s * kLadderSplitStride + st; }
988 [[nodiscard]] static constexpr int ladderHigh(int s, int st) noexcept
989 {
990 return s * kLadderSplitStride + kMaxStagesPerFilter + st;
991 }
993 [[nodiscard]] static constexpr int ladderAllpass(int b, int s, int st) noexcept
994 {
995 return kLadderAllpassBase + (b * kMaxSplits + s) * 2 + st;
996 }
997
1002 struct IirBank
1003 {
1004 std::array<SplitPoint, kMaxSplits> splits {};
1005 std::vector<AllPassChain> allpass;
1006 std::vector<NormalizedLadder<T, 16>> ladders;
1007 };
1008
1010 struct BandPtrs
1011 {
1012 T* p[MaxBands][16] {};
1013 };
1014
1015 [[nodiscard]] IirBank& bank(int index) noexcept { return *banks_[static_cast<size_t>(index)]; }
1016
1019 [[nodiscard]] bool treeInUse() const noexcept
1020 {
1021 return topology_.load(std::memory_order_relaxed) == Topology::Balanced || iirTopo_ == Topology::Balanced
1022 || (fadeBank_ >= 0 && fadeFromTopo_ == Topology::Balanced);
1023 }
1024
1028 void setSplitSection(int s, int st, const BiquadCoeffs& low, const BiquadCoeffs& high, int ramp) noexcept
1029 {
1030 for (int i = 0; i < 2; ++i)
1031 {
1032 if (i != bank_ && i != fadeBank_) continue;
1033 IirBank& k = bank(i);
1034 k.splits[static_cast<size_t>(s)].lp.setCoeffs(st, low);
1035 k.splits[static_cast<size_t>(s)].hp.setCoeffs(st, high);
1036 if (ladderActive_)
1037 {
1038 k.ladders[static_cast<size_t>(ladderLow(s, st))].rampCoeffs(low, ramp);
1039 k.ladders[static_cast<size_t>(ladderHigh(s, st))].rampCoeffs(high, ramp);
1040 }
1041 }
1042 }
1043
1045 void setAllpassSection(int b, int s, int st, const BiquadCoeffs& c, int ramp) noexcept
1046 {
1047 for (int i = 0; i < 2; ++i)
1048 {
1049 if (i != bank_ && i != fadeBank_) continue;
1050 IirBank& k = bank(i);
1051 k.allpass[static_cast<size_t>(b * kMaxSplits + s)].stages.setCoeffs(st, c);
1052 if (ladderActive_)
1053 k.ladders[static_cast<size_t>(ladderAllpass(b, s, st))].rampCoeffs(c, ramp);
1054 }
1055 }
1056
1059 void setCorrection(int s, int numSplits, int st, const BiquadCoeffs& c, int ramp) noexcept
1060 {
1061 const int end = treeInUse() ? numSplits : s;
1062 for (int b = 0; b < end; ++b)
1063 if (b != s) setAllpassSection(b, s, st, c, ramp);
1064 }
1065
1068 void runLadders(IirBank& k, const T* src, T* dst, int length, int first, int count, int channel) noexcept
1069 {
1070 double* tmp = ladderTmp_.data();
1071 for (int i = 0; i < length; ++i) tmp[i] = static_cast<double>(src[i]);
1072 for (int j = 0; j < count; ++j)
1073 k.ladders[static_cast<size_t>(first + j)].processSegment(tmp, length, channel);
1074 for (int i = 0; i < length; ++i) dst[i] = static_cast<T>(tmp[i]);
1075 }
1076
1078 void advanceLadders(IirBank& k, int first, int count, int length) noexcept
1079 {
1080 for (int j = 0; j < count; ++j)
1081 k.ladders[static_cast<size_t>(first + j)].advanceRamp(length);
1082 }
1083
1084 void processIIR(AudioBufferView<T> input, AudioBufferView<T>* outputs, int numBands, int nS, int nCh) noexcept
1085 {
1086 DenormalGuard guard;
1087 const int numSplits = numBands - 1;
1088
1089 // During a glide the coefficients are refreshed every kGlideGrid
1090 // samples on a grid that runs across blocks: a segment started in one
1091 // block keeps its coefficients into the next, so the glide is the
1092 // same whatever the host block size.
1093 int offset = 0;
1094 while (offset < nS)
1095 {
1096 if (glideRemain_ == 0)
1097 {
1098 bool anySmoothing = false;
1099 for (int i = 0; i < numSplits; ++i)
1100 anySmoothing = anySmoothing || freqSmoothers_[i].isSmoothing();
1101 if (!anySmoothing) break;
1102 for (int i = 0; i < numSplits; ++i)
1103 {
1104 for (int s = 0; s < kGlideGrid; ++s)
1105 (void)freqSmoothers_[i].getNextValue();
1106 frequencies_[i] = freqSmoothers_[i].getCurrentValue();
1107 }
1108 // The ladders ramp to the new coefficients over the segment.
1109 updateCoefficients(kGlideGrid);
1110 glideRemain_ = kGlideGrid;
1111 }
1112 const int len = std::min(glideRemain_, nS - offset);
1113 processRange(input, outputs, numBands, nCh, offset, len);
1114 offset += len;
1115 glideRemain_ -= len;
1116 }
1117 if (offset < nS)
1118 processRange(input, outputs, numBands, nCh, offset, nS - offset);
1119 }
1120
1121 [[nodiscard]] static BandPtrs bandsOf(AudioBufferView<T>* outputs, int numBands, int nCh, int offset) noexcept
1122 {
1123 BandPtrs out;
1124 for (int b = 0; b < numBands; ++b)
1125 for (int ch = 0; ch < nCh; ++ch) out.p[b][ch] = outputs[b].getChannel(ch) + offset;
1126 return out;
1127 }
1128
1130 void processRange(AudioBufferView<T> input, AudioBufferView<T>* outputs, int numBands, int nCh, int offset,
1131 int length) noexcept
1132 {
1133 while (fadeLeft_ > 0 && length > 0)
1134 {
1135 const int len = std::min({ length, fadeLeft_, kFadeChunk });
1136 if (fadeBank_ >= 0) processBankFadeRange(input, outputs, numBands, nCh, offset, len);
1137 else processFadeRange(input, outputs, numBands, nCh, offset, len);
1138 fadeLeft_ -= len;
1139 offset += len;
1140 length -= len;
1141 if (fadeLeft_ == 0 && fadeBank_ >= 0)
1142 {
1143 bank_ = fadeBank_;
1144 fadeBank_ = -1;
1145 }
1146 }
1147 if (length > 0)
1148 {
1149 BandPtrs out = bandsOf(outputs, numBands, nCh, offset);
1150 runTopology(bank(bank_), iirTopo_, numBands, input, offset, out, nCh, length);
1151 }
1152 }
1153
1155 static void resetBank(IirBank& k) noexcept
1156 {
1157 for (auto& sp : k.splits)
1158 {
1159 sp.lp.reset();
1160 sp.hp.reset();
1161 }
1162 for (auto& apChain : k.allpass)
1163 apChain.stages.reset();
1164 for (auto& l : k.ladders)
1165 l.reset();
1166 }
1167
1169 void startBandFade(int bands, Topology topology) noexcept
1170 {
1171 const bool shared = iirTopo_ == Topology::Cascade && topology == Topology::Cascade;
1172 fadeFrom_ = iirBands_;
1173 fadeFromTopo_ = iirTopo_;
1174 iirBands_ = bands;
1175 iirTopo_ = topology;
1176 fadeLeft_ = fadeLength_;
1177 if (!shared)
1178 {
1179 // The new configuration on the other bank: the coefficients of
1180 // the bank in play (the containers have the same sizes: copies,
1181 // no allocation), its memory from silence.
1182 fadeBank_ = 1 - bank_;
1183 IirBank& to = bank(fadeBank_);
1184 const IirBank& from = bank(bank_);
1185 to.splits = from.splits;
1186 std::copy(from.allpass.begin(), from.allpass.end(), to.allpass.begin());
1187 std::copy(from.ladders.begin(), from.ladders.end(), to.ladders.begin());
1188 resetBank(to);
1189 return;
1190 }
1191 // The splits that come in, and the corrections of the bands below
1192 // them, start from silence (their memory may be arbitrarily old).
1193 IirBank& k = bank(bank_);
1194 for (int s = fadeFrom_ - 1; s < bands - 1; ++s)
1195 {
1196 k.splits[static_cast<size_t>(s)].lp.reset();
1197 k.splits[static_cast<size_t>(s)].hp.reset();
1198 for (int b = 0; b < s; ++b)
1199 k.allpass[static_cast<size_t>(b * kMaxSplits + s)].stages.reset();
1200 if (!k.ladders.empty())
1201 {
1202 for (int st = 0; st < kMaxStagesPerFilter; ++st)
1203 {
1204 k.ladders[static_cast<size_t>(ladderLow(s, st))].reset();
1205 k.ladders[static_cast<size_t>(ladderHigh(s, st))].reset();
1206 }
1207 for (int b = 0; b < s; ++b)
1208 for (int st = 0; st < 2; ++st)
1209 k.ladders[static_cast<size_t>(ladderAllpass(b, s, st))].reset();
1210 }
1211 }
1212 }
1213
1215 void runSplit(IirBank& k, int s, T* const* work, T* const* low, int nCh, int len) noexcept
1216 {
1217 if (ladderActive_)
1218 {
1219 const int perFilter = numStagesPerFilter_;
1220 for (int ch = 0; ch < nCh; ++ch)
1221 {
1222 runLadders(k, work[ch], low[ch], len, ladderLow(s, 0), perFilter, ch);
1223 runLadders(k, work[ch], work[ch], len, ladderHigh(s, 0), perFilter, ch);
1224 }
1225 advanceLadders(k, ladderLow(s, 0), perFilter, len);
1226 advanceLadders(k, ladderHigh(s, 0), perFilter, len);
1227 return;
1228 }
1229 for (int ch = 0; ch < nCh; ++ch) std::copy(work[ch], work[ch] + len, low[ch]);
1230 k.splits[static_cast<size_t>(s)].lp.processBlock(AudioBufferView<T>(low, nCh, len));
1231 k.splits[static_cast<size_t>(s)].hp.processBlock(AudioBufferView<T>(work, nCh, len));
1232 }
1233
1235 void runAllpass(IirBank& k, int b, int s, T* const* band, int nCh, int len) noexcept
1236 {
1237 if (ladderActive_)
1238 {
1239 for (int ch = 0; ch < nCh; ++ch)
1240 runLadders(k, band[ch], band[ch], len, ladderAllpass(b, s, 0), numStagesAllpass_, ch);
1241 advanceLadders(k, ladderAllpass(b, s, 0), numStagesAllpass_, len);
1242 return;
1243 }
1244 k.allpass[static_cast<size_t>(b * kMaxSplits + s)].stages.processBlock(AudioBufferView<T>(band, nCh, len));
1245 }
1246
1255 void runTree(IirBank& k, int lo, int hi, T* const* buf, BandPtrs& out, int nCh, int len) noexcept
1256 {
1257 if (lo >= hi) return;
1258 const int r = lo + (hi - lo - 1) / 2;
1259 T* const* low = out.p[r];
1260 runSplit(k, r, buf, low, nCh, len);
1261 if (numStagesAllpass_ > 0)
1262 {
1263 for (int s = r + 1; s < hi; ++s) runAllpass(k, r, s, low, nCh, len);
1264 for (int s = lo; s < r; ++s) runAllpass(k, r, s, buf, nCh, len);
1265 }
1266 runTree(k, lo, r, low, out, nCh, len);
1267 runTree(k, r + 1, hi, buf, out, nCh, len);
1268 }
1269
1272 void runTopology(IirBank& k, Topology topology, int numBands, AudioBufferView<T> input, int offset, BandPtrs& out,
1273 int nCh, int len) noexcept
1274 {
1275 const int numSplits = numBands - 1;
1276
1277 // Non-finite input samples enter as silence: in the recursive
1278 // sections they would latch for good.
1279 T* work[16] = {};
1280 for (int ch = 0; ch < nCh; ++ch)
1281 {
1282 const T* src = input.getChannel(ch) + offset;
1283 work[ch] = getWorkBufChannel(ch);
1284 for (int i = 0; i < len; ++i)
1285 work[ch][i] = std::isfinite(src[i]) ? src[i] : T(0);
1286 }
1287
1288 if (topology == Topology::Balanced)
1289 {
1290 runTree(k, 0, numSplits, work, out, nCh, len);
1291 for (int ch = 0; ch < nCh; ++ch) std::copy(work[ch], work[ch] + len, out.p[numBands - 1][ch]);
1292 return;
1293 }
1294
1295 // Each split: its low band from what is left, and what is left above
1296 // it, every section of a filter and every channel in one pass (the
1297 // memory in double: re-quantising to T between sections would put
1298 // the reconstruction error back where the double memory removed it).
1299 for (int s = 0; s < numSplits; ++s)
1300 runSplit(k, s, work, out.p[s], nCh, len);
1301
1302 for (int ch = 0; ch < nCh; ++ch) std::copy(work[ch], work[ch] + len, out.p[numBands - 1][ch]);
1303
1304 for (int s = 1; s < numSplits; ++s)
1305 for (int b = 0; b < s; ++b)
1306 runAllpass(k, b, s, out.p[b], nCh, len);
1307 }
1308
1309 [[nodiscard]] T* fadeBandOf(std::vector<T>& scratch, int band, int ch) noexcept
1310 {
1311 return scratch.data()
1312 + (static_cast<size_t>(band) * static_cast<size_t>(numChannels_) + static_cast<size_t>(ch))
1313 * static_cast<size_t>(kFadeChunk);
1314 }
1315
1325 void processFadeRange(AudioBufferView<T> input, AudioBufferView<T>* outputs, int numBands, int nCh,
1326 int offset, int len) noexcept
1327 {
1328 IirBank& k = bank(bank_);
1329 const int most = std::max(fadeFrom_, iirBands_);
1330 const int fewest = std::min(fadeFrom_, iirBands_);
1331 const bool adding = iirBands_ > fadeFrom_;
1332 T* work[16] = {};
1333 for (int ch = 0; ch < nCh; ++ch)
1334 {
1335 const T* src = input.getChannel(ch) + offset;
1336 work[ch] = getWorkBufChannel(ch);
1337 for (int i = 0; i < len; ++i) work[ch][i] = std::isfinite(src[i]) ? src[i] : T(0);
1338 }
1339 T* top[16] = {};
1340 for (int ch = 0; ch < nCh; ++ch) top[ch] = fadeTop_.data() + static_cast<size_t>(ch) * kFadeChunk;
1341 for (int s = 0; s < most - 1; ++s)
1342 {
1343 if (s == fewest - 1)
1344 for (int ch = 0; ch < nCh; ++ch) std::copy(work[ch], work[ch] + len, top[ch]);
1345 T* low[16] = {};
1346 for (int ch = 0; ch < nCh; ++ch) low[ch] = fadeBandOf(fadeBands_, s, ch);
1347 runSplit(k, s, work, low, nCh, len);
1348 }
1349 for (int ch = 0; ch < nCh; ++ch)
1350 std::copy(work[ch], work[ch] + len, fadeBandOf(fadeBands_, most - 1, ch));
1351 // The corrections, the smaller topology's lower bands read off
1352 // before the first split it does not have (fewest - 1 <= most - 2).
1353 for (int s = 1; s < most - 1; ++s)
1354 {
1355 if (s == fewest - 1)
1356 for (int b = 0; b < fewest - 1; ++b)
1357 for (int ch = 0; ch < nCh; ++ch)
1358 std::copy_n(fadeBandOf(fadeBands_, b, ch), len, fadeBandOf(fadeLower_, b, ch));
1359 for (int b = 0; b < s; ++b)
1360 {
1361 T* band[16] = {};
1362 for (int ch = 0; ch < nCh; ++ch) band[ch] = fadeBandOf(fadeBands_, b, ch);
1363 runAllpass(k, b, s, band, nCh, len);
1364 }
1365 }
1366
1367 // Each written band from the old version to the new one.
1368 const T step = T(1) / static_cast<T>(fadeLength_);
1369 const T start = static_cast<T>(fadeLength_ - fadeLeft_);
1370 for (int b = 0; b < numBands; ++b)
1371 for (int ch = 0; ch < nCh; ++ch)
1372 {
1373 T* out = outputs[b].getChannel(ch) + offset;
1374 const T* lg = fadeBandOf(fadeBands_, b, ch);
1375 const T* sm = b < fewest - 1 ? fadeBandOf(fadeLower_, b, ch) : b == fewest - 1 ? top[ch] : nullptr;
1376 for (int i = 0; i < len; ++i)
1377 {
1378 const T w = (start + static_cast<T>(i + 1)) * step; // the new topology's share
1379 T inLarge = lg[i];
1380 if (!adding && b == fewest - 1)
1381 for (int j = b + 1; j < most; ++j) inLarge += fadeBandOf(fadeBands_, j, ch)[i];
1382 const T inSmall = sm != nullptr ? sm[i] : T(0);
1383 out[i] = adding ? inSmall + (inLarge - inSmall) * w : inLarge + (inSmall - inLarge) * w;
1384 }
1385 }
1386 }
1387
1394 void processBankFadeRange(AudioBufferView<T> input, AudioBufferView<T>* outputs, int numBands, int nCh,
1395 int offset, int len) noexcept
1396 {
1397 BandPtrs before;
1398 for (int b = 0; b < fadeFrom_; ++b)
1399 for (int ch = 0; ch < nCh; ++ch) before.p[b][ch] = fadeBandOf(fadeBands_, b, ch);
1400 runTopology(bank(bank_), fadeFromTopo_, fadeFrom_, input, offset, before, nCh, len);
1401 BandPtrs now = bandsOf(outputs, numBands, nCh, offset);
1402 runTopology(bank(fadeBank_), iirTopo_, numBands, input, offset, now, nCh, len);
1403
1404 const T step = T(1) / static_cast<T>(fadeLength_);
1405 const T start = static_cast<T>(fadeLength_ - fadeLeft_);
1406 for (int b = 0; b < numBands; ++b)
1407 for (int ch = 0; ch < nCh; ++ch)
1408 {
1409 T* out = now.p[b][ch];
1410 for (int i = 0; i < len; ++i)
1411 {
1412 T was = T(0);
1413 if (b < numBands - 1) was = b < fadeFrom_ ? before.p[b][ch][i] : T(0);
1414 else
1415 for (int j = b; j < fadeFrom_; ++j) was += before.p[j][ch][i];
1416 const T w = (start + static_cast<T>(i + 1)) * step;
1417 out[i] = was + (out[i] - was) * w;
1418 }
1419 }
1420 }
1421
1422 inline T* getWorkBufChannel(int ch) noexcept
1423 {
1424 return workBuf_.data() + static_cast<size_t>(ch) * static_cast<size_t>(spec_.maxBlockSize);
1425 }
1426
1430 void passExtraChannels(AudioBufferView<T> input, AudioBufferView<T>* outputs, int numBands, int nS,
1431 int firstCh) noexcept
1432 {
1433 const int inCh = input.getNumChannels();
1434 for (int ch = firstCh; ch < inCh; ++ch)
1435 {
1436 for (int b = 0; b < numBands; ++b)
1437 {
1438 if (ch >= outputs[b].getNumChannels()) continue;
1439 T* dst = outputs[b].getChannel(ch);
1440 if (b == 0)
1441 {
1442 const T* src = input.getChannel(ch);
1443 std::copy(src, src + nS, dst);
1444 }
1445 else
1446 {
1447 std::fill(dst, dst + nS, T(0));
1448 }
1449 }
1450 }
1451 }
1452
1453 // -- Linear-phase kernel design -------------------------------------------
1454 //
1455 // A design builds every band's kernel into the kernel set that is not
1456 // playing, one small step at a time, then swaps sets in one assignment:
1457 // the bands always come from one consistent design, so they keep summing
1458 // to the delayed input. Steps per band: the band's ideal magnitudes (in
1459 // kLpMagChunks pieces), the long inverse FFT (one step per pass), then one
1460 // windowed partition transform per partition. The last band is the
1461 // residual and needs no kernel. Everything runs on the audio thread from
1462 // scratch allocated in prepare().
1463
1464 [[nodiscard]] T* lpKernelSet(int set) noexcept
1465 {
1466 const size_t specLen = static_cast<size_t>(2 * lpPart_ + 2);
1467 return lpKernelSpec_.data() + static_cast<size_t>(set) * static_cast<size_t>(kMaxSplits * kLpPartitions) * specLen;
1468 }
1469
1472 [[nodiscard]] double lpPartitionCost(int bands, int chans, int parts) const noexcept
1473 {
1474 return static_cast<double>(chans)
1475 * (lpCostFft_ + static_cast<double>(parts) * lpCostCma_
1476 + static_cast<double>(bands - 1) * lpCostIfft_
1477 + static_cast<double>(bands) * lpCostResidualPerBand_);
1478 }
1479
1481 void startLinearPhaseDesign() noexcept
1482 {
1483 lpDesignBands_ = std::clamp(numBands_.load(std::memory_order_relaxed), 2, MaxBands);
1484 const double sr = spec_.sampleRate;
1485 for (int sp = 0; sp < lpDesignBands_ - 1; ++sp)
1486 lpDesignFc_[static_cast<size_t>(sp)] = clampSplitFreq(static_cast<double>(frequencies_[static_cast<size_t>(sp)]), sr);
1487 switch (order_.load(std::memory_order_relaxed))
1488 {
1489 case 6: lpDesignExpo_ = 1; break;
1490 case 12: lpDesignExpo_ = 2; break;
1491 case 36: lpDesignExpo_ = 6; break;
1492 case 48: lpDesignExpo_ = 8; break;
1493 default: lpDesignExpo_ = 4; break;
1494 }
1495 lpDesignSet_ = 1 - lpActiveSet_;
1496 lpDesignBand_ = 0;
1497 lpDesignStep_ = 0;
1498 lpDesignParts_ = 0;
1499 lpDesignRedo_ = false;
1500 lpDesignActive_ = true;
1501 // The pace is a share of the steady work of a stereo stream with the
1502 // design's band count and every partition convolved, whatever the
1503 // channel count and however many partitions the design keeps.
1504 lpDesignRate_ = kLpDesignShare * lpPartitionCost(lpDesignBands_, 2, (lpDesignBands_ - 1) * kLpPartitions)
1505 / static_cast<double>(lpPart_);
1506 }
1507
1512 template <int Expo>
1513 void designBandMagnitudes(double fc, int begin, int end) noexcept
1514 {
1515 const double* freq = lpBinFreq_.data();
1516 double* carry = lpCarry_.data();
1517 T* mag = lpMag_.data();
1518 const double invFc = 1.0 / fc;
1519 for (int k = begin; k < end; ++k)
1520 {
1521 const double r = freq[k] * invFc;
1522 double rPow = r;
1523 if constexpr (Expo >= 2) rPow = r * r;
1524 if constexpr (Expo == 6) rPow *= rPow * rPow;
1525 else
1526 {
1527 if constexpr (Expo >= 4) rPow *= rPow;
1528 if constexpr (Expo >= 8) rPow *= rPow;
1529 }
1530 const double lp = 1.0 / (1.0 + rPow);
1531 const double c = carry[k];
1532 mag[k] = static_cast<T>(c * lp);
1533 carry[k] = c * (rPow * lp); // the high-pass, 1 - lp
1534 }
1535 // A separate interleave keeps the loop above contiguous (vectorised).
1536 T* re = lpTimeResponse_.data();
1537 for (int k = begin; k < end; ++k) re[2 * k] = mag[k];
1538 }
1539
1542 [[nodiscard]] double linearPhaseDesignStepCost() const noexcept
1543 {
1544 if (lpDesignStep_ < kLpMagChunks) return lpCostMagChunk_;
1545 if (lpDesignStep_ < kLpMagChunks + lpDesignFftSteps_) return lpCostDesignFftStep_;
1546 return lpCostPartitionStep_;
1547 }
1548
1551 double linearPhaseDesignStep() noexcept
1552 {
1553 const int designSize = 2 * firLength_;
1554 const int numBins = firLength_ + 1;
1555 const int b = lpDesignBand_;
1556
1557 if (lpDesignStep_ < kLpMagChunks)
1558 {
1559 // Ideal zero-phase magnitudes of band b. Each band carries the
1560 // high-pass of every split below it (lpCarry_, the running
1561 // product), like the IIR tree, so the bands telescope to exactly 1
1562 // (LP + HP = 1 per split). Ideal Linkwitz-Riley
1563 // |LP| = 1/(1 + (f/fc)^N) with N = order/6 (1/2/4/6/8 ->
1564 // 6/12/24/36/48 dB/oct), matching the IIR path's slope; integer
1565 // powers by repeated squaring. The imaginary parts stay zero (set in
1566 // prepare(); the inverse FFT does not write its input).
1567 const int chunk = (numBins + kLpMagChunks - 1) / kLpMagChunks;
1568 const int begin = std::min(numBins, lpDesignStep_ * chunk);
1569 const int end = std::min(numBins, begin + chunk);
1570 if (b == 0) std::fill(lpCarry_.begin() + begin, lpCarry_.begin() + end, 1.0);
1571 // One straight loop per slope keeps the divisions vectorised.
1572 const double fc = lpDesignFc_[static_cast<size_t>(b)];
1573 switch (lpDesignExpo_)
1574 {
1575 case 1: designBandMagnitudes<1>(fc, begin, end); break;
1576 case 2: designBandMagnitudes<2>(fc, begin, end); break;
1577 case 6: designBandMagnitudes<6>(fc, begin, end); break;
1578 case 8: designBandMagnitudes<8>(fc, begin, end); break;
1579 default: designBandMagnitudes<4>(fc, begin, end); break;
1580 }
1581 ++lpDesignStep_;
1582 return lpCostMagChunk_;
1583 }
1584
1585 if (lpDesignStep_ < kLpMagChunks + lpDesignFftSteps_)
1586 {
1587 // The long inverse FFT, one pass per step (bit-identical to a
1588 // single inverse()).
1589 lpDesignFft_->inverseStep(lpDesignStep_ - kLpMagChunks, lpTimeResponse_.data(), lpFirKernel_.data());
1590 ++lpDesignStep_;
1591 return lpCostDesignFftStep_;
1592 }
1593
1594 // One partition of band b: the zero-phase response centred at
1595 // firLength/2 under the flat-top window (a cosine taper over the
1596 // outer quarter on each side: it leaves the response's core
1597 // untouched, so the passband and slopes stay exact where a
1598 // full-length window would smear them), then its spectrum.
1599 const int part = lpDesignStep_ - kLpMagChunks - lpDesignFftSteps_;
1600 const int halfLen = firLength_ / 2;
1601 const size_t specLen = static_cast<size_t>(2 * lpPart_ + 2);
1602 const int first = part * lpPart_; // tap index of the partition start (the
1603 // centre is a partition boundary)
1604 // Tap i reads the inverse FFT at i - halfLen, wrapped into [0, 2L).
1605 const int shift = (first >= halfLen) ? -halfLen : designSize - halfLen;
1606 const T* src = lpFirKernel_.data() + (first + shift);
1607 const T* win = lpWindow_.data() + first;
1608 simd::multiplyT(lpScratch_.data(), src, win, lpPart_);
1609 // A partition whose taps sum below kLpSkipL1 is dropped (not
1610 // convolved): it changes the band by less than that at any frequency.
1611 // Away from the centre most partitions hold only the design's rounding
1612 // noise, so this skips most of the products of the higher bands.
1613 double l1 = 0.0;
1614 for (int j = 0; j < lpPart_; ++j) l1 += std::abs(static_cast<double>(lpScratch_[static_cast<size_t>(j)]));
1615 const size_t slot = static_cast<size_t>(lpDesignSet_ * kMaxSplits * kLpPartitions + b * kLpPartitions + part);
1616 const bool keep = l1 >= kLpSkipL1;
1617 lpPartOn_[slot] = keep ? 1 : 0;
1618 double cost = 2.0 * kLpCopyUnitsPerSample * static_cast<double>(lpPart_);
1619 if (keep)
1620 {
1621 ++lpDesignParts_;
1622 std::fill(lpScratch_.begin() + lpPart_, lpScratch_.end(), T(0));
1623 lpFft_->forward(lpScratch_.data(),
1624 lpKernelSet(lpDesignSet_) + static_cast<size_t>(b * kLpPartitions + part) * specLen);
1625 cost = lpCostPartitionStep_;
1626 }
1627
1628 if (++lpDesignStep_ == kLpMagChunks + lpDesignFftSteps_ + kLpPartitions)
1629 {
1630 lpDesignStep_ = 0;
1631 if (++lpDesignBand_ == lpDesignBands_ - 1)
1632 {
1633 // Every convolved band of the new design is ready: swap.
1634 // Partition work started from here on uses it; the work in
1635 // flight finishes on the previous design.
1636 lpActiveSet_ = lpDesignSet_;
1637 lpSetBands_[static_cast<size_t>(lpActiveSet_)] = lpDesignBands_;
1638 lpSetParts_[static_cast<size_t>(lpActiveSet_)] = lpDesignParts_;
1639 lpDesignActive_ = false;
1640 }
1641 }
1642 return cost;
1643 }
1644
1646 void designLinearPhaseNow() noexcept
1647 {
1648 lpMagDirty_.store(false, std::memory_order_relaxed);
1649 startLinearPhaseDesign();
1650 while (lpDesignActive_) (void)linearPhaseDesignStep();
1651 lpDesignCredit_ = 0.0;
1652 }
1653
1658 void advanceLinearPhaseDesign(int nS) noexcept
1659 {
1660 if (lpMagDirty_.load(std::memory_order_relaxed) &&
1661 lpMagDirty_.exchange(false, std::memory_order_acquire))
1662 {
1663 if (lpDesignActive_) lpDesignRedo_ = true;
1664 else { startLinearPhaseDesign(); lpDesignCredit_ = 0.0; }
1665 }
1666 if (!lpDesignActive_) return;
1667
1668 // A step runs only when the credit covers it, so a block adds at most
1669 // its budget plus the credit a short block left (under one step), or
1670 // one step when a step is larger than a block's budget (the credit
1671 // then builds up over a few blocks). The cap keeps a wait from
1672 // turning into a burst.
1673 const double budget = lpDesignRate_ * static_cast<double>(nS);
1674 const double maxStep = std::max(lpCostMagChunk_, std::max(lpCostDesignFftStep_, lpCostPartitionStep_));
1675 lpDesignCredit_ = std::min(lpDesignCredit_ + budget, budget + maxStep);
1676 while (lpDesignActive_)
1677 {
1678 // The partition work in flight may still read the set the design
1679 // writes (right after a swap); the design then waits for it.
1680 if (lpDesignSet_ == lpTaskSet_ && lpTaskUnit_ < lpTaskUnits_) break;
1681 // Nor the previous design while a fade from it is in flight or still to start.
1682 if (lpDesignSet_ == lpTaskFadeSet_ && lpTaskUnit_ < lpTaskUnits_) break;
1683 if (lpLaunchedSet_ >= 0 && lpLaunchedSet_ != lpActiveSet_ && lpDesignSet_ == lpLaunchedSet_) break;
1684 if (linearPhaseDesignStepCost() > lpDesignCredit_) break;
1685 lpDesignCredit_ -= linearPhaseDesignStep();
1686 if (!lpDesignActive_ && lpDesignRedo_) startLinearPhaseDesign();
1687 }
1688 if (!lpDesignActive_) lpDesignCredit_ = 0.0;
1689 }
1690
1691 // -- Linear-phase engine ---------------------------------------------------
1692 //
1693 // Input partition i (lpPart_ samples) is staged into a history ring. When
1694 // it is complete, the work for it starts: per channel, the transform of
1695 // the frame [partition i - 1, partition i] into the frequency-domain delay
1696 // line; per convolved band, the partition products and the inverse
1697 // transform, whose last half is the band's output partition y_i; then the
1698 // residual band, the input delayed by the latency minus the other bands.
1699 // y_i is heard kLpLeadBlocks partitions later, so the work has the whole
1700 // of partition i + 1 to run: it is split into units and run in
1701 // proportion to the samples of partition i + 1 staged so far.
1702
1703 inline T* lpRingOf(int ch) noexcept
1704 {
1705 return lpRing_.data() + static_cast<size_t>(ch) * static_cast<size_t>(kLpRingBlocks * lpPart_);
1706 }
1707 inline T* lpOutOf(int ch, int buf, int band) noexcept
1708 {
1709 return lpOut_.data()
1710 + ((static_cast<size_t>(ch) * 2 + static_cast<size_t>(buf)) * MaxBands + static_cast<size_t>(band))
1711 * static_cast<size_t>(lpPart_);
1712 }
1713
1717 [[nodiscard]] int lpUnitsPerChannel() const noexcept
1718 {
1719 const int fading = lpTaskFadeSet_ >= 0 ? lpTaskFadeBands_ - 1 : 0;
1720 return 2 + (lpTaskBands_ - 1 + fading) * (kLpPartitions + 1);
1721 }
1722
1724 void launchLinearPhaseTask(int block) noexcept
1725 {
1726 // The first partition on a new design also runs the previous one,
1727 // and each band goes from that design to the new over the partition.
1728 lpTaskFadeSet_ = (lpLaunchedSet_ >= 0 && lpLaunchedSet_ != lpActiveSet_) ? lpLaunchedSet_ : -1;
1729 lpTaskFadeBands_ = lpTaskFadeSet_ >= 0 ? std::max(2, lpSetBands_[static_cast<size_t>(lpTaskFadeSet_)]) : 0;
1730 lpLaunchedSet_ = lpActiveSet_;
1731 lpTaskSet_ = lpActiveSet_;
1732 lpTaskBands_ = std::max(2, lpSetBands_[static_cast<size_t>(lpActiveSet_)]);
1733 lpTaskBlock_ = block;
1734 lpTaskFdl_ = (lpTaskFdl_ + 1) % kLpPartitions;
1735 lpTaskUnit_ = 0;
1736 lpTaskUnits_ = numChannels_ * lpUnitsPerChannel();
1737 lpTaskDone_ = 0.0;
1738 lpTaskTotal_ = lpPartitionCost(lpTaskBands_, numChannels_, lpSetParts_[static_cast<size_t>(lpActiveSet_)]);
1739 if (lpTaskFadeSet_ >= 0)
1740 lpTaskTotal_ += static_cast<double>(numChannels_)
1741 * (static_cast<double>(lpSetParts_[static_cast<size_t>(lpTaskFadeSet_)]) * lpCostCma_
1742 + static_cast<double>(lpTaskFadeBands_ - 1) * lpCostIfft_
1743 + static_cast<double>(lpTaskFadeBands_ + lpTaskBands_) * lpCostResidualPerBand_);
1744 }
1745
1747 double runLinearPhaseUnit(int unit) noexcept
1748 {
1749 const int perCh = lpUnitsPerChannel();
1750 const int ch = unit / perCh;
1751 const int u = unit - ch * perCh;
1752 const int N = lpPart_;
1753 const size_t specLen = static_cast<size_t>(2 * N + 2);
1754 T* fdl = lpFdl_.data() + static_cast<size_t>(ch) * static_cast<size_t>(kLpPartitions) * specLen;
1755 const int next = 1 - lpPlay_;
1756
1757 if (u == 0)
1758 {
1759 // Overlap-save frame [partition i - 1, partition i].
1760 const T* ring = lpRingOf(ch);
1761 const int prev = (lpTaskBlock_ + kLpRingBlocks - 1) & (kLpRingBlocks - 1);
1762 std::copy_n(ring + static_cast<size_t>(prev) * static_cast<size_t>(N), N, lpScratch_.begin());
1763 std::copy_n(ring + static_cast<size_t>(lpTaskBlock_) * static_cast<size_t>(N), N, lpScratch_.begin() + N);
1764 lpFft_->forward(lpScratch_.data(), fdl + static_cast<size_t>(lpTaskFdl_) * specLen);
1765 return lpCostFft_;
1766 }
1767
1768 const int conv = lpTaskBands_ - 1;
1769 const int delayed = (lpTaskBlock_ + kLpRingBlocks - kLpPartitions / 2) & (kLpRingBlocks - 1);
1770 const T* delayedInput = lpRingOf(ch) + static_cast<size_t>(delayed) * static_cast<size_t>(N);
1771 if (u == perCh - 1)
1772 {
1773 if (lpTaskFadeSet_ >= 0) blendLinearPhaseFade(ch, next, delayedInput);
1774 // Residual band: the input delayed by the latency, minus the
1775 // convolved bands, so the bands sum to the delayed input exactly.
1776 T* dst = lpOutOf(ch, next, conv);
1777 std::copy_n(delayedInput, N, dst);
1778 for (int b = 0; b < conv; ++b)
1779 simd::addWithGainT(dst, lpOutOf(ch, next, b), T(-1), N); // exact: dst - src
1780 return static_cast<double>(lpTaskBands_) * lpCostResidualPerBand_;
1781 }
1782
1783 // The bands of the design (then, in a fade, those of the previous one).
1784 int band = (u - 1) / (kLpPartitions + 1);
1785 const int step = (u - 1) - band * (kLpPartitions + 1);
1786 const bool previous = band >= conv;
1787 const int set = previous ? lpTaskFadeSet_ : lpTaskSet_;
1788 if (previous) band -= conv;
1789 if (step < kLpPartitions)
1790 {
1791 if (step == 0) std::fill(lpAccum_.begin(), lpAccum_.end(), T(0));
1792 if (lpPartOn_[static_cast<size_t>(set * kMaxSplits * kLpPartitions + band * kLpPartitions + step)] == 0)
1793 return 0.0; // a dropped (negligible) partition
1794 const T* kernel = lpKernelSet(set) + static_cast<size_t>(band * kLpPartitions + step) * specLen;
1795 const int slot = (lpTaskFdl_ - step + kLpPartitions) % kLpPartitions;
1796 simd::complexMulAccum(lpAccum_.data(), fdl + static_cast<size_t>(slot) * specLen, kernel, N + 1);
1797 return lpCostCma_;
1798 }
1799 lpFft_->inverse(lpAccum_.data(), lpResult_.data());
1800 T* to = previous ? lpFadeOld_.data() + static_cast<size_t>(band) * static_cast<size_t>(N) : lpOutOf(ch, next, band);
1801 std::copy_n(lpResult_.begin() + N, N, to);
1802 return lpCostIfft_;
1803 }
1804
1813 void blendLinearPhaseFade(int ch, int next, const T* delayedInput) noexcept
1814 {
1815 const int N = lpPart_;
1816 const int before = lpTaskFadeBands_;
1817 const int conv = lpTaskBands_ - 1;
1818 auto old = [&](int b) { return lpFadeOld_.data() + static_cast<size_t>(b) * static_cast<size_t>(N); };
1819 T* oldResidual = old(before - 1);
1820 std::copy_n(delayedInput, N, oldResidual);
1821 for (int b = 0; b < before - 1; ++b) simd::addWithGainT(oldResidual, old(b), T(-1), N);
1822 const T invN = T(1) / static_cast<T>(N);
1823 for (int b = 0; b < conv; ++b)
1824 {
1825 T* out = lpOutOf(ch, next, b);
1826 const T* from = b < before ? old(b) : nullptr;
1827 for (int i = 0; i < N; ++i)
1828 {
1829 const T was = from != nullptr ? from[i] : T(0);
1830 out[i] = was + (out[i] - was) * (static_cast<T>(i + 1) * invN);
1831 }
1832 }
1833 }
1834
1837 void runLinearPhaseTask(int staged) noexcept
1838 {
1839 if (lpTaskSet_ < 0) return;
1840 const double target = (staged >= lpPart_)
1841 ? lpTaskTotal_ + 1.0
1842 : lpTaskTotal_ * static_cast<double>(staged) / static_cast<double>(lpPart_);
1843 while (lpTaskUnit_ < lpTaskUnits_ && lpTaskDone_ < target)
1844 lpTaskDone_ += runLinearPhaseUnit(lpTaskUnit_++);
1845 }
1846
1847 void processLinearPhase(AudioBufferView<T> input, AudioBufferView<T>* outputs, int numBands, int nS,
1848 int nCh) noexcept
1849 {
1850 advanceLinearPhaseDesign(nS);
1851
1852 const int N = lpPart_;
1853 int done = 0;
1854 while (done < nS)
1855 {
1856 const int run = std::min(nS - done, N - lpPos_);
1857 // The output partition was computed with lpOutBands_ bands. Until
1858 // a band-count change lands, missing bands are silent and extra
1859 // ones fold into the last requested band, so the sum stays exact.
1860 const int have = lpOutBands_;
1861 const size_t stage = static_cast<size_t>(lpStageBlock_) * static_cast<size_t>(N)
1862 + static_cast<size_t>(lpPos_);
1863 for (int ch = 0; ch < numChannels_; ++ch)
1864 {
1865 // Stage the input first (the outputs may alias it). Every
1866 // prepared channel advances, so the shared delay-line slot
1867 // stays coherent when a later block has more channels.
1868 T* dst = lpRingOf(ch) + stage;
1869 if (ch >= nCh)
1870 {
1871 std::fill_n(dst, run, T(0));
1872 continue;
1873 }
1874 const T* src = input.getChannel(ch) + done;
1875 for (int i = 0; i < run; ++i)
1876 dst[i] = std::isfinite(src[i]) ? src[i] : T(0); // never latch a NaN
1877 for (int b = 0; b < numBands; ++b)
1878 {
1879 T* out = outputs[b].getChannel(ch) + done;
1880 if (b < have) std::copy_n(lpOutOf(ch, lpPlay_, b) + lpPos_, run, out);
1881 else std::fill_n(out, run, T(0));
1882 }
1883 for (int b = numBands; b < have; ++b)
1884 {
1885 simd::addT(outputs[numBands - 1].getChannel(ch) + done, lpOutOf(ch, lpPlay_, b) + lpPos_, run);
1886 }
1887 }
1888 lpPos_ += run;
1889 done += run;
1890 runLinearPhaseTask(lpPos_);
1891
1892 if (lpPos_ == N)
1893 {
1894 // The work in flight is complete (its window has ended): its
1895 // partition plays next, and the work for the partition just
1896 // staged starts.
1897 if (lpTaskSet_ >= 0)
1898 {
1899 lpPlay_ = 1 - lpPlay_;
1900 lpOutBands_ = lpTaskBands_;
1901 }
1902 launchLinearPhaseTask(lpStageBlock_);
1903 lpStageBlock_ = (lpStageBlock_ + 1) & (kLpRingBlocks - 1);
1904 lpPos_ = 0;
1905 }
1906 }
1907 }
1908
1909 // -- Members -------------------------------------------------------------
1910
1911 AudioSpec spec_ {};
1912 bool prepared_ = false;
1913 std::atomic<int> numBands_ { 2 };
1914 std::atomic<int> order_ { 24 };
1915 int numChannels_ = 2;
1916 std::atomic<FilterMode> filterMode_ { FilterMode::MinimumPhase };
1917 std::atomic<bool> dirty_ { true };
1918
1919 std::array<std::atomic<T>, kMaxSplits> targetFrequencies_ {};
1920 std::atomic<bool> freqUpdatePending_ { false };
1921
1922 std::array<T, kMaxSplits> frequencies_ {};
1923 std::array<SmoothedValue<T>, kMaxSplits> freqSmoothers_;
1924
1925 int numStagesPerFilter_ = 2;
1926 int numStagesAllpass_ = 1;
1928
1929 std::array<std::unique_ptr<IirBank>, 2> banks_;
1930 int bank_ = 0;
1931 int fadeBank_ = -1;
1932 std::vector<T> workBuf_;
1933
1934 // The same sections as normalized ladders (setStructure()): per split the
1935 // low then the high branch (kMaxStagesPerFilter each), then two per
1936 // phase-correction chain [band * kMaxSplits + split]. Heap, from prepare().
1937 std::vector<double> ladderTmp_;
1938 std::atomic<Structure> structure_ { Structure::DirectForm };
1939 std::atomic<Topology> topology_ { Topology::Cascade };
1940 bool ladderActive_ = false;
1941
1942 // Linear-phase state (uniformly partitioned convolution)
1943 std::unique_ptr<FFTReal<T>> lpFft_; // partition transforms (2 x lpPart_); the engine gate
1944 std::unique_ptr<FFTReal<T>> lpDesignFft_; // kernel design (2 x firLength_)
1945 int firLength_ = 0;
1946 int lpPart_ = 0;
1947 int lpLatency_ = 0;
1948 int lpPos_ = 0; // samples staged in the current partition
1949 int lpStageBlock_ = 0; // history-ring block being staged
1950 int lpPlay_ = 0; // output buffer that plays (the other is being computed)
1951 int lpOutBands_ = 0; // bands in the output partition being emitted
1952 int lpActiveSet_ = 0; // kernel set that new partition work uses (audio thread)
1953 std::array<int, 2> lpSetBands_ { 0, 0 }; // band count of each kernel set
1954 std::array<int, 2> lpSetParts_ { 0, 0 }; // convolved partitions of each kernel set (all bands)
1955 // Partition work in flight (audio thread).
1956 int lpTaskSet_ = -1; // kernel set it reads (-1: none in flight)
1957 int lpTaskBands_ = 2;
1958 int lpTaskBlock_ = 0; // history-ring block of its input partition
1959 int lpTaskFdl_ = 0; // delay-line slot of its input spectrum
1960 int lpTaskUnit_ = 0;
1961 int lpTaskUnits_ = 0;
1962 double lpTaskDone_ = 0.0;
1963 double lpTaskTotal_ = 0.0;
1964 int lpLaunchedSet_ = -1; // kernel set of the last partition work launched
1965 int lpTaskFadeSet_ = -1; // previous set the work in flight fades from (-1: none)
1966 int lpTaskFadeBands_ = 0;
1967 // Cost model (units), set in prepare().
1968 double lpCostFft_ = 0.0, lpCostCma_ = 0.0, lpCostIfft_ = 0.0, lpCostResidualPerBand_ = 0.0;
1969 double lpCostMagChunk_ = 0.0, lpCostDesignFftStep_ = 0.0, lpCostPartitionStep_ = 0.0;
1970 // Design step machine (audio thread; prepare() runs it whole).
1971 bool lpDesignActive_ = false;
1972 bool lpDesignRedo_ = false; // a change arrived during the design
1973 int lpDesignSet_ = 1; // kernel set the design writes
1974 int lpDesignBand_ = 0;
1975 int lpDesignStep_ = 0; // magnitude chunks, inverse FFT passes, partitions
1976 int lpDesignBands_ = 0;
1977 int lpDesignParts_ = 0; // partitions the design keeps so far
1978 int lpDesignExpo_ = 4;
1979 int lpDesignFftSteps_ = 1;
1980 std::array<double, kMaxSplits> lpDesignFc_ {};
1981 double lpDesignCredit_ = 0.0;
1982 double lpDesignRate_ = 0.0; // design units per sample
1983 int glideRemain_ = 0; // samples left in the current IIR glide segment
1984 // The minimum-phase engine's band count and the fade of a change.
1985 int iirBands_ = 0; // bands of the topology heading to (0: none yet since a reset)
1986 int fadeFrom_ = 0; // bands of the topology fading out
1987 Topology iirTopo_ = Topology::Cascade; // the topology heading to
1988 Topology fadeFromTopo_ = Topology::Cascade; // the topology fading out
1989 int fadeLeft_ = 0; // samples left of the fade
1990 int fadeLength_ = 960;
1991 std::vector<T> fadeBands_, fadeLower_, fadeTop_; // [band][ch][kFadeChunk] scratch of the fade
1992 std::atomic<bool> lpMagDirty_ { true };
1993
1994 std::vector<T> lpKernelSpec_; // [set][(band * partitions + part) * specLen] kernel partition spectra
1995 std::vector<uint8_t> lpPartOn_; // [set][band * partitions + part] 1 = convolved, 0 = negligible
1996 std::vector<T> lpFdl_; // [(ch * partitions + slot) * specLen] input spectra
1997 std::vector<T> lpRing_; // [ch][ring block][lpPart_] input history
1998 std::vector<T> lpOut_; // [((ch * 2 + buffer) * MaxBands + band) * lpPart_] output partitions
1999 std::vector<T> lpAccum_, lpResult_, lpScratch_;
2000 std::vector<T> lpFadeOld_; // [band][lpPart_] one channel's previous-design bands in a fade
2001 std::vector<double> lpCarry_; // [bin] product of the high-passes below the band being designed
2002 std::vector<double> lpBinFreq_; // [bin] design grid frequencies
2003 std::vector<T> lpMag_; // [bin] magnitudes of the band being designed
2004 std::vector<T> lpWindow_; // [tap] flat-top window
2005 std::vector<T> lpTimeResponse_; // design IFFT input scratch (2 x firLength_ + 2)
2006 std::vector<T> lpFirKernel_; // design IFFT output scratch (2 x firLength_)
2007};
2008
2009} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Up to MaxSections second-order sections in series, run in one pass.
Linkwitz-Riley crossover with 2-12 bands: 6, 12, 24, 36 or 48 dB per octave.
int getLatency() const noexcept
Returns latency in samples: 0 for IIR; for linear-phase, three quarters of the FIR (3072 at 48 kHz),...
void setStructure(Structure structure) noexcept
Chooses how the sections of the minimum-phase engine are realised.
void setNumBandsKeepingSplits(int n) noexcept
Sets the number of output bands (2..MaxBands) and keeps the splits.
void setOrder(int order) noexcept
Sets the crossover slope: 6, 12, 24, 36 or 48 (dB/oct). Other values are ignored.
int getNumBands() const noexcept
void setNumBands(int n) noexcept
Sets the number of output bands (2..MaxBands).
void setTopology(Topology topology) noexcept
Arranges the splits of the minimum-phase engine.
Structure
How the minimum-phase sections are realised (see setStructure()).
@ Ladder
Normalized ladders: passive under any movement of the splits.
@ DirectForm
Direct form with a double memory, all sections in one pass (default).
bool setState(const uint8_t *data, size_t size)
Restores the split topology from a blob.
void setCrossoverFrequency(int index, T freqHz) noexcept
Sets a crossover frequency. Automatically maintains sorting.
T getCrossoverFrequency(int index) const noexcept
Returns the target frequency of split point index.
int processBlock(AudioBufferView< T > input, AudioBufferView< T > *bandOutputs, int numOutputBands) noexcept
Splits input into separate band outputs.
FilterMode
Filter processing mode.
@ LinearPhase
FFT-based FIR crossover (introduces latency, zero phase distortion, introduces pre-ringing).
@ MinimumPhase
IIR biquads with allpass phase correction (zero latency).
FilterMode getFilterMode() const noexcept
std::vector< uint8_t > getState() const
Serializes the split topology (setup/UI threads; allocates).
Topology
How the splits of the minimum-phase engine are arranged (see setTopology()).
@ Cascade
Each split takes what the one below left above it (default).
@ Balanced
The middle split first, each half divided the same way.
int getOrder() const noexcept
Topology getTopology() const noexcept
The arrangement set by setTopology().
void setFilterMode(FilterMode mode) noexcept
Sets the processing mode. A live switch resets filter state (transient).
Structure getStructure() const noexcept
The structure set by setStructure().
void prepare(const AudioSpec &spec)
Prepares the crossover for processing.
One second-order section in normalized ladder form, per channel.
Zero-allocation parameter smoother for real-time audio.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
void complexMulAccum(float *DSPARK_RESTRICT accum, const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int bins) noexcept
Complex multiply-accumulate over interleaved [re, im, ...] spectra.
Definition SimdOps.h:1234
void addT(T *DSPARK_RESTRICT dst, const T *DSPARK_RESTRICT src, int count) noexcept
Definition SimdOps.h:1433
void multiplyT(T *DSPARK_RESTRICT dst, const T *DSPARK_RESTRICT a, const T *DSPARK_RESTRICT b, int count) noexcept
Definition SimdOps.h:1440
void addWithGainT(T *DSPARK_RESTRICT dst, const T *DSPARK_RESTRICT src, T gain, int count) noexcept
Definition SimdOps.h:1405
Main namespace for the DSPark framework.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
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
static BiquadCoeffs makeFirstOrderHighPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) high-pass filter.
Definition Biquad.h:552
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
Definition Biquad.h:143
static BiquadCoeffs makeAllPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
All-pass filter.
Definition Biquad.h:500
static BiquadCoeffs makeFirstOrderLowPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) low-pass filter.
Definition Biquad.h:529
static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Low-pass filter.
Definition Biquad.h:119