DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DynamicEQ.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
140#include "MidSide.h"
141#include "../Core/AudioBuffer.h"
142#include "../Core/AudioSpec.h"
143#include "../Core/Biquad.h"
144#include "../Core/BiquadCascade.h"
145#include "../Core/DspMath.h"
146#include "../Core/FilterDesign.h"
147#include "../Core/FirBank.h"
148#include "../Core/FFT.h"
149#include "../Core/Hilbert.h"
150#include "../Core/NormalizedLadder.h"
151#include "../Core/Oversampling.h"
152#include "../Core/RingBuffer.h"
153#include "../Core/DenormalGuard.h"
154#include "../Core/StateBlob.h"
155
156#include <algorithm>
157#include <array>
158#include <atomic>
159#include <cmath>
160#include <complex>
161#include <cstddef>
162#include <cstdint>
163#include <cstdio>
164#include <memory>
165#include <numbers>
166#include <type_traits>
167#include <utility>
168#include <vector>
169
170namespace dspark {
171
179template <FloatType T, int MaxBands = 8>
181{
182public:
184 enum class BandShape
185 {
186 Bell,
187 LowShelf,
188 HighShelf
189 };
190
192 enum class Scope
193 {
194 Stereo,
195 Left,
196 Right,
197 Mid,
198 Side
199 };
200
202 enum class Timing
203 {
204 Manual,
205 Program
206 };
207
209 static constexpr T kAutomaticKnee = T(-1);
210
216 {
217 T frequency = T(1000);
218 T q = T(1.0);
219 T threshold = T(-20);
221 bool enabled = true;
222
223 T gain = T(0);
224 T knee = T(0);
227 bool relativeThreshold = false;
228 T listenLow = T(0);
229 T listenHigh = T(0);
230
231 T aboveRatio = T(1);
233 T aboveReleaseMs = T(50);
234 T aboveRangeDb = T(12);
235 bool aboveBoost = false;
236
237 T belowRatio = T(1);
238 T belowAttackMs = T(10);
239 T belowReleaseMs = T(100);
240 T belowRangeDb = T(12);
241 bool belowBoost = false;
242 };
243
244 static_assert(std::is_trivially_copyable_v<BandConfig>, "BandConfig must be trivially copyable for std::atomic");
245 static_assert(std::atomic<T>::is_always_lock_free,
246 "audio-thread stores must not lock");
247
249 {
250 for (int i = 0; i < MaxBands; ++i) {
251 masterConfigs_[i] = BandConfig{};
252 staged_[static_cast<size_t>(i)].publish(masterConfigs_[i]);
253 paramsDirty_[i].store(true, std::memory_order_relaxed);
254 }
255 }
256
261 void prepare(const AudioSpec& spec)
262 {
263 if (!spec.isValid()) return; // invalid specs are ignored (state kept)
264 isPrepared_.store(false, std::memory_order_relaxed); // basic guarantee
265 spec_ = spec;
266 sampleRate_ = spec.sampleRate;
267 if (oversamplingAutomatic_)
268 oversamplingFactor_ = Oversampling<T>::factorForRate(spec.sampleRate, kAutomaticInternalRate, 4);
269
270 if (oversamplingFactor_ > 1 && !linearWanted_)
271 {
272 // Two oversamplers: the audio-path one owns the buffer that we
273 // both process and downsample back; the sidechain one only acts
274 // as a level-detection upsampler so its buffer is read-only.
275 oversampler_ = std::make_unique<Oversampling<T>>(oversamplingFactor_);
276 oversamplerSc_ = std::make_unique<Oversampling<T>>(oversamplingFactor_);
277 oversampler_ ->prepare(spec);
278 oversamplerSc_->prepare(spec);
279 }
280 else
281 {
282 oversampler_.reset();
283 oversamplerSc_.reset();
284 }
285
286 analytic_.assign(static_cast<size_t>(MaxBands * kMaxChannels), HilbertIIR<double> {});
287
288 // The mixed engine: three fixed filters per band, and the rate their
289 // designs are fitted at (the one the bands run at).
290 mixedEngine_ = std::make_unique<MixedEngine>();
291 for (auto& band : mixedEngine_->bands)
292 {
293 band.rest.setNumSections(1);
294 band.cut.setNumSections(1);
295 band.lift.setNumSections(1);
296 }
297 designBand_.prepare(sampleRate_ * runFactor());
298
299 // The linear-phase mode: a bank of kernels (one per band and branch),
300 // the signal and the weights late by its latency, and the transform
301 // the kernels are designed with. linear_ gates the mode: set last.
302 linear_.reset();
303 if (linearWanted_)
304 {
305 auto engine = std::make_unique<LinearEngine>();
306 LinearEngine& e = *engine;
307 e.kernel = resolveLinearTaps(spec.sampleRate);
308 e.channels = std::min(spec.numChannels, kMaxChannels);
309 e.bank.prepare(e.kernel, e.kernel / kLinearPartitions, e.channels + (e.channels >= 2 ? 2 : 0),
310 MaxBands * kLinearBranches);
311 e.latency = e.kernel / 2 + e.bank.getLatency();
312 e.designFft = std::make_unique<FFTReal<T>>(static_cast<size_t>(e.kernel));
313 e.spectrum.assign(static_cast<size_t>(e.kernel + 2), T(0));
314 e.time.assign(static_cast<size_t>(e.kernel), T(0));
315 e.taps.assign(static_cast<size_t>(e.kernel), T(0));
316 e.window.resize(static_cast<size_t>(e.kernel));
317 for (int m = 0; m < e.kernel; ++m)
318 {
319 const double t = 2.0 * std::numbers::pi * m / e.kernel;
320 e.window[static_cast<size_t>(m)] = static_cast<T>(
321 0.35875 - 0.48829 * std::cos(t) + 0.14128 * std::cos(2.0 * t) - 0.01168 * std::cos(3.0 * t));
322 }
323 for (int ch = 0; ch < kMaxChannels; ++ch) e.dry[ch].prepare(e.latency + 1);
324 int ring = 1;
325 while (ring < e.latency + kDetChunk + 1) ring <<= 1;
326 e.weightMask = ring - 1;
327 e.weights.assign(static_cast<size_t>(MaxBands * 2) * static_cast<size_t>(ring), T(0));
328 linear_ = std::move(engine);
329 }
330
331 int maxLaSamples = static_cast<int>(sampleRate_ * runFactor() * 0.01) + 1;
332 for (int ch = 0; ch < kMaxChannels; ++ch)
333 lookaheadBuf_[ch].prepare(maxLaSamples);
334
335 updateLookahead();
336 reset();
337 for (int ch = 0; ch < std::min(spec.numChannels, kMaxChannels); ++ch)
338 deltaRing_[static_cast<size_t>(ch)].prepare(kRemovalCapacity + std::max(1, spec.maxBlockSize));
339
340 // The key listen: the key a band hears, kept for the longest latency
341 // the mode can have (its lookahead goes up to 10 ms).
342 listenChannels_ = std::min(spec.numChannels, kMaxChannels);
343 listenBlock_ = std::max(1, spec.maxBlockSize);
344 listenReach_ = linear_ ? linear_->latency
345 : maxLaSamples / runFactor() + 1 + (oversampler_ ? oversampler_->getLatency() : 0);
346 for (int ch = 0; ch < listenChannels_; ++ch)
347 listenRing_[static_cast<size_t>(ch)].prepare(listenReach_ + listenBlock_ + 1);
348 listenHeard_.assign(static_cast<size_t>(listenChannels_) * static_cast<size_t>(listenBlock_), T(0));
349 isPrepared_.store(true, std::memory_order_relaxed);
350 }
351
356 void processBlock(AudioBufferView<T> buffer) noexcept
357 {
358 processBlock(buffer, buffer);
359 }
360
366 void processBlock(AudioBufferView<T> audio, AudioBufferView<T> sidechain) noexcept
367 {
368 if (!isPrepared_.load(std::memory_order_relaxed)) return;
369 const bool removal = removalListen_.load(std::memory_order_relaxed);
370 const bool keyed = keyListen_.load(std::memory_order_relaxed) >= 0 || listenBand_ >= 0;
371 if (!removal && !keyed)
372 {
373 processImpl(audio, sidechain);
374 return;
375 }
376 // The listens, in chunks of the prepared block. Removal: the input,
377 // late by the latency, minus the output. Key: what a band's detector
378 // hears, late by the latency, in place of the output.
379 const bool selfKeyed = sidechain.getNumChannels() <= 0 || sidechain.getNumSamples() < audio.getNumSamples()
380 || sidechain.getChannel(0) == audio.getChannel(0);
381 const int nCh = std::min(audio.getNumChannels(), kMaxChannels);
382 const int step = std::max(1, spec_.maxBlockSize);
383 for (int off = 0; off < audio.getNumSamples(); off += step)
384 {
385 const int m = std::min(step, audio.getNumSamples() - off);
386 auto part = audio.getSubView(off, m);
387 auto key = selfKeyed ? part : sidechain.getSubView(off, m);
388 const bool heard = keyed && hearKey(key, nCh, m); // before the bands write over the signal
389 if (removal)
390 {
391 for (int ch = 0; ch < nCh; ++ch)
392 {
393 const T* d = part.getChannel(ch);
394 for (int i = 0; i < m; ++i) deltaRing_[static_cast<size_t>(ch)].push(d[i]);
395 }
396 }
397 const int late = std::min(getLatency(), kRemovalCapacity);
398 processImpl(part, key);
399 if (removal)
400 {
401 for (int ch = 0; ch < nCh; ++ch)
402 {
403 T* d = part.getChannel(ch);
404 const auto& ring = deltaRing_[static_cast<size_t>(ch)];
405 for (int i = 0; i < m; ++i) d[i] = ring.read(late + (m - 1 - i)) - d[i];
406 }
407 }
408 if (heard) playKey(part, nCh, m);
409 }
410 }
411
417 void setRemovalListen(bool on) noexcept { removalListen_.store(on, std::memory_order_relaxed); }
419 [[nodiscard]] bool isRemovalListen() const noexcept { return removalListen_.load(std::memory_order_relaxed); }
420
436 void setKeyListen(int band) noexcept
437 {
438 keyListen_.store(band >= 0 && band < MaxBands ? band : -1, std::memory_order_relaxed);
439 }
441 [[nodiscard]] int getKeyListen() const noexcept { return keyListen_.load(std::memory_order_relaxed); }
442
443private:
444 void processImpl(AudioBufferView<T> audio, AudioBufferView<T> sidechain) noexcept
445 {
446
447 // A sidechain shorter than the audio block would be read past its
448 // end; fall back to self-keying instead of over-reading the caller.
449 if (sidechain.getNumChannels() <= 0 ||
450 sidechain.getNumSamples() < audio.getNumSamples())
451 {
452 if (audio.getNumChannels() <= 0) return;
453 sidechain = audio;
454 }
455
456 DenormalGuard guard;
457
458 if (oversamplingFactor_ > 1 && oversampler_ && oversamplerSc_)
459 {
460 // Up-sample audio and sidechain through their dedicated oversamplers.
461 // Each Oversampling instance owns one internal high-rate buffer, so
462 // we cannot share one between the two streams; processing them
463 // separately keeps each stream's polyphase filter state consistent.
464 // The oversamplers hold at most maxBlockSize base samples, so a
465 // longer block runs in chunks (its tail used to pass dry).
466 const int total = audio.getNumSamples();
467 const int chunk = std::max(1, spec_.maxBlockSize);
468 for (int off = 0; off < total; off += chunk)
469 {
470 const int m = std::min(chunk, total - off);
471 auto audioChunk = audio.getSubView(off, m);
472 auto upAudio = oversampler_->upsample(audioChunk);
473 auto upSc = oversamplerSc_->upsample(sidechain.getSubView(off, m));
474
475 processCore(upAudio, upSc, sampleRate_ * oversamplingFactor_);
476
477 oversampler_->downsample(audioChunk);
478 }
479 }
480 else
481 {
482 // Standard processing path
483 processCore(audio, sidechain, sampleRate_);
484 }
485 }
486
497 bool hearKey(AudioBufferView<T>& key, int nCh, int m) noexcept
498 {
499 const int wanted = keyListen_.load(std::memory_order_relaxed);
500 if (wanted != listenBand_ && listenWeight_ <= 0.0)
501 {
502 listenBand_ = wanted;
503 listenDesigned_ = false;
504 listenFirst_.reset();
505 listenSecond_.reset();
506 for (int ch = 0; ch < listenChannels_; ++ch) listenRing_[static_cast<size_t>(ch)].reset();
507 }
508 if (listenBand_ < 0 || listenChannels_ <= 0 || m > listenBlock_) return false;
509 listenGoal_ = wanted == listenBand_ ? 1.0 : 0.0;
510
511 // The band as the audio thread has adopted it. A change still waiting
512 // is adopted here, as the bands would a moment later, so the key is
513 // heard through the settings in force from its first sample (a band
514 // past the count in use keeps the settings it last ran with).
515 if (listenBand_ < numBands_.load(std::memory_order_relaxed)
516 && paramsDirty_[listenBand_].exchange(false, std::memory_order_acquire))
517 updateBandInternalState(listenBand_, sampleRate_ * runFactor());
518 const BandConfig cfg = states_[listenBand_].cfg;
519 const bool moved = !listenDesigned_ || cfg.frequency != listenCfg_.frequency || cfg.q != listenCfg_.q
520 || cfg.shape != listenCfg_.shape || cfg.timing != listenCfg_.timing
521 || cfg.listenLow != listenCfg_.listenLow || cfg.listenHigh != listenCfg_.listenHigh;
522 if (listenDesigned_ && cfg.scope != listenCfg_.scope)
523 {
524 listenFirst_.reset(); // another signal: nothing of the old one rings on
525 listenSecond_.reset();
526 }
527 if (moved)
528 {
529 const DetectorDesign detector = designDetector(cfg, sampleRate_);
530 listenFirst_.setCoeffsNow(detector.first);
531 listenSecond_.setCoeffsNow(detector.second);
532 if (detector.two && !listenTwo_) listenSecond_.reset();
533 listenTwo_ = detector.two;
534 }
535 listenCfg_ = cfg;
536 listenDesigned_ = true;
537
538 const int scCh = key.getNumChannels();
539 const int channels = std::min(nCh, listenChannels_);
540 const auto line = [this](int ch) noexcept {
541 return listenHeard_.data() + static_cast<size_t>(ch) * static_cast<size_t>(listenBlock_);
542 };
543 const auto through = [this, m](const T* one, const T* other, T sign, int slot, T* out) noexcept {
544 for (int i = 0; i < m; ++i)
545 {
546 T x = std::isfinite(one[i]) ? one[i] : T(0);
547 if (other != nullptr) x = (x + sign * (std::isfinite(other[i]) ? other[i] : T(0))) * T(0.5);
548 x = listenFirst_.processSample(x, slot);
549 out[i] = listenTwo_ ? listenSecond_.processSample(x, slot) : x;
550 }
551 };
552 for (int ch = 0; ch < channels; ++ch) std::fill_n(line(ch), m, T(0));
553 if (scCh > 0)
554 {
555 switch (cfg.scope)
556 {
557 case Scope::Stereo:
558 for (int ch = 0; ch < channels; ++ch)
559 through(key.getChannel(std::min(ch, scCh - 1)), nullptr, T(1), ch, line(ch));
560 break;
561 case Scope::Left:
562 through(key.getChannel(0), nullptr, T(1), 0, line(0));
563 break;
564 case Scope::Right:
565 if (channels >= 2) through(key.getChannel(std::min(1, scCh - 1)), nullptr, T(1), 1, line(1));
566 break;
567 case Scope::Mid:
568 through(key.getChannel(0), scCh >= 2 ? key.getChannel(1) : nullptr, T(1), 0, line(0));
569 if (channels >= 2) std::copy_n(line(0), m, line(1)); // heard in the centre
570 break;
571 case Scope::Side:
572 if (channels >= 2 && scCh >= 2)
573 {
574 through(key.getChannel(0), key.getChannel(1), T(-1), 0, line(0));
575 for (int i = 0; i < m; ++i) line(1)[i] = -line(0)[i]; // the sides: opposed
576 }
577 break;
578 }
579 }
580 for (int ch = 0; ch < channels; ++ch)
581 {
582 const T* heard = line(ch);
583 auto& ring = listenRing_[static_cast<size_t>(ch)];
584 for (int i = 0; i < m; ++i) ring.push(heard[i]);
585 }
586 return true;
587 }
588
590 void playKey(AudioBufferView<T>& out, int nCh, int m) noexcept
591 {
592 const int channels = std::min(nCh, listenChannels_);
593 const int late = std::min(getLatency(), listenReach_);
594 const double step = 1.0 / std::max(1.0, kListenFadeMs * 0.001 * sampleRate_);
595 const double from = listenWeight_, goal = listenGoal_;
596 double weight = from;
597 for (int ch = 0; ch < channels; ++ch)
598 {
599 T* d = out.getChannel(ch);
600 const auto& ring = listenRing_[static_cast<size_t>(ch)];
601 weight = from;
602 for (int i = 0; i < m; ++i)
603 {
604 weight = goal > weight ? std::min(goal, weight + step) : std::max(goal, weight - step);
605 const T heard = ring.read(late + (m - 1 - i));
606 if (weight >= 1.0) d[i] = heard;
607 else if (weight > 0.0) d[i] = static_cast<T>(d[i] + static_cast<T>(weight) * (heard - d[i]));
608 }
609 }
610 listenWeight_ = weight;
611 }
612
613public:
628 void setBand(int band, const BandConfig& config) noexcept
629 {
630 if (band < 0 || band >= MaxBands) return;
631
632 BandConfig c = config;
633 // The fallback reads the control thread's own private master, never the
634 // published words: a setter must not race the audio thread to decide
635 // what "the band's previously published value" is.
636 const BandConfig& prev = masterConfigs_[static_cast<size_t>(band)];
637 auto keep = [](T v, T fallback) { return std::isfinite(v) ? v : fallback; };
638 c.frequency = std::max(keep(c.frequency, prev.frequency), T(1));
639 c.q = keep(c.q, prev.q);
640 c.threshold = keep(c.threshold, prev.threshold);
641 c.shape = static_cast<BandShape>(std::clamp(static_cast<int>(c.shape), 0, 2));
642 c.gain = std::clamp(keep(c.gain, prev.gain), T(-24), T(24));
643 c.knee = std::min(keep(c.knee, prev.knee), T(40));
644 if (c.knee < T(0)) c.knee = kAutomaticKnee;
645 if (static_cast<int>(c.scope) < 0 || static_cast<int>(c.scope) > static_cast<int>(Scope::Side))
646 c.scope = prev.scope;
647 if (static_cast<int>(c.timing) < 0 || static_cast<int>(c.timing) > static_cast<int>(Timing::Program))
648 c.timing = prev.timing;
649 c.listenLow = std::max(keep(c.listenLow, prev.listenLow), T(0));
650 c.listenHigh = std::max(keep(c.listenHigh, prev.listenHigh), T(0));
651 if (c.listenLow > T(0) && c.listenHigh > T(0) && c.listenHigh < c.listenLow)
652 std::swap(c.listenLow, c.listenHigh);
653 c.aboveRatio = keep(c.aboveRatio, prev.aboveRatio);
654 c.aboveAttackMs = keep(c.aboveAttackMs, prev.aboveAttackMs);
656 c.aboveRangeDb = std::max(keep(c.aboveRangeDb, prev.aboveRangeDb), T(0));
657 c.belowRatio = keep(c.belowRatio, prev.belowRatio);
658 c.belowAttackMs = keep(c.belowAttackMs, prev.belowAttackMs);
660 c.belowRangeDb = std::max(keep(c.belowRangeDb, prev.belowRangeDb), T(0));
661
662 masterConfigs_[static_cast<size_t>(band)] = c;
663 staged_[static_cast<size_t>(band)].publish(c);
664 paramsDirty_[band].store(true, std::memory_order_release);
665 // Single control writer: a plain load/store pair cannot lose a write.
666 if (numBands_.load(std::memory_order_relaxed) < band + 1)
667 numBands_.store(band + 1, std::memory_order_relaxed);
668 }
669
670 void setNumBands(int n) noexcept
671 {
672 numBands_.store(std::clamp(n, 1, MaxBands), std::memory_order_relaxed);
673 }
674
689 void setMixedBands(bool on) noexcept { mixedWanted_.store(on, std::memory_order_relaxed); }
690
692 [[nodiscard]] bool isMixedBands() const noexcept { return mixedWanted_.load(std::memory_order_relaxed); }
693
695 enum class LinkMode
696 {
697 Loudest,
698 Dominant
699 };
700
713 void setLinkMode(LinkMode mode) noexcept
714 {
715 linkMode_.store(static_cast<LinkMode>(std::clamp(static_cast<int>(mode), 0, 1)), std::memory_order_relaxed);
716 }
717
719 [[nodiscard]] LinkMode getLinkMode() const noexcept { return linkMode_.load(std::memory_order_relaxed); }
720
722 enum class Structure
723 {
724 DirectForm,
725 Ladder
726 };
727
741 void setStructure(Structure structure) noexcept
742 {
743 structure_.store(static_cast<Structure>(std::clamp(static_cast<int>(structure), 0, 1)), std::memory_order_relaxed);
744 }
745
747 [[nodiscard]] Structure getStructure() const noexcept { return structure_.load(std::memory_order_relaxed); }
748
771 void setLinearPhase(bool on) noexcept
772 {
773 if (on == linearWanted_) return;
774 linearWanted_ = on;
775 isPrepared_.store(false, std::memory_order_relaxed);
776 }
777
779 [[nodiscard]] bool isLinearPhase() const noexcept { return linearWanted_; }
780
792 void setLinearPhaseKernelLength(int taps) noexcept
793 {
794 taps = std::clamp(taps, 0, 65536);
795 if (taps == linearTaps_) return;
796 linearTaps_ = taps;
797 if (linearWanted_) isPrepared_.store(false, std::memory_order_relaxed);
798 }
799
801 [[nodiscard]] int getLinearPhaseKernelLength() const noexcept { return linear_ ? linear_->kernel : linearTaps_; }
802
817 void getBandMagnitude(int band, T dynamicGainDb, const T* frequencies, T* magnitudes, int numPoints) const noexcept
818 {
819 if (frequencies == nullptr || magnitudes == nullptr) return;
820 for (int i = 0; i < numPoints; ++i) magnitudes[i] = T(1);
821 if (band < 0 || band >= MaxBands || sampleRate_ <= 0.0 || !std::isfinite(dynamicGainDb)) return;
822
823 const BandConfig cfg = staged_[static_cast<size_t>(band)].read();
824 const double fs = sampleRate_ * runFactor();
825 const double rest = static_cast<double>(cfg.gain), moved = static_cast<double>(dynamicGainDb);
826
827 if (linearWanted_)
828 {
829 // Linear phase: the magnitudes of the prototypes, mixed as the mode mixes them.
830 const double range = rangeTowards(cfg, moved > 0.0);
831 const bool acts = range > kRestDb && moved != 0.0;
832 const double side = moved > 0.0 ? range : -range;
833 const double ratio = std::pow(10.0, moved / 20.0), endRatio = std::pow(10.0, side / 20.0);
834 const double weight = acts ? std::clamp((ratio - 1.0) / (endRatio - 1.0), 0.0, 1.0) : 0.0;
835 const double reach = 1.0 + std::pow(10.0, side / 40.0);
836 const AnalogSection atRest = prototypeOf(cfg, rest), atHalf = prototypeOf(cfg, 0.5 * side);
837 for (int i = 0; i < numPoints; ++i)
838 {
839 const double omega = 2.0 * std::numbers::pi * static_cast<double>(frequencies[i]);
840 const double base = std::abs(rest) > kRestDb ? std::sqrt(atRest.magnitudeSquared(omega)) : 1.0;
841 const double moving = acts ? 1.0 + weight * reach * (std::sqrt(atHalf.magnitudeSquared(omega)) - 1.0) : 1.0;
842 magnitudes[i] = static_cast<T>(base * moving);
843 }
844 return;
845 }
846
847 if (!isMixedBands())
848 {
849 const double total = rest + moved;
850 BiquadCoeffs c;
851 if (std::abs(total) > 0.01)
852 switch (cfg.shape)
853 {
854 case BandShape::LowShelf: c = BiquadCoeffs::makeLowShelf(fs, static_cast<double>(cfg.frequency), total); break;
855 case BandShape::HighShelf: c = BiquadCoeffs::makeHighShelf(fs, static_cast<double>(cfg.frequency), total); break;
856 default: c = BiquadCoeffs::makePeakMatched(fs, static_cast<double>(cfg.frequency),
857 static_cast<double>(cfg.q), total); break;
858 }
859 for (int i = 0; i < numPoints; ++i)
860 magnitudes[i] = static_cast<T>(std::abs(responseOf(c, static_cast<double>(frequencies[i]), fs)));
861 return;
862 }
863
864 // Mixed: the filter at rest, and after it the dry signal plus a share
865 // of what the end of that side adds to it.
866 const double range = rangeTowards(cfg, moved > 0.0);
867 const bool acts = range > kRestDb && moved != 0.0;
868 const double side = moved > 0.0 ? range : -range;
869 const double ratio = std::pow(10.0, moved / 20.0), endRatio = std::pow(10.0, side / 20.0);
870 const double weight = acts ? std::clamp((ratio - 1.0) / (endRatio - 1.0), 0.0, 1.0) : 0.0;
871 const bool rests = std::abs(rest) > kRestDb;
872 const BiquadCoeffs atRest = rests ? designShape(cfg, rest) : BiquadCoeffs {};
873 const BiquadCoeffs atEnd = acts ? designEnd(cfg, side) : BiquadCoeffs {};
874 for (int i = 0; i < numPoints; ++i)
875 {
876 const double hz = static_cast<double>(frequencies[i]);
877 const std::complex<double> moving = 1.0 + weight * (responseOf(atEnd, hz, fs) - 1.0);
878 magnitudes[i] = static_cast<T>(std::abs(responseOf(atRest, hz, fs) * moving));
879 }
880 }
881
902 void setOversampling(int factor) noexcept
903 {
904 oversamplingFactor_ = std::clamp(factor, 1, 4);
905 if (oversamplingFactor_ == 3) oversamplingFactor_ = 4;
906 oversamplingAutomatic_ = false;
907 isPrepared_.store(false, std::memory_order_relaxed); // Forces user to call prepare()
908 }
909
923 void setAutomaticOversampling(bool on) noexcept
924 {
925 if (on == oversamplingAutomatic_) return;
926 oversamplingAutomatic_ = on;
927 isPrepared_.store(false, std::memory_order_relaxed);
928 }
929
931 [[nodiscard]] bool isOversamplingAutomatic() const noexcept { return oversamplingAutomatic_; }
932
934 [[nodiscard]] int getOversamplingFactor() const noexcept { return oversamplingFactor_; }
935
938 void setLookahead(T ms) noexcept
939 {
940 if (!std::isfinite(ms)) return;
941 lookaheadMs_ = std::clamp(ms, T(0), T(10));
942 updateLookahead();
943 }
944
953 [[nodiscard]] int getLatency() const noexcept
954 {
955 if (linear_) return linear_->latency; // the lookahead comes out of it
956 const int factor = runFactor();
957 const int la = lookaheadSamples_.load(std::memory_order_relaxed) / factor;
958 const int os = oversampler_ ? oversampler_->getLatency() : 0;
959 return la + os;
960 }
961
963 [[nodiscard]] T getBandGainDb(int band) const noexcept
964 {
965 if (band < 0 || band >= MaxBands) return T(0);
966 return meterGainDb_[band].load(std::memory_order_relaxed);
967 }
968
969 void reset() noexcept
970 {
971 // The analytic detectors and the oversamplers hold signal history
972 // too: leaving it made reset() replay the old programme (a silent
973 // input produced a 0.84 peak at 2x and a -13 dB gain reading).
974 for (auto& c : bandCov_) c = {};
975 for (int b = 0; b < MaxBands; ++b)
976 {
977 cleanBand(b);
978 meterGainDb_[b].store(T(0), std::memory_order_relaxed);
979 paramsDirty_[b].store(true, std::memory_order_relaxed);
980 }
981 for (int ch = 0; ch < kMaxChannels; ++ch)
982 lookaheadBuf_[ch].reset();
983 if (linear_)
984 {
985 linear_->bank.reset();
986 for (auto& line : linear_->dry) line.reset();
987 std::fill(linear_->weights.begin(), linear_->weights.end(), T(0));
988 linear_->weightPos = 0;
989 linear_->played.fill(false);
990 linear_->snap = true;
991 }
992 if (oversampler_) oversampler_->reset();
993 if (oversamplerSc_) oversamplerSc_->reset();
994 refreshCounter_ = 0;
995 lastNumBands_ = MaxBands;
996 // The key listen starts over: it fades in again if it is still asked for.
997 listenBand_ = -1;
998 listenWeight_ = 0.0;
999 listenDesigned_ = false;
1000 listenFirst_.reset();
1001 listenSecond_.reset();
1002 for (auto& ring : listenRing_) ring.reset();
1003 }
1004
1005
1007 [[nodiscard]] std::vector<uint8_t> getState() const
1008 {
1009 StateWriter w(stateId("DYEQ"), 1);
1010 const int n = numBands_.load(std::memory_order_relaxed);
1011 w.write("numBands", n);
1012 w.write("lookahead", static_cast<float>(lookaheadMs_));
1013 w.write("mixed", isMixedBands());
1014 w.write("linkMode", static_cast<int32_t>(getLinkMode()));
1015 w.write("structure", static_cast<int32_t>(getStructure()));
1016 w.write("linear", linearWanted_);
1017 w.write("linearTaps", linearTaps_);
1018 char key[28];
1019 for (int i = 0; i < n; ++i)
1020 {
1021 // Seqlock read into a private copy: reading the band by reference
1022 // here made getState() a plain cross-thread read of the words
1023 // setBand() writes.
1024 const BandConfig c = staged_[static_cast<size_t>(i)].read();
1025 std::snprintf(key, sizeof(key), "b%d.freq", i);
1026 w.write(key, static_cast<float>(c.frequency));
1027 std::snprintf(key, sizeof(key), "b%d.q", i);
1028 w.write(key, static_cast<float>(c.q));
1029 std::snprintf(key, sizeof(key), "b%d.thresh", i);
1030 w.write(key, static_cast<float>(c.threshold));
1031 std::snprintf(key, sizeof(key), "b%d.shape", i);
1032 w.write(key, static_cast<int>(c.shape));
1033 std::snprintf(key, sizeof(key), "b%d.on", i);
1034 w.write(key, c.enabled);
1035 std::snprintf(key, sizeof(key), "b%d.gain", i);
1036 w.write(key, static_cast<float>(c.gain));
1037 std::snprintf(key, sizeof(key), "b%d.knee", i);
1038 w.write(key, static_cast<float>(c.knee));
1039 std::snprintf(key, sizeof(key), "b%d.scope", i);
1040 w.write(key, static_cast<int>(c.scope));
1041 std::snprintf(key, sizeof(key), "b%d.timing", i);
1042 w.write(key, static_cast<int>(c.timing));
1043 std::snprintf(key, sizeof(key), "b%d.relative", i);
1044 w.write(key, c.relativeThreshold);
1045 std::snprintf(key, sizeof(key), "b%d.listenLo", i);
1046 w.write(key, static_cast<float>(c.listenLow));
1047 std::snprintf(key, sizeof(key), "b%d.listenHi", i);
1048 w.write(key, static_cast<float>(c.listenHigh));
1049 std::snprintf(key, sizeof(key), "b%d.aRatio", i);
1050 w.write(key, static_cast<float>(c.aboveRatio));
1051 std::snprintf(key, sizeof(key), "b%d.aAtk", i);
1052 w.write(key, static_cast<float>(c.aboveAttackMs));
1053 std::snprintf(key, sizeof(key), "b%d.aRel", i);
1054 w.write(key, static_cast<float>(c.aboveReleaseMs));
1055 std::snprintf(key, sizeof(key), "b%d.aRange", i);
1056 w.write(key, static_cast<float>(c.aboveRangeDb));
1057 std::snprintf(key, sizeof(key), "b%d.aBoost", i);
1058 w.write(key, c.aboveBoost);
1059 std::snprintf(key, sizeof(key), "b%d.bRatio", i);
1060 w.write(key, static_cast<float>(c.belowRatio));
1061 std::snprintf(key, sizeof(key), "b%d.bAtk", i);
1062 w.write(key, static_cast<float>(c.belowAttackMs));
1063 std::snprintf(key, sizeof(key), "b%d.bRel", i);
1064 w.write(key, static_cast<float>(c.belowReleaseMs));
1065 std::snprintf(key, sizeof(key), "b%d.bRange", i);
1066 w.write(key, static_cast<float>(c.belowRangeDb));
1067 std::snprintf(key, sizeof(key), "b%d.bBoost", i);
1068 w.write(key, c.belowBoost);
1069 }
1070 return w.blob();
1071 }
1072
1074 bool setState(const uint8_t* data, size_t size)
1075 {
1076 StateReader r(data, size);
1077 if (!r.isValid() || r.processorId() != stateId("DYEQ")) return false;
1078 const int n = std::clamp(r.read("numBands", 0), 0, MaxBands);
1079 char key[28];
1080 for (int i = 0; i < n; ++i)
1081 {
1082 BandConfig c;
1083 std::snprintf(key, sizeof(key), "b%d.freq", i);
1084 c.frequency = static_cast<T>(r.read(key, 1000.0f));
1085 std::snprintf(key, sizeof(key), "b%d.q", i);
1086 c.q = static_cast<T>(r.read(key, 1.0f));
1087 std::snprintf(key, sizeof(key), "b%d.thresh", i);
1088 c.threshold = static_cast<T>(r.read(key, -20.0f));
1089 std::snprintf(key, sizeof(key), "b%d.shape", i);
1090 c.shape = static_cast<BandShape>(std::clamp(r.read(key, 0), 0, 2));
1091 std::snprintf(key, sizeof(key), "b%d.on", i);
1092 c.enabled = r.read(key, true);
1093 std::snprintf(key, sizeof(key), "b%d.gain", i);
1094 c.gain = static_cast<T>(r.read(key, 0.0f));
1095 std::snprintf(key, sizeof(key), "b%d.knee", i);
1096 c.knee = static_cast<T>(r.read(key, 0.0f));
1097 std::snprintf(key, sizeof(key), "b%d.scope", i);
1098 c.scope = static_cast<Scope>(std::clamp(r.read(key, 0), 0, static_cast<int>(Scope::Side)));
1099 std::snprintf(key, sizeof(key), "b%d.timing", i);
1100 c.timing = static_cast<Timing>(std::clamp(r.read(key, 0), 0, static_cast<int>(Timing::Program)));
1101 std::snprintf(key, sizeof(key), "b%d.relative", i);
1102 c.relativeThreshold = r.read(key, false);
1103 std::snprintf(key, sizeof(key), "b%d.listenLo", i);
1104 c.listenLow = static_cast<T>(r.read(key, 0.0f));
1105 std::snprintf(key, sizeof(key), "b%d.listenHi", i);
1106 c.listenHigh = static_cast<T>(r.read(key, 0.0f));
1107 std::snprintf(key, sizeof(key), "b%d.aRatio", i);
1108 c.aboveRatio = static_cast<T>(r.read(key, 1.0f));
1109 std::snprintf(key, sizeof(key), "b%d.aAtk", i);
1110 c.aboveAttackMs = static_cast<T>(r.read(key, 5.0f));
1111 std::snprintf(key, sizeof(key), "b%d.aRel", i);
1112 c.aboveReleaseMs = static_cast<T>(r.read(key, 50.0f));
1113 std::snprintf(key, sizeof(key), "b%d.aRange", i);
1114 c.aboveRangeDb = static_cast<T>(r.read(key, 12.0f));
1115 std::snprintf(key, sizeof(key), "b%d.aBoost", i);
1116 c.aboveBoost = r.read(key, false);
1117 std::snprintf(key, sizeof(key), "b%d.bRatio", i);
1118 c.belowRatio = static_cast<T>(r.read(key, 1.0f));
1119 std::snprintf(key, sizeof(key), "b%d.bAtk", i);
1120 c.belowAttackMs = static_cast<T>(r.read(key, 10.0f));
1121 std::snprintf(key, sizeof(key), "b%d.bRel", i);
1122 c.belowReleaseMs = static_cast<T>(r.read(key, 100.0f));
1123 std::snprintf(key, sizeof(key), "b%d.bRange", i);
1124 c.belowRangeDb = static_cast<T>(r.read(key, 12.0f));
1125 std::snprintf(key, sizeof(key), "b%d.bBoost", i);
1126 c.belowBoost = r.read(key, false);
1127 setBand(i, c);
1128 }
1129 setNumBands(n);
1130 // Blobs written before the key existed were rendered without lookahead.
1131 setLookahead(static_cast<T>(r.read("lookahead", 0.0f)));
1132 setMixedBands(r.read("mixed", false));
1133 setLinkMode(static_cast<LinkMode>(r.read("linkMode", 0)));
1134 setStructure(static_cast<Structure>(r.read("structure", 0)));
1135 setLinearPhaseKernelLength(r.read("linearTaps", 0));
1136 setLinearPhase(r.read("linear", false));
1137 return true;
1138 }
1139
1140private:
1141 static constexpr int kMaxChannels = 16;
1142 static constexpr T kMinLevelDb = T(-100.0);
1143 static constexpr T kMinEnvelope = T(1e-12); // Prevents NaN in log10
1144 static constexpr int kDetChunk = 64;
1145
1146 // Program timing. The followers count their times in units of the time
1147 // constant of the detector's own envelope (Q / (pi f) for a band-pass),
1148 // each with a floor: a band cannot know its level sooner than its filter
1149 // lets it, and a narrow or low band is slower for that reason alone.
1150 static constexpr double kDetectorNarrowing = 1.5;
1151 static constexpr double kFastRiseFloor = 0.0003;
1152 static constexpr double kFastFallUnits = 12.0;
1153 static constexpr double kFastFallFloor = 0.020;
1154 static constexpr double kSlowRiseUnits = 40.0;
1155 static constexpr double kSlowRiseFloor = 0.080;
1156 static constexpr double kSlowFallUnits = 150.0;
1157 static constexpr double kSlowFallFloor = 0.400;
1158 static constexpr double kLastFallShare = 0.25;
1159 static constexpr double kDbPerNeper = 8.685889638065037;
1160
1161 static constexpr double kReferenceFallDb = 2.0;
1162 static constexpr double kReferenceWatch = 0.5;
1163 static constexpr double kZoneFloorHz = 10.0;
1164 static constexpr double kListenFadeMs = 10.0;
1165
1166 static constexpr double kKneePerOctave = 3.0;
1167 static constexpr double kMixedRampMs = 20.0;
1168 static constexpr double kRestDb = 0.01;
1169
1170 struct BandState
1171 {
1172 BandConfig cfg;
1173 T aboveAtkCoeff = T(0), aboveRelCoeff = T(0);
1174 T belowAtkCoeff = T(0), belowRelCoeff = T(0);
1175 T knee = T(0);
1176 bool zoned = false;
1177
1178 // Program timing: the three followers, in amplitude.
1179 double fastUp = 1.0, fastDown = 1.0, slowUp = 1.0, slowDown = 1.0, lastDown = 1.0;
1180 double fast = 0.0, slow = 0.0, heard = 0.0;
1181
1182 // Relative threshold: the reference level and the one that listens to a new zone.
1183 double reference = -100.0, candidate = -100.0;
1184 double referenceFall = 0.0;
1185 int watching = 0;
1186
1187 // Mixed engine.
1188 bool rests = false;
1189 bool cuts = false, lifts = false;
1190 double cutScale = 0.0, liftScale = 0.0;
1191 // The reach of each end (1 - end and end - 1) on its way to a new range, with the filters.
1192 double cutReach = 0.0, liftReach = 0.0, cutReachGoal = 0.0, liftReachGoal = 0.0;
1193 double cutReachStep = 0.0, liftReachStep = 0.0;
1194 int reachRamp = 0;
1195 bool designed = false;
1196 };
1197
1199 struct MixedBand
1200 {
1201 BiquadCascade<T, 1, kMaxChannels> rest, cut, lift;
1202 };
1203
1205 struct MixedEngine
1206 {
1207 std::array<MixedBand, MaxBands> bands;
1208 std::array<std::array<T, kDetChunk>, kMaxChannels> cut {}, lift {};
1209 std::array<std::array<T, kDetChunk>, kMaxChannels> held {};
1210 std::array<double, kDetChunk> cutWeight {}, liftWeight {};
1211 };
1212
1213 [[nodiscard]] static bool ofThePair(const BandConfig& cfg) noexcept
1214 {
1215 return cfg.scope == Scope::Mid || cfg.scope == Scope::Side;
1216 }
1217
1219 struct DetectorDesign
1220 {
1221 BiquadCoeffs first, second;
1222 bool two = false;
1223 double unit = 0.0;
1224 };
1225
1241 [[nodiscard]] static DetectorDesign designDetector(const BandConfig& cfg, double fs) noexcept
1242 {
1243 DetectorDesign d;
1244 const double top = 0.45 * fs;
1245 const double low = static_cast<double>(cfg.listenLow), high = static_cast<double>(cfg.listenHigh);
1246 if (low > 0.0 && high > 0.0)
1247 {
1248 const double lo = std::clamp(low, kZoneFloorHz, top), hi = std::clamp(high, kZoneFloorHz, top);
1249 d.first = BiquadCoeffs::makeHighPassMatched(fs, lo, T(0.707));
1250 d.second = BiquadCoeffs::makeLowPassMatched(fs, hi, T(0.707));
1251 d.two = true;
1252 const double middle = std::sqrt(lo * hi);
1253 const double there = d.first.getMagnitude(middle, fs) * d.second.getMagnitude(middle, fs);
1254 if (there > 1e-3)
1255 {
1256 d.first.b0 /= there;
1257 d.first.b1 /= there;
1258 d.first.b2 /= there;
1259 }
1260 // Two sections on one corner are still a band about that wide.
1261 d.unit = 1.0 / (std::numbers::pi * std::max(hi - lo, middle));
1262 return d;
1263 }
1264 if (low > 0.0 || high > 0.0)
1265 {
1266 const double edge = std::clamp(low > 0.0 ? low : high, kZoneFloorHz, top);
1267 d.first = low > 0.0 ? BiquadCoeffs::makeHighPassMatched(fs, edge, T(0.707))
1268 : BiquadCoeffs::makeLowPassMatched(fs, edge, T(0.707));
1269 d.unit = 1.0 / (std::numbers::pi * edge);
1270 return d;
1271 }
1272
1273 const bool program = cfg.timing == Timing::Program;
1274 const T detectorQ = program ? cfg.q * static_cast<T>(kDetectorNarrowing) : cfg.q;
1275 const double hz = std::clamp(static_cast<double>(cfg.frequency), 10.0, top);
1276 switch (cfg.shape)
1277 {
1278 case BandShape::Bell:
1279 d.first = BiquadCoeffs::makeBandPassMatched(fs, cfg.frequency, detectorQ);
1280 d.unit = std::max(static_cast<double>(detectorQ), 0.1) / (std::numbers::pi * hz);
1281 break;
1283 d.first = BiquadCoeffs::makeLowPassMatched(fs, cfg.frequency, T(0.707));
1284 d.unit = 1.0 / (std::numbers::pi * hz);
1285 break;
1287 d.first = BiquadCoeffs::makeHighPassMatched(fs, cfg.frequency, T(0.707));
1288 d.unit = 1.0 / (std::numbers::pi * hz);
1289 break;
1290 }
1291 return d;
1292 }
1293
1295 [[nodiscard]] int runFactor() const noexcept { return linearWanted_ ? 1 : std::max(oversamplingFactor_, 1); }
1296
1298 [[nodiscard]] static bool plays(const BandConfig& cfg, int numChannels) noexcept
1299 {
1300 if (!cfg.enabled) return false;
1301 return numChannels >= 2 || (cfg.scope != Scope::Right && cfg.scope != Scope::Side);
1302 }
1303
1304 void processCore(AudioBufferView<T>& audio, AudioBufferView<T>& sidechain, double currentFs) noexcept
1305 {
1306 const int nCh = std::min(audio.getNumChannels(), kMaxChannels);
1307 const int scCh = sidechain.getNumChannels();
1308 const int nS = audio.getNumSamples();
1309 if (scCh <= 0) return; // a 0-channel sidechain would index getChannel(-1)
1310 const int nb = numBands_.load(std::memory_order_relaxed);
1311 const int laSamples = lookaheadSamples_.load(std::memory_order_relaxed);
1312 dominantLink_ = linkMode_.load(std::memory_order_relaxed) == LinkMode::Dominant && nCh == 2;
1313 if (dominantLink_)
1314 {
1315 if (currentFs != linkRate_)
1316 {
1317 linkRate_ = currentFs;
1318 linkCoeff_ = 1.0 - std::exp(-1.0 / (0.02 * currentFs));
1319 }
1320 for (auto& c : bandCov_)
1321 for (double& v : c) if (std::abs(v) < 1e-30) v = 0.0; // no subnormals in silence
1322 }
1323
1324 // A change of structure: the bands' filters restart in the new one.
1325 const bool ladder = structure_.load(std::memory_order_relaxed) == Structure::Ladder;
1326 if (ladder != ladderActive_)
1327 {
1328 ladderActive_ = ladder;
1329 for (int b = 0; b < MaxBands; ++b)
1330 {
1331 bandFilter_[b].reset();
1332 bandLadder_[static_cast<size_t>(b)].reset();
1333 bandLadder_[static_cast<size_t>(b)].setCoeffs(bandFilter_[b].getCoeffs());
1334 }
1335 }
1336
1337 // A change of engine: every band starts clean in the new one.
1338 const bool mixed = mixedWanted_.load(std::memory_order_relaxed) && mixedEngine_ != nullptr && !linear_;
1339 if (mixed != mixedActive_)
1340 {
1341 mixedActive_ = mixed;
1342 for (int b = 0; b < MaxBands; ++b) restartBand(b);
1343 }
1344
1345 // Bands re-activated by a band-count increase start clean: they would
1346 // otherwise replay the gain and filter state from when they were last
1347 // active (a boosted band re-added on a 0.001 tone peaked at 5.4).
1348 if (nb > lastNumBands_)
1349 for (int b = lastNumBands_; b < nb; ++b) restartBand(b);
1350 lastNumBands_ = nb;
1351
1352 // 1. Thread-Safe State Update
1353 for (int b = 0; b < nb; ++b)
1354 {
1355 if (paramsDirty_[b].exchange(false, std::memory_order_acquire))
1356 updateBandInternalState(b, currentFs);
1357 }
1358
1359 // The bands that play, in the order they are applied: the stereo, left
1360 // and right ones first, then the ones of the middle and the sides.
1361 numFirst_ = numSecond_ = 0;
1362 for (int b = 0; b < nb; ++b)
1363 {
1364 playing_[static_cast<size_t>(b)] = plays(states_[b].cfg, nCh);
1365 if (!playing_[static_cast<size_t>(b)]) continue;
1366 if (ofThePair(states_[b].cfg)) second_[static_cast<size_t>(numSecond_++)] = b;
1367 else first_[static_cast<size_t>(numFirst_++)] = b;
1368 }
1369 if (linear_) serviceLinear(nb);
1370
1371 // 2. Chunks: the detection and the gain of every band run first, band
1372 // by band and channel by channel, so each detector (and its allpass
1373 // pair) keeps its state in registers; the filters then run over
1374 // the chunk. Feed-forward, so the order changes nothing.
1375 for (int chunkStart = 0; chunkStart < nS; chunkStart += kDetChunk)
1376 {
1377 const int chunkLen = std::min(kDetChunk, nS - chunkStart);
1378
1379 for (int b = 0; b < nb; ++b)
1380 {
1381 if (!playing_[static_cast<size_t>(b)]) continue;
1382 detectBand(b, sidechain, chunkStart, chunkLen, nCh, scCh);
1383 computeGains(b, chunkLen);
1384 }
1385
1386 if (linear_) applyLinear(audio, chunkStart, chunkLen, nCh, laSamples);
1387 else if (mixedActive_) applyMixed(audio, chunkStart, chunkLen, nCh, laSamples);
1388 else applyRedesigned(audio, chunkStart, chunkLen, nCh, nb, laSamples, currentFs);
1389 }
1390 }
1391
1393 void setBandCoeffs(int b, const BiquadCoeffs& c) noexcept
1394 {
1395 bandFilter_[b].setCoeffsNow(c);
1396 if (ladderActive_) bandLadder_[static_cast<size_t>(b)].setCoeffs(c);
1397 }
1398
1400 T runBand(int b, T x, int ch) noexcept
1401 {
1402 if (ladderActive_)
1403 return static_cast<T>(bandLadder_[static_cast<size_t>(b)].processSample(static_cast<double>(x), ch));
1404 return bandFilter_[b].processSample(x, ch);
1405 }
1406
1415 void detectBand(int b, AudioBufferView<T>& sidechain, int start, int n, int nCh, int scCh) noexcept
1416 {
1417 const BandConfig& cfg = states_[b].cfg;
1418 const bool program = cfg.timing == Timing::Program;
1419 T* levels = detLevelDb_[static_cast<size_t>(b)].data();
1420 std::fill(levels, levels + n, kMinLevelDb);
1421 if (program) std::fill(detLinear_.begin(), detLinear_.begin() + n, 0.0);
1422
1423 const Scope where = cfg.scope;
1424 const int listeners = where == Scope::Stereo ? nCh : 1;
1425 const bool dominant = dominantLink_ && where == Scope::Stereo;
1426 for (int k = 0; k < listeners; ++k)
1427 {
1428 int slot = k;
1429 const T* first = sidechain.getChannel(std::min(k, scCh - 1)) + start;
1430 const T* second = nullptr;
1431 T sign = T(1);
1432 if (where == Scope::Right)
1433 {
1434 slot = 1;
1435 first = sidechain.getChannel(std::min(1, scCh - 1)) + start;
1436 }
1437 else if (where == Scope::Mid || where == Scope::Side)
1438 {
1439 if (scCh >= 2) second = sidechain.getChannel(1) + start;
1440 else if (where == Scope::Side) break; // one channel has no sides: silence
1441 sign = where == Scope::Mid ? T(1) : T(-1);
1442 }
1443
1444 if (second == nullptr)
1445 {
1446 for (int j = 0; j < n; ++j)
1447 detBand_[static_cast<size_t>(j)] = static_cast<double>(bandDetector_[b].processSample(
1448 std::isfinite(first[j]) ? first[j] : T(0), slot)); // non-finite would latch
1449 }
1450 else
1451 {
1452 for (int j = 0; j < n; ++j)
1453 {
1454 const T one = std::isfinite(first[j]) ? first[j] : T(0);
1455 const T other = std::isfinite(second[j]) ? second[j] : T(0);
1456 detBand_[static_cast<size_t>(j)] = static_cast<double>(
1457 bandDetector_[b].processSample((one + sign * other) * T(0.5), slot));
1458 }
1459 }
1460 if (states_[b].zoned)
1461 {
1462 // A zone with both edges: the low-pass after the high-pass.
1463 for (int j = 0; j < n; ++j)
1464 detBand_[static_cast<size_t>(j)] = static_cast<double>(bandZone_[b].processSample(
1465 static_cast<T>(detBand_[static_cast<size_t>(j)]), slot));
1466 }
1467 analytic_[static_cast<size_t>(b * kMaxChannels + slot)].magnitudeBlock(
1468 detBand_.data(), detMag_.data(), n);
1469
1470 // The dominant link reads the pair once the second channel is in.
1471 if (dominant)
1472 {
1473 if (k == 0)
1474 {
1475 std::copy_n(detBand_.begin(), n, pairBand_.begin());
1476 std::copy_n(detMag_.begin(), n, pairMag_.begin());
1477 continue;
1478 }
1479 auto& cov = bandCov_[static_cast<size_t>(b)];
1480 for (int j = 0; j < n; ++j)
1481 {
1482 const size_t s = static_cast<size_t>(j);
1483 const double l = pairBand_[s], r = detBand_[s];
1484 cov[0] += linkCoeff_ * (l * l - cov[0]);
1485 cov[1] += linkCoeff_ * (r * r - cov[1]);
1486 cov[2] += linkCoeff_ * (l * r - cov[2]);
1487 const double den = cov[0] * cov[1];
1488 const double rho2 = den > 1e-60 ? std::min(1.0, cov[2] * cov[2] / den) : 0.0;
1489 const double amp = dominantPairLevel(std::max(std::abs(l), pairMag_[s]),
1490 std::max(std::abs(r), detMag_[s]), rho2);
1491 if (program) detLinear_[s] = amp;
1492 else levels[j] = gainToDecibels(std::max(static_cast<T>(amp), kMinEnvelope));
1493 }
1494 continue;
1495 }
1496
1497 // max(|x|, analytic magnitude): a steady tone reads as its flat
1498 // amplitude, not a rectified wave (see @file).
1499 if (program)
1500 {
1501 for (int j = 0; j < n; ++j)
1502 detLinear_[static_cast<size_t>(j)] = std::max(detLinear_[static_cast<size_t>(j)],
1503 std::max(std::abs(detBand_[static_cast<size_t>(j)]), detMag_[static_cast<size_t>(j)]));
1504 }
1505 else
1506 {
1507 for (int j = 0; j < n; ++j)
1508 {
1509 const T detected = std::max(static_cast<T>(std::abs(detBand_[static_cast<size_t>(j)])),
1510 static_cast<T>(detMag_[static_cast<size_t>(j)]));
1511 const T levelDb = gainToDecibels(std::max(detected, kMinEnvelope));
1512 if (levelDb > levels[j]) levels[j] = levelDb;
1513 }
1514 }
1515 }
1516 }
1517
1522 void computeGains(int b, int n) noexcept
1523 {
1524 BandState& st = states_[b];
1525 const BandConfig& cfg = st.cfg;
1526 const bool program = cfg.timing == Timing::Program;
1527 const T* levels = detLevelDb_[static_cast<size_t>(b)].data();
1528 T* gains = dynDb_[static_cast<size_t>(b)].data();
1529 T& currentGain = currentGainDb_[b];
1530
1531 for (int j = 0; j < n; ++j)
1532 {
1533 T levelDb;
1534 if (program)
1535 {
1536 // Fast; slow, which follows the fast; and a last one over the
1537 // larger of the two, which takes the corner out of the hand-over.
1538 const double x = detLinear_[static_cast<size_t>(j)];
1539 st.fast += (x > st.fast ? st.fastUp : st.fastDown) * (x - st.fast);
1540 st.slow += (st.fast > st.slow ? st.slowUp : st.slowDown) * (st.fast - st.slow);
1541 const double larger = std::max(st.fast, st.slow);
1542 st.heard = larger > st.heard ? larger : st.heard + st.lastDown * (larger - st.heard);
1543 levelDb = std::max(static_cast<T>(fastLog(std::max(st.heard, 1e-12)) * kDbPerNeper), kMinLevelDb);
1544 }
1545 else
1546 {
1547 levelDb = levels[j];
1548 }
1549
1550 T threshold = cfg.threshold;
1551 if (cfg.relativeThreshold)
1552 {
1553 const double level = static_cast<double>(levelDb);
1554 st.reference = std::max(level, st.reference - st.referenceFall);
1555 if (st.watching > 0)
1556 {
1557 st.candidate = std::max(level, st.candidate - st.referenceFall);
1558 if (--st.watching == 0) st.reference = st.candidate;
1559 }
1560 threshold = static_cast<T>(st.reference + static_cast<double>(cfg.threshold));
1561 }
1562
1563 // Gain Computer
1564 const T targetGainDb = computeTargetGain(cfg, levelDb, threshold, st.knee);
1565
1566 if (program)
1567 {
1568 currentGain = targetGainDb; // the followers have set the pace
1569 }
1570 else
1571 {
1572 // Gain Ballistics (Attack/Release applied to the Gain itself)
1573 const T diff = targetGainDb - currentGain;
1574 T coeff;
1575 if (levelDb > threshold) {
1576 coeff = (std::abs(targetGainDb) > std::abs(currentGain))
1577 ? st.aboveAtkCoeff : st.aboveRelCoeff;
1578 } else {
1579 coeff = (std::abs(targetGainDb) > std::abs(currentGain))
1580 ? st.belowAtkCoeff : st.belowRelCoeff;
1581 }
1582 currentGain += coeff * diff;
1583 }
1584 gains[j] = currentGain;
1585 }
1586
1587 // A follower left to fall for long reaches numbers too small to carry.
1588 if (st.fast < 1e-30) st.fast = 0.0;
1589 if (st.slow < 1e-30) st.slow = 0.0;
1590 if (st.heard < 1e-30) st.heard = 0.0;
1591 }
1592
1597 void applyRedesigned(AudioBufferView<T>& audio, int start, int n, int nCh, int nb,
1598 int laSamples, double currentFs) noexcept
1599 {
1600 for (int j = 0; j < n; ++j)
1601 {
1602 const int i = start + j;
1603 for (int b = 0; b < nb; ++b)
1604 {
1605 if (!playing_[static_cast<size_t>(b)]) continue;
1606 const T currentGain = dynDb_[static_cast<size_t>(b)][static_cast<size_t>(j)];
1607
1608 // Refresh gain-filter coefficients every 16 samples - the gain
1609 // envelope is slow enough that this granularity is inaudible.
1610 // The grid is a free-running counter, not the block index, so
1611 // the output does not depend on how the host cuts the stream.
1612 // Bells run the matched design; at 1/16th rate it stays
1613 // negligible (+1.6% CPU over the cookbook form).
1614 // Stream-owner direct writes (setCoeffsNow): these values are
1615 // computed HERE, on the audio thread, for this thread's own
1616 // use, so they never touch the staged cross-thread channel.
1617 if ((refreshCounter_ & 15u) == 0u)
1618 {
1619 const T total = states_[b].cfg.gain + currentGain;
1620 if (std::abs(total) > T(0.01))
1621 {
1622 switch (states_[b].cfg.shape)
1623 {
1624 case BandShape::Bell:
1625 setBandCoeffs(b, BiquadCoeffs::makePeakMatched(
1626 currentFs, static_cast<double>(states_[b].cfg.frequency),
1627 static_cast<double>(states_[b].cfg.q), static_cast<double>(total)));
1628 break;
1630 setBandCoeffs(b, BiquadCoeffs::makeLowShelf(
1631 currentFs, static_cast<double>(states_[b].cfg.frequency),
1632 static_cast<double>(total)));
1633 break;
1635 setBandCoeffs(b, BiquadCoeffs::makeHighShelf(
1636 currentFs, static_cast<double>(states_[b].cfg.frequency),
1637 static_cast<double>(total)));
1638 break;
1639 }
1640 }
1641 else
1642 setBandCoeffs(b, BiquadCoeffs{}); // Bypass
1643 }
1644
1645 if ((refreshCounter_ & 63u) == 0u) // Sub-sample metering update
1646 meterGainDb_[b].store(currentGain, std::memory_order_relaxed);
1647 }
1648 ++refreshCounter_;
1649
1650 // The frame, delayed by the lookahead. A non-finite sample passes
1651 // without entering the filter state, where it would latch for good.
1652 T frame[kMaxChannels] = {};
1653 bool finite[kMaxChannels] = {};
1654 for (int ch = 0; ch < nCh; ++ch)
1655 {
1656 T audioSample = audio.getChannel(ch)[i];
1657 if (laSamples > 0) {
1658 lookaheadBuf_[ch].push(audioSample);
1659 audioSample = lookaheadBuf_[ch].read(laSamples);
1660 }
1661 frame[ch] = audioSample;
1662 finite[ch] = std::isfinite(audioSample);
1663 }
1664
1665 for (int k = 0; k < numFirst_; ++k)
1666 {
1667 const int b = first_[static_cast<size_t>(k)];
1668 switch (states_[b].cfg.scope)
1669 {
1670 case Scope::Left:
1671 if (finite[0]) frame[0] = runBand(b, frame[0], 0);
1672 break;
1673 case Scope::Right:
1674 if (finite[1]) frame[1] = runBand(b, frame[1], 1);
1675 break;
1676 default:
1677 for (int ch = 0; ch < nCh; ++ch)
1678 if (finite[ch]) frame[ch] = runBand(b, frame[ch], ch);
1679 break;
1680 }
1681 }
1682
1683 if (numSecond_ > 0 && finite[0] && (nCh < 2 || finite[1]))
1684 {
1685 // The middle and the sides of the pair (one channel is its own middle).
1686 T middle = frame[0], sides = T(0);
1687 if (nCh >= 2)
1688 {
1689 middle = (frame[0] + frame[1]) * T(0.5);
1690 sides = (frame[0] - frame[1]) * T(0.5);
1691 }
1692 for (int k = 0; k < numSecond_; ++k)
1693 {
1694 const int b = second_[static_cast<size_t>(k)];
1695 if (states_[b].cfg.scope == Scope::Mid)
1696 middle = runBand(b, middle, 0);
1697 else
1698 sides = runBand(b, sides, 0);
1699 }
1700 if (nCh >= 2)
1701 {
1702 frame[0] = middle + sides;
1703 frame[1] = middle - sides;
1704 }
1705 else
1706 {
1707 frame[0] = middle;
1708 }
1709 }
1710
1711 for (int ch = 0; ch < nCh; ++ch)
1712 audio.getChannel(ch)[i] = frame[ch];
1713 }
1714 }
1715
1720 void applyMixed(AudioBufferView<T>& audio, int start, int n, int nCh, int laSamples) noexcept
1721 {
1722 MixedEngine& engine = *mixedEngine_;
1723 T* channels[kMaxChannels] = {};
1724 bool bad[kMaxChannels] = {}; // channels with a non-finite sample in this chunk
1725 bool anyBad = false;
1726
1727 // The chunk, delayed by the lookahead. A non-finite sample stays out
1728 // of the filters and goes back to its place at the end.
1729 for (int ch = 0; ch < nCh; ++ch)
1730 {
1731 T* data = audio.getChannel(ch) + start;
1732 channels[ch] = data;
1733 if (laSamples > 0)
1734 for (int j = 0; j < n; ++j)
1735 {
1736 lookaheadBuf_[ch].push(data[j]);
1737 data[j] = lookaheadBuf_[ch].read(laSamples);
1738 }
1739 for (int j = 0; j < n; ++j)
1740 if (!std::isfinite(data[j]))
1741 {
1742 auto& held = engine.held[static_cast<size_t>(ch)];
1743 if (!bad[ch]) held.fill(T(0));
1744 held[static_cast<size_t>(j)] = data[j];
1745 data[j] = T(0);
1746 bad[ch] = anyBad = true;
1747 }
1748 }
1749
1750 for (int k = 0; k < numFirst_; ++k)
1751 {
1752 const int b = first_[static_cast<size_t>(k)];
1753 const Scope where = states_[b].cfg.scope;
1754 if (where == Scope::Stereo)
1755 {
1756 mixBand(b, AudioBufferView<T>(channels, nCh, n), n);
1757 }
1758 else
1759 {
1760 T* single[1] = { channels[where == Scope::Left ? 0 : 1] };
1761 mixBand(b, AudioBufferView<T>(single, 1, n), n);
1762 }
1763 }
1764
1765 if (numSecond_ > 0)
1766 {
1767 AudioBufferView<T> pair(channels, nCh, n);
1768 if (nCh >= 2) MidSide<T>::encode(pair);
1769 for (int k = 0; k < numSecond_; ++k)
1770 {
1771 const int b = second_[static_cast<size_t>(k)];
1772 T* single[1] = { channels[states_[b].cfg.scope == Scope::Mid ? 0 : 1] };
1773 mixBand(b, AudioBufferView<T>(single, 1, n), n);
1774 }
1775 if (nCh >= 2) MidSide<T>::decode(pair);
1776 }
1777
1778 if (anyBad)
1779 for (int ch = 0; ch < nCh; ++ch)
1780 {
1781 if (!bad[ch]) continue;
1782 const auto& held = engine.held[static_cast<size_t>(ch)];
1783 for (int j = 0; j < n; ++j)
1784 if (!std::isfinite(held[static_cast<size_t>(j)])) channels[ch][j] = held[static_cast<size_t>(j)];
1785 }
1786 }
1787
1796 void mixBand(int b, AudioBufferView<T> where, int n) noexcept
1797 {
1798 BandState& st = states_[b];
1799 MixedEngine& engine = *mixedEngine_;
1800 MixedBand& filters = engine.bands[static_cast<size_t>(b)];
1801 const T* gains = dynDb_[static_cast<size_t>(b)].data();
1802 const int count = where.getNumChannels();
1803
1804 bool down = false, up = false;
1805 for (int j = 0; j < n; ++j)
1806 {
1807 if (st.reachRamp > 0) stepReach(st);
1808 const double d = static_cast<double>(gains[j]);
1809 const double cut = cutWeight(st, d), lift = liftWeight(st, d);
1810 engine.cutWeight[static_cast<size_t>(j)] = cut;
1811 engine.liftWeight[static_cast<size_t>(j)] = lift;
1812 down = down || cut > 0.0;
1813 up = up || lift > 0.0;
1814 }
1815 meterGainDb_[b].store(gains[n - 1], std::memory_order_relaxed);
1816
1817 // The filter at rest is a filter in series. The ends hear what comes
1818 // out of it, on copies: always, moving or not, so that their memory
1819 // is the signal's.
1820 if (st.rests) filters.rest.processBlock(where);
1821 T* copies[kMaxChannels] = {};
1822 if (st.cuts)
1823 {
1824 for (int ch = 0; ch < count; ++ch)
1825 {
1826 copies[ch] = engine.cut[static_cast<size_t>(ch)].data();
1827 std::copy_n(where.getChannel(ch), n, copies[ch]);
1828 }
1829 filters.cut.processBlock(AudioBufferView<T>(copies, count, n));
1830 }
1831 if (st.lifts)
1832 {
1833 for (int ch = 0; ch < count; ++ch)
1834 {
1835 copies[ch] = engine.lift[static_cast<size_t>(ch)].data();
1836 std::copy_n(where.getChannel(ch), n, copies[ch]);
1837 }
1838 filters.lift.processBlock(AudioBufferView<T>(copies, count, n));
1839 }
1840
1841 for (int ch = 0; ch < count; ++ch)
1842 {
1843 T* y = where.getChannel(ch);
1844 if (down)
1845 {
1846 const T* end = engine.cut[static_cast<size_t>(ch)].data();
1847 for (int j = 0; j < n; ++j)
1848 y[j] += static_cast<T>(engine.cutWeight[static_cast<size_t>(j)]) * (end[j] - y[j]);
1849 }
1850 if (up)
1851 {
1852 const T* end = engine.lift[static_cast<size_t>(ch)].data();
1853 for (int j = 0; j < n; ++j)
1854 y[j] += static_cast<T>(engine.liftWeight[static_cast<size_t>(j)]) * (end[j] - y[j]);
1855 }
1856 }
1857 }
1858
1859 // -- Linear phase ---------------------------------------------------------
1860
1861 static constexpr int kLinearBranches = 3;
1862 static constexpr int kLinearDefaultTaps = 4096;
1863 static constexpr int kLinearPartitions = 8;
1864
1866 struct LinearEngine
1867 {
1868 FirBank<T> bank;
1869 std::unique_ptr<FFTReal<T>> designFft;
1870 std::vector<T> spectrum, time, taps, window;
1871 std::array<RingBuffer<T>, kMaxChannels> dry;
1872 std::vector<T> weights;
1873 int weightMask = 0, weightPos = 0;
1874 std::array<std::array<bool, kLinearBranches>, MaxBands> pending {};
1875 std::array<bool, MaxBands> played {};
1876 std::array<std::array<T, kDetChunk>, kMaxChannels + 2> lines {};
1877 int next = 0;
1878 int kernel = 0, latency = 0, channels = 0;
1879 bool snap = true;
1880 };
1881
1883 [[nodiscard]] int resolveLinearTaps(double sampleRate) const noexcept
1884 {
1885 int taps = linearTaps_;
1886 if (taps <= 0)
1887 {
1888 taps = kLinearDefaultTaps;
1889 while (taps < 65536 && sampleRate > 1.5 * 48000.0 * (taps / kLinearDefaultTaps)) taps <<= 1;
1890 }
1891 int size = 1024;
1892 while (size < taps && size < 65536) size <<= 1;
1893 return size;
1894 }
1895
1897 [[nodiscard]] unsigned linearMask(const BandConfig& cfg) const noexcept
1898 {
1899 const int channels = linear_->channels;
1900 switch (cfg.scope)
1901 {
1902 case Scope::Left: return 1u;
1903 case Scope::Right: return channels >= 2 ? 2u : 0u;
1904 case Scope::Mid: return channels >= 2 ? 1u << channels : 1u;
1905 case Scope::Side: return channels >= 2 ? 1u << (channels + 1) : 0u;
1906 default: return (1u << channels) - 1u;
1907 }
1908 }
1909
1919 void designLinearBranch(int b, int branch) noexcept
1920 {
1921 LinearEngine& e = *linear_;
1922 const BandState& st = states_[b];
1923 const BandConfig& cfg = st.cfg;
1924 const int index = b * kLinearBranches + branch;
1925 const bool has = branch == 0 ? st.rests : (branch == 1 ? st.cuts : st.lifts);
1926 if (!has)
1927 {
1928 e.bank.removeKernel(index);
1929 return;
1930 }
1931
1932 const AnalogSection rest = prototypeOf(cfg, static_cast<double>(cfg.gain));
1933 const double range = branch == 1 ? -rangeTowards(cfg, false) : rangeTowards(cfg, true);
1934 const AnalogSection half = prototypeOf(cfg, 0.5 * range);
1935 const double reach = 1.0 + std::pow(10.0, range / 40.0);
1936 const int bins = e.kernel / 2;
1937 const double step = 2.0 * std::numbers::pi * sampleRate_ / static_cast<double>(e.kernel);
1938 for (int k = 0; k <= bins; ++k)
1939 {
1940 const double omega = step * static_cast<double>(k);
1941 const double atRest = st.rests ? std::sqrt(rest.magnitudeSquared(omega)) : 1.0;
1942 const double level = branch == 0 ? atRest - 1.0
1943 : atRest * reach * (std::sqrt(half.magnitudeSquared(omega)) - 1.0);
1944 e.spectrum[static_cast<size_t>(2 * k)] = static_cast<T>(level);
1945 e.spectrum[static_cast<size_t>(2 * k + 1)] = T(0);
1946 }
1947 e.designFft->inverse(e.spectrum.data(), e.time.data());
1948 // Centred on half the kernel, and windowed.
1949 const int centre = e.kernel / 2;
1950 for (int m = 0; m < e.kernel; ++m)
1951 e.taps[static_cast<size_t>(m)] = e.time[static_cast<size_t>((m + centre) % e.kernel)] * e.window[static_cast<size_t>(m)];
1952 e.bank.setKernel(index, e.taps.data(), linearMask(cfg));
1953 }
1954
1960 void serviceLinear(int nb) noexcept
1961 {
1962 LinearEngine& e = *linear_;
1963 for (int b = 0; b < MaxBands; ++b)
1964 {
1965 const auto at = static_cast<size_t>(b);
1966 const bool on = b < nb && playing_[at];
1967 if (on && !e.played[at])
1968 e.pending[at].fill(true);
1969 if (!on && e.played[at])
1970 for (int branch = 0; branch < kLinearBranches; ++branch)
1971 e.bank.removeKernel(b * kLinearBranches + branch);
1972 e.played[at] = on;
1973 }
1974
1975 const int total = MaxBands * kLinearBranches;
1976 for (int step = 0; step < total; ++step)
1977 {
1978 const int index = (e.next + step) % total;
1979 const int b = index / kLinearBranches, branch = index % kLinearBranches;
1980 if (!e.pending[static_cast<size_t>(b)][static_cast<size_t>(branch)]) continue;
1981 e.pending[static_cast<size_t>(b)][static_cast<size_t>(branch)] = false;
1982 if (!e.played[static_cast<size_t>(b)]) continue;
1983 designLinearBranch(b, branch);
1984 if (e.snap) continue;
1985 e.next = (index + 1) % total;
1986 break;
1987 }
1988 if (e.snap)
1989 {
1990 e.bank.reset(); // nothing has sounded: the kernels land with no fade
1991 e.snap = false;
1992 }
1993 }
1994
2003 void applyLinear(AudioBufferView<T>& audio, int start, int n, int nCh, int laSamples) noexcept
2004 {
2005 LinearEngine& e = *linear_;
2006 const size_t ring = static_cast<size_t>(e.weightMask) + 1u;
2007 const int lineChannels = std::min(nCh, e.channels);
2008 const bool pair = e.channels >= 2;
2009 const int delay = e.latency - std::clamp(laSamples, 0, e.latency);
2010
2011 // The weights of this chunk, into their delay.
2012 for (int k = 0; k < numFirst_ + numSecond_; ++k)
2013 {
2014 const int b = k < numFirst_ ? first_[static_cast<size_t>(k)] : second_[static_cast<size_t>(k - numFirst_)];
2015 const BandState& st = states_[b];
2016 const T* gains = dynDb_[static_cast<size_t>(b)].data();
2017 T* cuts = e.weights.data() + static_cast<size_t>(b * 2) * ring;
2018 T* lifts = cuts + ring;
2019 for (int j = 0; j < n; ++j)
2020 {
2021 const double d = static_cast<double>(gains[j]);
2022 const auto at = static_cast<size_t>((e.weightPos + j) & e.weightMask);
2023 cuts[at] = static_cast<T>(cutWeight(st, d));
2024 lifts[at] = static_cast<T>(liftWeight(st, d));
2025 }
2026 meterGainDb_[b].store(gains[n - 1], std::memory_order_relaxed);
2027 }
2028
2029 int done = 0;
2030 while (done < n)
2031 {
2032 const int run = std::min(n - done, e.bank.room());
2033
2034 // What the bank hears: the channels (a non-finite sample as
2035 // silence), and the middle and the sides of the pair.
2036 const T* heard[kMaxChannels + 2] = {};
2037 for (int ch = 0; ch < lineChannels; ++ch)
2038 {
2039 const T* x = audio.getChannel(ch) + start + done;
2040 T* line = e.lines[static_cast<size_t>(ch)].data();
2041 for (int j = 0; j < run; ++j) line[j] = std::isfinite(x[j]) ? x[j] : T(0);
2042 heard[ch] = line;
2043 }
2044 if (pair && lineChannels >= 1)
2045 {
2046 T* middle = e.lines[static_cast<size_t>(kMaxChannels)].data();
2047 T* sides = e.lines[static_cast<size_t>(kMaxChannels + 1)].data();
2048 const T* left = e.lines[0].data();
2049 if (lineChannels >= 2)
2050 {
2051 const T* right = e.lines[1].data();
2052 for (int j = 0; j < run; ++j)
2053 {
2054 middle[j] = (left[j] + right[j]) * T(0.5);
2055 sides[j] = (left[j] - right[j]) * T(0.5);
2056 }
2057 heard[e.channels + 1] = sides;
2058 }
2059 else
2060 {
2061 std::copy_n(left, run, middle); // one channel is its own middle
2062 }
2063 heard[e.channels] = middle;
2064 }
2065
2066 // The signal, late.
2067 for (int ch = 0; ch < nCh; ++ch)
2068 {
2069 T* y = audio.getChannel(ch) + start + done;
2070 for (int j = 0; j < run; ++j)
2071 {
2072 e.dry[ch].push(y[j]);
2073 y[j] = e.dry[ch].read(e.latency);
2074 }
2075 }
2076
2077 // What each branch of each band adds.
2078 for (int k = 0; k < numFirst_ + numSecond_; ++k)
2079 {
2080 const int b = k < numFirst_ ? first_[static_cast<size_t>(k)] : second_[static_cast<size_t>(k - numFirst_)];
2081 const Scope where = states_[b].cfg.scope;
2082 const T* sideWeights[kLinearBranches] = { nullptr, e.weights.data() + static_cast<size_t>(b * 2) * ring,
2083 e.weights.data() + static_cast<size_t>(b * 2 + 1) * ring };
2084 for (int branch = 0; branch < kLinearBranches; ++branch)
2085 {
2086 const int index = b * kLinearBranches + branch;
2087 if (e.bank.isKernelSilent(index)) continue;
2088 const T* weights = sideWeights[branch];
2089 const auto add = [&](int line, int ch, T sign) noexcept {
2090 if (ch >= nCh) return;
2091 const T* wet = e.bank.tap(index, line);
2092 T* y = audio.getChannel(ch) + start + done;
2093 if (weights == nullptr)
2094 {
2095 for (int j = 0; j < run; ++j) y[j] += sign * wet[j];
2096 return;
2097 }
2098 for (int j = 0; j < run; ++j)
2099 y[j] += sign * weights[static_cast<size_t>((e.weightPos + done + j - delay) & e.weightMask)] * wet[j];
2100 };
2101 switch (where)
2102 {
2103 case Scope::Left: add(0, 0, T(1)); break;
2104 case Scope::Right: add(1, 1, T(1)); break;
2105 case Scope::Mid:
2106 add(pair ? e.channels : 0, 0, T(1));
2107 if (pair) add(e.channels, 1, T(1));
2108 break;
2109 case Scope::Side:
2110 if (pair) { add(e.channels + 1, 0, T(1)); add(e.channels + 1, 1, T(-1)); }
2111 break;
2112 default:
2113 for (int ch = 0; ch < lineChannels; ++ch) add(ch, ch, T(1));
2114 break;
2115 }
2116 }
2117 }
2118
2119 e.bank.push(heard, run);
2120 done += run;
2121 }
2122 e.weightPos = (e.weightPos + n) & e.weightMask;
2123 }
2124
2131 [[nodiscard]] static T computeTargetGain(const BandConfig& cfg, T levelDb, T threshold, T knee) noexcept
2132 {
2133 T gainDb = T(0);
2134
2135 if (knee > T(0))
2136 {
2137 const T over = levelDb - threshold;
2138 const T half = knee * T(0.5);
2139 if (cfg.aboveRatio > T(1.001) && over > -half)
2140 {
2141 const T bent = over < half ? (over + half) * (over + half) / (T(2) * knee) : over;
2142 const T amount = std::min(bent * (T(1) - T(1) / cfg.aboveRatio), cfg.aboveRangeDb);
2143 gainDb += cfg.aboveBoost ? amount : -amount;
2144 }
2145 if (cfg.belowRatio > T(1.001) && over < half)
2146 {
2147 const T under = -over;
2148 const T bent = under < half ? (under + half) * (under + half) / (T(2) * knee) : under;
2149 const T amount = std::min(bent * (T(1) - T(1) / cfg.belowRatio), cfg.belowRangeDb);
2150 gainDb += cfg.belowBoost ? amount : -amount;
2151 }
2152 return gainDb;
2153 }
2154
2155 if (levelDb > threshold)
2156 {
2157 if (cfg.aboveRatio > T(1.001)) {
2158 T overDb = levelDb - threshold;
2159 T amount = std::min(overDb * (T(1) - T(1) / cfg.aboveRatio), cfg.aboveRangeDb);
2160 gainDb += cfg.aboveBoost ? amount : -amount;
2161 }
2162 }
2163 else
2164 {
2165 if (cfg.belowRatio > T(1.001)) {
2166 T underDb = threshold - levelDb;
2167 T amount = std::min(underDb * (T(1) - T(1) / cfg.belowRatio), cfg.belowRangeDb);
2168 gainDb += cfg.belowBoost ? amount : -amount;
2169 }
2170 }
2171 return gainDb;
2172 }
2173
2175 void cleanBand(int b) noexcept
2176 {
2177 bandDetector_[b].reset();
2178 bandZone_[b].reset();
2179 bandFilter_[b].reset();
2180 bandLadder_[static_cast<size_t>(b)].reset();
2181 currentGainDb_[b] = T(0);
2182 BandState& st = states_[b];
2183 st.fast = st.slow = st.heard = 0.0;
2184 st.reference = st.candidate = static_cast<double>(kMinLevelDb);
2185 st.watching = 0;
2186 st.designed = false;
2187 if (!analytic_.empty()) // allocated in prepare()
2188 for (int ch = 0; ch < kMaxChannels; ++ch)
2189 analytic_[static_cast<size_t>(b * kMaxChannels + ch)].reset();
2190 if (mixedEngine_)
2191 {
2192 MixedBand& filters = mixedEngine_->bands[static_cast<size_t>(b)];
2193 filters.rest.reset();
2194 filters.cut.reset();
2195 filters.lift.reset();
2196 }
2197 if (linear_)
2198 {
2199 const size_t ring = static_cast<size_t>(linear_->weightMask) + 1u;
2200 std::fill_n(linear_->weights.begin() + static_cast<std::ptrdiff_t>(static_cast<size_t>(b * 2) * ring),
2201 2u * ring, T(0));
2202 }
2203 }
2204
2206 void restartBand(int b) noexcept
2207 {
2208 cleanBand(b);
2209 meterGainDb_[b].store(T(0), std::memory_order_relaxed);
2210 paramsDirty_[b].store(true, std::memory_order_release);
2211 }
2212
2214 [[nodiscard]] static std::complex<double> responseOf(const BiquadCoeffs& c, double hz, double fs) noexcept
2215 {
2216 const double w = 2.0 * std::numbers::pi * std::clamp(hz, 0.0, 0.5 * fs) / fs;
2217 const std::complex<double> z1 = std::polar(1.0, -w), z2 = std::polar(1.0, -2.0 * w);
2218 return (c.b0 + c.b1 * z1 + c.b2 * z2) / (1.0 + c.a1 * z1 + c.a2 * z2);
2219 }
2220
2222 [[nodiscard]] static double rangeTowards(const BandConfig& cfg, bool boost) noexcept
2223 {
2224 double range = 0.0;
2225 if (cfg.aboveRatio > T(1.001) && cfg.aboveBoost == boost)
2226 range = std::max(range, static_cast<double>(cfg.aboveRangeDb));
2227 if (cfg.belowRatio > T(1.001) && cfg.belowBoost == boost)
2228 range = std::max(range, static_cast<double>(cfg.belowRangeDb));
2229 return range;
2230 }
2231
2233 [[nodiscard]] static AnalogSection prototypeOf(const BandConfig& cfg, double gainDb) noexcept
2234 {
2235 const double hz = std::clamp(static_cast<double>(cfg.frequency), 1.0, 80000.0);
2236 const double q = std::max(static_cast<double>(cfg.q), 0.025);
2237 const double gain = std::clamp(gainDb, -96.0, 96.0);
2238 switch (cfg.shape)
2239 {
2240 case BandShape::LowShelf: return AnalogSection::lowShelf(hz, gain);
2241 case BandShape::HighShelf: return AnalogSection::highShelf(hz, gain);
2242 default: return AnalogSection::peak(hz, q, gain);
2243 }
2244 }
2245
2247 [[nodiscard]] BiquadCoeffs designShape(const BandConfig& cfg, double gainDb) const noexcept
2248 {
2249 return FilterDesign::digital(prototypeOf(cfg, gainDb), designBand_);
2250 }
2251
2253 struct Sides
2254 {
2255 bool rests = false, cuts = false, lifts = false;
2256 double cutRange = 0.0, liftRange = 0.0;
2257 };
2258
2259 [[nodiscard]] static Sides sidesOf(const BandConfig& cfg) noexcept
2260 {
2261 Sides s;
2262 s.cutRange = rangeTowards(cfg, false);
2263 s.liftRange = rangeTowards(cfg, true);
2264 s.cuts = s.cutRange > kRestDb;
2265 s.lifts = s.liftRange > kRestDb;
2266 s.rests = std::abs(static_cast<double>(cfg.gain)) > kRestDb;
2267 return s;
2268 }
2269
2283 static void adoptSides(BandState& st, const Sides& s, int ramp = 0) noexcept
2284 {
2285 const double cutGoal = s.cuts ? 1.0 - std::pow(10.0, -s.cutRange / 20.0) : 0.0;
2286 const double liftGoal = s.lifts ? std::pow(10.0, s.liftRange / 20.0) - 1.0 : 0.0;
2287 // A side that was not playing, or a band without a design, starts at its reach.
2288 const bool glide = ramp > 0 && st.designed;
2289 const bool cutGlides = glide && st.cuts && s.cuts, liftGlides = glide && st.lifts && s.lifts;
2290 st.cutReachGoal = cutGoal;
2291 st.liftReachGoal = liftGoal;
2292 if (!cutGlides) st.cutReach = cutGoal;
2293 if (!liftGlides) st.liftReach = liftGoal;
2294 st.reachRamp = (cutGlides || liftGlides) ? ramp : 0;
2295 st.cutReachStep = st.reachRamp > 0 ? (cutGoal - st.cutReach) / st.reachRamp : 0.0;
2296 st.liftReachStep = st.reachRamp > 0 ? (liftGoal - st.liftReach) / st.reachRamp : 0.0;
2297 st.rests = s.rests;
2298 st.cuts = s.cuts;
2299 st.lifts = s.lifts;
2300 st.cutScale = st.cutReach > 0.0 ? 1.0 / st.cutReach : 0.0;
2301 st.liftScale = st.liftReach > 0.0 ? 1.0 / st.liftReach : 0.0;
2302 st.designed = true;
2303 }
2304
2306 static void stepReach(BandState& st) noexcept
2307 {
2308 if (--st.reachRamp == 0)
2309 {
2310 st.cutReach = st.cutReachGoal;
2311 st.liftReach = st.liftReachGoal;
2312 }
2313 else
2314 {
2315 st.cutReach += st.cutReachStep;
2316 st.liftReach += st.liftReachStep;
2317 }
2318 st.cutScale = st.cutReach > 0.0 ? 1.0 / st.cutReach : 0.0;
2319 st.liftScale = st.liftReach > 0.0 ? 1.0 / st.liftReach : 0.0;
2320 }
2321
2323 [[nodiscard]] static double cutWeight(const BandState& st, double d) noexcept
2324 {
2325 return (d < 0.0 && st.cuts) ? std::min((1.0 - fastPow10(d * 0.05)) * st.cutScale, 1.0) : 0.0;
2326 }
2327
2329 [[nodiscard]] static double liftWeight(const BandState& st, double d) noexcept
2330 {
2331 return (d > 0.0 && st.lifts) ? std::min((fastPow10(d * 0.05) - 1.0) * st.liftScale, 1.0) : 0.0;
2332 }
2333
2350 [[nodiscard]] BiquadCoeffs designEnd(const BandConfig& cfg, double rangeDb) const noexcept
2351 {
2352 const BiquadCoeffs half = designShape(cfg, 0.5 * rangeDb);
2353 const double reach = 1.0 + std::pow(10.0, rangeDb / 40.0);
2354 BiquadCoeffs end = half;
2355 end.b0 = 1.0 + reach * (half.b0 - 1.0);
2356 end.b1 = half.a1 + reach * (half.b1 - half.a1);
2357 end.b2 = half.a2 + reach * (half.b2 - half.a2);
2358 return end;
2359 }
2360
2362 void designMixedBand(int b, double fs) noexcept
2363 {
2364 BandState& st = states_[b];
2365 const BandConfig& cfg = st.cfg;
2366 MixedBand& filters = mixedEngine_->bands[static_cast<size_t>(b)];
2367 const double rest = static_cast<double>(cfg.gain);
2368 const Sides sides = sidesOf(cfg);
2369 const bool rests = sides.rests, cuts = sides.cuts, lifts = sides.lifts;
2370 const double cutRange = sides.cutRange, liftRange = sides.liftRange;
2371
2372 // A filter that was out of the band comes in clean; one that was
2373 // playing glides to its new design.
2374 const int ramp = static_cast<int>(kMixedRampMs * 0.001 * fs);
2375 const auto place = [&](BiquadCascade<T, 1, kMaxChannels>& filter, const BiquadCoeffs& design, bool was, bool is) noexcept {
2376 if (!is) return;
2377 if (!was || !st.designed) filter.reset();
2378 filter.rampCoeffs(0, design, was && st.designed ? ramp : 0);
2379 };
2380 if (rests) place(filters.rest, designShape(cfg, rest), st.rests, rests);
2381 if (cuts) place(filters.cut, designEnd(cfg, -cutRange), st.cuts, cuts);
2382 if (lifts) place(filters.lift, designEnd(cfg, liftRange), st.lifts, lifts);
2383
2384 adoptSides(st, sides, ramp);
2385 }
2386
2387 void updateBandInternalState(int b, double fs) noexcept
2388 {
2389 // Bounded seqlock read of the published config into a thread-private
2390 // plain copy. Every word crossing threads is std::atomic (see
2391 // StagedBand): copying the struct itself here, even under a correct
2392 // counter, was a plain concurrent read of words the control thread
2393 // writes and so a data race by the C++ model, not merely a torn-value
2394 // hazard. This runs on the audio thread, so the read is bounded: it
2395 // never waits for the control thread to finish publishing.
2396 BandConfig cfg;
2397 if (!staged_[static_cast<size_t>(b)].tryRead(cfg))
2398 {
2399 // Gave up: leave states_[b] exactly as it is -- the band keeps
2400 // running on its current config -- and re-arm so the publication is
2401 // adopted on a later block.
2402 paramsDirty_[b].store(true, std::memory_order_release);
2403 return;
2404 }
2405
2406 BandState& st = states_[b];
2407 const BandConfig old = st.cfg;
2408
2409 // A band re-enabled after being disabled would replay arbitrarily old
2410 // filter history and gain state: start it clean. So does one that
2411 // moves to other channels, whose memory is of another signal.
2412 if ((cfg.enabled && !old.enabled) || cfg.scope != old.scope)
2413 cleanBand(b);
2414
2415 // The zone the band listens to has moved: with a relative threshold,
2416 // a second reference listens there before it takes over.
2417 const bool moved = cfg.frequency != old.frequency || cfg.q != old.q || cfg.shape != old.shape
2418 || cfg.timing != old.timing
2419 || cfg.listenLow != old.listenLow || cfg.listenHigh != old.listenHigh;
2420 if (cfg.relativeThreshold && old.relativeThreshold && moved)
2421 {
2422 // The detector starts clean there: what it still rings of the old
2423 // zone is not the level of the new one.
2424 bandDetector_[b].reset();
2425 bandZone_[b].reset();
2426 for (int ch = 0; ch < kMaxChannels; ++ch)
2427 analytic_[static_cast<size_t>(b * kMaxChannels + ch)].reset();
2428 st.fast = st.slow = st.heard = 0.0;
2429 st.candidate = static_cast<double>(kMinLevelDb);
2430 st.watching = std::max(1, static_cast<int>(kReferenceWatch * fs));
2431 }
2432 else if (cfg.relativeThreshold && !old.relativeThreshold)
2433 {
2434 st.reference = st.candidate = static_cast<double>(kMinLevelDb);
2435 st.watching = 0;
2436 }
2437 st.referenceFall = kReferenceFallDb / fs;
2438 st.cfg = cfg;
2439
2440 // The detector: where the gain filter acts, or the zone the band was
2441 // given (designDetector()). Direct writes (setCoeffsNow): this runs on
2442 // the audio thread, which owns these Biquads (one-master rule, see the
2443 // threading block), so even this cold reconfiguration must not
2444 // self-publish through the staged channel.
2445 const DetectorDesign detector = designDetector(cfg, fs);
2446 bandDetector_[b].setCoeffsNow(detector.first);
2447 bandZone_[b].setCoeffsNow(detector.second);
2448 if (detector.two && !st.zoned) bandZone_[b].reset(); // it starts from nothing, not from an old zone
2449 st.zoned = detector.two;
2450
2451 auto calcCoeff = [fs](T ms) -> T {
2452 const double tauSec = std::max(static_cast<double>(ms), 0.01) / 1000.0;
2453 return static_cast<T>(1.0 - std::exp(-1.0 / (fs * tauSec)));
2454 };
2455
2456 st.aboveAtkCoeff = calcCoeff(cfg.aboveAttackMs);
2457 st.aboveRelCoeff = calcCoeff(cfg.aboveReleaseMs);
2458 st.belowAtkCoeff = calcCoeff(cfg.belowAttackMs);
2459 st.belowRelCoeff = calcCoeff(cfg.belowReleaseMs);
2460
2461 // Program timing: the time constant of the detector's envelope is the unit.
2462 const double unit = detector.unit;
2463 const auto pole = [fs](double seconds) noexcept { return 1.0 - std::exp(-1.0 / (fs * seconds)); };
2464 const double fastFall = std::max(kFastFallUnits * unit, kFastFallFloor);
2465 st.fastUp = pole(std::max(unit, kFastRiseFloor));
2466 st.fastDown = pole(fastFall);
2467 st.slowUp = pole(std::max(kSlowRiseUnits * unit, kSlowRiseFloor));
2468 st.slowDown = pole(std::max(kSlowFallUnits * unit, kSlowFallFloor));
2469 st.lastDown = pole(kLastFallShare * fastFall);
2470
2471 // The knee: the one asked for, or one that grows with the width of the
2472 // band (a wide band is a tone control and wants a gentle onset) and
2473 // with the root of its range.
2474 if (cfg.knee >= T(0))
2475 {
2476 st.knee = cfg.knee;
2477 }
2478 else
2479 {
2480 const double range = std::max(rangeTowards(cfg, false), rangeTowards(cfg, true));
2481 const double octaves = cfg.shape == BandShape::Bell
2482 ? 2.0 / std::numbers::ln2 * std::asinh(0.5 / std::max(static_cast<double>(cfg.q), 0.05))
2483 : 2.0;
2484 st.knee = static_cast<T>(std::min(kKneePerOctave * (1.0 + octaves) * std::sqrt(range / 12.0), 40.0));
2485 }
2486
2487 if (linear_)
2488 {
2489 // The kernels of the band are designed again, one per block.
2490 adoptSides(st, sidesOf(cfg));
2491 linear_->pending[static_cast<size_t>(b)].fill(true);
2492 }
2493 else if (mixedActive_)
2494 {
2495 designMixedBand(b, fs);
2496 }
2497 }
2498
2499 void updateLookahead() noexcept
2500 {
2501 if (sampleRate_ > 0) {
2502 int samples = static_cast<int>(sampleRate_ * runFactor() * lookaheadMs_ / T(1000));
2503 lookaheadSamples_.store(samples, std::memory_order_relaxed);
2504 }
2505 }
2506
2507 // -- State & Mem ---------------------------------------------------------
2508 std::atomic<bool> isPrepared_ { false };
2509 AudioSpec spec_ {};
2510 double sampleRate_ = 0;
2511
2512 std::atomic<int> numBands_ { 0 };
2513
2524 struct StagedBand
2525 {
2526 std::atomic<T> frequency { T(1000) };
2527 std::atomic<T> q { T(1.0) };
2528 std::atomic<T> threshold { T(-20) };
2529 std::atomic<int> shape { static_cast<int>(BandShape::Bell) };
2530 std::atomic<bool> enabled { true };
2531 std::atomic<T> gain { T(0) };
2532 std::atomic<T> knee { T(0) };
2533 std::atomic<int> scope { static_cast<int>(Scope::Stereo) };
2534 std::atomic<int> timing { static_cast<int>(Timing::Manual) };
2535 std::atomic<bool> relative { false };
2536 std::atomic<T> listenLow { T(0) };
2537 std::atomic<T> listenHigh { T(0) };
2538
2539 std::atomic<T> aboveRatio { T(1) };
2540 std::atomic<T> aboveAttackMs { T(5) };
2541 std::atomic<T> aboveReleaseMs { T(50) };
2542 std::atomic<T> aboveRangeDb { T(12) };
2543 std::atomic<bool> aboveBoost { false };
2544
2545 std::atomic<T> belowRatio { T(1) };
2546 std::atomic<T> belowAttackMs { T(10) };
2547 std::atomic<T> belowReleaseMs { T(100) };
2548 std::atomic<T> belowRangeDb { T(12) };
2549 std::atomic<bool> belowBoost { false };
2550
2551 std::atomic<unsigned> seq { 0 };
2552
2564 void publish(const BandConfig& c) noexcept
2565 {
2566 seq.fetch_add(1, std::memory_order_acq_rel); // -> odd
2567 std::atomic_thread_fence(std::memory_order_release);
2568 frequency.store(c.frequency, std::memory_order_relaxed);
2569 q.store(c.q, std::memory_order_relaxed);
2570 threshold.store(c.threshold, std::memory_order_relaxed);
2571 shape.store(static_cast<int>(c.shape), std::memory_order_relaxed);
2572 enabled.store(c.enabled, std::memory_order_relaxed);
2573 gain.store(c.gain, std::memory_order_relaxed);
2574 knee.store(c.knee, std::memory_order_relaxed);
2575 scope.store(static_cast<int>(c.scope), std::memory_order_relaxed);
2576 timing.store(static_cast<int>(c.timing), std::memory_order_relaxed);
2577 relative.store(c.relativeThreshold, std::memory_order_relaxed);
2578 listenLow.store(c.listenLow, std::memory_order_relaxed);
2579 listenHigh.store(c.listenHigh, std::memory_order_relaxed);
2580 aboveRatio.store(c.aboveRatio, std::memory_order_relaxed);
2581 aboveAttackMs.store(c.aboveAttackMs, std::memory_order_relaxed);
2582 aboveReleaseMs.store(c.aboveReleaseMs, std::memory_order_relaxed);
2583 aboveRangeDb.store(c.aboveRangeDb, std::memory_order_relaxed);
2584 aboveBoost.store(c.aboveBoost, std::memory_order_relaxed);
2585 belowRatio.store(c.belowRatio, std::memory_order_relaxed);
2586 belowAttackMs.store(c.belowAttackMs, std::memory_order_relaxed);
2587 belowReleaseMs.store(c.belowReleaseMs, std::memory_order_relaxed);
2588 belowRangeDb.store(c.belowRangeDb, std::memory_order_relaxed);
2589 belowBoost.store(c.belowBoost, std::memory_order_relaxed);
2590 seq.fetch_add(1, std::memory_order_release); // -> even
2591 }
2592
2598 static constexpr int kSeqlockMaxAttempts = 3;
2599
2606 void loadWordsRelaxed(BandConfig& c) const noexcept
2607 {
2608 c.frequency = frequency.load(std::memory_order_relaxed);
2609 c.q = q.load(std::memory_order_relaxed);
2610 c.threshold = threshold.load(std::memory_order_relaxed);
2611 c.shape = static_cast<BandShape>(shape.load(std::memory_order_relaxed));
2612 c.enabled = enabled.load(std::memory_order_relaxed);
2613 c.gain = gain.load(std::memory_order_relaxed);
2614 c.knee = knee.load(std::memory_order_relaxed);
2615 c.scope = static_cast<Scope>(scope.load(std::memory_order_relaxed));
2616 c.timing = static_cast<Timing>(timing.load(std::memory_order_relaxed));
2617 c.relativeThreshold = relative.load(std::memory_order_relaxed);
2618 c.listenLow = listenLow.load(std::memory_order_relaxed);
2619 c.listenHigh = listenHigh.load(std::memory_order_relaxed);
2620 c.aboveRatio = aboveRatio.load(std::memory_order_relaxed);
2621 c.aboveAttackMs = aboveAttackMs.load(std::memory_order_relaxed);
2622 c.aboveReleaseMs = aboveReleaseMs.load(std::memory_order_relaxed);
2623 c.aboveRangeDb = aboveRangeDb.load(std::memory_order_relaxed);
2624 c.aboveBoost = aboveBoost.load(std::memory_order_relaxed);
2625 c.belowRatio = belowRatio.load(std::memory_order_relaxed);
2626 c.belowAttackMs = belowAttackMs.load(std::memory_order_relaxed);
2627 c.belowReleaseMs = belowReleaseMs.load(std::memory_order_relaxed);
2628 c.belowRangeDb = belowRangeDb.load(std::memory_order_relaxed);
2629 c.belowBoost = belowBoost.load(std::memory_order_relaxed);
2630 }
2631
2652 [[nodiscard]] bool tryRead(BandConfig& out) const noexcept
2653 {
2654 for (int attempt = 0; attempt < kSeqlockMaxAttempts; ++attempt)
2655 {
2656 const unsigned s0 = seq.load(std::memory_order_acquire);
2657 if ((s0 & 1u) != 0u) continue; // writer mid-publish: do not copy
2658 BandConfig c;
2659 loadWordsRelaxed(c);
2660 std::atomic_thread_fence(std::memory_order_acquire);
2661 if (s0 == seq.load(std::memory_order_relaxed))
2662 {
2663 out = c; // commit only on validation
2664 return true;
2665 }
2666 }
2667 return false;
2668 }
2669
2685 [[nodiscard]] BandConfig read() const noexcept
2686 {
2687 BandConfig c;
2688 unsigned s0, s1;
2689 do {
2690 s0 = seq.load(std::memory_order_acquire);
2691 loadWordsRelaxed(c);
2692 std::atomic_thread_fence(std::memory_order_acquire);
2693 s1 = seq.load(std::memory_order_relaxed);
2694 } while ((s0 & 1u) != 0u || s0 != s1);
2695 return c;
2696 }
2697 };
2698
2700 std::array<StagedBand, MaxBands> staged_ {};
2701
2706 std::array<BandConfig, MaxBands> masterConfigs_ {};
2707 std::array<std::atomic<bool>, MaxBands> paramsDirty_ {};
2708 std::array<BandState, MaxBands> states_ {};
2709 unsigned refreshCounter_ = 0;
2710 int lastNumBands_ = MaxBands;
2711
2712 // Biquads must span the class's full channel capacity (kMaxChannels); the
2713 // default Biquad<T> is only 8 channels, which would index its per-channel state
2714 // out of bounds when processing 9..16-channel (surround/immersive) audio.
2715 std::array<Biquad<T, kMaxChannels>, MaxBands> bandDetector_ {};
2716 std::array<Biquad<T, kMaxChannels>, MaxBands> bandZone_ {};
2717 std::array<Biquad<T, kMaxChannels>, MaxBands> bandFilter_ {};
2718 std::array<NormalizedLadder<T, kMaxChannels>, MaxBands> bandLadder_ {};
2719 std::atomic<Structure> structure_ { Structure::DirectForm };
2720 bool ladderActive_ = false;
2721 std::array<T, MaxBands> currentGainDb_ {};
2722 std::array<std::atomic<T>, MaxBands> meterGainDb_ {};
2723
2724 int oversamplingFactor_ = 1;
2725 bool oversamplingAutomatic_ = false;
2726 static constexpr double kAutomaticInternalRate = 88200.0;
2727 std::unique_ptr<Oversampling<T>> oversampler_; // audio path
2728 std::unique_ptr<Oversampling<T>> oversamplerSc_; // sidechain path
2729
2730 T lookaheadMs_ = T(0);
2731 std::atomic<int> lookaheadSamples_ { 0 };
2732 std::array<RingBuffer<T>, kMaxChannels> lookaheadBuf_ {};
2733 std::vector<HilbertIIR<double>> analytic_;
2734 std::array<double, kDetChunk> detBand_ {};
2735 std::array<double, kDetChunk> detMag_ {};
2736 std::array<double, kDetChunk> pairBand_ {};
2737 std::array<double, kDetChunk> pairMag_ {};
2738 std::array<std::array<double, 3>, MaxBands> bandCov_ {};
2739 std::atomic<LinkMode> linkMode_ { LinkMode::Loudest };
2740 bool dominantLink_ = false;
2741 double linkRate_ = 0.0;
2742 double linkCoeff_ = 0.0;
2743 std::array<std::array<T, kDetChunk>, MaxBands> detLevelDb_ {};
2744 std::array<double, kDetChunk> detLinear_ {};
2745 std::array<std::array<T, kDetChunk>, MaxBands> dynDb_ {};
2746
2747 std::array<bool, MaxBands> playing_ {};
2748 std::array<int, MaxBands> first_ {};
2749 std::array<int, MaxBands> second_ {};
2750 int numFirst_ = 0, numSecond_ = 0;
2751
2752 std::atomic<bool> mixedWanted_ { false };
2753 static constexpr int kRemovalCapacity = 32768;
2754 std::atomic<bool> removalListen_ { false };
2755 std::array<RingBuffer<T>, kMaxChannels> deltaRing_ {};
2756
2757 // The key listen (audio thread, but for the band asked for).
2758 std::atomic<int> keyListen_ { -1 };
2759 int listenBand_ = -1;
2760 double listenWeight_ = 0.0, listenGoal_ = 0.0;
2761 bool listenDesigned_ = false, listenTwo_ = false;
2762 BandConfig listenCfg_ {};
2763 Biquad<T, kMaxChannels> listenFirst_ {}, listenSecond_ {};
2764 std::array<RingBuffer<T>, kMaxChannels> listenRing_ {};
2765 std::vector<T> listenHeard_;
2766 int listenChannels_ = 0, listenBlock_ = 0, listenReach_ = 0;
2767
2768 bool mixedActive_ = false;
2769 std::unique_ptr<MixedEngine> mixedEngine_;
2770 std::unique_ptr<LinearEngine> linear_;
2771 bool linearWanted_ = false;
2772 int linearTaps_ = 0;
2773 FilterDesign::Band designBand_;
2774};
2775
2776} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
void setCoeffsNow(const BiquadCoeffs &c) noexcept
Stream-owner direct set: makes c the active set immediately.
Definition Biquad.h:963
void reset() noexcept
Resets all per-channel filter states to zero to avoid ringing/clicks.
Definition Biquad.h:1003
T processSample(T input, int channel) noexcept
Processes a single sample for a specific channel.
Definition Biquad.h:1029
Dynamic parametric EQ with dual above/below threshold per band.
Definition DynamicEQ.h:181
void setMixedBands(bool on) noexcept
Chooses the engine of the bands: fixed filters mixed by the gain, or one filter designed again as the...
Definition DynamicEQ.h:689
std::vector< uint8_t > getState() const
Serializes bands and modes (setup/UI threads; allocates).
Definition DynamicEQ.h:1007
int getLinearPhaseKernelLength() const noexcept
The kernel length in use (after prepare()), or the one asked for.
Definition DynamicEQ.h:801
bool setState(const uint8_t *data, size_t size)
Restores bands from a blob (tolerant; rejects foreign ids).
Definition DynamicEQ.h:1074
void reset() noexcept
Definition DynamicEQ.h:969
void processBlock(AudioBufferView< T > buffer) noexcept
Processes audio in-place using self-sidechain.
Definition DynamicEQ.h:356
T getBandGainDb(int band) const noexcept
The gain the dynamic part of a band is applying, in dB from its rest (metering; any thread).
Definition DynamicEQ.h:963
void setAutomaticOversampling(bool on) noexcept
Lets the host rate choose the factor (setup threads only: like setOversampling() it un-prepares the p...
Definition DynamicEQ.h:923
bool isOversamplingAutomatic() const noexcept
Whether the factor follows the host rate (setAutomaticOversampling()).
Definition DynamicEQ.h:931
int getLatency() const noexcept
Total latency in samples at the base rate.
Definition DynamicEQ.h:953
int getKeyListen() const noexcept
Definition DynamicEQ.h:441
void setRemovalListen(bool on) noexcept
Removal listen: the output is what the bands take out (or add), the input delayed by the latency minu...
Definition DynamicEQ.h:417
void setOversampling(int factor) noexcept
Sets the internal oversampling factor.
Definition DynamicEQ.h:902
void setKeyListen(int band) noexcept
Key listen: the output is what one band's detector hears.
Definition DynamicEQ.h:436
BandShape
Shape of the dynamic gain filter (and its detector region).
Definition DynamicEQ.h:185
@ LowShelf
Dynamic low shelf; detector hears below freq.
@ Bell
Parametric bell; detector is a bandpass at freq/Q.
@ HighShelf
Dynamic high shelf; detector hears above freq.
void setBand(int band, const BandConfig &config) noexcept
Thread-safe configuration update for a specific band.
Definition DynamicEQ.h:628
void getBandMagnitude(int band, T dynamicGainDb, const T *frequencies, T *magnitudes, int numPoints) const noexcept
The magnitude response of a band with its dynamic part at a given gain, as the engine in use plays it...
Definition DynamicEQ.h:817
Structure getStructure() const noexcept
Definition DynamicEQ.h:747
LinkMode getLinkMode() const noexcept
Definition DynamicEQ.h:719
bool isRemovalListen() const noexcept
Definition DynamicEQ.h:419
void prepare(const AudioSpec &spec)
Initializes the dynamic EQ, allocating ring buffers and oversamplers.
Definition DynamicEQ.h:261
void setLinearPhaseKernelLength(int taps) noexcept
Asks for the length of the linear-phase kernels, in taps.
Definition DynamicEQ.h:792
void setLookahead(T ms) noexcept
Sets the lookahead (0..10 ms). Applied immediately (may click); non-finite values are ignored.
Definition DynamicEQ.h:938
bool isLinearPhase() const noexcept
Whether the bands run in linear phase (setLinearPhase()).
Definition DynamicEQ.h:779
void setStructure(Structure structure) noexcept
Chooses how the filter of each band is realised in the default engine.
Definition DynamicEQ.h:741
LinkMode
What a stereo band's linked level reads (see setLinkMode()).
Definition DynamicEQ.h:696
@ Dominant
The level of the pair's dominant component in the band.
@ Loudest
The louder channel's level (the default).
Scope
Where in a stereo pair a band acts and listens.
Definition DynamicEQ.h:193
@ Mid
The middle of the first two channels: what they share.
@ Right
The second channel only.
@ Left
The first channel only.
@ Stereo
Every channel, linked by the loudest. Default.
@ Side
Their sides: what sets them apart.
void setNumBands(int n) noexcept
Definition DynamicEQ.h:670
void setLinearPhase(bool on) noexcept
Linear phase: the bands change the level of the signal and nothing of its phase.
Definition DynamicEQ.h:771
int getOversamplingFactor() const noexcept
Active oversampling factor (1 = off), as the last prepare() or setter left it.
Definition DynamicEQ.h:934
Timing
What sets how fast the gain of a band moves.
Definition DynamicEQ.h:203
@ Program
Three followers of the level, timed from the band's frequency and width.
@ Manual
The attack and release fields, applied to the gain. Default.
static constexpr T kAutomaticKnee
BandConfig::knee value that asks for the automatic knee.
Definition DynamicEQ.h:209
void setLinkMode(LinkMode mode) noexcept
Chooses how the bands placed on the stereo pair link it.
Definition DynamicEQ.h:713
bool isMixedBands() const noexcept
Whether the bands are mixed from fixed filters (setMixedBands()).
Definition DynamicEQ.h:692
void processBlock(AudioBufferView< T > audio, AudioBufferView< T > sidechain) noexcept
Processes audio with an external sidechain.
Definition DynamicEQ.h:366
Structure
How the band filter is realised (see setStructure()).
Definition DynamicEQ.h:723
@ Ladder
Normalized ladder: passive while the gain moves the filter.
@ DirectForm
Direct form (the default).
void prepare(double sampleRate) noexcept
Sets the sample rate (an invalid one leaves 48 kHz).
static BiquadCoeffs digital(const AnalogSection &section, const Band &band) noexcept
The biquad whose magnitude follows an analog section up to Nyquist.
Zero-latency analytic pair from two allpass chains (a 90-degree phase-difference network).
Definition Hilbert.h:245
static constexpr int factorForRate(double sampleRate, double minimumInternalRate=176400.0, int maxFactor=1<< kMaxStages) noexcept
The smallest factor that brings a host rate up to an internal rate.
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
constexpr int delay
Delay of the projected output behind the newest input, in samples.
void add(float *DSPARK_RESTRICT dst, const float *DSPARK_RESTRICT src, int count) noexcept
Adds source samples into a destination buffer (no scaling).
Definition SimdOps.h:829
Main namespace for the DSPark framework.
T dominantPairLevel(T levelL, T levelR, double rho2) noexcept
Level of the dominant component of a stereo pair from the levels of its two channels and their square...
Definition DspMath.h:285
T fastPow10(T x) noexcept
Fast approximation of 10^x using exp2.
Definition DspMath.h:197
T fastLog(T x) noexcept
Fast natural logarithm approximation.
Definition DspMath.h:393
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
A first or second order analog section, in radians per second: (b2 s^2 + b1 s + b0) / (a2 s^2 + a1 s ...
static AnalogSection peak(double hz, double q, double gainDb) noexcept
Bell: gainDb at the centre, bandwidth hz / Q at half that gain in decibels.
double magnitudeSquared(double omega) const noexcept
Squared magnitude at an angular frequency (rad/s).
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 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 makePeakMatched(double sampleRate, double freq, double Q, double gainDb) noexcept
Analog-matched ("de-cramped") peaking filter (Vicanek design).
Definition Biquad.h:248
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
Full configuration for a single dynamic EQ band.
Definition DynamicEQ.h:216
Scope scope
The channels the band acts on and listens to.
Definition DynamicEQ.h:225
bool relativeThreshold
The threshold counts from the band's own recent level instead of from full scale.
Definition DynamicEQ.h:227
T knee
Width of the knee around the threshold in dB (0 to 40); negative (kAutomaticKnee): from the band's wi...
Definition DynamicEQ.h:224
Timing timing
Program: the times come from the band, and the attack and release fields are not used.
Definition DynamicEQ.h:226
T listenLow
Low edge, in Hz, of the zone the detector listens to; 0: no edge on that side.
Definition DynamicEQ.h:228
T gain
Gain of the band at rest, in dB (-24 to 24). The dynamic part moves from here.
Definition DynamicEQ.h:223
T listenHigh
High edge of that zone; with both at 0 the detector listens where the band acts.
Definition DynamicEQ.h:229
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