DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Equalizer.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
109#include "Filters.h"
110#include "MidSide.h"
111#include "../Core/AudioSpec.h"
112#include "../Core/AudioBuffer.h"
113#include "../Core/Biquad.h"
114#include "../Core/BiquadCascade.h"
115#include "../Core/DenormalGuard.h"
116#include "../Core/DspMath.h"
117#include "../Core/FFT.h"
118#include "../Core/FilterDesign.h"
119#include "../Core/StateBlob.h"
120
121#include <algorithm>
122#include <array>
123#include <atomic>
124#include <cassert>
125#include <cmath>
126#include <complex>
127#include <cstddef>
128#include <cstdint>
129#include <cstdio>
130#include <memory>
131#include <numbers>
132#include <vector>
133
134namespace dspark {
135
143template <FloatType T, int MaxBands = 16>
145{
146public:
148 enum class FilterMode
149 {
153 };
154
156 ~Equalizer() = default;
157
159 enum class BandType
160 {
161 Peak,
162 LowShelf,
163 HighShelf,
164 LowPass,
165 HighPass,
166 Notch,
167 BandPass,
168 Tilt,
169 AllPass,
175 };
176
178 enum class Scope
179 {
180 Stereo,
181 Left,
182 Right,
183 Mid,
184 Side
185 };
186
191 {
192 T frequency = T(1000);
193 T gain = T(0);
194 T q = T(0.707);
196 T slope = T(12);
197 T order = T(1);
198 bool enabled = true;
200 };
201
202 static_assert(std::atomic<T>::is_always_lock_free,
203 "audio-thread stores must not lock");
204 static_assert(MaxBands > 0, "an equalizer needs at least one band");
205
206 // -- Lifecycle --------------------------------------------------------------
207
219 void prepare(const AudioSpec& spec)
220 {
221 if (!spec.isValid()) return; // release-safe: keep previous state
222
223 spec_ = spec;
224 for (int i = 0; i < MaxBands; ++i)
225 bands_[i].prepare(spec);
226 // The K weighting of BS.1770 (its shelf and its high-pass).
227 kShelf_ = BiquadCoeffs::makeHighShelf(spec.sampleRate, 1681.974450955533, 3.999843853973347);
228 kHighPass_ = BiquadCoeffs::makeHighPass(spec.sampleRate, 38.13547087602444, 0.5003270373238773);
229 compRamp_ = std::max(1, static_cast<int>(0.05 * spec.sampleRate));
231 compLeft_ = 0;
232
233 // Band crossfade scratch: one block of dry signal per channel the
234 // FilterEngines process (they hold at most 16 channels).
235 bandDryChannels_ = std::min(spec.numChannels, 16);
237 bandDry_.assign(static_cast<size_t>(bandDryChannels_) * static_cast<size_t>(bandDryStride_), T(0));
238 bandFadeStep_ = static_cast<T>(1.0 / std::max(1.0, spec.sampleRate * kBandFadeSeconds));
239 bandSnap_ = true;
240
241 // The engine of the analog response: one cascade per band, settled on
242 // the published configuration.
244 analog_ = std::make_unique<std::array<AnalogBand, MaxBands>>();
245 for (int i = 0; i < MaxBands; ++i)
246 {
247 const BandConfig cfg = staged_[i].read();
248 bandAnalog_[static_cast<size_t>(i)] = usesAnalog(cfg);
249 bandScope_[static_cast<size_t>(i)] = static_cast<int>(cfg.scope);
250 if (bandAnalog_[static_cast<size_t>(i)]) designAnalogBand(i, cfg, true);
251 }
252
253 // The prototype-phase mode: the grid its correction is designed on, the
254 // window that cuts it to length, and its filters at rest (the signal,
255 // late). prototype_ gates the mode, so it is set last.
256 prototype_.reset();
257 {
258 auto engine = std::make_unique<PrototypeEngine>();
259 PrototypeEngine& e = *engine;
260 e.channels = spec.numChannels;
261 e.spectrum.assign(static_cast<size_t>(2 * kPrototypeBins + 2), 0.0);
262 e.time.assign(static_cast<size_t>(2 * kPrototypeBins), 0.0);
263 e.work.assign(static_cast<size_t>(e.channels) * static_cast<size_t>(kPrototypeTaps - 1 + kPrototypeGrid), T(0));
264 const double nyquist = 0.5 * spec.sampleRate;
265 const double top = std::min(designBand_.getHighHz(), 0.98 * nyquist);
266 for (int k = 0; k <= kPrototypeBins; ++k)
267 {
268 const auto at = static_cast<size_t>(k);
269 const double theta = std::numbers::pi * k / kPrototypeBins, hz = nyquist * k / kPrototypeBins;
270 e.omega[at] = 2.0 * std::numbers::pi * hz;
271 e.cosOne[at] = std::cos(theta);
272 e.sinOne[at] = std::sin(theta);
273 e.cosTwo[at] = std::cos(2.0 * theta);
274 e.sinTwo[at] = std::sin(2.0 * theta);
275 const double past = std::clamp((hz - top) / (nyquist - top), 0.0, 1.0);
276 const double fall = std::cos(0.5 * std::numbers::pi * past);
277 e.taper[at] = fall * fall;
278 }
279 for (int m = 0; m < kPrototypeTaps; ++m)
280 {
281 // Whole over the middle half, down to nothing at the first tap.
282 const double away = std::abs(m - kPrototypeDelay) / static_cast<double>(kPrototypeDelay);
283 const double fall = std::cos(0.5 * std::numbers::pi * std::clamp(2.0 * away - 1.0, 0.0, 1.0));
284 e.window[static_cast<size_t>(m)] = fall * fall;
285 }
286 e.fadeLength = kPrototypeGrid * std::max(1, static_cast<int>(
287 std::lround(kPrototypeFadeSeconds * spec.sampleRate / kPrototypeGrid)));
288 prototype_ = std::move(engine);
289 }
290 designPrototype(true);
291 prototypeWasActive_ = false;
292
293 // Rebuild the linear-phase engine. lpFft_ gates the LP audio path, so
294 // it is torn down first and re-created last (basic guarantee if an
295 // allocation throws mid-way).
296 lpFft_.reset();
297 lpDesignFft_.reset();
298 lpKernelLength_ = 0;
299 lpPartition_ = 0;
300 lpPartitions_ = 0;
302 lpSlots_ = lpChannels_ >= 2 ? (lpChannels_ > 2 ? 5 : 4) : 1;
303
304 const int kernel = resolveKernelLength(spec.sampleRate);
305 const int part = std::max(kLpMinPartition, kernel / kLpPartitionCount);
306 const int parts = kernel / part;
307 const size_t specLen = static_cast<size_t>(2 * part + 2);
308 const size_t channels = static_cast<size_t>(lpChannels_);
309
310 for (auto& set : lpKernelSet_)
311 set.assign(static_cast<size_t>(lpSlots_) * static_cast<size_t>(parts) * specLen, T(0));
312 lpFdl_.assign(channels * static_cast<size_t>(parts) * specLen, T(0));
313 lpInput_.assign(channels * static_cast<size_t>(2 * part), T(0));
314 lpOutput_.assign(channels * static_cast<size_t>(part), T(0));
315 lpAccum_.assign(specLen, T(0));
316 lpWarm_.assign(channels * static_cast<size_t>(2 * part), T(0));
317 lpWarmChannels_.assign(channels, nullptr);
318 lpBlockTime_.assign(static_cast<size_t>(2 * part), T(0));
319 lpBlockTimeOld_.assign(static_cast<size_t>(2 * part), T(0));
320
321 const int design = 2 * kernel;
322 lpWindow_.resize(static_cast<size_t>(kernel));
323 for (int i = 0; i < kernel; ++i)
324 {
325 // Periodic Blackman-Harris: symmetric about i = kernel/2, the
326 // kernel's centre, so the FIR is exactly linear phase.
327 const double t = 2.0 * pi<double> * static_cast<double>(i) / static_cast<double>(kernel);
328 lpWindow_[static_cast<size_t>(i)] = static_cast<T>(
329 0.35875 - 0.48829 * std::cos(t) + 0.14128 * std::cos(2.0 * t) - 0.01168 * std::cos(3.0 * t));
330 }
331 lpMag_.assign(static_cast<size_t>(lpSlots_) * static_cast<size_t>(kernel + 1), T(1));
332 lpBandPower_.assign(static_cast<size_t>(MaxBands) * static_cast<size_t>(kernel + 1), 1.0f);
333 lpBandKept_.fill(false);
334 lpPlaced_[0] = lpPlaced_[1] = false;
335 lpDesignSpec_.assign(static_cast<size_t>(design + 2), T(0));
336 lpDesignTime_.assign(static_cast<size_t>(design), T(0));
337 lpKernelTime_.assign(static_cast<size_t>(kernel), T(0));
338
339 lpDesignFft_ = std::make_unique<FFTReal<T>>(static_cast<size_t>(design));
340 auto partitionFft = std::make_unique<FFTReal<T>>(static_cast<size_t>(2 * part));
341
342 lpKernelLength_ = kernel;
343 lpPartition_ = part;
344 lpPartitions_ = parts;
345 lpFft_ = std::move(partitionFft); // gate opens last
346
347 // Design the kernel of the current configuration now, on the setup
348 // thread, so the engine never starts on an empty kernel.
349 lpDirty_.store(false, std::memory_order_relaxed);
351 lpRestartPending_ = false;
352 lpSwapPending_ = false;
353 lpActive_ = 0;
354 for (int guard = 0; lpStage_ != LpStage::Idle && guard < kLpSyncSteps; ++guard)
356 if (lpSwapPending_) { lpActive_ = 1 - lpActive_; lpSwapPending_ = false; }
358 lpSnap_ = true;
359 lpWasActive_ = false;
360 }
361
375 void processBlock(AudioBufferView<T> buffer) noexcept
376 {
377 DenormalGuard guard;
378
379 // Front-door non-finite guard: the IIR bands (and the FFT overlap-save
380 // history in LinearPhase mode) latch a NaN/Inf input permanently.
381 // Scrub non-finite input to 0 before either path runs.
382 // No-op on finite input, so conformance metrics stay byte-identical.
383 {
384 const int gN = buffer.getNumSamples();
385 for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
386 {
387 T* d = buffer.getChannel(ch);
388 for (int i = 0; i < gN; ++i)
389 if (!std::isfinite(d[i])) d[i] = T(0);
390 }
391 }
392
393 // Check if config was updated from the UI thread (Lock-free acquire)
394 if (configDirty_.exchange(false, std::memory_order_acquire))
395 {
398 lpDirty_.store(true, std::memory_order_release);
399 }
400
401 FilterMode currentMode = filterMode_.load(std::memory_order_acquire);
402
403 if (currentMode == FilterMode::LinearPhase && lpFft_)
404 {
405 if (!lpWasActive_)
406 {
407 // Entering the mode: the engine's history belongs to an
408 // earlier stretch of audio, and any pending design completes
409 // on this block.
411 lpSnap_ = true;
412 lpWasActive_ = true;
413 }
414 processLinearPhase(buffer);
415 applyCompensation(buffer);
416 return;
417 }
419 lpWasActive_ = false;
420 processMinimumPhase(buffer);
421
422 if (currentMode == FilterMode::PrototypePhase && prototype_)
423 {
424 // Entering the mode: the correction lands at once on the bands as
425 // they are, with nothing of an earlier stretch of audio in it.
428 prototypeWasActive_ = true;
429 processPrototype(buffer);
430 }
431 else
432 {
433 prototypeWasActive_ = false;
434 }
435 applyCompensation(buffer);
436 }
437
454 [[nodiscard]] T processSample(T input, int channel) noexcept
455 {
456 // Plain load first: the exchange RMW is only paid when a publication
457 // is actually pending (this runs per sample).
458 if (configDirty_.load(std::memory_order_acquire)
459 && configDirty_.exchange(false, std::memory_order_acquire))
460 {
463 const int n = numBands_.load(std::memory_order_relaxed);
464 for (int i = 0; i < n; ++i)
465 bands_[i].applyParametersNow();
466 lpDirty_.store(true, std::memory_order_release);
467 }
468
469 T sample = input;
470 const int activeBands = numBands_.load(std::memory_order_relaxed);
471
472 for (int i = 0; i < activeBands; ++i)
473 {
474 if (!bandEnabled_[i].load(std::memory_order_relaxed)) continue;
475 // A band of one channel keeps its memory in the first slot of its
476 // engine, as in the block form. Middle and sides need both
477 // channels of a frame: those bands only run in processBlock().
478 const int scope = bandScope_[static_cast<size_t>(i)];
479 if (scope >= static_cast<int>(Scope::Mid)) continue;
480 if (scope != static_cast<int>(Scope::Stereo)
481 && channel != (scope == static_cast<int>(Scope::Left) ? 0 : 1)) continue;
482 const int slot = scope == static_cast<int>(Scope::Stereo) ? channel : 0;
483 if (bandAnalog_[static_cast<size_t>(i)] && analog_)
484 {
485 // Ramps move once per frame, on the first channel the band plays.
486 AnalogBand& band = (*analog_)[static_cast<size_t>(i)];
487 if (slot == 0)
488 {
489 band.cascade.advanceRamps(1);
490 advanceGlide(band, 1);
491 settleAnalogBand(band);
492 }
493 if (slot >= 0 && slot < kEngineChannels && !band.idle)
494 sample = static_cast<T>(band.cascade.processSample(static_cast<double>(sample), slot));
495 }
496 else
497 {
498 sample = bands_[i].processSample(sample, slot);
499 }
500 }
501 // The compensation, at its target at once.
502 return compTarget_ == 1.0 ? sample : static_cast<T>(static_cast<double>(sample) * compTarget_);
503 }
504
508 void reset() noexcept
509 {
510 for (int i = 0; i < MaxBands; ++i)
511 bands_[i].reset();
513 compLeft_ = 0;
514 if (analog_)
515 for (auto& band : *analog_) band.cascade.reset();
516
517 bandSnap_ = true;
519 lpSnap_ = true;
521 }
522
523 // -- API --------------------------------------------------------------------
524
531 void setBand(int index, T frequency, T gainDb)
532 {
533 setBand(index, frequency, gainDb, T(0.707));
534 }
535
543 void setBand(int index, T frequency, T gainDb, T q)
544 {
545 BandConfig cfg;
546 cfg.frequency = frequency;
547 cfg.gain = gainDb;
548 cfg.q = q;
549 cfg.type = BandType::Peak;
550 cfg.slope = 12;
551 cfg.enabled = true;
552 setBand(index, cfg);
553 }
554
566 void setBand(int index, const BandConfig& config)
567 {
568 if (index < 0 || index >= MaxBands) return;
569
570 BandConfig cfg = config;
571 // The fallback reads the control thread's own private master, never the
572 // published words: a setter must not race the audio thread to decide
573 // what "the band's current value" is.
574 const BandConfig& prev = masterConfigs_[index];
575 if (!std::isfinite(cfg.frequency)) cfg.frequency = prev.frequency;
576 if (!std::isfinite(cfg.gain)) cfg.gain = prev.gain;
577 if (!std::isfinite(cfg.q)) cfg.q = prev.q;
578 if (!std::isfinite(cfg.slope)) cfg.slope = prev.slope;
579 if (static_cast<int>(cfg.type) < 0 || static_cast<int>(cfg.type) > static_cast<int>(BandType::HighPassWall))
580 cfg.type = prev.type;
581 if (static_cast<int>(cfg.scope) < 0 || static_cast<int>(cfg.scope) > static_cast<int>(Scope::Side))
582 cfg.scope = prev.scope;
583 cfg.slope = std::clamp(cfg.slope, T(0), T(96));
584 cfg.order = std::isfinite(cfg.order) ? std::clamp(cfg.order, T(1), static_cast<T>(kMaxBandSections)) : prev.order;
585
586 masterConfigs_[index] = cfg;
587 staged_[index].publish(cfg);
588 bandEnabled_[index].store(cfg.enabled, std::memory_order_release);
589
590 int currentBands = numBands_.load(std::memory_order_relaxed);
591 if (index >= currentBands)
592 numBands_.store(index + 1, std::memory_order_relaxed);
593
594 // Signal audio thread to update filters
595 configDirty_.store(true, std::memory_order_release);
596 }
597
602 void setNumBands(int count)
603 {
604 int validCount = std::clamp(count, 1, MaxBands);
605 numBands_.store(validCount, std::memory_order_relaxed);
606
607 const T logMin = std::log(T(80));
608 const T logMax = std::log(T(16000));
609
610 for (int i = 0; i < validCount; ++i)
611 {
612 T t = (validCount > 1) ? static_cast<T>(i) / static_cast<T>(validCount - 1) : T(0.5);
613
614 BandConfig cfg;
615 cfg.frequency = std::exp(logMin + t * (logMax - logMin));
616 cfg.gain = T(0);
617 cfg.q = T(0.707);
618 cfg.type = BandType::Peak;
619 cfg.slope = 12;
620 cfg.enabled = true;
621
622 masterConfigs_[i] = cfg;
623 staged_[i].publish(cfg);
624 bandEnabled_[i].store(true, std::memory_order_release);
625 }
626 configDirty_.store(true, std::memory_order_release);
627 }
628
630 [[nodiscard]] int getNumBands() const noexcept
631 {
632 return numBands_.load(std::memory_order_relaxed);
633 }
634
642 void setLoudnessCompensation(bool on) noexcept
643 {
644 loudnessComp_.store(on, std::memory_order_relaxed);
645 configDirty_.store(true, std::memory_order_release);
646 }
647
649 [[nodiscard]] bool getLoudnessCompensation() const noexcept { return loudnessComp_.load(std::memory_order_relaxed); }
650
652 [[nodiscard]] T getCompensationDb() const noexcept { return compensationDb_.load(std::memory_order_relaxed); }
653
666 void setMatchedBells(bool enabled) noexcept
667 {
668 matchedBells_.store(enabled, std::memory_order_relaxed);
669 configDirty_.store(true, std::memory_order_release);
670 }
671
673 [[nodiscard]] bool isMatchedBells() const noexcept
674 {
675 return matchedBells_.load(std::memory_order_relaxed);
676 }
677
680
693 void setStructure(Structure structure) noexcept
694 {
695 structure = static_cast<Structure>(std::clamp(static_cast<int>(structure), 0, 1));
696 structure_.store(structure, std::memory_order_relaxed);
697 for (auto& band : bands_) band.setStructure(structure);
698 }
699
701 [[nodiscard]] Structure getStructure() const noexcept { return structure_.load(std::memory_order_relaxed); }
702
715 void setMatchedFilters(bool enabled) noexcept
716 {
717 matchedFilters_.store(enabled, std::memory_order_relaxed);
718 configDirty_.store(true, std::memory_order_release);
719 }
720
722 [[nodiscard]] bool isMatchedFilters() const noexcept
723 {
724 return matchedFilters_.load(std::memory_order_relaxed);
725 }
726
737 void setAnalogResponse(bool enabled) noexcept
738 {
739 analogResponse_.store(enabled, std::memory_order_relaxed);
740 configDirty_.store(true, std::memory_order_release);
741 }
742
754 void setResonantShelves(bool enabled) noexcept
755 {
756 resonantShelves_.store(enabled, std::memory_order_relaxed);
757 configDirty_.store(true, std::memory_order_release);
758 }
759
761 [[nodiscard]] bool isResonantShelves() const noexcept
762 {
763 return resonantShelves_.load(std::memory_order_relaxed);
764 }
765
767 [[nodiscard]] bool isAnalogResponse() const noexcept
768 {
769 return analogResponse_.load(std::memory_order_relaxed);
770 }
771
782 [[nodiscard]] BandConfig getBandConfig(int index) const noexcept
783 {
784 if (index < 0 || index >= MaxBands) return {};
785 return staged_[index].read();
786 }
787
793 void setBandEnabled(int index, bool enabled) noexcept
794 {
795 if (index >= 0 && index < MaxBands)
796 {
797 masterConfigs_[index].enabled = enabled;
798 staged_[index].publish(masterConfigs_[index]);
799 bandEnabled_[index].store(enabled, std::memory_order_release);
800 configDirty_.store(true, std::memory_order_release);
801 }
802 }
803
821 void setFilterMode(FilterMode mode) noexcept
822 {
823 const int m = std::clamp(static_cast<int>(mode), 0,
824 static_cast<int>(FilterMode::PrototypePhase));
825 const bool prototype = static_cast<FilterMode>(m) == FilterMode::PrototypePhase;
826 const bool wasPrototype = filterMode_.exchange(static_cast<FilterMode>(m), std::memory_order_acq_rel) == FilterMode::PrototypePhase;
827 if (static_cast<FilterMode>(m) == FilterMode::LinearPhase)
828 lpDirty_.store(true, std::memory_order_release);
829 // PrototypePhase runs every band from its analog prototype: going in
830 // or out of it, the bands are looked at again.
831 if (prototype != wasPrototype)
832 configDirty_.store(true, std::memory_order_release);
833 }
834
836 [[nodiscard]] FilterMode getFilterMode() const noexcept
837 {
838 return filterMode_.load(std::memory_order_relaxed);
839 }
840
851 [[nodiscard]] int getLatency() const noexcept
852 {
853 const FilterMode mode = filterMode_.load(std::memory_order_relaxed);
854 if (mode == FilterMode::PrototypePhase) return prototype_ ? kPrototypeDelay : 0;
855 return (mode == FilterMode::LinearPhase && lpFft_) ? lpKernelLength_ / 2 + lpPartition_ : 0;
856 }
857
870 [[nodiscard]] T getAnalogBandResponse(int index, T hz) const noexcept
871 {
872 if (index < 0 || index >= MaxBands || !analog_ || !bandAnalog_[static_cast<size_t>(index)]
873 || !(spec_.sampleRate > 0.0)) return T(0);
874 const AnalogBand& band = (*analog_)[static_cast<size_t>(index)];
875 if (!band.configured || band.idle) return T(0);
876 const double w = 2.0 * pi<double> * std::clamp(static_cast<double>(hz), 0.0, 0.5 * spec_.sampleRate) / spec_.sampleRate;
877 const double c1 = std::cos(w), s1 = std::sin(w), c2 = std::cos(2.0 * w), s2 = std::sin(2.0 * w);
878 double power = 1.0;
879 for (int s = 0; s < band.cascade.getNumSections(); ++s)
880 {
881 if (!band.cascade.isSectionEnabled(s)) continue;
882 const BiquadCoeffs c = band.cascade.getCoeffs(s);
883 const double nRe = c.b0 + c.b1 * c1 + c.b2 * c2, nIm = -(c.b1 * s1 + c.b2 * s2);
884 const double dRe = 1.0 + c.a1 * c1 + c.a2 * c2, dIm = -(c.a1 * s1 + c.a2 * s2);
885 power *= (nRe * nRe + nIm * nIm) / std::max(dRe * dRe + dIm * dIm, 1e-300);
886 }
887 return static_cast<T>(10.0 * std::log10(std::max(power, 1e-30)));
888 }
889
900 void setLinearPhaseKernelLength(int taps) noexcept
901 {
902 lpKernelRequest_.store(taps <= 0 ? 0 : std::clamp(taps, kLpMinKernel, kLpMaxKernel),
903 std::memory_order_relaxed);
904 }
905
908 [[nodiscard]] int getLinearPhaseKernelLength() const noexcept { return lpKernelLength_; }
909
914 void setSoftMode(bool enabled) noexcept
915 {
916 softMode_.store(enabled, std::memory_order_relaxed);
917 configDirty_.store(true, std::memory_order_release);
918 }
919
921 [[nodiscard]] bool getSoftMode() const noexcept
922 {
923 return softMode_.load(std::memory_order_relaxed);
924 }
925
938 void getMagnitudeForFrequencyArray(const T* frequencies, T* magnitudes, int numPoints) const noexcept
939 {
940 magnitudeOfBands(frequencies, magnitudes, numPoints, -1);
941 }
942
952 void getMagnitudeForFrequencyArray(const T* frequencies, T* magnitudes, int numPoints, Scope where) const noexcept
953 {
954 magnitudeOfBands(frequencies, magnitudes, numPoints, static_cast<int>(where));
955 }
956
957protected:
959 void magnitudeOfBands(const T* frequencies, T* magnitudes, int numPoints, int where) const noexcept
960 {
961 for (int i = 0; i < numPoints; ++i)
962 magnitudes[i] = T(1);
963
964 const int activeBands = numBands_.load(std::memory_order_relaxed);
965 for (int b = 0; b < activeBands; ++b)
966 {
967 const BandConfig cfg = staged_[b].read();
968 if (!cfg.enabled) continue;
969 if (where >= 0 && cfg.scope != Scope::Stereo && static_cast<int>(cfg.scope) != where) continue;
970
972 const int ns = buildBandSections(cfg, st, kMaxBandSections);
973
974 for (int i = 0; i < numPoints; ++i)
975 {
976 double mag = 1.0;
977 for (int s = 0; s < ns; ++s)
978 mag *= st[s].getMagnitude(static_cast<double>(frequencies[i]), spec_.sampleRate);
979 magnitudes[i] = static_cast<T>(static_cast<double>(magnitudes[i]) * mag);
980 }
981 }
982 }
983
984public:
985
997 [[nodiscard]] FilterEngine<T>& getBandFilter(int index) noexcept
998 {
999 assert(index >= 0 && index < MaxBands);
1000 return bands_[static_cast<std::size_t>(std::clamp(index, 0, MaxBands - 1))];
1001 }
1002
1004 [[nodiscard]] const FilterEngine<T>& getBandFilter(int index) const noexcept
1005 {
1006 assert(index >= 0 && index < MaxBands);
1007 return bands_[static_cast<std::size_t>(std::clamp(index, 0, MaxBands - 1))];
1008 }
1009
1010
1012 [[nodiscard]] std::vector<uint8_t> getState() const
1013 {
1014 StateWriter w(stateId("PEQZ"), 1);
1015 const int n = numBands_.load(std::memory_order_relaxed);
1016 w.write("numBands", n);
1017 w.write("matchedBells", matchedBells_.load(std::memory_order_relaxed));
1018 w.write("matchedFilters", matchedFilters_.load(std::memory_order_relaxed));
1019 w.write("structure", static_cast<int32_t>(getStructure()));
1020 w.write("filterMode", static_cast<int32_t>(filterMode_.load(std::memory_order_relaxed)));
1021 w.write("softMode", softMode_.load(std::memory_order_relaxed));
1022 w.write("loudnessComp", getLoudnessCompensation());
1023 w.write("analog", analogResponse_.load(std::memory_order_relaxed));
1024 w.write("resonantShelves", resonantShelves_.load(std::memory_order_relaxed));
1025 char key[24];
1026 for (int i = 0; i < n; ++i)
1027 {
1028 const BandConfig cfg = getBandConfig(i);
1029 std::snprintf(key, sizeof(key), "b%d.freq", i);
1030 w.write(key, static_cast<float>(cfg.frequency));
1031 std::snprintf(key, sizeof(key), "b%d.gain", i);
1032 w.write(key, static_cast<float>(cfg.gain));
1033 std::snprintf(key, sizeof(key), "b%d.q", i);
1034 w.write(key, static_cast<float>(cfg.q));
1035 std::snprintf(key, sizeof(key), "b%d.type", i);
1036 w.write(key, static_cast<int32_t>(cfg.type));
1037 std::snprintf(key, sizeof(key), "b%d.slope", i);
1038 w.write(key, static_cast<int32_t>(std::lround(static_cast<double>(cfg.slope))));
1039 std::snprintf(key, sizeof(key), "b%d.slopeDb", i);
1040 w.write(key, static_cast<float>(cfg.slope));
1041 std::snprintf(key, sizeof(key), "b%d.order", i);
1042 w.write(key, static_cast<int32_t>(std::lround(static_cast<double>(cfg.order))));
1043 std::snprintf(key, sizeof(key), "b%d.orderReal", i);
1044 w.write(key, static_cast<float>(cfg.order));
1045 std::snprintf(key, sizeof(key), "b%d.on", i);
1046 w.write(key, cfg.enabled);
1047 std::snprintf(key, sizeof(key), "b%d.scope", i);
1048 w.write(key, static_cast<int32_t>(cfg.scope));
1049 }
1050 return w.blob();
1051 }
1052
1054 bool setState(const uint8_t* data, size_t size)
1055 {
1056 StateReader r(data, size);
1057 if (!r.isValid() || r.processorId() != stateId("PEQZ")) return false;
1058 const int n = std::clamp(r.read("numBands", 0), 0, MaxBands);
1059 setMatchedBells(r.read("matchedBells", true));
1060 setMatchedFilters(r.read("matchedFilters", false)); // older blobs: bilinear, as before
1061 setStructure(static_cast<Structure>(r.read("structure", 0)));
1062 // Older blobs carry no mode keys: keep the instance's current modes.
1063 setFilterMode(static_cast<FilterMode>(
1064 r.read("filterMode", static_cast<int32_t>(filterMode_.load(std::memory_order_relaxed)))));
1065 setSoftMode(r.read("softMode", softMode_.load(std::memory_order_relaxed)));
1066 setLoudnessCompensation(r.read("loudnessComp", false));
1067 setAnalogResponse(r.read("analog", analogResponse_.load(std::memory_order_relaxed)));
1068 setResonantShelves(r.read("resonantShelves", false));
1069 char key[24];
1070 for (int i = 0; i < n; ++i)
1071 {
1072 BandConfig cfg;
1073 std::snprintf(key, sizeof(key), "b%d.freq", i);
1074 cfg.frequency = static_cast<T>(r.read(key, 1000.0f));
1075 std::snprintf(key, sizeof(key), "b%d.gain", i);
1076 cfg.gain = static_cast<T>(r.read(key, 0.0f));
1077 std::snprintf(key, sizeof(key), "b%d.q", i);
1078 cfg.q = static_cast<T>(r.read(key, 0.707f));
1079 std::snprintf(key, sizeof(key), "b%d.type", i);
1080 cfg.type = static_cast<BandType>(r.read(key, 0));
1081 std::snprintf(key, sizeof(key), "b%d.slope", i);
1082 const int wholeSlope = r.read(key, 12);
1083 std::snprintf(key, sizeof(key), "b%d.slopeDb", i);
1084 cfg.slope = static_cast<T>(r.read(key, static_cast<float>(wholeSlope))); // older blobs: the whole slope
1085 std::snprintf(key, sizeof(key), "b%d.order", i);
1086 const int wholeOrder = r.read(key, 1);
1087 std::snprintf(key, sizeof(key), "b%d.orderReal", i);
1088 cfg.order = static_cast<T>(r.read(key, static_cast<float>(wholeOrder))); // older blobs: the whole order
1089 std::snprintf(key, sizeof(key), "b%d.on", i);
1090 cfg.enabled = r.read(key, true);
1091 std::snprintf(key, sizeof(key), "b%d.scope", i);
1092 cfg.scope = static_cast<Scope>(r.read(key, 0));
1093 setBand(i, cfg);
1094 }
1095 numBands_.store(n, std::memory_order_relaxed);
1096 configDirty_.store(true, std::memory_order_release);
1097 return true;
1098 }
1099
1100protected:
1101
1105 [[nodiscard]] T effectiveQ(const BandConfig& cfg) const noexcept
1106 {
1107 T q = cfg.q;
1108 if (softMode_.load(std::memory_order_relaxed))
1109 {
1110 const T absGain = std::abs(cfg.gain);
1111 const T maxQ = T(1) + T(8) / (absGain + T(1));
1112 q = std::min(q, maxQ);
1113 }
1114 return q;
1115 }
1116
1138 void refreshCompensation() noexcept
1139 {
1140 double target = 1.0;
1141 if (loudnessComp_.load(std::memory_order_relaxed) && spec_.sampleRate > 0.0)
1142 {
1143 constexpr int kPoints = 96;
1144 const double top = std::min(20000.0, 0.45 * spec_.sampleRate);
1145 T f[kPoints], m[kPoints];
1146 for (int i = 0; i < kPoints; ++i)
1147 f[i] = static_cast<T>(20.0 * std::pow(top / 20.0, static_cast<double>(i) / (kPoints - 1)));
1148 magnitudeOfBands(f, m, kPoints, -1);
1149 double num = 0.0, den = 0.0;
1150 for (int i = 0; i < kPoints; ++i)
1151 {
1152 const double hz = static_cast<double>(f[i]);
1154 const double w = k * k, g = static_cast<double>(m[i]);
1155 num += w * g * g;
1156 den += w;
1157 }
1158 if (num > 0.0 && den > 0.0) target = std::sqrt(den / num);
1159 }
1160 compensationDb_.store(static_cast<T>(20.0 * std::log10(target)), std::memory_order_relaxed);
1161 if (target == compTarget_) return;
1162 compTarget_ = target;
1163 compStep_ = (compTarget_ - compNow_) / static_cast<double>(compRamp_);
1165 }
1166
1169 {
1170 if (compLeft_ == 0 && compNow_ == 1.0) return;
1171 const int nS = buffer.getNumSamples(), nCh = buffer.getNumChannels();
1172 for (int i = 0; i < nS; ++i)
1173 {
1174 if (compLeft_ > 0 && --compLeft_ == 0) compNow_ = compTarget_;
1175 else if (compLeft_ > 0) compNow_ += compStep_;
1176 const T g = static_cast<T>(compNow_);
1177 for (int ch = 0; ch < nCh; ++ch) buffer.getChannel(ch)[i] *= g;
1178 }
1179 }
1180
1181 void updateActiveFilters() noexcept
1182 {
1183 const bool matched = matchedBells_.load(std::memory_order_relaxed);
1184 const bool matchedOthers = matchedFilters_.load(std::memory_order_relaxed);
1185 int activeBands = numBands_.load(std::memory_order_relaxed);
1186
1187 for (int i = 0; i < activeBands; ++i)
1188 {
1189 auto& filter = bands_[i];
1190 BandConfig cfg;
1191 if (!staged_[i].tryRead(cfg))
1192 {
1193 // Bounded read gave up: keep this band's current coefficients
1194 // and pick the publication up on a later call.
1195 configDirty_.store(true, std::memory_order_release);
1196 continue;
1197 }
1198
1199 // A band that moves to other channels comes in through the band fade.
1200 if (static_cast<int>(cfg.scope) != bandScope_[static_cast<size_t>(i)])
1201 {
1202 bandScope_[static_cast<size_t>(i)] = static_cast<int>(cfg.scope);
1203 bandMix_[static_cast<size_t>(i)] = T(0);
1204 }
1205
1206 // A band of the analog response runs in its cascade; one that
1207 // changes engine comes in through the band fade.
1208 const bool analog = analog_ != nullptr && usesAnalog(cfg);
1209 if (analog != bandAnalog_[static_cast<size_t>(i)])
1210 {
1211 bandAnalog_[static_cast<size_t>(i)] = analog;
1212 bandMix_[static_cast<size_t>(i)] = T(0);
1213 if (analog) (*analog_)[static_cast<size_t>(i)].configured = false;
1214 }
1215 if (analog)
1216 {
1217 designAnalogBand(i, cfg, false);
1218 continue;
1219 }
1220
1221 float freq = static_cast<float>(cfg.frequency);
1222 float gain = static_cast<float>(cfg.gain);
1223 float q = static_cast<float>(effectiveQ(cfg));
1224
1225 filter.setMatchedPeak(matched);
1226 filter.setMatchedFilters(matchedOthers);
1227 switch (cfg.type)
1228 {
1229 case BandType::Peak: filter.setPeaking(freq, gain, q); break;
1230 // Shelves take a SLOPE (0..1], not a Q: convert with the RBJ
1231 // S<->Q relation so the user's Q behaves consistently here and
1232 // in the linear-phase kernel (which uses the same conversion).
1233 case BandType::LowShelf: filter.setLowShelf(freq, gain,
1234 static_cast<float>(shelfSlopeFromQ(q, gain))); break;
1235 case BandType::HighShelf: filter.setHighShelf(freq, gain,
1236 static_cast<float>(shelfSlopeFromQ(q, gain))); break;
1237 case BandType::LowPass: filter.setLowPass(freq, q, legacySlope(cfg)); break;
1238 case BandType::HighPass: filter.setHighPass(freq, q, legacySlope(cfg)); break;
1239 case BandType::Notch: filter.setNotch(freq, q); break;
1240 case BandType::BandPass: filter.setBandPass(freq, q); break;
1241 case BandType::Tilt: filter.setTilt(freq, gain); break;
1242 default: break; // the other types run in the analog engine
1243 }
1244 }
1245 }
1246
1254 [[nodiscard]] static double shelfSlopeFromQ(double q, double gainDb) noexcept
1255 {
1256 q = std::max(q, 0.05);
1257 const double A = std::pow(10.0, std::abs(gainDb) / 40.0);
1258 const double denom = A + 1.0 / A;
1259 const double invS = (1.0 / (q * q) - 2.0) / denom + 1.0;
1260 if (invS <= 1.0) return 1.0; // steeper-than-standard requests clamp to S = 1
1261 return std::clamp(1.0 / invS, 0.0001, 1.0);
1262 }
1263
1269 [[nodiscard]] BiquadCoeffs computeBandCoeffs(const BandConfig& cfg) const noexcept
1270 {
1271 double sr = spec_.sampleRate;
1272 double f = static_cast<double>(cfg.frequency);
1273 double g = static_cast<double>(cfg.gain);
1274 double q = static_cast<double>(cfg.q);
1275 const bool mf = matchedFilters_.load(std::memory_order_relaxed);
1276
1277 switch (cfg.type)
1278 {
1279 case BandType::Peak:
1280 return matchedBells_.load(std::memory_order_relaxed)
1281 ? BiquadCoeffs::makePeakMatched(sr, f, q, g)
1282 : BiquadCoeffs::makePeak(sr, f, q, g);
1283 case BandType::LowShelf:
1285 {
1286 const double slope = shelfSlopeFromQ(q, g);
1287 const bool lowShelf = cfg.type == BandType::LowShelf;
1288 if (mf && slope >= 1.0)
1289 return lowShelf ? BiquadCoeffs::makeLowShelfMatched(sr, f, g)
1291 return lowShelf ? BiquadCoeffs::makeLowShelf(sr, f, g, slope)
1292 : BiquadCoeffs::makeHighShelf(sr, f, g, slope);
1293 }
1294 case BandType::LowPass: return mf ? BiquadCoeffs::makeLowPassMatched(sr, f, q)
1295 : BiquadCoeffs::makeLowPass(sr, f, q);
1296 case BandType::HighPass: return mf ? BiquadCoeffs::makeHighPassMatched(sr, f, q)
1297 : BiquadCoeffs::makeHighPass(sr, f, q);
1298 case BandType::Notch: return BiquadCoeffs::makeNotch(sr, f, q);
1299 case BandType::BandPass: return mf ? BiquadCoeffs::makeBandPassMatched(sr, f, q)
1300 : BiquadCoeffs::makeBandPass(sr, f, q);
1301 case BandType::Tilt: return BiquadCoeffs::makeTilt(sr, f, g);
1302 default: break; // the other types have no single section
1303 }
1304 return {};
1305 }
1306
1307public:
1319 [[nodiscard]] int buildBandStages(const BandConfig& cfg, BiquadCoeffs* stages) const noexcept
1320 {
1321 const double sr = spec_.sampleRate;
1322 // Mirror the FilterEngine's own clamps so the analysis matches the audio.
1323 const double f = std::clamp(static_cast<double>(cfg.frequency), 10.0, sr * 0.499);
1324 const T q = std::max(effectiveQ(cfg), T(0.1));
1325
1326 if (cfg.type == BandType::LowPass || cfg.type == BandType::HighPass)
1327 {
1328 const bool lp = (cfg.type == BandType::LowPass);
1329 // The user Q scales the final cascade stage exactly like the engine.
1330 auto casc = FilterEngine<T>::cascadeForSlope(legacySlope(cfg), static_cast<float>(q));
1331 int n = 0;
1332 if (casc.hasFirstOrder)
1333 stages[n++] = lp ? BiquadCoeffs::makeFirstOrderLowPass(sr, f)
1335 const bool mf = matchedFilters_.load(std::memory_order_relaxed);
1336 for (int s = 0; s < casc.numSecondOrder; ++s)
1337 {
1338 const double stageQ = static_cast<double>(casc.qValues[s]);
1339 if (mf)
1340 stages[n++] = lp ? BiquadCoeffs::makeLowPassMatched(sr, f, stageQ)
1341 : BiquadCoeffs::makeHighPassMatched(sr, f, stageQ);
1342 else
1343 stages[n++] = lp ? BiquadCoeffs::makeLowPass(sr, f, stageQ)
1344 : BiquadCoeffs::makeHighPass(sr, f, stageQ);
1345 }
1346 return n;
1347 }
1348
1349 BandConfig eff = cfg;
1350 eff.frequency = static_cast<T>(f);
1351 eff.q = q;
1352 stages[0] = computeBandCoeffs(eff);
1353 return 1;
1354 }
1355
1356public:
1370 [[nodiscard]] int buildBandSections(const BandConfig& cfg, BiquadCoeffs* sections, int capacity) const noexcept
1371 {
1372 if (usesAnalog(cfg)) return designSections(cfg, sections, capacity);
1373 BiquadCoeffs stages[5];
1374 const int n = std::min(buildBandStages(cfg, stages), capacity);
1375 for (int i = 0; i < n; ++i) sections[i] = stages[i];
1376 return n;
1377 }
1378
1379protected:
1381 static constexpr int kEngineChannels = 16;
1382 static constexpr double kRampSlowMs = 40.0;
1383 static constexpr double kRampFastMs = 10.0;
1384 static constexpr int kMaxStretches = 32;
1385 static constexpr int kStretchSamples = 16;
1386 static constexpr double kRestDb = 0.05;
1387 static constexpr double kTiltCeilingDb = 36.0;
1388
1407
1409 [[nodiscard]] static int legacySlope(const BandConfig& cfg) noexcept
1410 {
1411 return static_cast<int>(std::lround(std::clamp(static_cast<double>(cfg.slope), 6.0, 48.0)));
1412 }
1413
1415 [[nodiscard]] bool usesAnalog(const BandConfig& cfg) const noexcept
1416 {
1417 return analogResponse_.load(std::memory_order_relaxed)
1418 || filterMode_.load(std::memory_order_relaxed) == FilterMode::PrototypePhase
1419 || static_cast<int>(cfg.type) > static_cast<int>(BandType::Tilt)
1420 || cfg.order > T(1)
1421 || (resonantShelves_.load(std::memory_order_relaxed)
1422 && (cfg.type == BandType::LowShelf || cfg.type == BandType::HighShelf)
1423 && static_cast<double>(effectiveQ(cfg)) > FilterDesign::kButterworthQ + 1e-4);
1424 }
1425
1427 [[nodiscard]] AnalogCascade bandPrototype(const BandConfig& cfg) const noexcept
1428 {
1429 const double f = std::clamp(static_cast<double>(cfg.frequency), 1.0, 80000.0);
1430 const double g = std::clamp(static_cast<double>(cfg.gain), -96.0, 96.0);
1431 const double q = std::max(static_cast<double>(effectiveQ(cfg)), 0.025);
1432 const double order = std::clamp(static_cast<double>(cfg.order), 1.0, static_cast<double>(kMaxBandSections));
1433 const double slope = static_cast<double>(cfg.slope);
1434 // The Q of a shelf: above 0.7071 only with setResonantShelves().
1435 const bool resonant = resonantShelves_.load(std::memory_order_relaxed);
1436 const bool above = resonant && q > FilterDesign::kButterworthQ + 1e-4;
1437 const double shelfQ = resonant ? std::clamp(q, 0.1, 20.0) : FilterDesign::kButterworthQ;
1438 AnalogCascade one;
1439 switch (cfg.type)
1440 {
1441 case BandType::Peak:
1442 if (order > 1) return FilterDesign::bell(f, q, g, order);
1443 one.add(AnalogSection::peak(f, q, g));
1444 break;
1445 case BandType::LowShelf:
1446 if (order > 1) return FilterDesign::lowShelf(f, g, std::max(order, 2.0), shelfQ); // a shelf is of two orders at least
1447 one.add(above ? AnalogSection::lowShelfQ(f, g, shelfQ) : AnalogSection::lowShelf(f, g, shelfSlopeFromQ(q, g)));
1448 break;
1450 if (order > 1) return FilterDesign::highShelf(f, g, std::max(order, 2.0), shelfQ);
1451 one.add(above ? AnalogSection::highShelfQ(f, g, shelfQ) : AnalogSection::highShelf(f, g, shelfSlopeFromQ(q, g)));
1452 break;
1453 case BandType::LowPass: return FilterDesign::highCut(f, slope, q);
1454 case BandType::HighPass: return FilterDesign::lowCut(f, slope, q);
1455 case BandType::Notch:
1456 if (order > 1) return FilterDesign::bandStop(f, q, order);
1457 one.add(AnalogSection::notch(f, q));
1458 break;
1459 case BandType::BandPass:
1460 if (order > 1) return FilterDesign::bandPass(f, q, order);
1461 one.add(AnalogSection::bandPass(f, q));
1462 break;
1463 case BandType::Tilt:
1464 // Order 1: six decibels per octave at most. From 2: twelve, with a Q.
1465 one.add(order > 1 ? AnalogSection::tiltSecondOrder(f, g, resonant ? shelfQ : std::min(std::max(q, 0.1), FilterDesign::kButterworthQ))
1466 : AnalogSection::tilt(f, g));
1467 break;
1468 case BandType::AllPass: return FilterDesign::allPass(f, q, order);
1472 }
1473 return one;
1474 }
1475
1484 [[nodiscard]] int designSections(const BandConfig& cfg, BiquadCoeffs* sections, int capacity) const noexcept
1485 {
1486 const AnalogCascade proto = bandPrototype(cfg);
1487 if (cfg.type != BandType::LowPassWall && cfg.type != BandType::HighPassWall)
1488 return FilterDesign::digital(proto, designBand_, sections, capacity);
1489 const int n = std::min(proto.count, capacity);
1490 const double corner = std::clamp(static_cast<double>(cfg.frequency), 1.0, 80000.0);
1491 for (int i = 0; i < n; ++i)
1492 sections[i] = FilterDesign::bilinear(proto.sections[static_cast<size_t>(i)], spec_.sampleRate, corner);
1493 return n;
1494 }
1495
1497 [[nodiscard]] static bool restsAtUnity(const BandConfig& cfg) noexcept
1498 {
1499 const double gain = std::abs(static_cast<double>(cfg.gain));
1500 switch (cfg.type)
1501 {
1502 case BandType::Peak:
1503 case BandType::LowShelf:
1505 case BandType::Tilt: return gain < kRestDb;
1506 case BandType::ConstantTilt: return gain < 0.1 * kRestDb;
1507 default: return false;
1508 }
1509 }
1510
1515 [[nodiscard]] int rampSamples(const BandConfig& from, const BandConfig& to) const noexcept
1516 {
1517 double distance = 1.0;
1518 if (from.type == to.type)
1519 {
1520 const double f0 = std::max(static_cast<double>(from.frequency), 1.0), f1 = std::max(static_cast<double>(to.frequency), 1.0);
1521 const double q0 = std::max(static_cast<double>(from.q), 0.025), q1 = std::max(static_cast<double>(to.q), 0.025);
1522 distance = std::max({ std::abs(static_cast<double>(to.gain) - static_cast<double>(from.gain)) / 24.0,
1523 std::abs(static_cast<double>(to.order) - static_cast<double>(from.order)) / 2.0,
1524 std::abs(std::log2(f1 / f0)) / 4.0,
1525 std::abs(std::log2(q1 / q0)) / 4.0,
1526 std::abs(static_cast<double>(to.slope) - static_cast<double>(from.slope)) / 48.0 });
1527 }
1528 const double closeness = std::max(0.0, 1.0 - distance);
1529 const double ms = kRampFastMs + (kRampSlowMs - kRampFastMs) * closeness * closeness;
1530 return std::max(1, static_cast<int>(ms * 0.001 * spec_.sampleRate));
1531 }
1532
1545 void designAnalogBand(int index, const BandConfig& cfg, bool snap) noexcept
1546 {
1547 AnalogBand& band = (*analog_)[static_cast<size_t>(index)];
1548 const bool soft = softMode_.load(std::memory_order_relaxed);
1549 const bool resonant = resonantShelves_.load(std::memory_order_relaxed);
1550 if (!snap && band.configured && band.soft == soft && band.resonant == resonant && sameDesign(band.config, cfg)) return;
1551 band.soft = soft;
1552 band.resonant = resonant;
1554 const int n = designSections(cfg, target, kMaxBandSections);
1555 const bool rest = restsAtUnity(cfg);
1556 auto& cascade = band.cascade;
1557 const bool fresh = snap || !band.configured;
1558 const int had = band.configured ? cascade.getNumSections() : 0;
1559 const int count = std::max(had, n);
1560 // Where the coefficients are now: on a design of the way, or on the last one asked for.
1561 const BandConfig origin = band.stretches > 0 ? band.heading : band.config;
1562 const int ramp = fresh ? 0 : rampSamples(origin, cfg);
1563 const int stretches = !fresh && !rest && !band.resting && !band.idle && n == had && n == band.wanted
1564 ? glideStretches(origin, cfg, ramp) : 1;
1565 band.stretches = 0;
1566 if (stretches > 1)
1567 {
1568 // A move of some length: through the designs of the parameters in
1569 // between, so the band on the way is a band and not a blend of two.
1570 band.origin = origin;
1571 band.config = cfg;
1572 band.stretches = stretches;
1573 band.stretch = 0;
1574 band.stretchLength = std::max(1, ramp / stretches);
1575 nextStretch(band);
1576 return;
1577 }
1578
1579 if (!band.configured) cascade.setNumSections(0);
1580 for (int s = had; s < count; ++s)
1581 {
1582 cascade.setSectionEnabled(s, true);
1583 cascade.setCoeffs(s, target[s].bypassed());
1584 }
1585 cascade.setNumSections(count);
1586 if (band.idle)
1587 for (int s = 0; s < count; ++s) cascade.setSectionEnabled(s, true);
1588 for (int s = 0; s < count; ++s)
1589 {
1590 if (s >= n) cascade.rampToBypass(s, ramp);
1591 else cascade.rampCoeffs(s, rest ? target[s].bypassed() : target[s], ramp);
1592 }
1593 band.config = cfg;
1594 band.heading = cfg;
1595 band.wanted = n;
1596 band.resting = rest;
1597 band.idle = false;
1598 band.configured = true;
1599 settleAnalogBand(band);
1600 }
1601
1610 [[nodiscard]] static int glideStretches(const BandConfig& from, const BandConfig& to, int ramp) noexcept
1611 {
1612 if (from.type != to.type || from.order != to.order || from.slope != to.slope) return 1;
1613 switch (to.type)
1614 {
1617 case BandType::HighPassWall: return 1; // their sections change in number along the way
1618 default: break;
1619 }
1620 const double f0 = std::max(static_cast<double>(from.frequency), 1.0), f1 = std::max(static_cast<double>(to.frequency), 1.0);
1621 const double q0 = std::max(static_cast<double>(from.q), 0.025), q1 = std::max(static_cast<double>(to.q), 0.025);
1622 const double way = std::max({ 4.0 * std::abs(std::log2(f1 / f0)),
1623 std::abs(static_cast<double>(to.gain) - static_cast<double>(from.gain)) / 12.0,
1624 std::abs(std::log2(q1 / q0)) });
1625 if (!(way > 1.0)) return 1;
1626 const int count = static_cast<int>(std::ceil(std::min(way, static_cast<double>(kMaxStretches))));
1627 return std::clamp(std::min(count, ramp / kStretchSamples), 1, kMaxStretches);
1628 }
1629
1631 [[nodiscard]] static BandConfig between(const BandConfig& from, const BandConfig& to, double share) noexcept
1632 {
1633 BandConfig point = to;
1634 const double f0 = std::max(static_cast<double>(from.frequency), 1.0), f1 = std::max(static_cast<double>(to.frequency), 1.0);
1635 const double q0 = std::max(static_cast<double>(from.q), 0.025), q1 = std::max(static_cast<double>(to.q), 0.025);
1636 point.frequency = static_cast<T>(f0 * std::pow(f1 / f0, share));
1637 point.q = static_cast<T>(q0 * std::pow(q1 / q0, share));
1638 point.gain = static_cast<T>(static_cast<double>(from.gain) + share * (static_cast<double>(to.gain) - static_cast<double>(from.gain)));
1639 return point;
1640 }
1641
1643 void nextStretch(AnalogBand& band) noexcept
1644 {
1645 ++band.stretch;
1646 bool last = band.stretch >= band.stretches;
1647 BandConfig point = last ? band.config
1648 : between(band.origin, band.config, static_cast<double>(band.stretch) / band.stretches);
1650 int n = designSections(point, target, kMaxBandSections);
1651 if (n != band.wanted && !last)
1652 {
1653 // A design of the way with other sections: straight to the end.
1654 last = true;
1655 point = band.config;
1656 n = designSections(point, target, kMaxBandSections);
1657 }
1658 auto& cascade = band.cascade;
1659 for (int s = 0; s < std::min(n, cascade.getNumSections()); ++s)
1660 cascade.rampCoeffs(s, target[s], band.stretchLength);
1661 band.heading = point;
1662 band.stretchLeft = band.stretchLength;
1663 if (last) band.stretches = 0; // the cascade lands by itself
1664 }
1665
1667 void advanceGlide(AnalogBand& band, int samples) noexcept
1668 {
1669 if (band.stretches <= 0) return;
1670 band.stretchLeft -= samples;
1671 if (band.stretchLeft <= 0) nextStretch(band);
1672 }
1673
1675 [[nodiscard]] static bool sameDesign(const BandConfig& a, const BandConfig& b) noexcept
1676 {
1677 return a.frequency == b.frequency && a.gain == b.gain && a.q == b.q && a.type == b.type
1678 && a.slope == b.slope && a.order == b.order;
1679 }
1680
1682 void settleAnalogBand(AnalogBand& band) noexcept
1683 {
1684 auto& cascade = band.cascade;
1685 if (cascade.isRamping()) return;
1686 if (cascade.getNumSections() > band.wanted) cascade.setNumSections(band.wanted);
1687 if (band.resting && !band.idle)
1688 {
1689 for (int s = 0; s < band.wanted; ++s) cascade.setSectionEnabled(s, false);
1690 band.idle = true;
1691 }
1692 }
1693
1695 void runBand(int index, AudioBufferView<T> view) noexcept
1696 {
1697 if (bandAnalog_[static_cast<size_t>(index)] && analog_)
1698 {
1699 AnalogBand& band = (*analog_)[static_cast<size_t>(index)];
1700 // A glide in stretches is cut where each one ends, whatever the block.
1701 const int total = view.getNumSamples();
1702 int done = 0;
1703 while (done < total)
1704 {
1705 const int n = band.stretches > 0 ? std::min(total - done, std::max(1, band.stretchLeft)) : total - done;
1706 if (!band.idle) band.cascade.processBlock(n == total ? view : view.getSubView(done, n));
1707 advanceGlide(band, n);
1708 done += n;
1709 }
1710 settleAnalogBand(band);
1711 return;
1712 }
1713 bands_[index].processBlock(view);
1714 }
1715
1716 void resetBand(int index) noexcept
1717 {
1718 if (bandAnalog_[static_cast<size_t>(index)] && analog_)
1719 (*analog_)[static_cast<size_t>(index)].cascade.reset();
1720 else
1721 bands_[index].reset();
1722 }
1723
1724 static constexpr double kBandFadeSeconds = 0.02;
1725
1726 [[nodiscard]] static T moveTowards(T from, T to, T delta) noexcept
1727 {
1728 return from < to ? std::min(to, from + delta) : std::max(to, from - delta);
1729 }
1730
1742 {
1743 const int activeBands = numBands_.load(std::memory_order_relaxed);
1744 const int total = buffer.getNumSamples();
1745 const int slice = bandDryStride_ > 0 ? bandDryStride_ : std::max(total, 1);
1746 const bool pair = buffer.getNumChannels() >= 2;
1747 const int firstOfThePair = static_cast<int>(Scope::Mid);
1748
1749 // Whether a band of the middle or the sides plays, or is still fading out.
1750 bool second = false;
1751 for (int i = 0; i < MaxBands; ++i)
1752 if (bandScope_[static_cast<size_t>(i)] >= firstOfThePair
1753 && ((i < activeBands && bandEnabled_[i].load(std::memory_order_relaxed))
1754 || bandMix_[static_cast<size_t>(i)] != T(0)))
1755 second = true;
1756
1757 for (int offset = 0; offset < total; offset += slice)
1758 {
1759 const int n = std::min(slice, total - offset);
1760 AudioBufferView<T> view = buffer.getSubView(offset, n);
1761 for (int i = 0; i < MaxBands; ++i)
1762 if (bandScope_[static_cast<size_t>(i)] < firstOfThePair) processBandSlice(i, view, n, activeBands);
1763 if (second)
1764 {
1765 if (pair) MidSide<T>::encode(view);
1766 for (int i = 0; i < MaxBands; ++i)
1767 if (bandScope_[static_cast<size_t>(i)] >= firstOfThePair) processBandSlice(i, view, n, activeBands);
1768 if (pair) MidSide<T>::decode(view);
1769 }
1770 bandSnap_ = false;
1771 }
1772 }
1773
1779 void processBandSlice(int i, AudioBufferView<T> view, int n, int activeBands) noexcept
1780 {
1781 const bool on = i < activeBands && bandEnabled_[i].load(std::memory_order_relaxed);
1782 const T target = on ? T(1) : T(0);
1783 T& mix = bandMix_[static_cast<size_t>(i)];
1784 if (bandSnap_ || bandDry_.empty()) mix = target;
1785
1786 T* single[1] = { nullptr };
1787 AudioBufferView<T> where = view;
1788 const int scope = bandScope_[static_cast<size_t>(i)];
1789 if (scope != static_cast<int>(Scope::Stereo))
1790 {
1791 const int channel = (scope == static_cast<int>(Scope::Left)
1792 || scope == static_cast<int>(Scope::Mid)) ? 0 : 1;
1793 if (channel >= view.getNumChannels())
1794 {
1795 mix = target; // nothing to act on: a single channel has no right and no sides
1796 return;
1797 }
1798 single[0] = view.getChannel(channel);
1799 where = AudioBufferView<T>(single, 1, n);
1800 }
1801
1802 if (mix == target)
1803 {
1804 if (on) runBand(i, where);
1805 return;
1806 }
1807
1808 if (mix == T(0)) resetBand(i); // re-entering band: clean state
1809
1810 const int nCh = std::min(where.getNumChannels(), bandDryChannels_);
1811 for (int ch = 0; ch < nCh; ++ch)
1812 std::copy_n(where.getChannel(ch), n,
1813 bandDry_.data() + static_cast<size_t>(ch) * static_cast<size_t>(bandDryStride_));
1814 runBand(i, where);
1815 const T start = mix;
1816 for (int ch = 0; ch < nCh; ++ch)
1817 {
1818 T* wet = where.getChannel(ch);
1819 const T* dry = bandDry_.data() + static_cast<size_t>(ch) * static_cast<size_t>(bandDryStride_);
1820 for (int k = 0; k < n; ++k)
1821 {
1822 const T m = moveTowards(start, target, bandFadeStep_ * static_cast<T>(k + 1));
1823 wet[k] = dry[k] + (wet[k] - dry[k]) * m;
1824 }
1825 }
1826 mix = moveTowards(start, target, bandFadeStep_ * static_cast<T>(n));
1827 }
1828
1829 // -- Prototype-phase engine ---------------------------------------------------
1830
1831 static constexpr int kPrototypeTaps = 64;
1832 static constexpr int kPrototypeDelay = kPrototypeTaps / 2;
1833 static constexpr int kPrototypeBins = 128;
1834 static constexpr int kPrototypeSlots = 5;
1835 static constexpr int kPrototypeGroups = 5;
1836 static constexpr int kPrototypeGrid = 32;
1837 static constexpr double kPrototypeFadeSeconds = 0.02;
1838 static constexpr double kPrototypeReach = 1.3815510557964274;
1839
1842 {
1844 bool soft = false;
1845 bool present = false;
1846 int group = 0;
1847 };
1848
1851 {
1852 using Curve = std::array<double, kPrototypeBins + 1>;
1853 using Taps = std::array<T, kPrototypeTaps>;
1854
1855 std::array<Curve, MaxBands> bandLog {}, bandArg {};
1856 std::array<PrototypeSeen, MaxBands> seen {};
1857 std::array<Curve, kPrototypeGroups> groupLog {}, groupArg {};
1858 std::array<bool, kPrototypeGroups> groupUsed {};
1859
1864 std::array<double, kPrototypeTaps> window {};
1865
1866 std::array<Taps, kPrototypeSlots> from {}, to {}, now {};
1867 bool crossFrom = false, crossTo = false;
1868 int fadeLength = 1, fadeLeft = 0;
1869 unsigned clock = 0;
1870
1872 std::vector<double> spectrum, time;
1873 std::vector<T> work;
1874 int channels = 0;
1875 };
1876
1878 [[nodiscard]] static bool prototypeCovers(const BandConfig& cfg) noexcept
1879 {
1880 return cfg.type != BandType::LowPassWall && cfg.type != BandType::HighPassWall;
1881 }
1882
1890 void prototypeBandCurves(int index) noexcept
1891 {
1893 const AnalogBand& band = (*analog_)[static_cast<size_t>(index)];
1894 auto& level = e.bandLog[static_cast<size_t>(index)];
1895 auto& phase = e.bandArg[static_cast<size_t>(index)];
1896 level.fill(0.0);
1897 phase.fill(0.0);
1898
1899 const AnalogCascade proto = bandPrototype(band.config);
1900 const int sections = std::min({ proto.count, band.wanted, band.cascade.getNumSections(), kMaxBandSections });
1901 for (int s = 0; s < sections; ++s)
1902 {
1903 const AnalogSection& a = proto.sections[static_cast<size_t>(s)];
1904 const BiquadCoeffs d = band.cascade.getTargetCoeffs(s);
1905 for (int k = 0; k <= kPrototypeBins; ++k)
1906 {
1907 const auto at = static_cast<size_t>(k);
1908 const double w = e.omega[at], w2 = w * w;
1909 // Analog numerator and denominator at jw.
1910 const double anr = a.b0 - a.b2 * w2, ani = a.b1 * w;
1911 const double adr = a.a0 - a.a2 * w2, adi = a.a1 * w;
1912 // Digital numerator and denominator at e^jw.
1913 const double c1 = e.cosOne[at], s1 = e.sinOne[at], c2 = e.cosTwo[at], s2 = e.sinTwo[at];
1914 const double dnr = d.b0 + d.b1 * c1 + d.b2 * c2, dni = -(d.b1 * s1 + d.b2 * s2);
1915 const double ddr = 1.0 + d.a1 * c1 + d.a2 * c2, ddi = -(d.a1 * s1 + d.a2 * s2);
1916 // Ha / Hd = (an * dd) / (ad * dn).
1917 const double nr = anr * ddr - ani * ddi, ni = anr * ddi + ani * ddr;
1918 const double dr = adr * dnr - adi * dni, di = adr * dni + adi * dnr;
1919 const double nn = nr * nr + ni * ni, dd = dr * dr + di * di;
1920 // A zero of either on the grid (the centre of a notch, DC of a
1921 // low cut) has no level to compare: nothing is corrected there.
1922 if (!(nn > 1e-300) || !(dd > 1e-300) || !std::isfinite(nn) || !std::isfinite(dd)) continue;
1923 level[at] += 0.5 * std::log(nn / dd);
1924 phase[at] += std::atan2(ni * dr - nr * di, nr * dr + ni * di);
1925 }
1926 }
1927 }
1928
1938 void refreshPrototype(bool snap) noexcept
1939 {
1941 const int activeBands = numBands_.load(std::memory_order_relaxed);
1942 bool changed = snap;
1943
1944 for (int b = 0; b < MaxBands; ++b)
1945 {
1946 const auto at = static_cast<size_t>(b);
1947 const AnalogBand& band = (*analog_)[at];
1948 PrototypeSeen want;
1949 want.present = b < activeBands && bandEnabled_[b].load(std::memory_order_relaxed)
1950 && bandAnalog_[at] && band.configured && !band.resting && prototypeCovers(band.config);
1951 if (want.present)
1952 {
1953 want.config = band.config;
1954 want.soft = band.soft;
1955 // One channel is its own left and its own middle, and has no right and no sides.
1956 const Scope where = band.config.scope;
1957 want.group = static_cast<int>(where);
1958 if (e.channels < 2)
1959 {
1960 if (where == Scope::Right || where == Scope::Side) want.present = false;
1961 want.group = 0;
1962 }
1963 }
1964
1965 PrototypeSeen& seen = e.seen[at];
1966 const bool same = want.present == seen.present
1967 && (!want.present || (want.group == seen.group && want.soft == seen.soft
1968 && sameDesign(want.config, seen.config)));
1969 if (same && !snap) continue;
1970 if (want.present) prototypeBandCurves(b);
1971 seen = want;
1972 changed = true;
1973 }
1974 if (changed) designPrototype(snap);
1975 }
1976
1978 void designPrototype(bool snap) noexcept
1979 {
1981
1982 // One curve per place: what the bands placed there add up to.
1983 for (int g = 0; g < kPrototypeGroups; ++g)
1984 {
1985 e.groupLog[static_cast<size_t>(g)].fill(0.0);
1986 e.groupArg[static_cast<size_t>(g)].fill(0.0);
1987 e.groupUsed[static_cast<size_t>(g)] = false;
1988 }
1989 for (int b = 0; b < MaxBands; ++b)
1990 {
1991 const PrototypeSeen& seen = e.seen[static_cast<size_t>(b)];
1992 if (!seen.present) continue;
1993 const auto g = static_cast<size_t>(seen.group);
1994 e.groupUsed[g] = true;
1995 for (int k = 0; k <= kPrototypeBins; ++k)
1996 {
1997 e.groupLog[g][static_cast<size_t>(k)] += e.bandLog[static_cast<size_t>(b)][static_cast<size_t>(k)];
1998 e.groupArg[g][static_cast<size_t>(k)] += e.bandArg[static_cast<size_t>(b)][static_cast<size_t>(k)];
1999 }
2000 }
2001
2002 // A fade in flight continues from where it is.
2003 if (!snap)
2004 {
2005 e.from = e.now;
2006 e.crossFrom = e.crossFrom || e.crossTo;
2007 }
2008
2009 const bool placed = e.groupUsed[1] || e.groupUsed[2] || e.groupUsed[3] || e.groupUsed[4];
2010 const auto group = [&](int g, int k) noexcept {
2011 // The correction of one place at one frequency: reduced towards
2012 // Nyquist, where no real filter can hold a phase, and bounded.
2013 const double t = e.taper[static_cast<size_t>(k)];
2014 const double level = std::clamp(e.groupLog[static_cast<size_t>(g)][static_cast<size_t>(k)], -kPrototypeReach, kPrototypeReach);
2015 return std::polar(std::exp(t * level), t * e.groupArg[static_cast<size_t>(g)][static_cast<size_t>(k)]);
2016 };
2017 const auto slot = [&](int index, bool used, bool unity, const auto& response) noexcept {
2018 auto& taps = e.to[static_cast<size_t>(index)];
2019 taps.fill(T(0));
2020 if (!used)
2021 {
2022 // No band of that place: the signal, late, to the bit (or nothing, between channels).
2023 if (unity) taps[static_cast<size_t>(kPrototypeTaps - 1 - kPrototypeDelay)] = T(1);
2024 return;
2025 }
2026 for (int k = 0; k <= kPrototypeBins; ++k)
2027 {
2028 const std::complex<double> c = response(k);
2029 e.spectrum[static_cast<size_t>(2 * k)] = c.real();
2030 e.spectrum[static_cast<size_t>(2 * k + 1)] = (k == 0 || k == kPrototypeBins) ? 0.0 : c.imag();
2031 }
2032 const double atDc = e.spectrum[0];
2033 e.fft.inverse(e.spectrum.data(), e.time.data());
2034 // Centred on the delay and cut to length; what the cut takes from
2035 // the gain at DC goes back to the centre.
2036 double h[kPrototypeTaps];
2037 double sum = 0.0;
2038 const int size = 2 * kPrototypeBins;
2039 for (int m = 0; m < kPrototypeTaps; ++m)
2040 {
2041 h[m] = e.time[static_cast<size_t>((m - kPrototypeDelay + size) % size)] * e.window[static_cast<size_t>(m)];
2042 sum += h[m];
2043 }
2044 h[kPrototypeDelay] += atDc - sum;
2045 for (int m = 0; m < kPrototypeTaps; ++m)
2046 taps[static_cast<size_t>(kPrototypeTaps - 1 - m)] = static_cast<T>(h[m]);
2047 };
2048
2049 if (!placed)
2050 {
2051 slot(0, e.groupUsed[0], true, [&](int k) noexcept { return group(0, k); });
2052 e.to[1] = e.to[0];
2053 e.to[4] = e.to[0];
2054 e.to[2].fill(T(0));
2055 e.to[3].fill(T(0));
2056 }
2057 else
2058 {
2059 // Left and right bands, then middle and sides, as one matrix (see
2060 // the linear-phase kernels): each output is its own channel
2061 // through one filter plus the other channel through another.
2062 const auto sum = [&](int k) noexcept { return 0.5 * (group(3, k) + group(4, k)); };
2063 const auto difference = [&](int k) noexcept { return 0.5 * (group(3, k) - group(4, k)); };
2064 const bool across = e.groupUsed[3] || e.groupUsed[4];
2065 slot(0, e.groupUsed[0] || e.groupUsed[1] || across, true, [&](int k) noexcept { return group(0, k) * group(1, k) * sum(k); });
2066 slot(1, e.groupUsed[0] || e.groupUsed[2] || across, true, [&](int k) noexcept { return group(0, k) * group(2, k) * sum(k); });
2067 slot(2, across, false, [&](int k) noexcept { return group(0, k) * group(2, k) * difference(k); });
2068 slot(3, across, false, [&](int k) noexcept { return group(0, k) * group(1, k) * difference(k); });
2069 slot(4, e.groupUsed[0], true, [&](int k) noexcept { return group(0, k); });
2070 }
2071 e.crossTo = placed && (e.groupUsed[3] || e.groupUsed[4]);
2072
2073 if (snap)
2074 {
2075 e.from = e.to;
2076 e.now = e.to;
2077 e.crossFrom = e.crossTo;
2078 e.fadeLeft = 0;
2079 }
2080 else
2081 {
2082 e.fadeLeft = e.fadeLength;
2083 }
2084 }
2085
2087 void clearPrototypeStream() noexcept
2088 {
2089 if (!prototype_) return;
2090 std::fill(prototype_->work.begin(), prototype_->work.end(), T(0));
2091 prototype_->clock = 0;
2092 }
2093
2100 {
2102 const int nCh = std::min(buffer.getNumChannels(), e.channels);
2103 const int total = buffer.getNumSamples();
2104 const size_t stride = static_cast<size_t>(kPrototypeTaps - 1 + kPrototypeGrid);
2105 const size_t history = static_cast<size_t>(kPrototypeTaps - 1);
2106
2107 int offset = 0;
2108 while (offset < total)
2109 {
2110 // Steps of the fade fall on a grid of the stream, not of the block.
2111 const int n = std::min(total - offset, kPrototypeGrid - static_cast<int>(e.clock % static_cast<unsigned>(kPrototypeGrid)));
2112 if (e.fadeLeft > 0 && e.clock % static_cast<unsigned>(kPrototypeGrid) == 0u)
2113 {
2114 e.fadeLeft = std::max(0, e.fadeLeft - kPrototypeGrid);
2115 const T share = static_cast<T>(1.0 - static_cast<double>(e.fadeLeft) / static_cast<double>(e.fadeLength));
2116 for (int s = 0; s < kPrototypeSlots; ++s)
2117 for (int m = 0; m < kPrototypeTaps; ++m)
2118 {
2119 const auto si = static_cast<size_t>(s), mi = static_cast<size_t>(m);
2120 e.now[si][mi] = e.fadeLeft == 0 ? e.to[si][mi]
2121 : e.from[si][mi] + (e.to[si][mi] - e.from[si][mi]) * share;
2122 }
2123 if (e.fadeLeft == 0) e.crossFrom = e.crossTo;
2124 }
2125 const bool cross = (e.crossFrom || e.crossTo) && nCh >= 2;
2126
2127 for (int ch = 0; ch < nCh; ++ch)
2128 std::copy_n(buffer.getChannel(ch) + offset, n, e.work.data() + static_cast<size_t>(ch) * stride + history);
2129
2130 for (int ch = 0; ch < nCh; ++ch)
2131 {
2132 const T* own = e.work.data() + static_cast<size_t>(ch) * stride;
2133 const T* taps = e.now[static_cast<size_t>(ch == 0 ? 0 : (ch == 1 ? 1 : 4))].data();
2134 T* out = buffer.getChannel(ch) + offset;
2135 for (int j = 0; j < n; ++j)
2136 out[j] = simd::dotProduct(own + j, taps, kPrototypeTaps);
2137 if (cross && ch < 2)
2138 {
2139 const T* other = e.work.data() + static_cast<size_t>(1 - ch) * stride;
2140 const T* across = e.now[static_cast<size_t>(ch == 0 ? 2 : 3)].data();
2141 for (int j = 0; j < n; ++j)
2142 out[j] += simd::dotProduct(other + j, across, kPrototypeTaps);
2143 }
2144 }
2145
2146 for (int ch = 0; ch < nCh; ++ch)
2147 {
2148 T* line = e.work.data() + static_cast<size_t>(ch) * stride;
2149 std::copy(line + n, line + n + history, line);
2150 }
2151 e.clock += static_cast<unsigned>(n);
2152 offset += n;
2153 }
2154 }
2155
2156 // -- Linear-phase engine ----------------------------------------------------
2157
2159
2160 static constexpr int kLpMinKernel = 256;
2161 static constexpr int kLpMaxKernel = 1 << 18;
2162 static constexpr int kLpPartitionCount = 16;
2163 static constexpr int kLpMinPartition = 64;
2164 static constexpr int kLpBinBudget = 131072;
2165 static constexpr int kLpProductBudget = 1048576;
2166 static constexpr int kLpPartitionSlices = 1;
2167 static constexpr int kLpSyncSteps = 16;
2168
2170 enum class DesignPace
2171 {
2172 Sliced,
2173 Immediate,
2174 Setup
2175 };
2176
2178 [[nodiscard]] int resolveKernelLength(double sampleRate) const noexcept
2179 {
2180 int n = kLpMinKernel;
2181 const int requested = lpKernelRequest_.load(std::memory_order_relaxed);
2182 if (requested > 0)
2183 {
2184 while (n < requested && n < kLpMaxKernel) n <<= 1;
2185 return n;
2186 }
2187 // Nearest power of two (in octaves) to 32768 * fs / 48 kHz.
2188 const double target = 32768.0 * sampleRate / 48000.0;
2189 while (n < kLpMaxKernel && static_cast<double>(n) * 1.4142135623730951 < target) n <<= 1;
2190 return n;
2191 }
2192
2195 {
2196 std::fill(lpFdl_.begin(), lpFdl_.end(), T(0));
2197 std::fill(lpInput_.begin(), lpInput_.end(), T(0));
2198 std::fill(lpOutput_.begin(), lpOutput_.end(), T(0));
2199 lpFifoPos_ = 0;
2200 lpFdlPos_ = 0;
2201 }
2202
2217 void advanceDesign(DesignPace pace) noexcept
2218 {
2219 const int kernel = lpKernelLength_;
2220 const int design = 2 * kernel;
2221 switch (lpStage_)
2222 {
2223 case LpStage::Idle:
2224 return;
2225
2226 case LpStage::Snapshot:
2227 {
2228 const int activeBands = numBands_.load(std::memory_order_relaxed);
2229 for (int b = 0; b < activeBands; ++b)
2230 {
2231 BandConfig cfg;
2232 if (pace == DesignPace::Setup)
2233 {
2234 cfg = staged_[b].read();
2235 }
2236 else if (!staged_[b].tryRead(cfg))
2237 {
2238 // Bounded read gave up: abandon this design (the active
2239 // kernel keeps playing) and re-arm, so the next hop
2240 // starts it again from a complete band set.
2241 lpDirty_.store(true, std::memory_order_release);
2243 return;
2244 }
2245 const auto at = static_cast<size_t>(b);
2246 lpBandGroup_[at] = 0;
2247 lpBandLive_[at] = false;
2248 lpBandDirty_[at] = false;
2249 if (!cfg.enabled) continue;
2250 if (lpSlots_ > 1)
2251 {
2252 lpBandGroup_[at] = static_cast<int>(cfg.scope);
2253 }
2254 else if (cfg.scope == Scope::Right || cfg.scope == Scope::Side)
2255 {
2256 continue; // a single channel has no right and no sides
2257 }
2258 // The band's design, and whether the curve kept for the band is this design's.
2259 BiquadCoeffs stages[5];
2260 AnalogCascade proto;
2261 int stageCount = 0, analogCount = 0;
2262 if (usesAnalog(cfg))
2263 {
2264 // The magnitude of the prototype itself: nothing to shrink.
2265 proto = bandPrototype(cfg);
2266 analogCount = proto.count;
2267 }
2268 else
2269 {
2270 stageCount = buildBandStages(cfg, stages);
2271 }
2272 BiquadCoeffs* keptStages = lpStages_.data() + at * 5;
2273 AnalogSection* keptProto = lpAnalog_.data() + at * static_cast<size_t>(kMaxBandSections);
2274 bool same = lpBandKept_[at] && stageCount == lpStageCount_[at] && analogCount == lpAnalogCount_[at];
2275 for (int s = 0; same && s < stageCount; ++s)
2276 {
2277 const BiquadCoeffs& p = stages[s];
2278 const BiquadCoeffs& q = keptStages[s];
2279 same = p.b0 == q.b0 && p.b1 == q.b1 && p.b2 == q.b2 && p.a1 == q.a1 && p.a2 == q.a2;
2280 }
2281 for (int s = 0; same && s < analogCount; ++s)
2282 {
2283 const AnalogSection& p = proto.sections[static_cast<size_t>(s)];
2284 const AnalogSection& q = keptProto[s];
2285 same = p.b0 == q.b0 && p.b1 == q.b1 && p.b2 == q.b2 && p.a0 == q.a0 && p.a1 == q.a1 && p.a2 == q.a2;
2286 }
2287 if (!same)
2288 {
2289 for (int s = 0; s < stageCount; ++s) keptStages[s] = stages[s];
2290 for (int s = 0; s < analogCount; ++s) keptProto[s] = proto.sections[static_cast<size_t>(s)];
2291 lpStageCount_[at] = stageCount;
2292 lpAnalogCount_[at] = analogCount;
2293 // A band with no sections has no curve to compute.
2294 lpBandKept_[at] = stageCount + analogCount == 0;
2295 lpBandDirty_[at] = !lpBandKept_[at];
2296 }
2297 lpBandLive_[at] = stageCount + analogCount > 0;
2298 }
2299 lpDesignBands_ = activeBands;
2300 lpDesignStages_ = 0;
2301 lpDesignLive_ = 0;
2302 lpDesignPlaced_ = false;
2303 for (int b = 0; b < activeBands; ++b)
2304 {
2305 const auto at = static_cast<size_t>(b);
2307 if (!lpBandLive_[at]) continue;
2308 ++lpDesignLive_;
2309 if (lpBandGroup_[at] != 0) lpDesignPlaced_ = true;
2310 }
2311 lpSlot_ = 0;
2312 lpStep_ = 0;
2314 }
2315 // The snapshot is cheap: start the magnitude in the same hop.
2316 [[fallthrough]];
2317
2318 case LpStage::Magnitude:
2319 {
2320 // The curves of the bands whose design changed; the others keep theirs.
2321 const int bins = kernel + 1;
2322 const int first = lpStep_;
2323 int last = bins;
2324 if (lpDesignStages_ > 0)
2325 {
2326 const int perSlice = pace == DesignPace::Sliced
2327 ? std::max(256, kLpBinBudget / lpDesignStages_ + 1)
2328 : bins;
2329 last = std::min(bins, first + perSlice);
2330 // Bin k sits at w = pi * k / kernel. The unit phasor is rotated
2331 // bin to bin in double (error grows ~1e-16 per step), seeded
2332 // exactly at the slice start.
2333 const double dw = pi<double> / static_cast<double>(kernel);
2334 const double rc = std::cos(dw), rs = std::sin(dw);
2335 double c1 = std::cos(dw * static_cast<double>(first));
2336 double s1 = std::sin(dw * static_cast<double>(first));
2337 for (int k = first; k < last; ++k)
2338 {
2339 const double c2 = 2.0 * c1 * c1 - 1.0;
2340 const double s2 = 2.0 * s1 * c1;
2341 const double omega = dw * static_cast<double>(k) * spec_.sampleRate;
2342 for (int b = 0; b < lpDesignBands_; ++b)
2343 {
2344 const auto at = static_cast<size_t>(b);
2345 if (!lpBandDirty_[at]) continue;
2346 double power = 1.0;
2347 const BiquadCoeffs* st = lpStages_.data() + at * 5;
2348 for (int s = 0; s < lpStageCount_[at]; ++s)
2349 {
2350 const BiquadCoeffs& c = st[s];
2351 const double nRe = c.b0 + c.b1 * c1 + c.b2 * c2;
2352 const double nIm = -(c.b1 * s1 + c.b2 * s2);
2353 const double dRe = 1.0 + c.a1 * c1 + c.a2 * c2;
2354 const double dIm = -(c.a1 * s1 + c.a2 * s2);
2355 const double den = dRe * dRe + dIm * dIm;
2356 power *= (den > 1e-300) ? (nRe * nRe + nIm * nIm) / den : 0.0;
2357 }
2358 const AnalogSection* sections = lpAnalog_.data() + at * static_cast<size_t>(kMaxBandSections);
2359 for (int s = 0; s < lpAnalogCount_[at]; ++s)
2360 power *= sections[s].magnitudeSquared(omega);
2361 // Under -300 dB a band is silent there.
2362 lpBandPower_[at * static_cast<size_t>(bins) + static_cast<size_t>(k)] =
2363 power > 1e-30 ? static_cast<float>(std::min(power, 1e30)) : 0.0f;
2364 }
2365 const double cn = c1 * rc - s1 * rs;
2366 s1 = s1 * rc + c1 * rs;
2367 c1 = cn;
2368 }
2369 if (last < bins)
2370 {
2371 lpStep_ = last;
2372 return;
2373 }
2374 // Whole: from here each curve stands for its band's design.
2375 for (int b = 0; b < lpDesignBands_; ++b)
2376 {
2377 const auto at = static_cast<size_t>(b);
2378 if (!lpBandDirty_[at]) continue;
2379 lpBandDirty_[at] = false;
2380 lpBandKept_[at] = true;
2381 }
2382 }
2383 lpStep_ = 0;
2385 // The product is cheap: in the same hop when the two fit in its budget.
2386 if (pace == DesignPace::Sliced
2387 && static_cast<double>(last - first) * lpDesignStages_ / kLpBinBudget
2388 + static_cast<double>(bins) * lpDesignLive_ / kLpProductBudget > 1.0)
2389 return;
2390 }
2391 [[fallthrough]];
2392
2393 case LpStage::Combine:
2394 {
2395 // The response: the product of the curves of the bands that act.
2396 const int bins = kernel + 1;
2397 const int perSlice = pace == DesignPace::Sliced
2398 ? std::max(256, kLpProductBudget / std::max(1, lpDesignLive_) + 1)
2399 : bins;
2400 const int first = lpStep_;
2401 const int last = std::min(bins, first + perSlice);
2402 for (int k = first; k < last; ++k)
2403 {
2404 // One product per place of the pair (all in the first when no band is placed).
2405 double powers[5] = { 1.0, 1.0, 1.0, 1.0, 1.0 };
2406 for (int b = 0; b < lpDesignBands_; ++b)
2407 {
2408 const auto at = static_cast<size_t>(b);
2409 if (!lpBandLive_[at]) continue;
2410 powers[lpDesignPlaced_ ? lpBandGroup_[at] : 0] *=
2411 static_cast<double>(lpBandPower_[at * static_cast<size_t>(bins) + static_cast<size_t>(k)]);
2412 }
2413 if (!lpDesignPlaced_)
2414 {
2415 lpMag_[static_cast<size_t>(k)] = static_cast<T>(std::sqrt(powers[0]));
2416 }
2417 else
2418 {
2419 // Left and right bands, then middle and sides, then back, as one matrix:
2420 // each output is its own channel times one response plus the other times another.
2421 const double both = std::sqrt(powers[0]), left = std::sqrt(powers[1]), right = std::sqrt(powers[2]);
2422 const double sum = 0.5 * (std::sqrt(powers[3]) + std::sqrt(powers[4]));
2423 const double difference = 0.5 * (std::sqrt(powers[3]) - std::sqrt(powers[4]));
2424 const size_t stride = static_cast<size_t>(kernel + 1), at = static_cast<size_t>(k);
2425 lpMag_[at] = static_cast<T>(both * left * sum); // left to left
2426 lpMag_[stride + at] = static_cast<T>(both * right * sum); // right to right
2427 lpMag_[2 * stride + at] = static_cast<T>(both * right * difference); // right to left
2428 lpMag_[3 * stride + at] = static_cast<T>(both * left * difference); // left to right
2429 if (lpSlots_ > 4) lpMag_[4 * stride + at] = static_cast<T>(both); // further channels
2430 }
2431 }
2432 if (last >= bins) lpStage_ = LpStage::Transform;
2433 else lpStep_ = last;
2434 return;
2435 }
2436
2437 case LpStage::Transform:
2438 {
2439 // Zero-phase spectrum -> impulse centred on t = 0 (circular).
2440 std::fill(lpDesignSpec_.begin(), lpDesignSpec_.end(), T(0));
2441 const T* response = lpMag_.data() + static_cast<size_t>(lpSlot_) * static_cast<size_t>(kernel + 1);
2442 for (int k = 0; k <= kernel; ++k)
2443 lpDesignSpec_[static_cast<size_t>(2 * k)] = response[static_cast<size_t>(k)];
2444 lpDesignFft_->inverse(lpDesignSpec_.data(), lpDesignTime_.data());
2445
2446 // Centre at kernel/2 and window. Tap 0 pairs with the absent
2447 // tap `kernel` and is zeroed, so the FIR is symmetric.
2448 lpKernelTime_[0] = T(0);
2449 for (int i = 1; i < kernel; ++i)
2450 {
2451 const int src = (i - kernel / 2 + design) % design;
2452 lpKernelTime_[static_cast<size_t>(i)] =
2453 lpDesignTime_[static_cast<size_t>(src)] * lpWindow_[static_cast<size_t>(i)];
2454 }
2455 lpStep_ = 0;
2457 return;
2458 }
2459
2460 case LpStage::Partition:
2461 {
2462 const int part = lpPartition_;
2463 const size_t specLen = static_cast<size_t>(2 * part + 2);
2464 auto& set = lpKernelSet_[static_cast<size_t>(1 - lpActive_)];
2465 const int perSlice = pace == DesignPace::Sliced
2467 : lpPartitions_;
2468 const int first = lpStep_ * perSlice;
2469 const int last = std::min(lpPartitions_, first + perSlice);
2470 for (int p = first; p < last; ++p)
2471 {
2472 std::copy_n(lpKernelTime_.data() + static_cast<size_t>(p) * static_cast<size_t>(part),
2473 part, lpBlockTime_.data());
2474 std::fill(lpBlockTime_.begin() + part, lpBlockTime_.end(), T(0));
2475 lpFft_->forward(lpBlockTime_.data(),
2476 set.data() + static_cast<size_t>(lpSlot_ * lpPartitions_ + p) * specLen);
2477 }
2478 if (last >= lpPartitions_ && lpDesignPlaced_ && lpSlot_ + 1 < lpSlots_)
2479 {
2480 // The next kernel of the matrix.
2481 ++lpSlot_;
2483 }
2484 else if (last >= lpPartitions_)
2485 {
2486 lpPlaced_[static_cast<size_t>(1 - lpActive_)] = lpDesignPlaced_;
2487 lpSwapPending_ = true;
2489 lpRestartPending_ = false;
2490 }
2491 else
2492 {
2493 ++lpStep_;
2494 }
2495 return;
2496 }
2497 }
2498 }
2499
2508 {
2509 const int part = lpPartition_;
2510 const int held = part + lpFifoPos_;
2511 const int channels = std::min(lpChannels_, static_cast<int>(lpWarmChannels_.size()));
2512 if (!lpFft_ || part <= 0 || channels <= 0
2513 || lpWarm_.size() < static_cast<size_t>(channels) * static_cast<size_t>(2 * part)) return;
2514 for (int i = 0; i < MaxBands; ++i) resetBand(i);
2515 for (int ch = 0; ch < channels; ++ch)
2516 std::copy_n(lpInput_.data() + static_cast<size_t>(ch) * static_cast<size_t>(2 * part), held,
2517 lpWarm_.data() + static_cast<size_t>(ch) * static_cast<size_t>(2 * part));
2518 const int step = std::max(1, spec_.maxBlockSize);
2519 for (int at = 0; at < held; at += step)
2520 {
2521 const int n = std::min(step, held - at);
2522 for (int ch = 0; ch < channels; ++ch)
2523 lpWarmChannels_[static_cast<size_t>(ch)] =
2524 lpWarm_.data() + static_cast<size_t>(ch) * static_cast<size_t>(2 * part) + static_cast<size_t>(at);
2526 }
2527 }
2528
2531 void finishDesignNow() noexcept
2532 {
2533 if (lpDirty_.exchange(false, std::memory_order_acquire))
2534 {
2536 lpRestartPending_ = false;
2537 }
2538 for (int guard = 0; lpStage_ != LpStage::Idle && guard < kLpSyncSteps; ++guard)
2540 if (lpSwapPending_)
2541 {
2542 lpActive_ = 1 - lpActive_;
2543 lpSwapPending_ = false;
2544 }
2545 }
2546
2551 void runLinearPhaseHop() noexcept
2552 {
2553 if (lpDirty_.load(std::memory_order_relaxed)
2554 && lpDirty_.exchange(false, std::memory_order_acquire))
2555 {
2557 else lpRestartPending_ = true;
2558 }
2559
2560 bool crossfade = false;
2561 if (lpSwapPending_)
2562 {
2563 crossfade = true;
2564 lpSwapPending_ = false;
2565 }
2566 else if (lpStage_ != LpStage::Idle)
2567 {
2569 }
2570
2571 const int part = lpPartition_;
2572 const int parts = lpPartitions_;
2573 const size_t specLen = static_cast<size_t>(2 * part + 2);
2574 const int bins = part + 1;
2575 const int newSet = crossfade ? 1 - lpActive_ : lpActive_;
2576 const T invPart = T(1) / static_cast<T>(part);
2577
2578 // Every channel's block into its delay line first: a matrix of
2579 // kernels reads the other channel's too.
2580 const size_t lineLen = static_cast<size_t>(parts) * specLen;
2581 for (int ch = 0; ch < lpChannels_; ++ch)
2582 lpFft_->forward(lpInput_.data() + static_cast<size_t>(ch) * static_cast<size_t>(2 * part),
2583 lpFdl_.data() + static_cast<size_t>(ch) * lineLen + static_cast<size_t>(lpFdlPos_) * specLen);
2584
2585 for (int ch = 0; ch < lpChannels_; ++ch)
2586 {
2587 T* input = lpInput_.data() + static_cast<size_t>(ch) * static_cast<size_t>(2 * part);
2588 T* output = lpOutput_.data() + static_cast<size_t>(ch) * static_cast<size_t>(part);
2589
2590 auto convolve = [&](int setIndex, T* time) noexcept {
2591 std::fill(lpAccum_.begin(), lpAccum_.end(), T(0));
2592 const bool placed = lpPlaced_[static_cast<size_t>(setIndex)];
2593 const T* kernels = lpKernelSet_[static_cast<size_t>(setIndex)].data();
2594 const auto add = [&](int slot, int from) noexcept {
2595 const T* kernel = kernels + static_cast<size_t>(slot) * lineLen;
2596 const T* line = lpFdl_.data() + static_cast<size_t>(from) * lineLen;
2597 for (int p = 0; p < parts; ++p)
2598 {
2599 const int at = (lpFdlPos_ - p + parts) % parts;
2600 simd::complexMulAccum(lpAccum_.data(), line + static_cast<size_t>(at) * specLen,
2601 kernel + static_cast<size_t>(p) * specLen, bins);
2602 }
2603 };
2604 // Its own channel through its own kernel; with placed bands, the
2605 // other channel of the pair through the kernel that crosses.
2606 add(!placed ? 0 : (ch == 0 ? 0 : (ch == 1 ? 1 : 4)), ch);
2607 if (placed && ch < 2) add(ch == 0 ? 2 : 3, 1 - ch);
2608 lpFft_->inverse(lpAccum_.data(), time);
2609 };
2610
2611 convolve(newSet, lpBlockTime_.data());
2612 if (crossfade)
2613 {
2614 convolve(lpActive_, lpBlockTimeOld_.data());
2615 for (int i = 0; i < part; ++i)
2616 {
2617 const T oldY = lpBlockTimeOld_[static_cast<size_t>(part + i)];
2618 const T newY = lpBlockTime_[static_cast<size_t>(part + i)];
2619 output[i] = oldY + (newY - oldY) * (static_cast<T>(i + 1) * invPart);
2620 }
2621 }
2622 else
2623 {
2624 std::copy_n(lpBlockTime_.data() + part, part, output);
2625 }
2626
2627 // The current half becomes the next hop's history.
2628 std::copy_n(input + part, part, input);
2629 }
2630
2631 lpFdlPos_ = (lpFdlPos_ + 1) % parts;
2632 if (crossfade) lpActive_ = 1 - lpActive_;
2633 }
2634
2642 {
2643 if (lpSnap_)
2644 {
2646 lpSnap_ = false;
2647 }
2648
2649 const int nCh = std::min(buffer.getNumChannels(), lpChannels_);
2650 const int total = buffer.getNumSamples();
2651 const int part = lpPartition_;
2652 int done = 0;
2653 while (done < total)
2654 {
2655 const int seg = std::min(total - done, part - lpFifoPos_);
2656 for (int ch = 0; ch < lpChannels_; ++ch)
2657 {
2658 T* in = lpInput_.data() + static_cast<size_t>(ch) * static_cast<size_t>(2 * part)
2659 + static_cast<size_t>(part + lpFifoPos_);
2660 const T* out = lpOutput_.data() + static_cast<size_t>(ch) * static_cast<size_t>(part)
2661 + static_cast<size_t>(lpFifoPos_);
2662 if (ch < nCh)
2663 {
2664 T* data = buffer.getChannel(ch) + done;
2665 std::copy_n(data, seg, in); // read the input before
2666 std::copy_n(out, seg, data); // overwriting it in place
2667 }
2668 else
2669 {
2670 std::fill_n(in, seg, T(0));
2671 }
2672 }
2673 lpFifoPos_ += seg;
2674 done += seg;
2675 if (lpFifoPos_ == part)
2676 {
2678 lpFifoPos_ = 0;
2679 }
2680 }
2681 }
2682
2684 std::atomic<int> numBands_ { 0 };
2685
2686 std::array<FilterEngine<T>, MaxBands> bands_ {};
2687 std::atomic<Structure> structure_ { Structure::DirectForm };
2688
2700 {
2701 // Initialised FROM BandConfig's own defaults, never from a second copy
2702 // of the literals: a staged band that starts life disagreeing with the
2703 // BandConfig a caller reads back is a bug no test would obviously
2704 // catch, and two hand-written default sets drift one field at a time.
2705 std::atomic<T> frequency { BandConfig{}.frequency };
2706 std::atomic<T> gain { BandConfig{}.gain };
2707 std::atomic<T> q { BandConfig{}.q };
2708 std::atomic<int> type { static_cast<int>(BandConfig{}.type) };
2709 std::atomic<T> slope { BandConfig{}.slope };
2710 std::atomic<T> order { BandConfig{}.order };
2711 std::atomic<bool> enabled { BandConfig{}.enabled };
2712 std::atomic<int> scope { static_cast<int>(BandConfig{}.scope) };
2713 std::atomic<unsigned> seq { 0 };
2714
2727 void publish(const BandConfig& c) noexcept
2728 {
2729 seq.fetch_add(1, std::memory_order_acq_rel); // -> odd
2730 std::atomic_thread_fence(std::memory_order_release);
2731 frequency.store(c.frequency, std::memory_order_relaxed);
2732 gain.store(c.gain, std::memory_order_relaxed);
2733 q.store(c.q, std::memory_order_relaxed);
2734 type.store(static_cast<int>(c.type), std::memory_order_relaxed);
2735 slope.store(c.slope, std::memory_order_relaxed);
2736 order.store(c.order, std::memory_order_relaxed);
2737 enabled.store(c.enabled, std::memory_order_relaxed);
2738 scope.store(static_cast<int>(c.scope), std::memory_order_relaxed);
2739 seq.fetch_add(1, std::memory_order_release); // -> even
2740 }
2741
2747 static constexpr int kSeqlockMaxAttempts = 3;
2748
2755 void loadWordsRelaxed(BandConfig& c) const noexcept
2756 {
2757 c.frequency = frequency.load(std::memory_order_relaxed);
2758 c.gain = gain.load(std::memory_order_relaxed);
2759 c.q = q.load(std::memory_order_relaxed);
2760 c.type = static_cast<BandType>(type.load(std::memory_order_relaxed));
2761 c.slope = slope.load(std::memory_order_relaxed);
2762 c.order = order.load(std::memory_order_relaxed);
2763 c.enabled = enabled.load(std::memory_order_relaxed);
2764 c.scope = static_cast<Scope>(scope.load(std::memory_order_relaxed));
2765 }
2766
2787 [[nodiscard]] bool tryRead(BandConfig& out) const noexcept
2788 {
2789 for (int attempt = 0; attempt < kSeqlockMaxAttempts; ++attempt)
2790 {
2791 const unsigned s0 = seq.load(std::memory_order_acquire);
2792 if ((s0 & 1u) != 0u) continue; // writer mid-publish: do not copy
2793 BandConfig c;
2795 std::atomic_thread_fence(std::memory_order_acquire);
2796 if (s0 == seq.load(std::memory_order_relaxed))
2797 {
2798 out = c; // commit only on validation
2799 return true;
2800 }
2801 }
2802 return false;
2803 }
2804
2821 [[nodiscard]] BandConfig read() const noexcept
2822 {
2823 BandConfig c;
2824 unsigned s0, s1;
2825 do {
2826 s0 = seq.load(std::memory_order_acquire);
2828 std::atomic_thread_fence(std::memory_order_acquire);
2829 s1 = seq.load(std::memory_order_relaxed);
2830 } while ((s0 & 1u) != 0u || s0 != s1);
2831 return c;
2832 }
2833 };
2834
2836 std::array<StagedBand, MaxBands> staged_ {};
2837
2842 std::array<BandConfig, MaxBands> masterConfigs_ {};
2843
2844 // Per-band enable flag read lock-free every block. The full BandConfig is only
2845 // read under the configDirty_ acquire gate; `enabled` is toggled often and read
2846 // on the hot path, so it gets its own atomic to avoid a torn/unsynchronized read.
2847 std::array<std::atomic<bool>, MaxBands> bandEnabled_ {};
2848
2849 // Loudness compensation (setLoudnessCompensation()).
2850 std::atomic<bool> loudnessComp_ { false };
2851 std::atomic<T> compensationDb_ { T(0) };
2853 double compTarget_ = 1.0, compNow_ = 1.0, compStep_ = 0.0;
2854 int compRamp_ = 2400, compLeft_ = 0;
2855 std::atomic<bool> softMode_ { false };
2856 std::atomic<bool> configDirty_ { false };
2857 std::atomic<bool> matchedBells_ { true };
2858 std::atomic<bool> matchedFilters_ { false };
2859 std::atomic<bool> analogResponse_ { false };
2860 std::atomic<bool> resonantShelves_ { false };
2861
2862 // The engine of the analog response (allocated by prepare(), run by the audio thread).
2863 std::unique_ptr<std::array<AnalogBand, MaxBands>> analog_;
2864 std::unique_ptr<PrototypeEngine> prototype_;
2865 bool prototypeWasActive_ = false;
2867 std::array<bool, MaxBands> bandAnalog_ {};
2868 std::array<int, MaxBands> bandScope_ {};
2869
2870 // Linear-phase state
2871 std::atomic<FilterMode> filterMode_ { FilterMode::MinimumPhase };
2872 std::atomic<bool> lpDirty_ { true };
2873 std::atomic<int> lpKernelRequest_ { 0 };
2874
2875 // MinimumPhase band crossfades (audio thread).
2876 std::array<T, MaxBands> bandMix_ {};
2877 std::vector<T> bandDry_;
2881 bool bandSnap_ = true;
2882
2883 // Engine geometry (written by prepare(), read by the audio thread).
2884 std::unique_ptr<FFTReal<T>> lpFft_;
2885 std::unique_ptr<FFTReal<T>> lpDesignFft_;
2890
2891 // Streaming state (audio thread).
2892 std::array<std::vector<T>, 2> lpKernelSet_;
2893 int lpActive_ = 0;
2894 std::vector<T> lpFdl_;
2895 std::vector<T> lpInput_, lpOutput_;
2897 std::vector<T> lpWarm_;
2898 std::vector<T*> lpWarmChannels_;
2899 int lpFifoPos_ = 0;
2900 int lpFdlPos_ = 0;
2901 bool lpSnap_ = true;
2902 bool lpWasActive_ = false;
2903
2904 // Design state (audio thread, sliced).
2906 int lpStep_ = 0;
2907 bool lpRestartPending_ = false;
2908 bool lpSwapPending_ = false;
2912 std::vector<float> lpBandPower_;
2913 std::array<bool, MaxBands> lpBandKept_ {};
2914 std::array<bool, MaxBands> lpBandDirty_ {};
2915 std::array<bool, MaxBands> lpBandLive_ {};
2916 std::array<BiquadCoeffs, MaxBands * 5> lpStages_ {};
2917 std::array<int, MaxBands> lpStageCount_ {};
2918 std::array<AnalogSection, MaxBands * AnalogCascade::kMaxSections> lpAnalog_ {};
2919 std::array<int, MaxBands> lpAnalogCount_ {};
2920 std::array<int, MaxBands> lpBandGroup_ {};
2921 int lpSlots_ = 1;
2922 int lpSlot_ = 0;
2923 bool lpDesignPlaced_ = false;
2924 std::array<bool, 2> lpPlaced_ {};
2925 std::vector<T> lpWindow_, lpMag_;
2927};
2928
2929} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
AudioBufferView getSubView(int startSample, int length) const noexcept
Returns a zero-copy sub-view starting at an offset.
Up to MaxSections second-order sections in series, run in one pass.
void advanceRamps(int samples) noexcept
Moves every ramp on by a number of samples (for processSample() callers).
int getNumSections() const noexcept
Number of sections in the cascade.
void processBlock(AudioBufferView< T > buffer) noexcept
Runs a block through the cascade, in place.
BiquadCoeffs getCoeffs(int section) const noexcept
The coefficients a section is using now (mid ramp, where the ramp is).
double processSample(double input, int channel) noexcept
One sample of one channel through the cascade, in double.
BiquadCoeffs getTargetCoeffs(int section) const noexcept
The coefficients a section is heading to (its own when it is not ramping).
bool isSectionEnabled(int section) const noexcept
Whether a section is computed.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Parametric multi-band EQ using cascaded biquads or FFT overlap-save convolution.
Definition Equalizer.h:145
std::vector< T > lpBlockTime_
Definition Equalizer.h:2896
static constexpr int kPrototypeGrid
Samples between two steps of a fade of the correction.
Definition Equalizer.h:1836
typename FilterEngine< T >::Structure Structure
How the sections of the bands are realised (FilterEngine::Structure).
Definition Equalizer.h:679
bool setState(const uint8_t *data, size_t size)
Restores bands and modes from a blob (tolerant; rejects foreign ids).
Definition Equalizer.h:1054
BandType
Filter type for each EQ band.
Definition Equalizer.h:160
@ LowShelf
Shelf: boosts/cuts below frequency.
@ BandPass
Bandpass around frequency.
@ AllPass
Turns the phase around frequency, 180 degrees per order; the level stays.
@ Tilt
Tilt EQ: pivots spectrum around frequency.
@ LowPass
Removes frequencies above cutoff.
@ HighPassWall
Elliptic cut below frequency.
@ Peak
Parametric bell (boost/cut around frequency).
@ Notch
Narrow rejection at frequency.
@ HighShelf
Shelf: boosts/cuts above frequency.
@ HighPass
Removes frequencies below cutoff.
@ LowPassWall
Elliptic cut above frequency: flat to it, 100 dB down a quarter of an octave later.
void conditionBandsAfterLinearPhase() noexcept
Leaving LinearPhase: clears the bands and runs them over the input the engine still holds (the last w...
Definition Equalizer.h:2507
void processLinearPhase(AudioBufferView< T > buffer) noexcept
LinearPhase processing: any block length streams through a partition-sized FIFO, so the output is ide...
Definition Equalizer.h:2641
void setBand(int index, const BandConfig &config)
Configures a band with full control over all parameters. Thread-safe.
Definition Equalizer.h:566
void setAnalogResponse(bool enabled) noexcept
Designs every band from its analog prototype (see the file notes).
Definition Equalizer.h:737
std::array< AnalogSection, MaxBands *AnalogCascade::kMaxSections > lpAnalog_
Prototypes of the analog bands.
Definition Equalizer.h:2918
bool getSoftMode() const noexcept
Returns whether soft mode is enabled.
Definition Equalizer.h:921
static constexpr int kLpMinPartition
Definition Equalizer.h:2163
static constexpr int kLpPartitionSlices
Hops spent on partition FFTs.
Definition Equalizer.h:2166
std::atomic< bool > configDirty_
Definition Equalizer.h:2856
DesignPace
How much of a design one advanceDesign() call may do.
Definition Equalizer.h:2171
@ Immediate
Audio thread, whole stages at once (bounded seqlock reads).
@ Setup
Setup thread, whole stages, unbounded seqlock reads.
@ Sliced
Audio thread, one bounded slice per partition hop.
static constexpr double kTiltCeilingDb
Most a constant tilt lifts its rising end (20 Hz or 20 kHz).
Definition Equalizer.h:1387
FilterDesign::Band designBand_
Definition Equalizer.h:2866
std::array< bool, MaxBands > bandAnalog_
Which engine runs each band.
Definition Equalizer.h:2867
void refreshPrototype(bool snap) noexcept
Brings the correction up to date with the bands as they are now, and starts its fade if anything chan...
Definition Equalizer.h:1938
std::atomic< bool > loudnessComp_
Definition Equalizer.h:2850
void settleAnalogBand(AnalogBand &band) noexcept
Once a glide has landed: dropped sections leave, and a resting band stops computing.
Definition Equalizer.h:1682
int lpDesignLive_
Bands that act in this design.
Definition Equalizer.h:2911
bool isMatchedBells() const noexcept
Returns whether Peak bands use the matched design (setMatchedBells()).
Definition Equalizer.h:673
std::vector< float > lpBandPower_
Per band: its squared magnitude on the design grid.
Definition Equalizer.h:2912
static constexpr int kMaxBandSections
Most sections a band has.
Definition Equalizer.h:1380
T processSample(T input, int channel) noexcept
Processes a single sample through all enabled bands (IIR mode only).
Definition Equalizer.h:454
int getLinearPhaseKernelLength() const noexcept
The prepared linear-phase kernel length in taps (0 before prepare()). Read it from the setup thread o...
Definition Equalizer.h:908
std::vector< uint8_t > getState() const
Serializes bands and modes (setup/UI threads; allocates).
Definition Equalizer.h:1012
void setBand(int index, T frequency, T gainDb)
Configures a band with frequency and gain (Peak filter).
Definition Equalizer.h:531
std::atomic< bool > lpDirty_
Definition Equalizer.h:2872
bool prototypeWasActive_
The last block ran in that mode.
Definition Equalizer.h:2865
void advanceGlide(AnalogBand &band, int samples) noexcept
Counts the samples a gliding band has played and starts its next stretch when one ends.
Definition Equalizer.h:1667
void reset() noexcept
Resets all filter states to zero to prevent ringing on playback start.
Definition Equalizer.h:508
std::vector< T > lpInput_
Definition Equalizer.h:2895
static constexpr int kStretchSamples
Shortest stretch between two of them.
Definition Equalizer.h:1385
std::vector< T > lpWarm_
The held input the bands are run over on leaving the mode.
Definition Equalizer.h:2897
bool isResonantShelves() const noexcept
Returns whether the Q of a shelf can go above 0.7071 (setResonantShelves()).
Definition Equalizer.h:761
std::atomic< bool > matchedBells_
Matched (de-cramped) bells by default.
Definition Equalizer.h:2857
std::vector< T > lpBlockTimeOld_
Definition Equalizer.h:2896
static BandConfig between(const BandConfig &from, const BandConfig &to, double share) noexcept
The configuration a share of the way between two: frequency and Q in octaves, gain in decibels.
Definition Equalizer.h:1631
void setLinearPhaseKernelLength(int taps) noexcept
Requests the linear-phase kernel length in taps.
Definition Equalizer.h:900
static constexpr int kPrototypeDelay
Its centre: the latency of the mode.
Definition Equalizer.h:1832
std::vector< T > lpFdl_
Per channel: partitions x spectrum.
Definition Equalizer.h:2894
T effectiveQ(const BandConfig &cfg) const noexcept
The band Q the audio path actually uses (soft mode caps it by gain).
Definition Equalizer.h:1105
void runBand(int index, AudioBufferView< T > view) noexcept
One block through a band, in the engine that runs it.
Definition Equalizer.h:1695
static constexpr int kLpPartitionCount
Partitions per kernel.
Definition Equalizer.h:2162
std::array< StagedBand, MaxBands > staged_
Published band configurations. The ONLY band storage both threads reach.
Definition Equalizer.h:2836
void designAnalogBand(int index, const BandConfig &cfg, bool snap) noexcept
Designs a band of the analog response and starts its cascade towards the design (audio thread,...
Definition Equalizer.h:1545
T getAnalogBandResponse(int index, T hz) const noexcept
The response of a band of the analog response as its sections are at this moment, a glide in flight i...
Definition Equalizer.h:870
std::vector< T > lpDesignSpec_
Definition Equalizer.h:2926
static T moveTowards(T from, T to, T delta) noexcept
Definition Equalizer.h:1726
bool isAnalogResponse() const noexcept
Returns whether bands are designed from their analog prototypes (setAnalogResponse()).
Definition Equalizer.h:767
void prepare(const AudioSpec &spec)
Prepares all bands and allocates necessary resources for processing.
Definition Equalizer.h:219
std::array< bool, 2 > lpPlaced_
Whether each kernel set is one.
Definition Equalizer.h:2924
static constexpr int kLpProductBudget
Products of kept curves per hop (< 1 ms).
Definition Equalizer.h:2165
int buildBandStages(const BandConfig &cfg, BiquadCoeffs *stages) const noexcept
Fills stages with the ACTUAL biquad cascade for a band (per-stage Butterworth Q for multi-stage LP/HP...
Definition Equalizer.h:1319
int buildBandSections(const BandConfig &cfg, BiquadCoeffs *sections, int capacity) const noexcept
Fills sections with the biquads a band runs, whichever engine runs it, and returns how many (up to 16...
Definition Equalizer.h:1370
std::vector< T > bandDry_
Definition Equalizer.h:2877
std::array< int, MaxBands > lpAnalogCount_
Definition Equalizer.h:2919
static constexpr int kLpBinBudget
Stage evaluations per hop (< 1 ms).
Definition Equalizer.h:2164
std::vector< T > lpOutput_
Per channel FIFOs.
Definition Equalizer.h:2895
static constexpr int kLpMaxKernel
Definition Equalizer.h:2161
std::array< bool, MaxBands > lpBandDirty_
This design computes the band's curve.
Definition Equalizer.h:2914
std::vector< T > lpAccum_
Definition Equalizer.h:2896
std::array< BiquadCoeffs, MaxBands *5 > lpStages_
Definition Equalizer.h:2916
FilterMode getFilterMode() const noexcept
Returns the current filter mode.
Definition Equalizer.h:836
std::array< bool, MaxBands > lpBandKept_
The band's curve is that of its stored design.
Definition Equalizer.h:2913
bool lpDesignPlaced_
The design in flight is a matrix.
Definition Equalizer.h:2923
std::array< BandConfig, MaxBands > masterConfigs_
Definition Equalizer.h:2842
std::atomic< Structure > structure_
setStructure().
Definition Equalizer.h:2687
std::atomic< int > numBands_
Definition Equalizer.h:2684
AnalogCascade bandPrototype(const BandConfig &cfg) const noexcept
The analog prototype of a band.
Definition Equalizer.h:1427
void setResonantShelves(bool enabled) noexcept
Lets the Q of a shelf go above 0.7071 (off by default, where a Q above it is read as 0....
Definition Equalizer.h:754
std::array< bool, MaxBands > lpBandLive_
The band acts in this design.
Definition Equalizer.h:2915
int getNumBands() const noexcept
Returns the number of active bands.
Definition Equalizer.h:630
static constexpr double kRampSlowMs
Glide of a small move of a band of the analog response.
Definition Equalizer.h:1382
void getMagnitudeForFrequencyArray(const T *frequencies, T *magnitudes, int numPoints, Scope where) const noexcept
The magnitude response at one place of the stereo pair: the stereo bands and the bands placed there.
Definition Equalizer.h:952
void clearLinearPhaseStream() noexcept
Clears the engine's audio history (not the kernels).
Definition Equalizer.h:2194
int lpDesignStages_
Sections of the bands whose curve this design computes.
Definition Equalizer.h:2910
FilterEngine< T > & getBandFilter(int index) noexcept
Direct access to a band's underlying FilterEngine.
Definition Equalizer.h:997
std::vector< T > lpMag_
Definition Equalizer.h:2925
static bool sameDesign(const BandConfig &a, const BandConfig &b) noexcept
Whether two configurations give the same sections (the enabled flag is not part of the design).
Definition Equalizer.h:1675
void setMatchedBells(bool enabled) noexcept
Switches Peak bands to the analog-matched (de-cramped) design.
Definition Equalizer.h:666
static constexpr int kPrototypeGroups
One per Scope.
Definition Equalizer.h:1835
bool isMatchedFilters() const noexcept
Returns whether non-bell bands use the matched designs (setMatchedFilters()).
Definition Equalizer.h:722
void setNumBands(int count)
Sets the number of active bands with auto-logarithmic spacing.
Definition Equalizer.h:602
static constexpr double kPrototypeFadeSeconds
Definition Equalizer.h:1837
std::unique_ptr< FFTReal< T > > lpFft_
Partition FFT (2 x partition); gates the engine.
Definition Equalizer.h:2884
static constexpr int kPrototypeTaps
Length of the correction.
Definition Equalizer.h:1831
void processPrototype(AudioBufferView< T > buffer) noexcept
The correction over one block: every channel through its filter, and with placed bands the other chan...
Definition Equalizer.h:2099
void setBandEnabled(int index, bool enabled) noexcept
Enables or disables a band without changing its parameters.
Definition Equalizer.h:793
static bool restsAtUnity(const BandConfig &cfg) noexcept
Whether a band does nothing as configured: a gain band within kRestDb of 0 dB.
Definition Equalizer.h:1497
void processMinimumPhase(AudioBufferView< T > buffer) noexcept
MinimumPhase processing, with each band's on/off state crossfaded over kBandFadeSeconds.
Definition Equalizer.h:1741
static constexpr int kLpSyncSteps
Bound of a synchronous design.
Definition Equalizer.h:2167
void advanceDesign(DesignPace pace) noexcept
Runs one bounded slice of a kernel design into the inactive set.
Definition Equalizer.h:2217
void setMatchedFilters(bool enabled) noexcept
Switches LowPass/HighPass, BandPass and slope-1 shelf bands to the analog-matched designs.
Definition Equalizer.h:715
static constexpr double kRampFastMs
Glide of a jump.
Definition Equalizer.h:1383
void applyCompensation(AudioBufferView< T > &buffer) noexcept
The compensation's gain on a block (nothing at rest at unity).
Definition Equalizer.h:1168
static constexpr int kLpMinKernel
Definition Equalizer.h:2160
void designPrototype(bool snap) noexcept
Designs the correction filters from the curves of the bands and fades to them.
Definition Equalizer.h:1978
void prototypeBandCurves(int index) noexcept
The analog response of a band over its digital one, on the grid.
Definition Equalizer.h:1890
FilterMode
Filter processing mode.
Definition Equalizer.h:149
@ LinearPhase
Partitioned FFT convolution (fixed latency, see getLatency()).
@ PrototypePhase
The bands from their analog prototypes plus a short correction: the phase of the analog curve,...
@ MinimumPhase
IIR biquads (zero latency, minimum phase shift). Default.
void magnitudeOfBands(const T *frequencies, T *magnitudes, int numPoints, int where) const noexcept
The product of the enabled bands: all of them (where < 0), or the stereo ones and those placed at whe...
Definition Equalizer.h:959
std::unique_ptr< PrototypeEngine > prototype_
The correction of the prototype-phase mode.
Definition Equalizer.h:2864
bool getLoudnessCompensation() const noexcept
Definition Equalizer.h:649
void setFilterMode(FilterMode mode) noexcept
Sets the filter processing mode (minimum, linear or prototype phase).
Definition Equalizer.h:821
~Equalizer()=default
Non-virtual destructor to prevent vtable instantiation (zero virtual dispatch).
void resetBand(int index) noexcept
Definition Equalizer.h:1716
static constexpr double kBandFadeSeconds
Definition Equalizer.h:1724
std::atomic< bool > softMode_
Definition Equalizer.h:2855
void setBand(int index, T frequency, T gainDb, T q)
Configures a band with frequency, gain, and Q.
Definition Equalizer.h:543
void refreshCompensation() noexcept
Translates BandConfigs into internal FilterEngine parameters safely.
Definition Equalizer.h:1138
std::vector< T > lpWindow_
Definition Equalizer.h:2925
std::vector< T > lpKernelTime_
Definition Equalizer.h:2926
int lpSlot_
Kernel of the design being transformed.
Definition Equalizer.h:2922
void setStructure(Structure structure) noexcept
Chooses how the bands' sections are realised in minimum phase.
Definition Equalizer.h:693
BandConfig getBandConfig(int index) const noexcept
Returns the current configuration of a band.
Definition Equalizer.h:782
static int legacySlope(const BandConfig &cfg) noexcept
The slope the cookbook engine runs: 6 to 48 dB per octave, whole.
Definition Equalizer.h:1409
std::array< int, MaxBands > bandScope_
Where each band acts (audio thread's copy).
Definition Equalizer.h:2868
static constexpr double kRestDb
A gain band closer to 0 dB than this leaves the path.
Definition Equalizer.h:1386
std::array< std::atomic< bool >, MaxBands > bandEnabled_
Definition Equalizer.h:2847
Structure getStructure() const noexcept
Definition Equalizer.h:701
int resolveKernelLength(double sampleRate) const noexcept
Kernel length for a sample rate (see setLinearPhaseKernelLength()).
Definition Equalizer.h:2178
std::atomic< int > lpKernelRequest_
0 = automatic length.
Definition Equalizer.h:2873
BiquadCoeffs kShelf_
Definition Equalizer.h:2852
std::unique_ptr< FFTReal< T > > lpDesignFft_
Design FFT (2 x kernel).
Definition Equalizer.h:2885
std::atomic< T > compensationDb_
Definition Equalizer.h:2851
static double shelfSlopeFromQ(double q, double gainDb) noexcept
Converts a user-facing shelf Q into the RBJ shelf slope S.
Definition Equalizer.h:1254
void clearPrototypeStream() noexcept
Clears what the correction remembers of the signal.
Definition Equalizer.h:2087
void runLinearPhaseHop() noexcept
One partition hop: schedule the design, then convolve every prepared channel (uniformly partitioned o...
Definition Equalizer.h:2551
static constexpr int kMaxStretches
Most designs a glide goes through.
Definition Equalizer.h:1384
std::vector< T * > lpWarmChannels_
Definition Equalizer.h:2898
void setLoudnessCompensation(bool on) noexcept
Keeps the loudness (off by default): the bands' change of the K-weighted level of pink noise (as BS....
Definition Equalizer.h:642
std::array< int, MaxBands > lpStageCount_
Definition Equalizer.h:2917
void updateActiveFilters() noexcept
Definition Equalizer.h:1181
int designSections(const BandConfig &cfg, BiquadCoeffs *sections, int capacity) const noexcept
The biquads of a band of the analog response.
Definition Equalizer.h:1484
std::unique_ptr< std::array< AnalogBand, MaxBands > > analog_
Definition Equalizer.h:2863
int getLatency() const noexcept
Returns the latency in samples.
Definition Equalizer.h:851
std::array< int, MaxBands > lpBandGroup_
Where each band of the design acts (0 when it acts on every channel).
Definition Equalizer.h:2920
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio buffer in-place.
Definition Equalizer.h:375
static constexpr int kPrototypeSlots
Left to left, right to right, right to left, left to right, further channels.
Definition Equalizer.h:1834
std::array< std::vector< T >, 2 > lpKernelSet_
Partition spectra, active + incoming.
Definition Equalizer.h:2892
std::array< T, MaxBands > bandMix_
Definition Equalizer.h:2876
std::atomic< bool > analogResponse_
Every band from its analog prototype: opt-in.
Definition Equalizer.h:2859
int rampSamples(const BandConfig &from, const BandConfig &to) const noexcept
How long the coefficients of a band take to reach a new design: long for a small move,...
Definition Equalizer.h:1515
static constexpr double kPrototypeReach
Most the correction changes a level: 12 dB, in nepers.
Definition Equalizer.h:1838
T getCompensationDb() const noexcept
Definition Equalizer.h:652
std::atomic< FilterMode > filterMode_
Definition Equalizer.h:2871
void processBandSlice(int i, AudioBufferView< T > view, int n, int activeBands) noexcept
One band over one slice, on the channels of its scope, with its on/off fade. For a band of the middle...
Definition Equalizer.h:1779
void setSoftMode(bool enabled) noexcept
Enables soft mode (anti-ringing Q reduction dynamically based on gain).
Definition Equalizer.h:914
BiquadCoeffs computeBandCoeffs(const BandConfig &cfg) const noexcept
Computes single-biquad coefficients for a band (analysis/kernel).
Definition Equalizer.h:1269
std::vector< T > lpDesignTime_
Definition Equalizer.h:2926
std::atomic< bool > resonantShelves_
The Q of a shelf can go above 0.7071: opt-in.
Definition Equalizer.h:2860
std::atomic< bool > matchedFilters_
Matched LP/HP/BP/shelves: opt-in.
Definition Equalizer.h:2858
static constexpr int kPrototypeBins
The correction is designed on 129 frequencies up to Nyquist.
Definition Equalizer.h:1833
int lpSlots_
Kernels a set holds: 1, or the matrix of a pair (and one more for further channels).
Definition Equalizer.h:2921
void getMagnitudeForFrequencyArray(const T *frequencies, T *magnitudes, int numPoints) const noexcept
Computes the combined magnitude response of all enabled bands.
Definition Equalizer.h:938
void finishDesignNow() noexcept
Completes a pending design now and adopts it without a crossfade (first block after prepare/reset/mod...
Definition Equalizer.h:2531
bool usesAnalog(const BandConfig &cfg) const noexcept
Whether a band runs with the analog response (the switch, or a band only it can make).
Definition Equalizer.h:1415
std::array< FilterEngine< T >, MaxBands > bands_
Definition Equalizer.h:2686
Scope
Where in a stereo pair a band acts.
Definition Equalizer.h:179
@ Mid
The middle of the first two channels: what they share.
@ Right
The second channel only.
@ Left
The first channel only.
@ Stereo
Every channel. Default.
@ Side
Their sides: what sets them apart.
static bool prototypeCovers(const BandConfig &cfg) noexcept
Whether a band is one the correction covers: an elliptic wall is not (its digital form is itself).
Definition Equalizer.h:1878
const FilterEngine< T > & getBandFilter(int index) const noexcept
Const overload. Same clamping contract.
Definition Equalizer.h:1004
BiquadCoeffs kHighPass_
Definition Equalizer.h:2852
void nextStretch(AnalogBand &band) noexcept
Starts the next stretch of a glide: designs where it ends and sends the coefficients there.
Definition Equalizer.h:1643
static int glideStretches(const BandConfig &from, const BandConfig &to, int ramp) noexcept
In how many designs a band goes from one configuration to another: one for every quarter of an octave...
Definition Equalizer.h:1610
static constexpr int kEngineChannels
Channels the band engines hold.
Definition Equalizer.h:1381
FFT optimised for real-valued input signals (the common audio case).
Definition FFT.h:1197
void inverse(const T *freqData, T *timeData) noexcept
Inverse transform: complex frequency-domain -> real time-domain.
Definition FFT.h:1297
The frequencies a design is fitted over at one sample rate.
void prepare(double sampleRate) noexcept
Sets the sample rate (an invalid one leaves 48 kHz).
double getHighHz() const noexcept
static AnalogCascade bell(double hz, double q, double gainDb, double order) noexcept
Bell of any order: the higher the order, the flatter the top and the steeper the sides (6 dB per octa...
static AnalogCascade bandStop(double hz, double q, double order) noexcept
Butterworth band-stop: a null at the centre, -3 dB at the two edges hz / q apart, and a floor that wi...
static AnalogCascade allPass(double hz, double q, double order) noexcept
All-pass of any order: the magnitude stays at 1 and the phase turns 180 degrees per order around the ...
static constexpr double kButterworthQ
The Q that leaves a cut maximally flat.
static BiquadCoeffs digital(const AnalogSection &section, const Band &band) noexcept
The biquad whose magnitude follows an analog section up to Nyquist.
static double tiltSlopeWithin(double pivotHz, double slopeDbPerOctave, double ceilingDb) noexcept
The slope a tilt can have at a pivot without lifting the end that rises (20 kHz for a positive slope,...
static AnalogCascade bandPass(double hz, double q, double order) noexcept
Butterworth band-pass: 0 dB at the centre, -3 dB at the two edges hz / q apart, 6 dB per octave on ea...
static AnalogCascade ellipticHighCut(double hz, int order=12, double rippleDb=0.05, double stopDb=100.0) noexcept
Elliptic high cut: flat to the corner within the ripple, then a wall down to the stop level.
static AnalogCascade highShelf(double hz, double gainDb, double order, double q=kButterworthQ) noexcept
High shelf of any order: lowShelf() mirrored about the corner.
static BiquadCoeffs bilinear(const AnalogSection &section, double sampleRate, double exactHz) noexcept
The bilinear transform of a section, with one frequency mapped exactly.
static AnalogCascade highCut(double hz, double slopeDbPerOctave, double q=kButterworthQ) noexcept
High cut (low-pass) of any slope from 0 to 96 dB per octave.
static AnalogCascade lowCut(double hz, double slopeDbPerOctave, double q=kButterworthQ) noexcept
Low cut (high-pass) of any slope from 0 to 96 dB per octave: highCut() mirrored about the corner.
static AnalogCascade ellipticLowCut(double hz, int order=12, double rippleDb=0.05, double stopDb=100.0) noexcept
Elliptic low cut: ellipticHighCut() mirrored about the corner.
static AnalogCascade lowShelf(double hz, double gainDb, double order, double q=kButterworthQ) noexcept
Low shelf of any order from 1, whole or not: gainDb below the corner, half of it (in decibels) at the...
static AnalogCascade tilt(double pivotHz, double slopeDbPerOctave) noexcept
Tilt: the same slope across the whole band, 0 dB at the pivot.
Professional multi-mode filter with cascaded biquad stages.
Definition Filters.h:86
static CascadeInfo cascadeForSlope(int slopeDb, float userQ=0.707f) noexcept
Returns the exact Butterworth cascade (first-order flag + per-stage Q values) used internally for a g...
Definition Filters.h:397
Structure
How each second-order section is realised (see setStructure()).
Definition Filters.h:328
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
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
Definition SimdOps.h:644
Main namespace for the DSPark framework.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Up to kMaxSections analog sections in series.
std::array< AnalogSection, kMaxSections > sections
void add(const AnalogSection &section) noexcept
Appends a section (ignored once the cascade is full).
static constexpr int kMaxSections
A first or second order analog section, in radians per second: (b2 s^2 + b1 s + b0) / (a2 s^2 + a1 s ...
static AnalogSection lowShelfQ(double hz, double gainDb, double q) noexcept
Second-order low shelf by its Q: gainDb below the corner, half of it (in decibels) at the corner what...
static AnalogSection peak(double hz, double q, double gainDb) noexcept
Bell: gainDb at the centre, bandwidth hz / Q at half that gain in decibels.
static AnalogSection bandPass(double hz, double q=0.7071067811865476) noexcept
Band-pass, 0 dB at the centre.
static AnalogSection tilt(double hz, double gainDb) noexcept
First-order tilt: 0 dB at the pivot, half of gainDb down far below it and half of it up far above.
static AnalogSection notch(double hz, double q=0.7071067811865476) noexcept
Notch at the centre, 0 dB away from it.
static AnalogSection highShelfQ(double hz, double gainDb, double q) noexcept
Second-order high shelf by its Q: lowShelfQ() mirrored about the corner.
static AnalogSection lowShelf(double hz, double gainDb, double slope=1.0) noexcept
Second-order low shelf: gainDb below the corner, half of it (in decibels) at the corner.
static AnalogSection tiltSecondOrder(double hz, double gainDb, double q=0.7071067811865476) noexcept
Second-order tilt: 0 dB at the pivot, half of gainDb down far below it and half of it up far above,...
static AnalogSection highShelf(double hz, double gainDb, double slope=1.0) noexcept
Second-order high shelf: gainDb above the corner, half of it (in decibels) at the corner.
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
Stores normalised biquad coefficients (b0, b1, b2, a1, a2), always double.
Definition Biquad.h:107
static BiquadCoeffs makeFirstOrderHighPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) high-pass filter.
Definition Biquad.h:552
static BiquadCoeffs makePeakMatched(double sampleRate, double freq, double Q, double gainDb) noexcept
Analog-matched ("de-cramped") peaking filter (Vicanek design).
Definition Biquad.h:248
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
Definition Biquad.h:143
static BiquadCoeffs makeHighShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth high shelf (see makeLowShelfMatched()).
Definition Biquad.h:405
static BiquadCoeffs makeBandPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Band-pass filter (constant 0 dB peak gain).
Definition Biquad.h:172
static BiquadCoeffs makeLowShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth low shelf (Vicanek, "Matched Two-Pole Digital Shelving Filters",...
Definition Biquad.h:399
static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
Peak (parametric EQ) filter.
Definition Biquad.h:201
double getMagnitude(double frequency, double sampleRate) const noexcept
Evaluates magnitude response |H(f)| at a single frequency.
Definition Biquad.h:683
static BiquadCoeffs makeFirstOrderLowPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) low-pass filter.
Definition Biquad.h:529
static BiquadCoeffs makeTilt(double sampleRate, double pivotFreq, double gainDb) noexcept
Creates a first-order tilt filter.
Definition Biquad.h:578
static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Low-pass filter.
Definition Biquad.h:119
static BiquadCoeffs makeBandPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched band-pass, 0 dB at the centre (Vicanek 2016).
Definition Biquad.h:370
static BiquadCoeffs makeLowShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
Low-shelf filter.
Definition Biquad.h:417
static BiquadCoeffs makeLowPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched second-order low-pass (Vicanek, "Matched Second Order Digital Filters",...
Definition Biquad.h:321
static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
High-shelf filter.
Definition Biquad.h:447
static BiquadCoeffs makeHighPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched second-order high-pass (Vicanek 2016).
Definition Biquad.h:347
static BiquadCoeffs makeNotch(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Notch (band-reject) filter.
Definition Biquad.h:476
One band of the analog response.
Definition Equalizer.h:1391
bool resting
The design is transparent (a gain band at 0 dB).
Definition Equalizer.h:1398
BandConfig heading
Where the coefficients are going now: config, or a design on the way to it.
Definition Equalizer.h:1400
int stretchLength
Samples of each.
Definition Equalizer.h:1404
BiquadCascade< T, kMaxBandSections, kEngineChannels > cascade
Definition Equalizer.h:1392
int stretches
Designs the glide in flight goes through (0: none, or its last one).
Definition Equalizer.h:1402
int stretch
The one being approached, from 1.
Definition Equalizer.h:1403
bool idle
Resting and landed: no section is computed.
Definition Equalizer.h:1399
bool resonant
setResonantShelves() when it was designed (it changes a shelf).
Definition Equalizer.h:1395
int wanted
Sections of that design (a glide can still carry more).
Definition Equalizer.h:1396
bool soft
Soft mode when it was designed (it changes the Q).
Definition Equalizer.h:1394
BandConfig origin
Where a glide in stretches set out from.
Definition Equalizer.h:1401
BandConfig config
What the cascade is on, or gliding to.
Definition Equalizer.h:1393
int stretchLeft
Samples to the one being approached.
Definition Equalizer.h:1405
Full configuration for a single EQ band.
Definition Equalizer.h:191
Scope scope
The channels the band acts on.
Definition Equalizer.h:199
T q
Q factor (0.1 = wide, 10 = narrow).
Definition Equalizer.h:194
T gain
Gain in dB (Peak, Shelf, Tilt).
Definition Equalizer.h:193
bool enabled
False to bypass this band.
Definition Equalizer.h:198
BandType type
Filter type for this band.
Definition Equalizer.h:195
T slope
Slope in dB/oct (LP/HP only): 6 to 48 in steps of 6, or any value from 0 to 96 with the analog respon...
Definition Equalizer.h:196
T order
Order of a bell, shelf, notch, band-pass or all-pass, 1 to 16, whole or not (6 dB/oct each; a shelf i...
Definition Equalizer.h:197
T frequency
Center/cutoff frequency in Hz.
Definition Equalizer.h:192
The state of the prototype-phase mode, allocated in prepare().
Definition Equalizer.h:1851
std::array< Curve, MaxBands > bandArg
Analog over digital per band: level in nepers, phase in radians.
Definition Equalizer.h:1855
std::vector< double > spectrum
Definition Equalizer.h:1872
std::array< T, kPrototypeTaps > Taps
Definition Equalizer.h:1853
std::array< Curve, MaxBands > bandLog
Definition Equalizer.h:1855
std::array< Taps, kPrototypeSlots > to
Definition Equalizer.h:1866
std::array< Taps, kPrototypeSlots > now
Reversed, ready for a dot product.
Definition Equalizer.h:1866
std::array< bool, kPrototypeGroups > groupUsed
Definition Equalizer.h:1858
Curve taper
1 up to the top of the fitted band, down to 0 at Nyquist.
Definition Equalizer.h:1863
std::vector< T > work
Per channel: the last taps - 1 samples, then the chunk.
Definition Equalizer.h:1873
std::array< Taps, kPrototypeSlots > from
Definition Equalizer.h:1866
Curve sinOne
z^-1 on the grid ...
Definition Equalizer.h:1861
std::array< double, kPrototypeTaps > window
Definition Equalizer.h:1864
std::array< Curve, kPrototypeGroups > groupLog
Definition Equalizer.h:1857
std::array< Curve, kPrototypeGroups > groupArg
Definition Equalizer.h:1857
std::array< PrototypeSeen, MaxBands > seen
Definition Equalizer.h:1856
std::array< double, kPrototypeBins+1 > Curve
Definition Equalizer.h:1852
Curve omega
The grid, in rad/s.
Definition Equalizer.h:1860
unsigned clock
Free-running, so a fade does not depend on the host's blocks.
Definition Equalizer.h:1869
bool crossTo
Whether the matrix has terms between the channels.
Definition Equalizer.h:1867
What the correction of one band was designed from.
Definition Equalizer.h:1842
bool present
The band has a correction at all.
Definition Equalizer.h:1845
One band's published configuration: a seqlock over atomic words.
Definition Equalizer.h:2700
BandConfig read() const noexcept
Reads the band into a caller-private plain copy (readouts).
Definition Equalizer.h:2821
void loadWordsRelaxed(BandConfig &c) const noexcept
Relaxed copy of the six published words (no ordering of its own; the caller's fences and counter chec...
Definition Equalizer.h:2755
static constexpr int kSeqlockMaxAttempts
Definition Equalizer.h:2747
std::atomic< unsigned > seq
Definition Equalizer.h:2713
void publish(const BandConfig &c) noexcept
Publishes a whole band configuration (control thread only).
Definition Equalizer.h:2727
std::atomic< int > type
Definition Equalizer.h:2708
std::atomic< bool > enabled
Definition Equalizer.h:2711
bool tryRead(BandConfig &out) const noexcept
The bounded seqlock read for the AUDIO thread.
Definition Equalizer.h:2787
std::atomic< int > scope
Definition Equalizer.h:2712
static void encode(AudioBufferView< T > buffer) noexcept
Encodes an entire stereo buffer from Left/Right to Mid/Side.
Definition MidSide.h:108
static void decode(AudioBufferView< T > buffer) noexcept
Decodes an entire stereo buffer from Mid/Side back to Left/Right.
Definition MidSide.h:138