DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Compressor.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
50#include "../Core/DspMath.h"
51#include "../Core/AudioSpec.h"
52#include "../Core/AudioBuffer.h"
53#include "../Core/Biquad.h"
54#include "../Core/CharacterStage.h"
55#include "../Core/SmoothedValue.h"
56#include "../Core/RingBuffer.h"
57#include "../Core/DenormalGuard.h"
58#include "../Core/Hilbert.h"
59#include "../Core/KeyEqualizer.h"
60#include "../Core/TruePeakDetector.h"
61#include "../Core/StateBlob.h"
62
63#include <algorithm>
64#include <array>
65#include <atomic>
66#include <cmath>
67#include <cstddef>
68#include <cstdint>
69#include <limits>
70#include <memory>
71#include <new>
72#include <numbers>
73#include <vector>
74
75namespace dspark {
76
102template <FloatType T>
104{
105public:
106 ~Compressor() = default;
107
109 enum class DetectorType
110 {
111 Peak,
112 Rms,
113 TruePeak,
115 Hilbert,
123 Hybrid
129 };
130
132 enum class Topology
133 {
135 FeedBack
141 };
142
149 enum class Character
150 {
151 Clean,
157
158 Opto,
166
167 FET,
177
178 Varimu,
184
185 Layered
194 };
195
197 enum class Mode
198 {
199 Downward,
200 Upward,
204 Both,
210 Leveler
215 };
216
219 {
220 Branching,
223 Decoupled
226 };
227
229 enum class AutoMakeupMode
230 {
231 Off,
232 Static,
241 Adaptive,
244 Analytic
253 };
254
256 enum class Precision
257 {
258 Standard,
259 High
262 };
263
264 // -- Lifecycle --------------------------------------------------------------
265
275 void prepare(const AudioSpec& spec)
276 {
277 if (!spec.isValid()) return;
278 spec_ = spec;
279 sampleRate_ = spec.sampleRate;
280
281 T fs = static_cast<T>(sampleRate_);
283 timeConstantsDirty_.store(false, std::memory_order_relaxed);
284 linkCoeff_ = 1.0 - std::exp(-1.0 / (0.02 * sampleRate_));
285 linkLL_ = linkRR_ = linkLR_ = 0.0;
286
287 // Smoothed parameters initialization
288 T thresh = threshold_.load(std::memory_order_relaxed);
289 T rat = ratio_.load(std::memory_order_relaxed);
290 T knee = kneeWidth_.load(std::memory_order_relaxed);
291
292 thresholdSmooth_.prepare(sampleRate_, 30.0);
293 thresholdSmooth_.reset(thresh);
294 ratioSmooth_.prepare(sampleRate_, 30.0);
295 ratioSmooth_.reset(std::max(rat, T(1)));
296 kneeSmooth_.prepare(sampleRate_, 30.0);
297 kneeSmooth_.reset(std::max(knee, T(0)));
298 makeupSmooth_.prepare(sampleRate_, 30.0);
299 makeupSmooth_.reset(makeupGain_.load(std::memory_order_relaxed));
300 mixSmooth_.prepare(sampleRate_, 30.0);
301 mixSmooth_.reset(mix_.load(std::memory_order_relaxed));
302 colorSmooth_.prepare(sampleRate_, 30.0);
303 colorSmooth_.reset(characterColor_.load(std::memory_order_relaxed));
304 amountSmooth_.prepare(sampleRate_, 30.0);
305 amountSmooth_.reset(amount_.load(std::memory_order_relaxed));
306 analyticSmooth_.prepare(sampleRate_, 30.0);
307 makeupKey_.valid = false;
309
310 // The detector's points between samples at Precision::High: a
311 // Kaiser-windowed sinc per quarter of a sample.
312 for (int p = 0; p < kDetectorPoints - 1; ++p)
313 detail::designSincPhase<kInterpTaps>(interpPhase_[p], kInterpBeta,
314 static_cast<double>(p + 1) / kDetectorPoints);
315
316 // Pre-allocate and initialize per-channel instances. Capacity covers
317 // the 10 ms user lookahead. Every channel slot gets a delay line, not just spec.numChannels:
318 // a view wider than the spec would otherwise read an unprepared ring
319 // (silence) on the extra channels whenever lookahead is active.
320 int maxLaSamples = static_cast<int>(sampleRate_ * 0.01) + 1 + kDetectorDelay;
321 for (int ch = 0; ch < kMaxChannels; ++ch)
322 {
323 lookaheadBuffers_[ch].prepare(maxLaSamples);
324 gainDelay_[ch].prepare(maxLaSamples);
325 hilbertDetectors_[ch].reset();
326 }
328 // The windows of HoldMode::EveryPeak (without memory that mode holds as Deepest does).
329 holdWindows_.reset(new (std::nothrow) SlidingDeepest[kMaxChannels]);
330 if (holdWindows_)
331 for (int ch = 0; ch < kMaxChannels; ++ch) holdWindows_[static_cast<size_t>(ch)].configure(holdSamples_);
333 // The ramps of LookaheadShape::Ramp, for the channels of the layout.
334 rampCount_ = std::clamp(spec.numChannels, 1, kMaxChannels);
335 lookaheadRamps_.resize(static_cast<size_t>(rampCount_));
336 for (auto& ramp : lookaheadRamps_) ramp.prepare(maxLaSamples);
337
338 lookaheadSamples_ = static_cast<int>(fs * std::clamp(
339 lookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000));
340 latencySamples_ = std::max(lookaheadSamples_, static_cast<int>(fs * std::clamp(
341 maxLookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000)));
342 latencyKept_ = maxLookaheadMs_.load(std::memory_order_relaxed) > T(0);
343
345 scHpfDirty_.store(false, std::memory_order_relaxed);
347
348 // RMS Buffer pre-allocation (Max 500ms to ensure zero real-time allocation)
349 int maxRmsSamples = static_cast<int>(sampleRate_ * 0.5) + 1;
350 for (auto& buf : rmsBuffers_)
351 {
352 buf.assign(static_cast<size_t>(maxRmsSamples), T(0));
353 }
355
356 // The colour stage, both places; a change of place fades over 20 ms.
357 stageBefore_.prepare(spec);
358 stageAfter_.prepare(spec);
359 stageScratch_.resize(std::min(spec.numChannels, kMaxChannels), spec.maxBlockSize);
360 // The routes of a pair: the key as its middle and its sides, and the
361 // line the part that is not treated waits in.
362 routeBlock_ = std::max(1, spec.maxBlockSize);
363 routeKey_.resize(2, routeBlock_);
364 routeReach_ = maxLaSamples;
365 routeDelay_.prepare(routeReach_ + 1);
366 stageFade_.assign(static_cast<size_t>(std::max(1, spec.maxBlockSize)), 0.0);
367 stageFadeStep_ = 1.0 / (0.020 * sampleRate_);
368 {
369 const StagePosition stage = stagePosition_.load(std::memory_order_relaxed);
370 stageWeightBefore_ = stage == StagePosition::Before ? 1.0 : 0.0;
371 stageWeightAfter_ = stage == StagePosition::After ? 1.0 : 0.0;
372 }
373
374 reset();
375 }
376
381 void prepare(double sampleRate) noexcept
382 {
383 AudioSpec spec { sampleRate, 512, 2 };
384 prepare(spec);
385 }
386
391 void processBlock(AudioBufferView<T> buffer) noexcept
392 {
393 const StagePosition stage = stagePosition_.load(std::memory_order_relaxed);
395 processRouted(buffer, buffer);
397 }
398
408 void processBlock(AudioBufferView<T> audio, AudioBufferView<T> sidechain) noexcept
409 {
410 const StagePosition stage = stagePosition_.load(std::memory_order_relaxed);
412 processRouted(audio, sidechain);
414 }
415
445 [[nodiscard]] T processSample(T input, int channel) noexcept
446 {
447 // Release-safe guards: a wild channel would index every per-channel
448 // state array out of bounds (a negative one is a giant size_t).
449 if (channel < 0 || channel >= kMaxChannels) return input;
450 if (!(sampleRate_ > 0)) return input;
451
452 // Sync atomic parameters into the smoothers here too: processBlock does this
453 // per block, but a processSample-only workflow would otherwise never see
454 // setThreshold()/setRatio()/setKnee() changes (the smoothers stayed frozen).
455 thresholdSmooth_.setTargetValue(threshold_.load(std::memory_order_relaxed));
456 ratioSmooth_.setTargetValue(std::max(ratio_.load(std::memory_order_relaxed), T(1)));
457 kneeSmooth_.setTargetValue(std::max(kneeWidth_.load(std::memory_order_relaxed), T(0)));
458 makeupSmooth_.setTargetValue(makeupGain_.load(std::memory_order_relaxed));
459 colorSmooth_.setTargetValue(characterColor_.load(std::memory_order_relaxed));
460 amountSmooth_.setTargetValue(amount_.load(std::memory_order_relaxed));
461
462 // Channel 0 advances the shared smoothers; advancing on every call
463 // would scale their time constants with the caller's channel count.
464 const bool advanceShared = (channel == 0);
465 T thresh, ratio, knee, makeupDb, colorAmt, amount;
466 if (advanceShared)
467 {
468 thresh = thresholdSmooth_.getNextValue();
469 ratio = ratioSmooth_.getNextValue();
470 knee = kneeSmooth_.getNextValue();
471 makeupDb = makeupSmooth_.getNextValue();
472 colorAmt = colorSmooth_.getNextValue();
473 amount = amountSmooth_.getNextValue();
474 }
475 else
476 {
477 thresh = thresholdSmooth_.getCurrentValue();
478 ratio = ratioSmooth_.getCurrentValue();
479 knee = kneeSmooth_.getCurrentValue();
480 makeupDb = makeupSmooth_.getCurrentValue();
481 colorAmt = colorSmooth_.getCurrentValue();
482 amount = amountSmooth_.getCurrentValue();
483 }
484
485 auto detType = detectorType_.load(std::memory_order_relaxed);
486 auto topo = topology_.load(std::memory_order_relaxed);
487 auto charType = character_.load(std::memory_order_relaxed);
488 auto modeType = mode_.load(std::memory_order_relaxed);
489 bool scHpf = scHpfEnabled_.load(std::memory_order_relaxed);
490 auto autoMkup = autoMakeupMode_.load(std::memory_order_relaxed);
491
492 // Cheap relaxed pre-check keeps the per-sample cost to one load when
493 // nothing changed; the exchange claims the flag only when it is set.
494 if (timeConstantsDirty_.load(std::memory_order_relaxed)
495 && timeConstantsDirty_.exchange(false, std::memory_order_acquire))
496 {
497 updateTimeConstants(static_cast<T>(sampleRate_));
498 }
499 if (channel == 0
500 && rmsWindowDirty_.load(std::memory_order_relaxed)
501 && rmsWindowDirty_.exchange(false, std::memory_order_acquire))
502 {
503 rmsWindowMs_ = rmsWindowMsAtomic_.load(std::memory_order_relaxed);
505 }
506
507 // The FET character is a feedback design like the 1176 it models: it
508 // always detects on the compressed output with the hardware's peak
509 // rectifier, whatever Topology and Detector say.
510 const CharacterProfile& profile = profileOf(charType);
511 const Topology topoEff = topologyFor(profile, topo);
512 const DetectorType detTypeEff = detectorFor(profile, detType);
513 modeType = modeIn(modeType, topoEff);
514 const bool fbImplicit = topoEff == Topology::FeedBack
515 && modeType == Mode::Downward
516 && detTypeEff == DetectorType::Peak;
517
518 if (channel == 0
519 && scHpfDirty_.load(std::memory_order_relaxed)
520 && scHpfDirty_.exchange(false, std::memory_order_acquire))
522 // The equalizer of the key takes its settings and moves its ramps
523 // once per frame, on channel 0.
524 if (channel == 0)
525 {
526 (void)keyEq_.sync();
527 keyEq_.advance(1);
528 }
529
530 // The sidechain filter must process whatever the detector consumes:
531 // in FeedBack that is the compressed output (previous sample on the
532 // explicit path; on the semi-implicit path the loop equation supplies
533 // the gain, so the current input feeds the filter directly).
534 T detectorIn = detectorSafe((topoEff == Topology::FeedBack && !fbImplicit)
535 ? fbLastOutput_[channel] : input);
536 if (scHpf) detectorIn = applySidechainHPF(detectorIn, channel);
537 detectorIn = keyEq_.processSample(detectorIn, channel);
538 // The settings of the audio path that are not the plain gain, once per frame.
539 if (channel == 0) (void)syncAudioPath();
540 const T detectorRead = (lopsidedDetector() && rectifies(detTypeEff)) ? asymmetric(detectorIn, channel)
541 : detectorIn;
542
543 const bool layered = isLayered(profile, modeType);
544 syncLayerState(layered);
545 const bool splitAdaptive = detTypeEff == DetectorType::SplitPolarity && !layered;
546 const bool decoupled = useDecoupled(charType, topoEff);
547 syncDecoupledState(decoupled);
548 // Programme-dependent timing: the settings are taken on channel 0,
549 // which also advances the balance of the key.
550 if (advanceShared)
551 {
552 program_ = programTiming(charType, topoEff, decoupled, splitAdaptive);
554 if (program_.active && program_.spectral > 0.0)
555 {
556 double lowSq = 0.0, highSq = 0.0;
557 balanceBands(detectorSafe(input), channel, lowSq, highSq);
558 (void)balanceAdvance(lowSq, highSq);
559 }
560 }
561
562 T levelDb = detectLevel(detectorRead, channel, detTypeEff);
563
564 const GainPathConfig cfg { charType, modeType, topoEff, fbImplicit, splitAdaptive, decoupled,
565 feedbackDetectorDelay(detTypeEff), program_.active, layered };
566 // The automatic threshold counts from the recent peak of what this
567 // channel's detector reads (of its input, in FeedBack).
568 T threshNow = thresh;
569 if (autoThreshold_.load(std::memory_order_relaxed))
570 {
571 const T heard = (topoEff == Topology::FeedBack) ? gainToDecibels(std::abs(detectorSafe(input))) : levelDb;
572 double& ref = autoRefDb_[static_cast<size_t>(channel)];
573 ref = std::max(static_cast<double>(heard), ref - autoRefFall_);
574 threshNow = thresh + static_cast<T>(ref);
575 if (channel == 0) thresholdInUseDb_.store(threshNow, std::memory_order_relaxed);
576 }
577 T smoothedGR_Db = gainPath(levelDb, channel, cfg, threshNow, ratio, knee);
578 // The gain the loop reads back is the whole one; the amount scales
579 // what is heard (and metered).
580 const T loopGainLinear = decibelsToGain(smoothedGR_Db);
581 if (amount < T(1)) smoothedGR_Db *= amount;
582 const bool gainSmooth = shapesGain();
583 if (advanceShared) syncGainSmoothing(gainSmooth);
584 if (gainSmooth) smoothedGR_Db = smoothedGain(smoothedGR_Db, channel);
585 const bool heardApart = amount < T(1) || gainSmooth;
586 T smoothedGainLinear = heardApart ? decibelsToGain(smoothedGR_Db) : loopGainLinear;
587
588 const bool adaptiveMakeup = autoMkup == AutoMakeupMode::Adaptive && reducesOnly(modeType);
589 if (advanceShared)
590 {
591 syncAdaptiveMakeup(adaptiveMakeup);
592 if (adaptiveMakeup)
593 autoMakeupEnv_ = smoothedGR_Db + autoMakeupCoeff_ * (autoMakeupEnv_ - smoothedGR_Db);
594 }
595
596 T makeup = makeupDb;
597 if (reducesOnly(modeType))
598 {
599 if (autoMkup == AutoMakeupMode::Adaptive)
600 makeup += -autoMakeupEnv_;
601 else if (autoMkup == AutoMakeupMode::Static)
602 makeup += computeGain(T(0), thresh, ratio, knee, charType,
603 modeType, T(0)) * T(-0.5);
604 }
605 // The analytic makeup has a smoother of its own, advanced with the
606 // shared ones.
607 if (advanceShared)
608 {
609 analyticSmooth_.setTargetValue(autoMkup == AutoMakeupMode::Analytic
610 ? analyticMakeupDb(charType, modeType, detTypeEff, decoupled,
611 topoEff == Topology::FeedBack) : T(0));
612 makeup += analyticSmooth_.getNextValue();
613 }
614 else
615 {
616 makeup += analyticSmooth_.getCurrentValue();
617 }
618
619 const bool pushPull = colorAmt > T(0) && profile.colour == Colour::PushPull;
620 const bool extras = audioExtras_ && !pushPull;
621 T output = pushPull ? pushPullElement(input, smoothedGainLinear, colorAmt)
622 : (extras ? gained(input, smoothedGainLinear, channel) : input * smoothedGainLinear);
623 if (colorAmt > T(0) && profile.colour == Colour::SecondOrder)
624 {
625 // Same 2nd-order FET channel modulation as the block path.
626 const T sq = output * output;
627 T& dc = fetDcState_[channel];
628 if (std::isfinite(sq)) dc += fetDcCoeff_ * (sq - dc); // a non-finite sample would latch
629 const T grDepth = std::clamp(-smoothedGR_Db * T(0.1), T(0), T(1));
630 output += colorAmt * kFetColorH2 * grDepth * (sq - dc);
631 }
632 // The feedback detector reads the compressed signal BEFORE makeup:
633 // makeup is applied after the element, so feeding it back would shift
634 // the static curve by the makeup (and run away with auto makeup).
635 fbLastOutput_[channel] = (heardApart || extras) ? input * loopGainLinear : output;
636 output *= makeupToGain(makeup);
637 gainReductionDb_.store(smoothedGR_Db, std::memory_order_relaxed);
638 // Key listen: what the detector heard goes out instead.
639 return scListen_.load(std::memory_order_relaxed) ? detectorIn : output;
640 }
641
645 void reset() noexcept
646 {
647 keyEq_.reset();
648 routeDelay_.reset();
649 {
650 // The parts' weights start at the focus, without a glide from 1.
651 const T focus = midSideFocus_.load(std::memory_order_relaxed);
652 partFrom_[0] = focus > T(0) ? T(1) - focus : T(1);
653 partFrom_[1] = focus < T(0) ? T(1) + focus : T(1);
654 }
655 toneLow_.reset();
657 toneActive_ = false; // designed again, for the rate in use, at the next block
658 linkLL_ = linkRR_ = linkLR_ = 0.0;
659 stageBefore_.reset();
660 stageAfter_.reset();
662 gainDelayNow_ = -1.0;
663 for (auto& ramp : lookaheadRamps_) ramp.clear();
664 if (holdWindows_)
665 for (int ch = 0; ch < kMaxChannels; ++ch) holdWindows_[static_cast<size_t>(ch)].clear();
666 for (int ch = 0; ch < kMaxChannels; ++ch)
667 {
668 envFastDb_[ch] = 0.0; // 0 dB gain change = neutral
669 envSlowDb_[ch] = 0.0;
670 envMidDb_[ch] = 0.0;
671 envDeepDb_[ch] = 0.0;
672 envHoldDb_[ch] = 0.0;
673 upwardGuardDb_[ch] = T(-200);
674 fbLastOutput_[ch] = T(0);
675 fetDcState_[ch] = T(0);
676 scHpfState_[ch] = T(0);
677 scHpfPrev_[ch] = T(0);
678 pointLevelDb_[ch].fill(T(-200));
679 precLevel_[ch] = -100.0;
680 precTarget_[ch] = 0.0;
681 interp_[ch] = {};
682 programState_[ch] = {};
683 layerLevelDb_[ch] = 0.0;
684 layerPeakDb_[ch] = 0.0;
685 gainSmoothA_[ch] = 0.0;
686 gainSmoothB_[ch] = 0.0;
687 landingDb_[ch] = 0.0;
688 networkLow_[ch] = 0.0;
689 leakBase_[ch] = T(1);
690 asymCrest_[ch] = T(0);
691 asymDrift_[ch] = {};
692 asymDrift_[ch].rng = 0x9E3779B9u * static_cast<std::uint32_t>(ch + 1) + 0x6A09E667u;
693 asymNow_[ch] = T(0);
694 balanceBands_[ch] = {};
695 hybridMeanSq_[ch] = 0.0;
696 lookaheadBuffers_[ch].reset();
697 gainDelay_[ch].reset();
698 autoRefDb_[ch] = -100.0;
699 hilbertDetectors_[ch].reset();
700 }
701 for (auto& buf : rmsBuffers_)
702 std::fill(buf.begin(), buf.end(), T(0));
703 for (auto& sum : rmsSums_) sum = T(0);
704 for (auto& idx : rmsIndices_) idx = 0;
705 for (auto& cnt : rmsRecomputeCounters_) cnt = 0;
706
709 holdCounters_.fill(0);
710 heldGrDb_.fill(T(0));
711 gainReductionDb_.store(T(0), std::memory_order_relaxed);
712 autoMakeupEnv_ = T(0);
713 splitPosEnv_.fill(T(0));
714 splitNegEnv_.fill(T(0));
715
716 thresholdSmooth_.skip();
717 ratioSmooth_.skip();
718 kneeSmooth_.skip();
719 makeupSmooth_.skip();
720 mixSmooth_.skip();
721 colorSmooth_.skip();
722 amountSmooth_.skip();
723 analyticSmooth_.skip();
724 }
725
726 // =========================================================================
727 // Parameter Setters
728 // =========================================================================
729
730 // All numeric setters ignore non-finite values (NaN/Inf) and keep the
731 // previous parameter: a poisoned time constant, level or coefficient
732 // would otherwise contaminate the gain path permanently.
733
735 void setThreshold(T dB) noexcept
736 {
737 if (!std::isfinite(dB)) return;
738 threshold_.store(dB, std::memory_order_relaxed);
739 }
740
742 void setRatio(T ratio) noexcept
743 {
744 if (!std::isfinite(ratio)) return;
745 ratio_.store(std::max(ratio, T(1)), std::memory_order_relaxed);
746 // The feedback attack compensation depends on the loop gain (ratio).
747 timeConstantsDirty_.store(true, std::memory_order_release);
748 }
749
761 void setAttack(T ms) noexcept
762 {
763 if (!std::isfinite(ms)) return;
764 attackMs_.store(std::max(ms, T(0.01)), std::memory_order_relaxed);
765 timeConstantsDirty_.store(true, std::memory_order_release);
766 }
767
777 void setRelease(T ms) noexcept
778 {
779 if (!std::isfinite(ms)) return;
780 releaseMs_.store(std::max(ms, T(1)), std::memory_order_relaxed);
781 timeConstantsDirty_.store(true, std::memory_order_release);
782 }
783
785 void setKnee(T dB) noexcept
786 {
787 if (!std::isfinite(dB)) return;
788 kneeWidth_.store(std::max(dB, T(0)), std::memory_order_relaxed);
789 }
790
792 void setMakeupGain(T dB) noexcept
793 {
794 if (!std::isfinite(dB)) return;
795 makeupGain_.store(dB, std::memory_order_relaxed);
796 }
797
822 void setAutoMakeup(AutoMakeupMode mode) noexcept
823 {
825 std::memory_order_relaxed);
826 }
827
829 void setAutoMakeup(bool on) noexcept
830 {
832 }
833
835 void setMode(Mode mode) noexcept
836 {
837 mode_.store(clampEnum(mode, Mode::Leveler), std::memory_order_relaxed);
838 // Feedback attack compensation only applies to Downward loops.
839 timeConstantsDirty_.store(true, std::memory_order_release);
840 }
841
859 void setLift(T belowDb, T ratio, T rangeDb) noexcept
860 {
861 if (std::isfinite(belowDb)) liftBelow_.store(std::clamp(belowDb, T(0), T(80)), std::memory_order_relaxed);
862 if (std::isfinite(ratio)) liftRatio_.store(std::clamp(ratio, T(1), T(20)), std::memory_order_relaxed);
863 if (std::isfinite(rangeDb)) liftRange_.store(std::clamp(rangeDb, T(0), T(40)), std::memory_order_relaxed);
864 timeConstantsDirty_.store(true, std::memory_order_release);
865 }
866
868 [[nodiscard]] T getLiftBelow() const noexcept { return liftBelow_.load(std::memory_order_relaxed); }
869
871 [[nodiscard]] T getLiftRatio() const noexcept { return liftRatio_.load(std::memory_order_relaxed); }
872
874 [[nodiscard]] T getLiftRange() const noexcept { return liftRange_.load(std::memory_order_relaxed); }
875
877 void setStereoLink(T amount) noexcept
878 {
879 if (!std::isfinite(amount)) return;
880 stereoLink_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
881 }
882
884 enum class LinkMode
885 {
886 Loudest,
887 Dominant
888 };
889
906 void setLinkMode(LinkMode mode) noexcept
907 {
908 linkMode_.store(clampEnum(mode, LinkMode::Dominant), std::memory_order_relaxed);
909 }
910
912 [[nodiscard]] LinkMode getLinkMode() const noexcept { return linkMode_.load(std::memory_order_relaxed); }
913
915 enum class Route
916 {
917 Stereo,
918 MidSide,
919 Mid,
920 Side,
923 };
924
947 void setRoute(Route route) noexcept { route_.store(clampEnum(route, Route::SideKeysMid), std::memory_order_relaxed); }
948
950 [[nodiscard]] Route getRoute() const noexcept { return route_.load(std::memory_order_relaxed); }
951
963 void setMidSideFocus(T focus) noexcept
964 {
965 if (std::isfinite(focus)) midSideFocus_.store(std::clamp(focus, T(-1), T(1)), std::memory_order_relaxed);
966 }
967
969 [[nodiscard]] T getMidSideFocus() const noexcept { return midSideFocus_.load(std::memory_order_relaxed); }
970
972 void setMix(T dryWet) noexcept
973 {
974 if (!std::isfinite(dryWet)) return;
975 mix_.store(std::clamp(dryWet, T(0), T(1)), std::memory_order_relaxed);
976 }
977
982 void setLookahead(T ms) noexcept
983 {
984 if (!std::isfinite(ms)) return;
985 lookaheadMs_.store(std::clamp(ms, T(0), T(10)), std::memory_order_relaxed);
986 timeConstantsDirty_.store(true, std::memory_order_release);
987 }
988
1002 void setMaxLookahead(T ms) noexcept
1003 {
1004 if (!std::isfinite(ms)) return;
1005 maxLookaheadMs_.store(std::clamp(ms, T(0), T(10)), std::memory_order_relaxed);
1006 timeConstantsDirty_.store(true, std::memory_order_release);
1007 }
1008
1010 [[nodiscard]] T getMaxLookahead() const noexcept { return maxLookaheadMs_.load(std::memory_order_relaxed); }
1011
1014 {
1018 Lead,
1025 Ramp
1026 };
1027
1036 {
1037 lookaheadShape_.store(clampEnum(shape, LookaheadShape::Ramp), std::memory_order_relaxed);
1038 timeConstantsDirty_.store(true, std::memory_order_release);
1039 }
1040
1042 [[nodiscard]] LookaheadShape getLookaheadShape() const noexcept { return lookaheadShape_.load(std::memory_order_relaxed); }
1043
1059 void setFeedbackKeyed(bool on) noexcept
1060 {
1061 feedbackKeyed_.store(on, std::memory_order_relaxed);
1062 timeConstantsDirty_.store(true, std::memory_order_release);
1063 }
1064
1066 [[nodiscard]] bool isFeedbackKeyed() const noexcept { return feedbackKeyed_.load(std::memory_order_relaxed); }
1067
1077 void setAutoThreshold(bool on) noexcept { autoThreshold_.store(on, std::memory_order_relaxed); }
1078
1080 [[nodiscard]] bool isAutoThreshold() const noexcept { return autoThreshold_.load(std::memory_order_relaxed); }
1081
1086 [[nodiscard]] T getThresholdInUseDb() const noexcept
1087 {
1088 return isAutoThreshold() ? thresholdInUseDb_.load(std::memory_order_relaxed) : threshold_.load(std::memory_order_relaxed);
1089 }
1090
1102 void setAmount(T amount) noexcept
1103 {
1104 if (!std::isfinite(amount)) return;
1105 amount_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1106 }
1107
1109 [[nodiscard]] T getAmount() const noexcept { return amount_.load(std::memory_order_relaxed); }
1110
1120 void setSoftRange(bool on) noexcept
1121 {
1122 rangeShape_.store(static_cast<int>(on ? RangeShape::Asymptotic : RangeShape::Corner), std::memory_order_relaxed);
1123 }
1124
1126 [[nodiscard]] bool isSoftRange() const noexcept
1127 {
1128 return rangeShape_.load(std::memory_order_relaxed) != static_cast<int>(RangeShape::Corner);
1129 }
1130
1132 enum class RangeShape
1133 {
1134 Corner,
1135 Asymptotic,
1136 Local
1137 };
1138
1153 void setRangeShape(RangeShape shape) noexcept
1154 {
1155 rangeShape_.store(static_cast<int>(clampEnum(shape, RangeShape::Local)), std::memory_order_relaxed);
1156 }
1157
1159 [[nodiscard]] RangeShape getRangeShape() const noexcept
1160 {
1161 return static_cast<RangeShape>(rangeShape_.load(std::memory_order_relaxed));
1162 }
1163
1204 void setPrecision(Precision precision) noexcept
1205 {
1206 precision_.store(clampEnum(precision, Precision::High), std::memory_order_relaxed);
1207 }
1208
1210 [[nodiscard]] Precision getPrecision() const noexcept { return precision_.load(std::memory_order_relaxed); }
1211
1212
1214 enum class StagePosition
1215 {
1216 Off,
1217 Before,
1218 After
1219 };
1220
1223
1245 void setCharacterStage(StagePosition position) noexcept
1246 {
1247 stagePosition_.store(clampEnum(position, StagePosition::After), std::memory_order_relaxed);
1248 }
1249
1251 [[nodiscard]] StagePosition getCharacterStage() const noexcept { return stagePosition_.load(std::memory_order_relaxed); }
1252
1254 void setCharacterStageSettings(const StageSettings& settings) noexcept
1255 {
1256 stageBefore_.setSettings(settings);
1257 stageAfter_.setSettings(settings);
1258 }
1259
1261 [[nodiscard]] StageSettings getCharacterStageSettings() const noexcept { return stageBefore_.settings(); }
1262
1287 void setProgramRelease(T amount) noexcept
1288 {
1289 if (!std::isfinite(amount)) return;
1290 programRelease_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1291 }
1292
1294 [[nodiscard]] T getProgramRelease() const noexcept { return programRelease_.load(std::memory_order_relaxed); }
1295
1311 void setAdaptiveAttack(T amount) noexcept
1312 {
1313 if (!std::isfinite(amount)) return;
1314 adaptiveAttack_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1315 }
1316
1318 [[nodiscard]] T getAdaptiveAttack() const noexcept { return adaptiveAttack_.load(std::memory_order_relaxed); }
1319
1338 void setSpectralTiming(T amount) noexcept
1339 {
1340 if (!std::isfinite(amount)) return;
1341 spectralTiming_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1342 }
1343
1345 [[nodiscard]] T getSpectralTiming() const noexcept { return spectralTiming_.load(std::memory_order_relaxed); }
1346
1363 void setAttackEmphasis(T amount) noexcept
1364 {
1365 if (!std::isfinite(amount)) return;
1366 attackEmphasis_.store(std::clamp(amount, T(-1), T(1)), std::memory_order_relaxed);
1367 }
1368
1370 [[nodiscard]] T getAttackEmphasis() const noexcept { return attackEmphasis_.load(std::memory_order_relaxed); }
1371
1373 void setDetector(DetectorType type) noexcept
1374 {
1375 // The shared TruePeakDetector builds its coefficients lazily on first
1376 // use (thread-safe static), so this is a pure atomic publication.
1377 detectorType_.store(clampEnum(type, DetectorType::Hybrid), std::memory_order_relaxed);
1378 }
1379
1388 void setHoldTime(T ms) noexcept
1389 {
1390 if (!std::isfinite(ms)) return;
1391 holdMs_.store(std::clamp(ms, T(0), T(500)), std::memory_order_relaxed);
1392 timeConstantsDirty_.store(true, std::memory_order_release);
1393 }
1394
1396 enum class HoldMode
1397 {
1402 Deepest,
1408 EveryPeak
1409 };
1410
1412 void setHoldMode(HoldMode mode) noexcept
1413 {
1414 holdMode_.store(clampEnum(mode, HoldMode::EveryPeak), std::memory_order_relaxed);
1415 timeConstantsDirty_.store(true, std::memory_order_release);
1416 }
1417
1419 [[nodiscard]] HoldMode getHoldMode() const noexcept { return holdMode_.load(std::memory_order_relaxed); }
1420
1429 void setRange(T dB) noexcept
1430 {
1431 if (!std::isfinite(dB)) return;
1432 rangeDb_.store(std::max(dB, T(0)), std::memory_order_relaxed);
1433 }
1434
1436 void setTopology(Topology topo) noexcept
1437 {
1438 topology_.store(clampEnum(topo, Topology::FeedBack), std::memory_order_relaxed);
1439 // Feedback loops re-derive the attack coefficient (loop speed-up).
1440 timeConstantsDirty_.store(true, std::memory_order_release);
1441 }
1442
1444 void setCharacter(Character type) noexcept
1445 {
1446 character_.store(clampEnum(type, Character::Layered), std::memory_order_relaxed);
1447 timeConstantsDirty_.store(true, std::memory_order_release);
1448 }
1449
1451 enum class OptoCell
1452 {
1453 TwoStage,
1454 ThreeStage
1455 };
1456
1472 void setOptoCell(OptoCell cell) noexcept
1473 {
1474 optoCell_.store(clampEnum(cell, OptoCell::ThreeStage), std::memory_order_relaxed);
1475 timeConstantsDirty_.store(true, std::memory_order_release);
1476 }
1477
1479 [[nodiscard]] OptoCell getOptoCell() const noexcept { return optoCell_.load(std::memory_order_relaxed); }
1480
1505 void setCharacterColor(T amount) noexcept
1506 {
1507 if (!std::isfinite(amount)) return;
1508 characterColor_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1509 }
1510
1524 void setGainSmoothing(T ms) noexcept
1525 {
1526 if (!std::isfinite(ms)) return;
1527 gainSmoothMs_.store(std::clamp(ms, T(0), T(50)), std::memory_order_relaxed);
1528 timeConstantsDirty_.store(true, std::memory_order_release);
1529 }
1530
1532 [[nodiscard]] T getGainSmoothing() const noexcept { return gainSmoothMs_.load(std::memory_order_relaxed); }
1533
1550 void setReleaseLanding(T ms) noexcept
1551 {
1552 if (!std::isfinite(ms)) return;
1553 landingMs_.store(std::clamp(ms, T(0), T(2000)), std::memory_order_relaxed);
1554 timeConstantsDirty_.store(true, std::memory_order_release);
1555 }
1556
1558 [[nodiscard]] T getReleaseLanding() const noexcept { return landingMs_.load(std::memory_order_relaxed); }
1559
1580 void setControlNetwork(T depthDb, T cornerHz = T(10)) noexcept
1581 {
1582 if (!std::isfinite(depthDb)) return;
1583 networkDepthDb_.store(std::clamp(depthDb, T(0), T(12)), std::memory_order_relaxed);
1584 if (std::isfinite(cornerHz))
1585 networkCornerHz_.store(std::clamp(cornerHz, T(1), T(100)), std::memory_order_relaxed);
1586 timeConstantsDirty_.store(true, std::memory_order_release);
1587 }
1588
1590 [[nodiscard]] T getControlNetworkDepth() const noexcept { return networkDepthDb_.load(std::memory_order_relaxed); }
1591
1593 [[nodiscard]] T getControlNetworkCorner() const noexcept { return networkCornerHz_.load(std::memory_order_relaxed); }
1594
1596 static constexpr double kReductionToneLowHz = 200.0;
1598 static constexpr double kReductionToneHighHz = 4000.0;
1599
1625 void setReductionTone(T lowDb, T highDb) noexcept
1626 {
1627 if (std::isfinite(lowDb)) toneLowDb_.store(std::clamp(lowDb, T(-3), T(3)), std::memory_order_relaxed);
1628 if (std::isfinite(highDb)) toneHighDb_.store(std::clamp(highDb, T(-3), T(3)), std::memory_order_relaxed);
1629 }
1630
1632 [[nodiscard]] T getReductionToneLow() const noexcept { return toneLowDb_.load(std::memory_order_relaxed); }
1633
1635 [[nodiscard]] T getReductionToneHigh() const noexcept { return toneHighDb_.load(std::memory_order_relaxed); }
1636
1653 void setControlLeak(T amount) noexcept
1654 {
1655 if (!std::isfinite(amount)) return;
1656 controlLeak_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1657 }
1658
1660 [[nodiscard]] T getControlLeak() const noexcept { return controlLeak_.load(std::memory_order_relaxed); }
1661
1681 void setDetectorAsymmetry(T amount) noexcept
1682 {
1683 if (!std::isfinite(amount)) return;
1684 detectorAsymmetry_.store(std::clamp(amount, T(-1), T(1)), std::memory_order_relaxed);
1685 }
1686
1688 [[nodiscard]] T getDetectorAsymmetry() const noexcept { return detectorAsymmetry_.load(std::memory_order_relaxed); }
1689
1708 void setDetectorDrift(T amount) noexcept
1709 {
1710 if (!std::isfinite(amount)) return;
1711 detectorDrift_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1712 }
1713
1715 [[nodiscard]] T getDetectorDrift() const noexcept { return detectorDrift_.load(std::memory_order_relaxed); }
1716
1739 {
1740 cleanBallistics_.store(clampEnum(mode, CleanBallistics::Decoupled), std::memory_order_relaxed);
1741 }
1742
1744 [[nodiscard]] CleanBallistics getCleanBallistics() const noexcept
1745 {
1746 return cleanBallistics_.load(std::memory_order_relaxed);
1747 }
1748
1750 [[nodiscard]] T getCharacterColor() const noexcept
1751 {
1752 return characterColor_.load(std::memory_order_relaxed);
1753 }
1754
1765 void setSidechainHPF(bool enabled, T cutoffHz = T(80)) noexcept
1766 {
1767 scHpfEnabled_.store(enabled, std::memory_order_relaxed);
1768 if (std::isfinite(cutoffHz) && cutoffHz > T(0))
1769 scHpfFreq_.store(cutoffHz, std::memory_order_relaxed);
1770 // Consumed by processBlock() and by processSample() (channel 0).
1771 scHpfDirty_.store(true, std::memory_order_release);
1772 }
1773
1777 using KeyBand = typename KeyEq::Band;
1779 using KeyShape = typename KeyEq::Shape;
1783 static constexpr int kKeyBands = KeyEq::kBands;
1784
1810 void setSidechainBand(int band, const KeyBand& settings) noexcept { keyEq_.setBand(band, settings); }
1811
1813 [[nodiscard]] KeyBand getSidechainBand(int band) const noexcept { return keyEq_.getBand(band); }
1814
1819 [[nodiscard]] typename KeyEq::Response getSidechainResponse() const noexcept { return keyEq_.getResponse(); }
1820
1834 void setSidechainListen(bool on) noexcept { scListen_.store(on, std::memory_order_relaxed); }
1835
1837 [[nodiscard]] bool isSidechainListen() const noexcept { return scListen_.load(std::memory_order_relaxed); }
1838
1844 void setRemovalListen(bool on) noexcept { removalListen_.store(on, std::memory_order_relaxed); }
1846 [[nodiscard]] bool isRemovalListen() const noexcept { return removalListen_.load(std::memory_order_relaxed); }
1847
1864 void setRmsWindow(T ms) noexcept
1865 {
1866 if (!std::isfinite(ms)) return;
1867 rmsWindowMsAtomic_.store(std::clamp(ms, T(1), T(500)), std::memory_order_relaxed);
1868 rmsWindowDirty_.store(true, std::memory_order_release);
1869 }
1870
1871 // =========================================================================
1872 // Metering & Getters
1873 // =========================================================================
1874
1876 [[nodiscard]] T getGainReductionDb() const noexcept { return gainReductionDb_.load(std::memory_order_relaxed); }
1877
1879 [[nodiscard]] DetectorType getDetector() const noexcept { return detectorType_.load(std::memory_order_relaxed); }
1880
1882 [[nodiscard]] Topology getTopology() const noexcept { return topology_.load(std::memory_order_relaxed); }
1883
1885 [[nodiscard]] Character getCharacter() const noexcept { return character_.load(std::memory_order_relaxed); }
1886
1898 [[nodiscard]] int getLatency() const noexcept
1899 {
1900 const int coloured = (stagePosition_.load(std::memory_order_relaxed) != StagePosition::Off)
1901 ? stageBefore_.getLatency() : 0;
1902 return gainPathLatency() + coloured;
1903 }
1904
1905private:
1907 [[nodiscard]] int gainPathLatency() const noexcept
1908 {
1909 const CharacterProfile& profile = profileOf(character_.load(std::memory_order_relaxed));
1910 const bool feedback = topologyFor(profile, topology_.load(std::memory_order_relaxed)) == Topology::FeedBack;
1911 const DetectorType detType = detectorFor(profile, detectorType_.load(std::memory_order_relaxed));
1912 // The same routing as processBlock(): see usePrecision().
1913 const Mode mode = modeIn(mode_.load(std::memory_order_relaxed),
1915 const bool solved = feedback && detType == DetectorType::Peak && mode == Mode::Downward;
1916 const bool layered = isLayered(profile, mode);
1917 const int reading = (precision_.load(std::memory_order_relaxed) == Precision::High && !layered
1918 && readsBetweenSamples(detType) && (!feedback || solved)) ? kDetectorDelay : 0;
1919 if (feedback && !feedbackKeyed_.load(std::memory_order_relaxed)) return reading;
1920 // Derive the lookahead from the published parameter rather than the
1921 // audio-thread cache: hosts re-read the latency right after a setter,
1922 // before the next block has consumed the coefficient-update flag.
1923 const int lookNow = static_cast<int>(static_cast<T>(sampleRate_) * std::clamp(
1924 lookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000));
1925 const int kept = static_cast<int>(static_cast<T>(sampleRate_) * std::clamp(
1926 maxLookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000));
1927 return std::max(lookNow, kept) + reading;
1928 }
1929
1935 void processRouted(AudioBufferView<T> audio, AudioBufferView<T> sidechain) noexcept
1936 {
1937 const Route route = route_.load(std::memory_order_relaxed);
1938 const bool routed = route != Route::Stereo && audio.getNumChannels() == 2 && routeBlock_ > 0;
1939 if (routed != routeWas_ || (routed && route != routeIn_))
1940 {
1941 // Every state would carry another signal: the route starts clean.
1942 if (sampleRate_ > 0) reset();
1943 routeWas_ = routed;
1944 routeIn_ = route;
1945 }
1946 if (!routed)
1947 {
1948 processBlockImpl(audio, sidechain);
1949 return;
1950 }
1951 if (!(sampleRate_ > 0)) return;
1952
1953 const int total = audio.getNumSamples();
1954 const bool external = sidechain.getNumChannels() > 0 && sidechain.getNumSamples() >= total
1955 && sidechain.getChannel(0) != audio.getChannel(0);
1956 for (int off = 0; off < total; off += routeBlock_)
1957 {
1958 const int m = std::min(routeBlock_, total - off);
1959 T* const left = audio.getChannel(0) + off;
1960 T* const right = audio.getChannel(1) + off;
1961 // The pair as its middle and its sides, in place.
1962 for (int i = 0; i < m; ++i)
1963 {
1964 const T l = left[i], r = right[i];
1965 left[i] = (l + r) * T(0.5);
1966 right[i] = (l - r) * T(0.5);
1967 }
1968 T* keyMid = left;
1969 T* keySide = right;
1970 if (external)
1971 {
1972 const T* const kl = sidechain.getChannel(0) + off;
1973 const T* const kr = (sidechain.getNumChannels() > 1 ? sidechain.getChannel(1) : sidechain.getChannel(0)) + off;
1974 keyMid = routeKey_.getChannel(0);
1975 keySide = routeKey_.getChannel(1);
1976 for (int i = 0; i < m; ++i)
1977 {
1978 keyMid[i] = (kl[i] + kr[i]) * T(0.5);
1979 keySide[i] = (kl[i] - kr[i]) * T(0.5);
1980 }
1981 }
1982
1983 if (route == Route::MidSide)
1984 {
1985 T* pair[2] = { left, right };
1986 T* keys[2] = { keyMid, keySide };
1987 const T focus = midSideFocus_.load(std::memory_order_relaxed);
1988 partTo_[0] = focus > T(0) ? T(1) - focus : T(1);
1989 partTo_[1] = focus < T(0) ? T(1) + focus : T(1);
1990 parted_ = partFrom_[0] != T(1) || partFrom_[1] != T(1) || partTo_[0] != T(1) || partTo_[1] != T(1);
1991 processBlockImpl(AudioBufferView<T>(pair, 2, m), AudioBufferView<T>(keys, 2, m));
1993 parted_ = false;
1994 }
1995 else
1996 {
1997 const bool sides = route == Route::Side || route == Route::MidKeysSide;
1998 const bool keyOfSides = route == Route::Side || route == Route::SideKeysMid;
1999 T* treated[1] = { sides ? right : left };
2000 T* key[1] = { keyOfSides ? keySide : keyMid };
2001 T* const waiting = sides ? left : right;
2002 processBlockImpl(AudioBufferView<T>(treated, 1, m), AudioBufferView<T>(key, 1, m));
2003 // The other part waits for it; listened to, it is left out.
2004 const int late = std::min(gainPathLatency(), routeReach_);
2005 const bool listening = scListen_.load(std::memory_order_relaxed)
2006 || removalListen_.load(std::memory_order_relaxed);
2007 for (int i = 0; i < m; ++i)
2008 {
2009 routeDelay_.push(waiting[i]);
2010 waiting[i] = listening ? T(0) : routeDelay_.read(late);
2011 }
2012 }
2013
2014 // Back to left and right.
2015 for (int i = 0; i < m; ++i)
2016 {
2017 const T mid = left[i], side = right[i];
2018 left[i] = mid + side;
2019 right[i] = mid - side;
2020 }
2021 }
2022 }
2023
2024public:
2025
2026
2028 [[nodiscard]] std::vector<uint8_t> getState() const
2029 {
2030 StateWriter w(stateId("COMP"), 1);
2031 // Explicit float casts: the blob stores float, and with T = double the
2032 // unqualified write(key, double) would be ambiguous (float/int32/bool).
2033 w.write("threshold", static_cast<float>(threshold_.load(std::memory_order_relaxed)));
2034 w.write("ratio", static_cast<float>(ratio_.load(std::memory_order_relaxed)));
2035 w.write("attack", static_cast<float>(attackMs_.load(std::memory_order_relaxed)));
2036 w.write("release", static_cast<float>(releaseMs_.load(std::memory_order_relaxed)));
2037 w.write("knee", static_cast<float>(kneeWidth_.load(std::memory_order_relaxed)));
2038 w.write("makeup", static_cast<float>(makeupGain_.load(std::memory_order_relaxed)));
2039 const auto amMode = autoMakeupMode_.load(std::memory_order_relaxed);
2040 w.write("autoMakeup", amMode != AutoMakeupMode::Off); // legacy bool key
2041 w.write("autoMakeupMode", static_cast<int32_t>(amMode));
2042 w.write("stereoLink", static_cast<float>(stereoLink_.load(std::memory_order_relaxed)));
2043 w.write("linkMode", static_cast<int32_t>(linkMode_.load(std::memory_order_relaxed)));
2044 w.write("route", static_cast<int32_t>(getRoute()));
2045 w.write("midSideFocus", static_cast<float>(getMidSideFocus()));
2046 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
2047 w.write("lookahead", static_cast<float>(lookaheadMs_.load(std::memory_order_relaxed)));
2048 w.write("hold", static_cast<float>(holdMs_.load(std::memory_order_relaxed)));
2049 w.write("holdMode", static_cast<int32_t>(getHoldMode()));
2050 w.write("range", static_cast<float>(rangeDb_.load(std::memory_order_relaxed)));
2051 w.write("detector", static_cast<int32_t>(detectorType_.load(std::memory_order_relaxed)));
2052 w.write("topology", static_cast<int32_t>(topology_.load(std::memory_order_relaxed)));
2053 w.write("character", static_cast<int32_t>(character_.load(std::memory_order_relaxed)));
2054 w.write("optoCell", static_cast<int32_t>(optoCell_.load(std::memory_order_relaxed)));
2055 w.write("characterColor", static_cast<float>(characterColor_.load(std::memory_order_relaxed)));
2056 w.write("cleanBallistics", static_cast<int32_t>(cleanBallistics_.load(std::memory_order_relaxed)));
2057 w.write("mode", static_cast<int32_t>(mode_.load(std::memory_order_relaxed)));
2058 w.write("scHpf", scHpfEnabled_.load(std::memory_order_relaxed));
2059 w.write("scHpfFreq", static_cast<float>(scHpfFreq_.load(std::memory_order_relaxed)));
2060 w.write("rmsWindow", static_cast<float>(rmsWindowMsAtomic_.load(std::memory_order_relaxed)));
2061 w.write("autoThreshold", autoThreshold_.load(std::memory_order_relaxed));
2062 w.write("maxLookahead", static_cast<float>(maxLookaheadMs_.load(std::memory_order_relaxed)));
2063 w.write("lookaheadShape", static_cast<int32_t>(getLookaheadShape()));
2064 w.write("feedbackKeyed", isFeedbackKeyed());
2065 w.write("amount", static_cast<float>(amount_.load(std::memory_order_relaxed)));
2066 w.write("softRange", isSoftRange()); // what an older build understands
2067 w.write("rangeShape", static_cast<int32_t>(getRangeShape()));
2068 w.write("precision", static_cast<int32_t>(precision_.load(std::memory_order_relaxed)));
2069 {
2071 w.write("stage", static_cast<int32_t>(getCharacterStage()));
2072 w.write("stageDrive", static_cast<float>(st.driveDb));
2073 w.write("stageEmphasis", static_cast<float>(st.emphasisDb));
2074 w.write("stageAsymmetry", static_cast<float>(st.asymmetry));
2075 w.write("stageDrift", static_cast<float>(st.drift));
2076 w.write("stageSag", static_cast<float>(st.sag));
2077 w.write("stageNoise", static_cast<float>(st.noiseDb));
2078 }
2079 w.write("programRelease", static_cast<float>(programRelease_.load(std::memory_order_relaxed)));
2080 w.write("adaptiveAttack", static_cast<float>(adaptiveAttack_.load(std::memory_order_relaxed)));
2081 w.write("spectralTiming", static_cast<float>(spectralTiming_.load(std::memory_order_relaxed)));
2082 w.write("attackEmphasis", static_cast<float>(attackEmphasis_.load(std::memory_order_relaxed)));
2083 keyEq_.writeState(w, "key");
2084 w.write("gainSmoothing", static_cast<float>(gainSmoothMs_.load(std::memory_order_relaxed)));
2085 w.write("releaseLanding", static_cast<float>(landingMs_.load(std::memory_order_relaxed)));
2086 w.write("networkDepth", static_cast<float>(networkDepthDb_.load(std::memory_order_relaxed)));
2087 w.write("networkCorner", static_cast<float>(networkCornerHz_.load(std::memory_order_relaxed)));
2088 w.write("toneLow", static_cast<float>(toneLowDb_.load(std::memory_order_relaxed)));
2089 w.write("toneHigh", static_cast<float>(toneHighDb_.load(std::memory_order_relaxed)));
2090 w.write("controlLeak", static_cast<float>(controlLeak_.load(std::memory_order_relaxed)));
2091 w.write("detectorAsymmetry", static_cast<float>(detectorAsymmetry_.load(std::memory_order_relaxed)));
2092 w.write("detectorDrift", static_cast<float>(detectorDrift_.load(std::memory_order_relaxed)));
2093 w.write("liftBelow", static_cast<float>(liftBelow_.load(std::memory_order_relaxed)));
2094 w.write("liftRatio", static_cast<float>(liftRatio_.load(std::memory_order_relaxed)));
2095 w.write("liftRange", static_cast<float>(liftRange_.load(std::memory_order_relaxed)));
2096 return w.blob();
2097 }
2098
2100 bool setState(const uint8_t* data, size_t size)
2101 {
2102 StateReader r(data, size);
2103 if (!r.isValid() || r.processorId() != stateId("COMP")) return false;
2104 setThreshold(static_cast<T>(r.read("threshold", -20.0f)));
2105 setRatio(static_cast<T>(r.read("ratio", 4.0f)));
2106 setAttack(static_cast<T>(r.read("attack", 5.0f)));
2107 setRelease(static_cast<T>(r.read("release", 100.0f)));
2108 setKnee(static_cast<T>(r.read("knee", 0.0f)));
2109 setMakeupGain(static_cast<T>(r.read("makeup", 0.0f)));
2110 // The mode key wins; legacy blobs only carry the bool (true = Adaptive).
2111 const int amLegacy = r.read("autoMakeup", false) ? 2 : 0;
2112 setAutoMakeup(static_cast<AutoMakeupMode>(
2113 std::clamp(r.read("autoMakeupMode", amLegacy), 0, 3)));
2114 setStereoLink(static_cast<T>(r.read("stereoLink", 1.0f)));
2115 setLinkMode(static_cast<LinkMode>(r.read("linkMode", 0)));
2116 setRoute(static_cast<Route>(r.read("route", 0)));
2117 setMidSideFocus(static_cast<T>(r.read("midSideFocus", 0.0f)));
2118 setMix(static_cast<T>(r.read("mix", 1.0f)));
2119 setLookahead(static_cast<T>(r.read("lookahead", 0.0f)));
2120 setHoldTime(static_cast<T>(r.read("hold", 0.0f)));
2121 setHoldMode(static_cast<HoldMode>(r.read("holdMode", 0)));
2122 setRange(static_cast<T>(r.read("range", 100.0f)));
2123 setDetector(static_cast<DetectorType>(r.read("detector", 0)));
2124 setTopology(static_cast<Topology>(r.read("topology", 0)));
2125 setCharacter(static_cast<Character>(r.read("character", 0)));
2126 setOptoCell(static_cast<OptoCell>(r.read("optoCell", 0)));
2127 setCharacterColor(static_cast<T>(r.read("characterColor", 0.0f)));
2128 setCleanBallistics(static_cast<CleanBallistics>(r.read("cleanBallistics", 0)));
2129 setMode(static_cast<Mode>(r.read("mode", 0)));
2130 setSidechainHPF(r.read("scHpf", false), static_cast<T>(r.read("scHpfFreq", 80.0f)));
2131 setRmsWindow(static_cast<T>(r.read("rmsWindow", 10.0f)));
2132 setAutoThreshold(r.read("autoThreshold", false));
2133 setMaxLookahead(static_cast<T>(r.read("maxLookahead", 0.0f)));
2134 setLookaheadShape(static_cast<LookaheadShape>(r.read("lookaheadShape", 0)));
2135 setFeedbackKeyed(r.read("feedbackKeyed", false));
2136 setAmount(static_cast<T>(r.read("amount", 1.0f)));
2137 setRangeShape(static_cast<RangeShape>(r.read("rangeShape", r.read("softRange", false) ? 1 : 0)));
2138 setPrecision(static_cast<Precision>(r.read("precision", 0)));
2139 {
2140 const StageSettings defaults {};
2141 StageSettings st;
2142 st.driveDb = static_cast<T>(r.read("stageDrive", static_cast<float>(defaults.driveDb)));
2143 st.emphasisDb = static_cast<T>(r.read("stageEmphasis", static_cast<float>(defaults.emphasisDb)));
2144 st.asymmetry = static_cast<T>(r.read("stageAsymmetry", static_cast<float>(defaults.asymmetry)));
2145 st.drift = static_cast<T>(r.read("stageDrift", static_cast<float>(defaults.drift)));
2146 st.sag = static_cast<T>(r.read("stageSag", static_cast<float>(defaults.sag)));
2147 st.noiseDb = static_cast<T>(r.read("stageNoise", static_cast<float>(defaults.noiseDb)));
2149 setCharacterStage(static_cast<StagePosition>(r.read("stage", 0)));
2150 }
2151 setProgramRelease(static_cast<T>(r.read("programRelease", 0.0f)));
2152 setAdaptiveAttack(static_cast<T>(r.read("adaptiveAttack", 0.0f)));
2153 setSpectralTiming(static_cast<T>(r.read("spectralTiming", 0.0f)));
2154 setAttackEmphasis(static_cast<T>(r.read("attackEmphasis", 0.0f)));
2155 keyEq_.readState(r, "key");
2156 setGainSmoothing(static_cast<T>(r.read("gainSmoothing", 0.0f)));
2157 setReleaseLanding(static_cast<T>(r.read("releaseLanding", 0.0f)));
2158 setControlNetwork(static_cast<T>(r.read("networkDepth", 0.0f)), static_cast<T>(r.read("networkCorner", 10.0f)));
2159 setReductionTone(static_cast<T>(r.read("toneLow", 0.0f)), static_cast<T>(r.read("toneHigh", 0.0f)));
2160 setControlLeak(static_cast<T>(r.read("controlLeak", 0.0f)));
2161 setDetectorAsymmetry(static_cast<T>(r.read("detectorAsymmetry", 0.0f)));
2162 setDetectorDrift(static_cast<T>(r.read("detectorDrift", 0.0f)));
2163 setLift(static_cast<T>(r.read("liftBelow", 30.0f)), static_cast<T>(r.read("liftRatio", 2.0f)),
2164 static_cast<T>(r.read("liftRange", 6.0f)));
2165 return true;
2166 }
2167
2168protected:
2169 static constexpr int kMaxChannels = 16;
2170
2179 template <typename E>
2180 [[nodiscard]] static E clampEnum(E value, E last) noexcept
2181 {
2182 const int v = std::clamp(static_cast<int>(value), 0, static_cast<int>(last));
2183 return static_cast<E>(v);
2184 }
2185
2197 {
2198 if (!(sampleRate_ > 0)) return; // not prepared: leave the audio untouched
2199 DenormalGuard guard;
2200 const int nCh = std::min(audio.getNumChannels(), kMaxChannels);
2201 const int nS = audio.getNumSamples();
2202 // A short external sidechain would be read past its end; fall back
2203 // to the internal key instead (release-safe, documented above).
2204 const int scCh = (sidechain.getNumSamples() >= nS)
2205 ? sidechain.getNumChannels() : 0;
2206
2207 // Sync atomic parameters to block-local smoothed state
2208 thresholdSmooth_.setTargetValue(threshold_.load(std::memory_order_relaxed));
2209 ratioSmooth_.setTargetValue(std::max(ratio_.load(std::memory_order_relaxed), T(1)));
2210 kneeSmooth_.setTargetValue(std::max(kneeWidth_.load(std::memory_order_relaxed), T(0)));
2211 makeupSmooth_.setTargetValue(makeupGain_.load(std::memory_order_relaxed));
2212 mixSmooth_.setTargetValue(mix_.load(std::memory_order_relaxed));
2213 colorSmooth_.setTargetValue(characterColor_.load(std::memory_order_relaxed));
2214 amountSmooth_.setTargetValue(amount_.load(std::memory_order_relaxed));
2215
2216 if (timeConstantsDirty_.exchange(false, std::memory_order_acquire))
2217 updateTimeConstants(static_cast<T>(sampleRate_));
2218 if (scHpfDirty_.load(std::memory_order_relaxed)
2219 && scHpfDirty_.exchange(false, std::memory_order_acquire))
2221 const bool keyEqOn = keyEq_.sync();
2222 const bool listen = scListen_.load(std::memory_order_relaxed);
2223 // What is not the plain gain (a tone that follows the reduction, the
2224 // leak of the control, a detector that is not symmetric) runs frame by frame.
2225 const bool sampleWise = syncAudioPath();
2226
2227 // Apply a pending RMS window change here, on the audio thread.
2228 if (rmsWindowDirty_.exchange(false, std::memory_order_acquire))
2229 {
2230 rmsWindowMs_ = rmsWindowMsAtomic_.load(std::memory_order_relaxed);
2232 }
2233
2234 // Cache enum/bool params locally to prevent atomic stalls inside the tight DSP loop
2235 auto detType = detectorType_.load(std::memory_order_relaxed);
2236 auto topo = topology_.load(std::memory_order_relaxed);
2237 auto charType = character_.load(std::memory_order_relaxed);
2238 auto modeType = mode_.load(std::memory_order_relaxed);
2239 bool scHpf = scHpfEnabled_.load(std::memory_order_relaxed);
2240 auto autoMkup = autoMakeupMode_.load(std::memory_order_relaxed);
2241 T sLink = stereoLink_.load(std::memory_order_relaxed);
2242 const LinkMode linkMode = linkMode_.load(std::memory_order_relaxed);
2243
2244 // The FET character is a feedback design like the 1176 it models: it
2245 // always detects on the compressed output with the hardware's peak
2246 // rectifier, whatever Topology and Detector say.
2247 const CharacterProfile& profile = profileOf(charType);
2248 const Topology topoEff = topologyFor(profile, topo);
2249 const DetectorType detTypeEff = detectorFor(profile, detType);
2250 modeType = modeIn(modeType, topoEff);
2251
2252 // Downward feedback with the peak detector resolves the loop
2253 // semi-implicitly (the level the loop will read is a known function
2254 // of the gain): stable at any attack, and the observed static curve
2255 // lands exactly on the requested ratio/knee. Detectors with memory
2256 // (RMS/TruePeak/Hilbert/Split) keep the explicit one-sample loop.
2257 const bool fbImplicit = topoEff == Topology::FeedBack
2258 && modeType == Mode::Downward
2259 && detTypeEff == DetectorType::Peak;
2260
2261 const bool layered = isLayered(profile, modeType);
2262 syncLayerState(layered);
2263 const bool splitAdaptive = detTypeEff == DetectorType::SplitPolarity && !layered;
2264 const bool decoupled = useDecoupled(charType, topoEff);
2265 syncDecoupledState(decoupled);
2266 const bool precise = !layered && usePrecision(topoEff, fbImplicit, splitAdaptive);
2267 const bool gainSmooth = shapesGain();
2268 syncGainSmoothing(gainSmooth);
2269 syncPrecisionState(precise);
2270 program_ = programTiming(charType, topoEff, decoupled, splitAdaptive);
2272 const bool keyBalance = program_.active && program_.spectral > 0.0;
2273
2274 // A loop that reads its own output has no room for a lookahead: in
2275 // FeedBack it is off, unless the loop is closed around the key
2276 // (setFeedbackKeyed()).
2277 const bool keyedLoop = topoEff == Topology::FeedBack && feedbackKeyed_.load(std::memory_order_relaxed);
2278 int activeLookahead = (topoEff == Topology::FeedBack && !keyedLoop) ? 0 : latencySamples_;
2279 const bool autoThr = autoThreshold_.load(std::memory_order_relaxed);
2280 // An external key does not pass the colour stage placed before the
2281 // compressor: listened to, it waits for that stage too.
2282 // The lookahead as a ramp: its state starts clean when it comes in.
2283 const bool ramp = rampShape_ && activeLookahead > 0;
2284 if (ramp != rampActive_)
2285 {
2286 if (ramp)
2287 for (auto& r : lookaheadRamps_) r.clear();
2288 rampActive_ = ramp;
2289 }
2290 const bool externalKey = scCh > 0 && nCh > 0 && sidechain.getChannel(0) != audio.getChannel(0);
2291 const int stageKeyDelay = (externalKey && stagePosition_.load(std::memory_order_relaxed) == StagePosition::Before)
2292 ? std::min(stageBefore_.getLatency(), kStageKeyRoom) : 0;
2293
2294 // Fully linked channels share one gain computer: every channel reads
2295 // the same linked level into the same state, so computing it once per
2296 // frame gives the same gain (the per-channel path differs only in the
2297 // rounding of level + 1 * (linked - level)). SplitPolarity's adaptive
2298 // release reads each channel's own output, so it keeps the
2299 // per-channel path.
2300 const bool shared = (sLink >= T(1)) && !splitAdaptive && nCh > 1 && !parted_;
2301 // The dominant link reads the pair as one (two channels, some link).
2302 const bool dominantLink = linkMode == LinkMode::Dominant && nCh == 2 && sLink > T(0);
2303 if (dominantLink) flushLinkCovariance();
2304
2305 // Settled parameter smoothers: read once per block instead of a call
2306 // per sample (a settled smoother returns its target either way).
2307 analyticSmooth_.setTargetValue(autoMkup == AutoMakeupMode::Analytic
2308 ? analyticMakeupDb(charType, modeType, detTypeEff, decoupled,
2309 topoEff == Topology::FeedBack) : T(0));
2310 const bool paramsMoving = thresholdSmooth_.isSmoothing() || ratioSmooth_.isSmoothing()
2311 || kneeSmooth_.isSmoothing() || makeupSmooth_.isSmoothing()
2312 || mixSmooth_.isSmoothing() || colorSmooth_.isSmoothing()
2313 || amountSmooth_.isSmoothing() || analyticSmooth_.isSmoothing();
2314 T thresh = thresholdSmooth_.getCurrentValue();
2315 T ratio = ratioSmooth_.getCurrentValue();
2316 T knee = kneeSmooth_.getCurrentValue();
2317 T mkupBase = makeupSmooth_.getCurrentValue();
2318 T mixVal = mixSmooth_.getCurrentValue();
2319 T colorAmt = colorSmooth_.getCurrentValue();
2320 T amount = amountSmooth_.getCurrentValue();
2321 const bool staticMakeup = autoMkup == AutoMakeupMode::Static && reducesOnly(modeType);
2322 const bool adaptiveMakeup = autoMkup == AutoMakeupMode::Adaptive && reducesOnly(modeType);
2323 syncAdaptiveMakeup(adaptiveMakeup);
2324 T staticMakeupDb = staticMakeup
2325 ? computeGain(T(0), thresh, ratio, knee, charType, modeType, T(0)) * T(-0.5)
2326 : T(0);
2327 T analyticDb = analyticSmooth_.getCurrentValue();
2328
2329 const GainPathConfig cfg { charType, modeType, topoEff, fbImplicit, splitAdaptive, decoupled,
2330 feedbackDetectorDelay(detTypeEff), program_.active, layered };
2331
2332 // Feed-forward: the detector never reads the output, so the block
2333 // runs in passes (see processFeedForward). Feedback loops stay per
2334 // sample, and so do Precision::High, whose control signal is worked
2335 // out several times per sample, and the push-pull element, which
2336 // applies the gain through a curve.
2337 const bool feedForward = topoEff == Topology::FeedForward;
2338 const bool element = profile.colour == Colour::PushPull
2339 && (colorAmt > T(0) || colorSmooth_.isSmoothing());
2340 // A band of the key's equalizer on the middle or on the sides of a
2341 // pair takes the key a frame at a time.
2342 const bool keyFrames = keyEqOn && nCh == 2 && keyEq_.isPlaced();
2343 if (feedForward && !precise && !element && !sampleWise && !keyFrames)
2344 {
2345 const FeedForwardConfig ff { detTypeEff, charType, modeType, autoMkup, sLink,
2346 activeLookahead, scHpf, shared, decoupled,
2347 splitAdaptive, staticMakeup, adaptiveMakeup,
2348 paramsMoving, autoThr, activeLookahead - lookaheadSamples_,
2349 program_.active, keyBalance, keyEqOn, listen, layered, gainSmooth,
2350 dominantLink, activeLookahead + stageKeyDelay, latencyKept_, ramp };
2351 const ChunkParams constants { thresh, ratio, knee, mkupBase, mixVal,
2352 staticMakeupDb + analyticDb, amount };
2353 processFeedForward(audio, sidechain, nCh, nS, scCh, ff, constants);
2354 return;
2355 }
2356
2357 // At Precision::High the detectors that rectify read the key at
2358 // kDetectorPoints points per sample, kDetectorDelay samples late, and
2359 // the audio waits for them. The others keep one level per sample.
2360 const bool points = precise && readsBetweenSamples(detTypeEff);
2361 const bool lopsided = lopsidedDetector() && rectifies(detTypeEff);
2362 const int count = points ? kDetectorPoints : 1;
2363 const int audioDelay = activeLookahead + (points ? kDetectorDelay : 0);
2364 const int gainDelay = (feedForward || keyedLoop) ? activeLookahead - lookaheadSamples_ : 0;
2365 const bool gainLine = (feedForward || keyedLoop) && latencyKept_;
2366 const int listenDelay = audioDelay + stageKeyDelay;
2367
2368 for (int i = 0; i < nS; ++i)
2369 {
2370 if (paramsMoving)
2371 {
2372 thresh = thresholdSmooth_.getNextValue();
2373 ratio = ratioSmooth_.getNextValue();
2374 knee = kneeSmooth_.getNextValue();
2375 mkupBase = makeupSmooth_.getNextValue();
2376 mixVal = mixSmooth_.getNextValue();
2377 colorAmt = colorSmooth_.getNextValue();
2378 amount = amountSmooth_.getNextValue();
2379 // Static auto makeup follows the smoothed curve parameters, so
2380 // it stays click-free through threshold/ratio/knee automation.
2381 if (staticMakeup)
2382 staticMakeupDb = computeGain(T(0), thresh, ratio, knee, charType,
2383 modeType, T(0)) * T(-0.5);
2384 analyticDb = analyticSmooth_.getNextValue();
2385 }
2386
2387 // Makeup: shared by every channel of the frame, and usually
2388 // unchanged from the previous frame (the conversion is cached).
2389 // The adaptive envelope is the one left by the previous frame.
2390 T makeupDb = mkupBase + staticMakeupDb + analyticDb;
2391 if (adaptiveMakeup)
2392 makeupDb += -autoMakeupEnv_;
2393 const T makeupLin = makeupToGain(makeupDb);
2394
2395 // 1. Detection path (per channel: every detector keeps its own state)
2396 T linkedLin[kDetectorPoints] = {};
2397 T pairLevel[2][kDetectorPoints] = {};
2398 T heard[kMaxChannels] = {};
2399 T loopSource[kMaxChannels] = {}; // a keyed loop: the key before the gain
2400 double lowSq = 0.0, highSq = 0.0;
2401 // What the detector of a channel reads, before the key's equalizer.
2402 // The sidechain filter must process whatever the detector
2403 // consumes. In feed-forward that is the key (the audio when
2404 // the sidechain buffer lacks channels). In FeedBack it is the
2405 // compressed output (the external key is ignored): the
2406 // previous sample on the explicit path, or the channel's own
2407 // current input on the semi-implicit path (the loop equation
2408 // supplies the gain).
2409 const auto keyOf = [&](int ch) noexcept -> T {
2410 T source;
2411 if (feedForward)
2412 source = (scCh > 0) ? sidechain.getChannel(std::min(ch, scCh - 1))[i]
2413 : audio.getChannel(ch)[i];
2414 else if (keyedLoop)
2415 {
2416 // The loop around the key: the key itself where the loop
2417 // equation supplies the gain, the key times the last
2418 // gain where the detector keeps a memory.
2419 loopSource[ch] = detectorSafe((scCh > 0) ? sidechain.getChannel(std::min(ch, scCh - 1))[i]
2420 : audio.getChannel(ch)[i]);
2421 source = fbImplicit ? loopSource[ch] : fbLastOutput_[ch];
2422 }
2423 else
2424 source = fbImplicit ? audio.getChannel(ch)[i] : fbLastOutput_[ch];
2425 source = detectorSafe(source);
2426 if (keyBalance) balanceBands(source, ch, lowSq, highSq);
2427 if (scHpf) source = applySidechainHPF(source, ch);
2428 return source;
2429 };
2430 T keyPair[2] = {};
2431 if (keyFrames)
2432 {
2433 keyPair[0] = keyOf(0);
2434 keyPair[1] = keyOf(1);
2435 keyEq_.processFrame(keyPair, 2);
2436 }
2437 for (int ch = 0; ch < nCh; ++ch)
2438 {
2439 T detectorIn;
2440 if (keyFrames)
2441 detectorIn = keyPair[ch];
2442 else
2443 {
2444 detectorIn = keyOf(ch);
2445 if (keyEqOn) detectorIn = keyEq_.processSample(detectorIn, ch);
2446 }
2447 heard[ch] = detectorIn;
2448 if (lopsided) detectorIn = asymmetric(detectorIn, ch);
2449
2450 // dB is monotonic in the linear level, so the linked level is
2451 // the dB of the largest linear level (one log per frame and
2452 // point when the channels share the gain computer).
2453 T level[kDetectorPoints] = {};
2454 if (points) detectorPoints(detectorIn, ch, level);
2455 else level[0] = detectLevelLinear(detectorIn, ch, detTypeEff);
2456 for (int j = 0; j < count; ++j)
2457 {
2458 linkedLin[j] = std::max(linkedLin[j], level[j]);
2459 if (!shared) pointLevelDb_[ch][j] = gainToDecibels(level[j]);
2460 }
2461 if (dominantLink && ch < 2)
2462 for (int j = 0; j < count; ++j) pairLevel[ch][j] = level[j];
2463 }
2464 if (dominantLink)
2465 {
2466 const double rho2 = linkCorrelation(heard[0], heard[1]);
2467 for (int j = 0; j < count; ++j)
2468 linkedLin[j] = dominantLevel(pairLevel[0][j], pairLevel[1][j], rho2);
2469 }
2470
2471 if (keyBalance) (void)balanceAdvance(lowSq, highSq);
2472
2473 // The automatic threshold: its reference follows the largest
2474 // level the gain computers read in feed-forward, and the linked
2475 // input in feedback, where the detector reads the output.
2476 T threshNow = thresh;
2477 if (autoThr)
2478 {
2479 T top = T(0);
2480 if (feedForward)
2481 for (int j = 0; j < count; ++j) top = std::max(top, linkedLin[j]);
2482 else if (keyedLoop)
2483 for (int ch = 0; ch < nCh; ++ch) top = std::max(top, std::abs(loopSource[ch]));
2484 else
2485 for (int ch = 0; ch < nCh; ++ch) top = std::max(top, std::abs(detectorSafe(audio.getChannel(ch)[i])));
2486 autoRefDb_[0] = std::max(static_cast<double>(gainToDecibels(top)), autoRefDb_[0] - autoRefFall_);
2487 threshNow = thresh + static_cast<T>(autoRefDb_[0]);
2488 thresholdInUseDb_.store(threshNow, std::memory_order_relaxed);
2489 }
2490
2491 // 2. Stereo linking, static curve and character ballistics (log
2492 // domain). What is heard of the gain is held back inside a
2493 // latency kept for the lookahead and scaled by the amount; the
2494 // loop keeps the whole.
2495 const double slide = gainLine ? slideGainDelay(gainDelay) : 0.0;
2496 const int rampLength = gainLine ? activeLookahead - static_cast<int>(std::ceil(slide)) : activeLookahead;
2497 T blockGR = T(0);
2498 if (shared)
2499 {
2500 T levelDb[kDetectorPoints] = {};
2501 for (int j = 0; j < count; ++j) levelDb[j] = gainToDecibels(linkedLin[j]);
2502 const T loopGR = precise ? gainPathPrecise(levelDb, count, 0, cfg, threshNow, ratio, knee)
2503 : gainPath(levelDb[0], 0, cfg, threshNow, ratio, knee);
2504 // (0 dB is the common case below threshold: skip the exp.)
2505 const T gainLin = (loopGR == T(0)) ? T(1) : decibelsToGain(loopGR);
2506 blockGR = heldBack(rampedIn(loopGR, 0, rampLength, ramp), 0, slide, gainLine);
2507 if (amount < T(1)) blockGR *= amount;
2508 if (gainSmooth) blockGR = smoothedGain(blockGR, 0);
2509 const T outLin = (blockGR == loopGR) ? gainLin : decibelsToGain(blockGR);
2510 for (int ch = 0; ch < nCh; ++ch)
2511 applyGain(audio, ch, i, gainLin, blockGR, audioDelay, charType,
2512 colorAmt, makeupLin, mixVal, outLin);
2513 if (keyedLoop)
2514 for (int ch = 0; ch < nCh; ++ch) fbLastOutput_[ch] = loopSource[ch] * gainLin;
2515 }
2516 else
2517 {
2518 T linkedDb[kDetectorPoints] = {};
2519 for (int j = 0; j < count; ++j)
2520 {
2521 if (dominantLink)
2522 {
2523 linkedDb[j] = gainToDecibels(linkedLin[j]);
2524 continue;
2525 }
2526 linkedDb[j] = pointLevelDb_[0][j];
2527 for (int ch = 1; ch < nCh; ++ch) linkedDb[j] = std::max(linkedDb[j], pointLevelDb_[ch][j]);
2528 }
2529 for (int ch = 0; ch < nCh; ++ch)
2530 {
2531 T levelDb[kDetectorPoints] = {};
2532 for (int j = 0; j < count; ++j)
2533 {
2534 const T own = pointLevelDb_[ch][j];
2535 levelDb[j] = own + sLink * (linkedDb[j] - own);
2536 }
2537 const T loopGR = precise ? gainPathPrecise(levelDb, count, ch, cfg, threshNow, ratio, knee)
2538 : gainPath(levelDb[0], ch, cfg, threshNow, ratio, knee);
2539 const T gainLin = (loopGR == T(0)) ? T(1) : decibelsToGain(loopGR);
2540 T heardGR = heldBack(rampedIn(loopGR, ch, rampLength, ramp), ch, slide, gainLine);
2541 if (amount < T(1)) heardGR *= amount;
2542 if (gainSmooth) heardGR = smoothedGain(heardGR, ch);
2543 T partMakeup = makeupLin;
2544 if (parted_)
2545 {
2546 const T w = partWeight(ch, i, nS);
2547 heardGR *= w;
2548 partMakeup = weightedGain(makeupLin, w);
2549 }
2550 const T outLin = (heardGR == loopGR) ? gainLin : (heardGR == T(0) ? T(1) : decibelsToGain(heardGR));
2551 applyGain(audio, ch, i, gainLin, heardGR, audioDelay, charType,
2552 colorAmt, partMakeup, mixVal, outLin);
2553 if (keyedLoop) fbLastOutput_[ch] = loopSource[ch] * gainLin;
2554 if (ch == 0 || heardGR < blockGR)
2555 blockGR = heardGR; // Track worst-case GR for metering
2556 }
2557 }
2558
2559 if (keyEqOn) keyEq_.advance(1);
2560 // Key listen: what the detectors heard goes out instead, late by
2561 // the latency and under full scale.
2562 if (listen)
2563 {
2564 keyMonitor_.processFrame(heard, nCh, listenDelay);
2565 for (int ch = 0; ch < nCh; ++ch) audio.getChannel(ch)[i] = heard[ch];
2566 }
2567
2568 gainReductionDb_.store(blockGR, std::memory_order_relaxed);
2569
2570 // Auto-makeup envelope tracks slowly (~300ms)
2571 if (adaptiveMakeup)
2572 autoMakeupEnv_ = blockGR + autoMakeupCoeff_ * (autoMakeupEnv_ - blockGR);
2573 }
2574
2575 // The shared gain computer ran on channel 0's state: hand it to the
2576 // other channels so a later unlinked block continues from it.
2577 if (shared && nS > 0) copyGainStateFromChannel0(nCh);
2578 }
2579
2593
2623
2629
2630 static constexpr int kChunk = 32;
2631
2644 int nCh, int nS, int scCh, const FeedForwardConfig& ff,
2645 const ChunkParams& constants) noexcept
2646 {
2647 T thr[kChunk], rat[kChunk], kn[kChunk], mk[kChunk], mixA[kChunk], stMk[kChunk];
2648 T amt[kChunk], thrNow[kChunk];
2649 T mkLin[kChunk];
2650 T level[kMaxChannels][kChunk]; // linear level, then dB level, then linear gain
2651 T gain[kMaxChannels][kChunk]; // smoothed gain change (dB)
2652 T delayed[kMaxChannels][kChunk]; // lookahead-delayed input (the dry reference)
2653 T heard[kMaxChannels][kChunk]; // the key as the detectors read it (key listen)
2654 const int nGain = ff.shared ? 1 : nCh;
2655
2656 if (!ff.paramsMoving)
2657 {
2658 std::fill_n(thr, kChunk, constants.thresh);
2659 std::fill_n(rat, kChunk, constants.ratio);
2660 std::fill_n(kn, kChunk, constants.knee);
2661 std::fill_n(mk, kChunk, constants.makeup);
2662 std::fill_n(mixA, kChunk, constants.mix);
2663 std::fill_n(stMk, kChunk, constants.staticMakeup);
2664 std::fill_n(amt, kChunk, constants.amount);
2665 }
2666
2667 T lastGr = T(0);
2668 for (int o = 0; o < nS; o += kChunk)
2669 {
2670 const int m = std::min(kChunk, nS - o);
2671
2672 // A. Parameters (the colour smoother advances too: it only
2673 // applies to the FET character, which is always feedback).
2674 if (ff.paramsMoving)
2675 {
2676 for (int k = 0; k < m; ++k)
2677 {
2678 thr[k] = thresholdSmooth_.getNextValue();
2679 rat[k] = ratioSmooth_.getNextValue();
2680 kn[k] = kneeSmooth_.getNextValue();
2681 mk[k] = makeupSmooth_.getNextValue();
2682 mixA[k] = mixSmooth_.getNextValue();
2683 (void)colorSmooth_.getNextValue();
2684 amt[k] = amountSmooth_.getNextValue();
2685 stMk[k] = (ff.staticMakeup
2686 ? computeGain(T(0), thr[k], rat[k], kn[k], ff.charType, ff.modeType, T(0)) * T(-0.5)
2687 : T(0)) + analyticSmooth_.getNextValue();
2688 }
2689 }
2690
2691 // B. Detection (each channel's detector keeps its own state).
2692 for (int ch = 0; ch < nCh; ++ch)
2693 {
2694 const T* src = ((scCh > 0) ? sidechain.getChannel(std::min(ch, scCh - 1))
2695 : audio.getChannel(ch)) + o;
2696 T* lv = level[ch];
2697 if (ff.detType == DetectorType::Peak && !ff.scHpf && !ff.keyEq && !ff.listen && !ff.dominant)
2698 {
2699 for (int k = 0; k < m; ++k) lv[k] = std::abs(detectorSafe(src[k]));
2700 }
2701 else
2702 {
2703 T* key = heard[ch];
2704 for (int k = 0; k < m; ++k)
2705 {
2706 T d = detectorSafe(src[k]);
2707 if (ff.scHpf) d = applySidechainHPF(d, ch);
2708 if (ff.keyEq) d = keyEq_.processSample(d, ch);
2709 key[k] = d;
2710 lv[k] = detectLevelLinear(d, ch, ff.detType);
2711 }
2712 }
2713 }
2714 if (ff.keyEq) keyEq_.advance(m);
2715
2716 // The correlation of the key, frame by frame, for the dominant link.
2717 double rho2[kChunk] = {};
2718 if (ff.dominant)
2719 for (int k = 0; k < m; ++k) rho2[k] = linkCorrelation(heard[0][k], heard[1][k]);
2720
2721 // The spectral balance of the key, for the timing that follows it
2722 // (the key as the detector reads it, before the sidechain filter).
2723 double balance[kChunk];
2724 if (ff.keyBalance)
2725 {
2726 double lowSq[kChunk] = {}, highSq[kChunk] = {};
2727 for (int ch = 0; ch < nCh; ++ch)
2728 {
2729 const T* src = ((scCh > 0) ? sidechain.getChannel(std::min(ch, scCh - 1))
2730 : audio.getChannel(ch)) + o;
2731 for (int k = 0; k < m; ++k) balanceBands(detectorSafe(src[k]), ch, lowSq[k], highSq[k]);
2732 }
2733 for (int k = 0; k < m; ++k) balance[k] = balanceAdvance(lowSq[k], highSq[k]);
2734 }
2735 else
2736 {
2737 std::fill_n(balance, m, balance_);
2738 }
2739
2740 // Lookahead: the delayed audio is the input the gain applies to.
2741 if (ff.lookahead > 0)
2742 {
2743 for (int ch = 0; ch < nCh; ++ch)
2744 {
2745 const T* src = audio.getChannel(ch) + o;
2746 for (int k = 0; k < m; ++k)
2747 {
2748 lookaheadBuffers_[ch].push(src[k]);
2749 delayed[ch][k] = lookaheadBuffers_[ch].read(ff.lookahead);
2750 }
2751 }
2752 }
2753
2754 // C. Levels in dB and stereo linking. dB is monotonic in the
2755 // linear level, so the linked level is the largest channel's.
2756 if (ff.shared)
2757 {
2758 for (int k = 0; k < m; ++k)
2759 {
2760 T mx = level[0][k];
2761 if (ff.dominant) mx = dominantLevel(level[0][k], level[1][k], rho2[k]);
2762 else for (int ch = 1; ch < nCh; ++ch) mx = std::max(mx, level[ch][k]);
2763 level[0][k] = gainToDecibels(mx);
2764 }
2765 }
2766 else
2767 {
2768 T dominantDb[kChunk] = {};
2769 if (ff.dominant)
2770 for (int k = 0; k < m; ++k)
2771 dominantDb[k] = gainToDecibels(dominantLevel(level[0][k], level[1][k], rho2[k]));
2772 for (int ch = 0; ch < nCh; ++ch)
2773 for (int k = 0; k < m; ++k) level[ch][k] = gainToDecibels(level[ch][k]);
2774 if (nCh > 1 && ff.sLink > T(0))
2775 {
2776 for (int k = 0; k < m; ++k)
2777 {
2778 T linked = level[0][k];
2779 if (ff.dominant) linked = dominantDb[k];
2780 else for (int ch = 1; ch < nCh; ++ch) linked = std::max(linked, level[ch][k]);
2781 for (int ch = 0; ch < nCh; ++ch)
2782 level[ch][k] = level[ch][k] + ff.sLink * (linked - level[ch][k]);
2783 }
2784 }
2785 }
2786
2787 // The automatic threshold: the reference follows the largest
2788 // level the gain computers read, and the threshold counts from it.
2789 const T* thrUse = thr;
2790 if (ff.autoThreshold)
2791 {
2792 double ref = autoRefDb_[0];
2793 for (int k = 0; k < m; ++k)
2794 {
2795 T top = level[0][k];
2796 for (int g = 1; g < nGain; ++g) top = std::max(top, level[g][k]);
2797 ref = std::max(static_cast<double>(top), ref - autoRefFall_);
2798 thrNow[k] = thr[k] + static_cast<T>(ref);
2799 }
2800 autoRefDb_[0] = ref;
2801 thrUse = thrNow;
2802 if (m > 0) thresholdInUseDb_.store(thrNow[m - 1], std::memory_order_relaxed);
2803 }
2804
2805 // D. Static curve, hold/range and ballistics: the serial part.
2806 // SplitPolarity's level-adaptive release reads the previous
2807 // frame's output, so its recursion also forms the linear gain
2808 // (written over the consumed dB level).
2809 for (int g = 0; g < nGain; ++g)
2810 {
2811 const T* dryIn = (ff.lookahead > 0) ? delayed[g] : audio.getChannel(g) + o;
2812 runGainRecursion(level[g], gain[g], m, g, ff, thrUse, rat, kn,
2813 ff.splitAdaptive ? dryIn : nullptr, balance);
2814 }
2815
2816 // What is heard of the gain: held back while the lookahead is
2817 // shorter than the latency kept for it, and scaled by the amount.
2818 const bool scaled = ff.paramsMoving || constants.amount < T(1);
2819 if (ff.gainLine || scaled || ff.gainSmooth || ff.ramp)
2820 {
2821 // The gain line at rest reads a whole delay; while the lookahead
2822 // moves its delay slides, and the ramp's length with it.
2823 const bool atRest = !ff.gainLine || gainDelayNow_ == static_cast<double>(ff.gainDelay);
2824 double slide[kChunk] = {};
2825 if (!atRest)
2826 for (int k = 0; k < m; ++k) slide[k] = slideGainDelay(ff.gainDelay);
2827 for (int g = 0; g < nGain; ++g)
2828 {
2829 T* gd = gain[g];
2830 if (ff.ramp)
2831 for (int k = 0; k < m; ++k)
2832 gd[k] = rampedIn(gd[k], g, atRest ? ff.lookahead - ff.gainDelay
2833 : ff.lookahead - static_cast<int>(std::ceil(slide[k])), true);
2834 if (ff.gainLine && atRest)
2835 {
2836 auto& line = gainDelay_[static_cast<size_t>(g)];
2837 for (int k = 0; k < m; ++k)
2838 {
2839 line.push(gd[k]);
2840 gd[k] = line.read(ff.gainDelay);
2841 }
2842 }
2843 else if (ff.gainLine)
2844 for (int k = 0; k < m; ++k) gd[k] = heldBack(gd[k], g, slide[k], true);
2845 if (scaled)
2846 for (int k = 0; k < m; ++k)
2847 if (amt[k] < T(1)) gd[k] *= amt[k];
2848 if (ff.gainSmooth)
2849 for (int k = 0; k < m; ++k) gd[k] = smoothedGain(gd[k], g);
2850 // SplitPolarity formed its linear gain inside the recursion.
2851 if (ff.splitAdaptive)
2852 for (int k = 0; k < m; ++k)
2853 level[g][k] = (gd[k] == T(0)) ? T(1) : decibelsToGain(gd[k]);
2854 }
2855 }
2856
2857 // The parts' weights (MidSide with a focus): the heard gain in
2858 // decibels of each part, sample by sample across the block.
2859 if (parted_)
2860 for (int g = 0; g < nGain; ++g)
2861 for (int k = 0; k < m; ++k)
2862 {
2863 const T w = partWeight(g, o + k, nS);
2864 gain[g][k] *= w;
2865 if (ff.splitAdaptive) level[g][k] = weightedGain(level[g][k], w);
2866 }
2867
2868 // E. Metering, adaptive makeup (frame by frame, like the
2869 // per-sample path) and the linear gains.
2870 if (ff.adaptiveMakeup)
2871 {
2872 T env = autoMakeupEnv_; // a local: the audio pointers may alias members
2873 for (int k = 0; k < m; ++k)
2874 {
2875 T blockGR = gain[0][k];
2876 for (int g = 1; g < nGain; ++g) blockGR = std::min(blockGR, gain[g][k]);
2877 mkLin[k] = makeupToGain(mk[k] + stMk[k] + -env);
2878 env = blockGR + autoMakeupCoeff_ * (env - blockGR);
2879 }
2880 autoMakeupEnv_ = env;
2881 }
2882 else
2883 {
2884 for (int k = 0; k < m; ++k) mkLin[k] = makeupToGain(mk[k] + stMk[k]);
2885 }
2886 lastGr = gain[0][m - 1];
2887 for (int g = 1; g < nGain; ++g) lastGr = std::min(lastGr, gain[g][m - 1]);
2888 if (!ff.splitAdaptive)
2889 {
2890 for (int g = 0; g < nGain; ++g)
2891 {
2892 const T* gd = gain[g];
2893 T* gl = level[g];
2894 // (0 dB is the common case below threshold: skip the exp.)
2895 for (int k = 0; k < m; ++k) gl[k] = (gd[k] == T(0)) ? T(1) : decibelsToGain(gd[k]);
2896 }
2897 }
2898
2899 // F. Application: lookahead, makeup and the parallel mix. The dry
2900 // reference carries the same lookahead delay as the wet.
2901 const bool removal = removalListen_.load(std::memory_order_relaxed);
2902 const bool plain = ff.lookahead == 0 && !ff.paramsMoving && constants.mix >= T(1) && !removal;
2903 for (int ch = 0; ch < nCh; ++ch)
2904 {
2905 T* data = audio.getChannel(ch) + o;
2906 const T* gl = level[ff.shared ? 0 : ch];
2907 // A part's makeup takes its weight too (MidSide with a focus).
2908 T partMk[kChunk];
2909 const T* mkUse = mkLin;
2910 if (parted_)
2911 {
2912 for (int k = 0; k < m; ++k) partMk[k] = weightedGain(mkLin[k], partWeight(ch, o + k, nS));
2913 mkUse = partMk;
2914 }
2915 if (plain)
2916 {
2917 // No lookahead and fully wet: one multiply chain per sample.
2918 fbLastOutput_[ch] = data[m - 1] * gl[m - 1]; // pre-makeup history
2919 for (int k = 0; k < m; ++k) data[k] = (data[k] * gl[k]) * mkUse[k];
2920 continue;
2921 }
2922 const T* dry = (ff.lookahead > 0) ? delayed[ch] : data;
2923 T wet = T(0);
2924 for (int k = 0; k < m; ++k)
2925 {
2926 const T input = dry[k];
2927 wet = input * gl[k];
2928 const T out = wet * mkUse[k];
2929 data[k] = removal ? input - wet : ((mixA[k] < T(1)) ? (input * (T(1) - mixA[k]) + out * mixA[k]) : out);
2930 }
2931 // Feedback history (pre-makeup) for a later topology switch.
2932 fbLastOutput_[ch] = wet;
2933 }
2934
2935 // Key listen: what the detectors heard goes out instead, late by
2936 // the latency and under full scale.
2937 if (ff.listen)
2938 for (int k = 0; k < m; ++k)
2939 {
2940 T frame[kMaxChannels];
2941 for (int ch = 0; ch < nCh; ++ch) frame[ch] = heard[ch][k];
2942 keyMonitor_.processFrame(frame, nCh, ff.listenDelay);
2943 for (int ch = 0; ch < nCh; ++ch) audio.getChannel(ch)[o + k] = frame[ch];
2944 }
2945 }
2946 if (nS > 0) gainReductionDb_.store(lastGr, std::memory_order_relaxed);
2947
2948 // The shared gain computer ran on channel 0's state: hand it to the
2949 // other channels so a later unlinked block continues from it.
2950 if (ff.shared && nS > 0) copyGainStateFromChannel0(nCh);
2951 }
2952
2954 void copyGainStateFromChannel0(int nCh) noexcept
2955 {
2956 for (int ch = 1; ch < nCh; ++ch)
2957 {
2958 envFastDb_[ch] = envFastDb_[0];
2959 envSlowDb_[ch] = envSlowDb_[0];
2960 envMidDb_[ch] = envMidDb_[0];
2961 envDeepDb_[ch] = envDeepDb_[0];
2962 envHoldDb_[ch] = envHoldDb_[0];
2965 heldGrDb_[ch] = heldGrDb_[0];
2966 precLevel_[ch] = precLevel_[0];
2967 precTarget_[ch] = precTarget_[0];
2970 layerPeakDb_[ch] = layerPeakDb_[0];
2971 gainSmoothA_[ch] = gainSmoothA_[0];
2972 gainSmoothB_[ch] = gainSmoothB_[0];
2973 landingDb_[ch] = landingDb_[0];
2974 networkLow_[ch] = networkLow_[0];
2975 }
2977 for (int ch = 1; ch < nCh; ++ch) holdWindows_[static_cast<size_t>(ch)] = holdWindows_[0];
2978 }
2979
3000 void runGainRecursion(T* inDb, T* out, int m, int ch, const FeedForwardConfig& ff,
3001 const T* thr, const T* rat, const T* kn, const T* dryIn,
3002 const double* balance) noexcept
3003 {
3004 double fast = envFastDb_[ch];
3005 double slow = envSlowDb_[ch];
3006 double mid = envMidDb_[ch];
3007 double deep = envDeepDb_[ch];
3008 double hold = envHoldDb_[ch];
3009 T guard = upwardGuardDb_[ch];
3010 T held = heldGrDb_[ch];
3011 int counter = holdCounters_[ch];
3012 const T range = rangeDb_.load(std::memory_order_relaxed);
3013 const int soft = rangeShape_.load(std::memory_order_relaxed);
3014 const int holdN = holdSamples_;
3015 SlidingDeepest* const window = holdWindow(ch);
3016 const bool upward = ff.modeType == Mode::Upward;
3017
3018 // Static curve first: no state, so the frames overlap freely (the
3019 // Upward guard is a cheap recursion of its own).
3020 T tgtA[kChunk];
3021 if (upward)
3022 {
3023 for (int k = 0; k < m; ++k)
3024 {
3025 guard = std::max(inDb[k], guard - upwardGuardDecay_);
3026 tgtA[k] = computeGainUpward(inDb[k], thr[k], rat[k], kn[k], guard);
3027 }
3028 }
3029 else if (ff.modeType == Mode::Both)
3030 {
3031 for (int k = 0; k < m; ++k)
3032 {
3033 guard = std::max(inDb[k], guard - upwardGuardDecay_);
3034 tgtA[k] = downwardCurve(inDb[k], thr[k], rat[k], kn[k], ff.charType)
3035 + lift(inDb[k], thr[k], kn[k], guard);
3036 }
3037 }
3038 else if (ff.modeType == Mode::Leveler)
3039 {
3040 for (int k = 0; k < m; ++k) tgtA[k] = levelerCurve(inDb[k], thr[k]);
3041 }
3042 else
3043 {
3044 for (int k = 0; k < m; ++k)
3045 tgtA[k] = downwardCurve(inDb[k], thr[k], rat[k], kn[k], ff.charType);
3046 }
3047
3048 if (ff.layered)
3049 {
3050 // Two layers, each towards its own curve; the gain is their sum.
3051 const CharacterProfile profile = profileOf(ff.charType);
3052 double level = layerLevelDb_[ch], peak = layerPeakDb_[ch];
3053 for (int k = 0; k < m; ++k)
3054 {
3055 fast = layeredStep(inDb[k], thr[k], rat[k], kn[k], profile, range, holdN, soft,
3056 held, counter, level, peak, window);
3057 out[k] = static_cast<T>(fast);
3058 }
3059 layerLevelDb_[ch] = level;
3060 layerPeakDb_[ch] = peak;
3061 }
3062 else if (dryIn != nullptr)
3063 {
3064 // Level-adaptive release (SplitPolarity): full-scale output
3065 // halves the release time constant, as in applyBallistics().
3066 T lastWet = fbLastOutput_[ch];
3067 for (int k = 0; k < m; ++k)
3068 {
3069 const T tgt = holdAndRange(tgtA[k], range, holdN, held, counter, soft, window);
3070 const double lastOut = std::abs(static_cast<double>(lastWet));
3071 const double outputLevel = (lastOut < 1.0) ? lastOut : 1.0;
3072 double y;
3073 if (ff.decoupled)
3074 {
3075 const double c = decHoldCoeff_;
3076 y = decoupledStep(static_cast<double>(tgt), hold, fast, c + outputLevel * (c * c - c));
3077 }
3078 else
3079 {
3080 const double c = charRelCoeff_;
3081 y = ballisticsStep(static_cast<double>(tgt), fast, slow, mid, deep, charAttCoeff_,
3082 c + outputLevel * (c * c - c));
3083 }
3084 const T gr = static_cast<T>(y);
3085 out[k] = gr;
3086 const T gl = (gr == T(0)) ? T(1) : decibelsToGain(gr);
3087 inDb[k] = gl;
3088 lastWet = dryIn[k] * gl;
3089 }
3090 }
3091 else if (ff.program)
3092 {
3093 ProgramState state = programState_[ch];
3094 for (int k = 0; k < m; ++k)
3095 {
3096 const T tgt = holdAndRange(tgtA[k], range, holdN, held, counter, soft, window);
3097 out[k] = static_cast<T>(programStep(static_cast<double>(tgt), fast, state, balance[k]));
3098 }
3099 programState_[ch] = state;
3100 }
3101 else
3102 {
3103 for (int k = 0; k < m; ++k)
3104 {
3105 const T tgt = holdAndRange(tgtA[k], range, holdN, held, counter, soft, window);
3106 const double y = ff.decoupled
3107 ? decoupledStep(static_cast<double>(tgt), hold, fast, decHoldCoeff_)
3108 : ballisticsStep(static_cast<double>(tgt), fast, slow, mid, deep, charAttCoeff_, charRelCoeff_);
3109 out[k] = static_cast<T>(y);
3110 }
3111 }
3112
3113 envFastDb_[ch] = fast;
3114 envSlowDb_[ch] = slow;
3115 envMidDb_[ch] = mid;
3116 envDeepDb_[ch] = deep;
3117 envHoldDb_[ch] = hold;
3118 upwardGuardDb_[ch] = guard;
3119 heldGrDb_[ch] = held;
3120 holdCounters_[ch] = counter;
3121 }
3122
3137 [[nodiscard]] T gainPath(T inputDb, int ch, const GainPathConfig& cfg,
3138 T thresh, T ratio, T knee) noexcept
3139 {
3140 // Sustained-level guard envelope for Upward mode: instant rise,
3141 // constant 60 dB/s fall (peak hold with linear decay).
3142 T guardDb = inputDb;
3143 if (cfg.modeType == Mode::Upward || cfg.modeType == Mode::Both)
3144 {
3145 T& g = upwardGuardDb_[ch];
3146 g = std::max(inputDb, g - upwardGuardDecay_);
3147 guardDb = g;
3148 }
3149
3150 if (cfg.fbImplicit)
3151 return applyBallisticsFeedbackImplicit(inputDb, ch, cfg.charType, thresh, ratio, knee);
3152
3153 if (cfg.topoEff == Topology::FeedBack)
3154 {
3155 // Explicit loop (detector with memory): calibrated element law
3156 // plus a per-sample stability floor on the ballistics. Upward
3157 // feedback inverts the law from the output level, so the loop
3158 // settles on the panel ratio too.
3159 const auto law = (cfg.modeType == Mode::Downward)
3160 ? computeGainFeedback(inputDb, thresh, ratio, knee, cfg.charType)
3161 : computeGainFeedbackUpward(inputDb, thresh, ratio, knee, guardDb);
3162 const T targetGR_Db = applyHoldAndRange(law.target, ch);
3163 return applyBallistics(targetGR_Db, ch, cfg.splitAdaptive, law.slope, cfg.loopDelay);
3164 }
3165
3166 if (cfg.layered)
3167 {
3168 const double shown = layeredStep(inputDb, thresh, ratio, knee, profileOf(cfg.charType),
3169 rangeDb_.load(std::memory_order_relaxed), holdSamples_,
3170 rangeShape_.load(std::memory_order_relaxed),
3171 heldGrDb_[ch], holdCounters_[ch],
3172 layerLevelDb_[ch], layerPeakDb_[ch], holdWindow(ch));
3173 envFastDb_[ch] = shown;
3174 return static_cast<T>(shown);
3175 }
3176
3177 T targetGR_Db = computeGain(inputDb, thresh, ratio, knee, cfg.charType, cfg.modeType, guardDb);
3178 targetGR_Db = applyHoldAndRange(targetGR_Db, ch);
3179 if (cfg.program)
3180 return static_cast<T>(programStep(static_cast<double>(targetGR_Db), envFastDb_[ch],
3181 programState_[static_cast<size_t>(ch)], balance_));
3182 return cfg.decoupled ? applyBallisticsDecoupled(targetGR_Db, ch, cfg.splitAdaptive)
3183 : applyBallistics(targetGR_Db, ch, cfg.splitAdaptive);
3184 }
3185
3188 [[nodiscard]] T partWeight(int ch, int idx, int n) const noexcept
3189 {
3190 const auto c = static_cast<std::size_t>(std::clamp(ch, 0, 1));
3191 return partFrom_[c] + (partTo_[c] - partFrom_[c]) * static_cast<T>(idx + 1) / static_cast<T>(std::max(n, 1));
3192 }
3193
3195 [[nodiscard]] static T weightedGain(T g, T w) noexcept
3196 {
3197 if (w == T(1)) return g;
3198 if (w == T(0) || !(g > T(0))) return T(1);
3199 return std::exp(w * std::log(g));
3200 }
3201
3206 void applyGain(AudioBufferView<T>& audio, int ch, int i, T gainLin, T grDb,
3207 int activeLookahead, Character charType, T colorAmt, T makeupLin,
3208 T mixVal, T outLin) noexcept
3209 {
3210 T* data = audio.getChannel(ch);
3211 T input;
3212 if (activeLookahead > 0)
3213 {
3214 lookaheadBuffers_[ch].push(data[i]);
3215 input = lookaheadBuffers_[ch].read(activeLookahead);
3216 }
3217 else
3218 {
3219 input = data[i];
3220 }
3221
3222 // outLin is the gain that is heard (gainLin scaled by the amount);
3223 // gainLin is the one the loop reads back.
3224 const Colour colour = profileOf(charType).colour;
3225 const bool pushPull = colorAmt > T(0) && colour == Colour::PushPull;
3226 const bool extras = audioExtras_ && !pushPull;
3227 T wet = pushPull ? pushPullElement(input, outLin, colorAmt)
3228 : (extras ? gained(input, outLin, ch) : input * outLin);
3229 if (colorAmt > T(0) && colour == Colour::SecondOrder)
3230 {
3231 // 2nd-order FET channel modulation: the drain-source resistance
3232 // bends with the signal across it, so colour only appears while
3233 // the FET conducts (gain reduction active); the squared term is
3234 // AC-coupled like the hardware's output transformer. Applied
3235 // pre-makeup: the line amp after the element is clean.
3236 const T sq = wet * wet;
3237 T& dc = fetDcState_[ch];
3238 if (std::isfinite(sq)) dc += fetDcCoeff_ * (sq - dc); // a non-finite sample would latch
3239 const T grDepth = std::clamp(-grDb * T(0.1), T(0), T(1));
3240 wet += colorAmt * kFetColorH2 * grDepth * (sq - dc);
3241 }
3242 // The feedback detector reads the compressed signal before makeup
3243 // (makeup sits after the element; feeding it back would shift the
3244 // static curve and run away with auto makeup).
3245 fbLastOutput_[ch] = (outLin == gainLin && !extras) ? wet : input * gainLin;
3246 const T kept = wet;
3247 wet *= makeupLin;
3248
3249 // Parallel (New York) mix done inline: the dry reference is `input`,
3250 // which carries the SAME lookahead delay as the wet, so dry and wet
3251 // stay phase-aligned (the previous DryWetMixer captured the UNDELAYED
3252 // input and comb-filtered when lookahead + mix<1 were combined).
3253 data[i] = removalListen_.load(std::memory_order_relaxed) ? input - kept
3254 : ((mixVal < T(1)) ? (input * (T(1) - mixVal) + wet * mixVal) : wet);
3255 }
3256
3261 void updateTimeConstants(T fs) noexcept
3262 {
3263 T attMs = std::max(attackMs_.load(std::memory_order_relaxed), T(0.01));
3264 T relMs = std::max(releaseMs_.load(std::memory_order_relaxed), T(1));
3265 autoMakeupCoeff_ = std::exp(T(-1) / (fs * T(0.3)));
3266
3267 // One-pole coefficient for a time constant given in milliseconds
3268 // (double, like the envelopes it drives: a float one-pole stalls short
3269 // of its target once the per-sample step drops below an ulp).
3270 auto tc = [fs](T ms) { return std::exp(-1.0 / (static_cast<double>(fs) * static_cast<double>(ms) / 1000.0)); };
3271 const T prevWeight = charFastWeight_;
3272
3273 // Character ballistics: time constants of the dB-domain envelopes,
3274 // from the numbers of the character (see CharacterProfile). The knobs
3275 // are held to its limits first; a character without a memory stage
3276 // has the fast one stand in for it.
3277 const CharacterProfile& profile = profileOf(character_.load(std::memory_order_relaxed));
3278 bool threeStageWanted = false;
3279 {
3280 const T att = std::clamp(attMs, profile.attackFloorMs, profile.attackCeilMs);
3281 const T rel = std::clamp(relMs, profile.releaseFloorMs, profile.releaseCeilMs);
3282 charAttCoeff_ = tc(att);
3283 charRelCoeff_ = tc(rel * profile.fastRelease);
3284 charFastWeight_ = profile.fastWeight;
3285 if (profile.fastWeight >= T(1))
3286 {
3289 }
3290 else
3291 {
3292 charSlowRelCoeff_ = tc(std::min(rel * profile.slowRelease, profile.slowReleaseCeilMs));
3293 charChargeCoeff_ = tc(std::clamp(rel * profile.chargeScale, profile.chargeFloorMs,
3294 profile.chargeCeilMs));
3295 }
3296
3297 // The three-stage cell of Opto (setOptoCell()): a faster fast
3298 // stage and the medium memory; the deep memory is the one above.
3299 threeStageWanted = character_.load(std::memory_order_relaxed) == Character::Opto
3300 && optoCell_.load(std::memory_order_relaxed) == OptoCell::ThreeStage;
3301 if (threeStageWanted)
3302 {
3303 charRelCoeff_ = tc(rel * static_cast<T>(kOptoThreeFastRelease));
3304 charMidRelCoeff_ = tc(rel * static_cast<T>(kOptoMidRelease));
3305 charMidChargeCoeff_ = tc(std::clamp(rel * static_cast<T>(kOptoMidCharge),
3306 static_cast<T>(kOptoMidChargeFloorMs),
3307 static_cast<T>(kOptoMidChargeCeilMs)));
3308 }
3309
3310 // Decoupled detector (Clean, feed-forward): the smoothing pole's
3311 // release side is a tenth of the release (never faster than the
3312 // attack, never slower than half the release); the hold stage
3313 // takes the rest of the release so the series t63 lands on the
3314 // knob.
3315 const T smoothMs = std::min(std::max(relMs * T(0.1), attMs), relMs * T(0.5));
3316 decSmoothCoeff_ = tc(smoothMs);
3317 decHoldCoeff_ = tc(static_cast<T>(decoupledHoldTau(
3318 static_cast<double>(relMs), static_cast<double>(smoothMs))));
3319
3320 // The layers of a layered character run on rates (the share of
3321 // the distance covered per sample), which their pace then divides.
3322 if (profile.levelShare > T(0))
3323 {
3324 const double perMs = 1000.0 / static_cast<double>(fs);
3325 peakAttRate_ = perMs / static_cast<double>(att);
3326 peakRelRate_ = perMs / static_cast<double>(rel);
3327 layerAttRate_ = perMs / static_cast<double>(std::max(att * profile.levelAttack,
3328 profile.levelAttackFloorMs));
3329 layerRelRate_ = perMs / static_cast<double>(rel * profile.levelRelease);
3330 }
3331 }
3332
3333 // The smoothing of the gain after the ballistics: two sections of
3334 // half its time each.
3335 {
3336 const double ms = static_cast<double>(gainSmoothMs_.load(std::memory_order_relaxed));
3337 gainSmoothRate_ = (ms > 0.0) ? 1.0 - std::exp(-2000.0 / (static_cast<double>(fs) * ms)) : 0.0;
3338 }
3339
3340 // The landing of the release and the network of the control path.
3341 {
3342 const double rate = static_cast<double>(fs);
3343 const double landing = static_cast<double>(landingMs_.load(std::memory_order_relaxed));
3344 landingRate_ = (landing > 0.0) ? 1.0 - std::exp(-1000.0 / (rate * landing)) : 0.0;
3345 const double depth = static_cast<double>(networkDepthDb_.load(std::memory_order_relaxed));
3346 const double corner = static_cast<double>(networkCornerHz_.load(std::memory_order_relaxed));
3347 networkShare_ = (depth > 0.0) ? std::pow(10.0, -depth / 20.0) : 1.0;
3348 networkRate_ = 1.0 - std::exp(-2.0 * std::numbers::pi * corner / rate);
3349 leakCoeff_ = static_cast<T>(1.0 - std::exp(-2.0 * std::numbers::pi * kLeakCornerHz / rate));
3350 liftBelowDb_ = liftBelow_.load(std::memory_order_relaxed);
3351 liftRatioIn_ = std::max(liftRatio_.load(std::memory_order_relaxed), T(1));
3352 liftRangeDb_ = liftRange_.load(std::memory_order_relaxed);
3353 asymDecay_ = static_cast<T>(std::exp(-1.0 / (rate * kAsymCrestSeconds)));
3354 // Two one-poles of rate r (a = 1 - r) over a uniform in [-1, 1)
3355 // have a deviation of sqrt(r^4 (1 + a^2) / (3 (1 - a^2)^3)): the
3356 // walk of the drift, scaled to one.
3357 asymDriftRate_ = 1.0 - std::exp(-2.0 * std::numbers::pi * kAsymDriftHz * kAsymDriftTick / rate);
3358 {
3359 const double r = asymDriftRate_, a2 = (1.0 - r) * (1.0 - r);
3360 asymDriftScale_ = 1.0 / std::sqrt(r * r * r * r * (1.0 + a2) / (3.0 * (1.0 - a2) * (1.0 - a2) * (1.0 - a2)));
3361 }
3362 }
3363
3364 // The attack as it is observed (a feedback loop, below, changes the
3365 // coefficient and not the result), and the coefficients of an eighth
3366 // of a sample: the eight steps per sample of Precision::High.
3368 {
3369 const auto eighth = [](double c) { return std::pow(c, 1.0 / kSubsteps); };
3370 subAttCoeff_ = eighth(charAttCoeff_);
3371 subRelCoeff_ = eighth(charRelCoeff_);
3378 }
3379
3380 // A live character change moves the fast/slow blend weight. Re-seat
3381 // the envelopes so the gain shown before and after the change is the
3382 // same (otherwise the blend jumps by up to the full reduction).
3383 if (charFastWeight_ != prevWeight)
3384 {
3385 const double w0 = static_cast<double>(prevWeight);
3386 const double w1 = static_cast<double>(charFastWeight_);
3387 for (int ch = 0; ch < kMaxChannels; ++ch)
3388 {
3389 double& f = envFastDb_[static_cast<size_t>(ch)];
3390 double& s = envSlowDb_[static_cast<size_t>(ch)];
3391 const double shown = (w0 < 1.0) ? w0 * f + (1.0 - w0) * s : f;
3392 if (w1 >= 1.0) { f = shown; continue; }
3393 if (w0 >= 1.0)
3394 {
3395 s = shown;
3396 envMidDb_[static_cast<size_t>(ch)] = shown;
3397 envDeepDb_[static_cast<size_t>(ch)] = shown;
3398 }
3399 f = (shown - (1.0 - w1) * s) / w1;
3400 }
3401 }
3402
3403 // The three-stage cell starts with both memories where the memory
3404 // stage stands, so the gain does not jump when it engages.
3405 if (threeStageWanted && !threeStage_)
3406 {
3409 }
3410 threeStage_ = threeStageWanted;
3411
3412 // A feedback loop closes around the attack stage, which multiplies the
3413 // raw ballistics speed by (1 + loop gain). Re-derive the coefficient
3414 // from rho = coeff/(1 + w beta A) so the OBSERVED attack t63 stays on
3415 // the knob, exactly like the hardware panels (the 1176's 20-800 us
3416 // figures are measured results, not RC values). A is the
3417 // linear-region loop gain (R - 1) in both directions; Varimu uses its
3418 // base ratio (the progressive part is level-dependent).
3419 {
3420 const bool fbLoop = topologyFor(profile, topology_.load(std::memory_order_relaxed))
3422 if (fbLoop)
3423 {
3424 const double loopGain = static_cast<double>(charFastWeight_)
3425 * (static_cast<double>(std::max(ratio_.load(std::memory_order_relaxed), T(1))) - 1.0);
3426 const double rho = charAttCoeff_;
3427 charAttCoeff_ = 1.0 - (1.0 - rho) / (1.0 + rho * loopGain);
3428 // The same for a step of an eighth of a sample: eight of
3429 // them then observe the knob's attack too.
3430 const double rhoSub = subAttCoeff_;
3431 subAttCoeff_ = 1.0 - (1.0 - rhoSub) / (1.0 + rhoSub * loopGain);
3432 }
3433 }
3434
3435 // SplitPolarity detector ballistics. The time constants reproduce the
3436 // original per-sample coefficients (0.6 attack / 0.99 release) at
3437 // 44.1 kHz, but are now sample-rate invariant.
3438 splitDetAttCoeff_ = std::exp(T(-1) / (fs * T(44.39e-6)));
3439 splitDetRelCoeff_ = std::exp(T(-1) / (fs * T(2.2562e-3)));
3440
3441 // Programme-dependent timing: the two times as decays per sample
3442 // (the coefficient is fastDecay() of them, scaled), and the poles of
3443 // its measures.
3444 {
3445 const double rate = static_cast<double>(fs);
3446 const auto pole = [rate](double hz) { return 1.0 - std::exp(-2.0 * std::numbers::pi * hz / rate); };
3447 const auto over = [rate](double seconds) { return 1.0 - std::exp(-1.0 / (rate * seconds)); };
3448 attackX_ = -std::log(std::max(charAttCoeff_, 1e-300));
3449 releaseX_ = -std::log(std::max(charRelCoeff_, 1e-300));
3450 subRate_ = pole(kBalanceFloorHz);
3451 lowRate_ = pole(kBalanceLowHz);
3452 midRate_ = pole(kBalanceHighHz);
3453 highRate_ = pole(std::min(kBalanceCeilingHz, 0.45 * rate));
3455 // The windows of the two measures count in the knobs' own times, so
3456 // "sustained" and "the leading edge" mean the same at any setting.
3457 const double attackSeconds = static_cast<double>(std::clamp(attMs, profile.attackFloorMs, profile.attackCeilMs)) / 1000.0;
3458 const double releaseSeconds = static_cast<double>(std::clamp(relMs, profile.releaseFloorMs, profile.releaseCeilMs)) / 1000.0;
3459 sustainRate_ = over(std::clamp(kSustainReleases * releaseSeconds, kSustainFloorSeconds, kSustainCeilSeconds));
3460 emphasisRate_ = over(std::clamp(kEmphasisAttacks * attackSeconds, kEmphasisFloorSeconds, kEmphasisCeilSeconds));
3461 }
3462
3463 // Upward silence-guard envelope: 60 dB/s linear decay.
3464 upwardGuardDecay_ = T(60) / fs;
3465
3466 // AC coupling (~10 Hz) of the FET color's 2nd-order term.
3467 fetDcCoeff_ = T(1) - std::exp(T(-2) * std::numbers::pi_v<T> * T(10) / fs);
3468
3469 lookaheadSamples_ = static_cast<int>(fs * std::clamp(
3470 lookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000));
3471 latencySamples_ = std::max(lookaheadSamples_, static_cast<int>(fs * std::clamp(
3472 maxLookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000)));
3473 latencyKept_ = maxLookaheadMs_.load(std::memory_order_relaxed) > T(0);
3474 autoRefFall_ = kAutoRefFallDb / static_cast<double>(fs);
3475
3476 holdSamples_ = static_cast<int>(fs * holdMs_.load(std::memory_order_relaxed) / T(1000));
3477 rampShape_ = lookaheadShape_.load(std::memory_order_relaxed) == LookaheadShape::Ramp;
3478 // The hold's windows follow its length and its mode; a change of
3479 // either starts the hold again.
3480 const bool everyPeak = holdMode_.load(std::memory_order_relaxed) == HoldMode::EveryPeak;
3481 if (everyPeak != holdEveryPeak_ || (everyPeak && holdSamples_ != holdWindowFor_))
3482 {
3483 if (holdWindows_)
3484 for (int ch = 0; ch < kMaxChannels; ++ch) holdWindows_[static_cast<size_t>(ch)].configure(holdSamples_);
3486 holdCounters_.fill(0);
3487 heldGrDb_.fill(T(0));
3488 holdEveryPeak_ = everyPeak;
3489 }
3490 }
3491
3498 [[nodiscard]] T applyHoldAndRange(T targetGR_Db, int ch) noexcept
3499 {
3500 return holdAndRange(targetGR_Db, rangeDb_.load(std::memory_order_relaxed), holdSamples_,
3501 heldGrDb_[ch], holdCounters_[ch], rangeShape_.load(std::memory_order_relaxed),
3502 holdWindow(ch));
3503 }
3504
3515 {
3516 static constexpr int kBlocks = 256;
3517 static constexpr int kSlots = 2 * kBlocks;
3518 std::array<T, kSlots> depth {};
3519 std::array<uint32_t, kSlots> block {};
3520 int head = 0, count = 0, inBlock = 0, blockLength = 1, blocks = 1;
3522 T current = T(0);
3523
3525 void configure(int windowSamples) noexcept
3526 {
3527 const int w = std::max(1, windowSamples);
3528 blockLength = (w + kBlocks - 1) / kBlocks;
3529 blocks = (w + blockLength - 1) / blockLength;
3530 clear();
3531 }
3532
3534 {
3535 head = count = inBlock = 0;
3536 index = 0;
3537 current = T(0);
3538 }
3539
3545 [[nodiscard]] T push(T gr, int perSample = 1) noexcept
3546 {
3547 if (inBlock == 0 || std::abs(gr) >= std::abs(current)) current = gr;
3548 T deepest = current;
3549 if (count > 0 && std::abs(depth[static_cast<size_t>(head)]) > std::abs(deepest)) deepest = depth[static_cast<size_t>(head)];
3550 if (++inBlock >= blockLength * perSample)
3551 {
3552 // The block is done: it covers every queued block that is no deeper.
3553 while (count > 0 && std::abs(depth[static_cast<size_t>((head + count - 1) & (kSlots - 1))]) <= std::abs(current)) --count;
3554 const auto at = static_cast<size_t>((head + count) & (kSlots - 1));
3555 depth[at] = current;
3556 block[at] = index;
3557 ++count;
3558 ++index;
3559 inBlock = 0;
3560 // A block leaves when the window has passed it.
3561 while (count > 0 && index - block[static_cast<size_t>(head)] > static_cast<uint32_t>(blocks))
3562 {
3563 head = (head + 1) & (kSlots - 1);
3564 --count;
3565 }
3566 }
3567 return deepest;
3568 }
3569 };
3570
3584 {
3585 std::vector<T> deepVal, boxA, boxB;
3586 std::vector<uint32_t> deepPos;
3588 int mask = 0, head = 0, count = 0, length = 0, lenA = 1, lenB = 1, zerosA = 0, zerosB = 0;
3589 double sumA = 0.0, sumB = 0.0;
3590
3593 {
3594 size_t n = 8;
3595 while (n < static_cast<size_t>(std::max(0, maxLength)) + 4) n <<= 1;
3596 deepVal.assign(n, T(0));
3597 boxA.assign(n, T(0));
3598 boxB.assign(n, T(0));
3599 deepPos.assign(n, 0u);
3600 mask = static_cast<int>(n) - 1;
3601 clear();
3602 }
3603
3605 {
3606 std::fill(deepVal.begin(), deepVal.end(), T(0));
3607 std::fill(boxA.begin(), boxA.end(), T(0));
3608 std::fill(boxB.begin(), boxB.end(), T(0));
3609 t = 0;
3610 head = count = length = zerosA = zerosB = 0;
3611 lenA = lenB = 1;
3612 sumA = sumB = 0.0;
3613 }
3614
3616 void setLength(int wanted) noexcept
3617 {
3618 wanted = std::clamp(wanted, 0, mask - 3);
3619 while (length != wanted)
3620 {
3621 const int next = length + (wanted > length ? 1 : -1);
3622 const int a = (next + 2) / 2, b = next + 2 - a;
3623 // The averages hold the last lenA and lenB values (the last one came at t - 1).
3624 if (a > lenA) sumA += static_cast<double>(boxA[(t - 1u - static_cast<uint32_t>(lenA)) & static_cast<uint32_t>(mask)]);
3625 else if (a < lenA) sumA -= static_cast<double>(boxA[(t - static_cast<uint32_t>(lenA)) & static_cast<uint32_t>(mask)]);
3626 if (b > lenB) sumB += static_cast<double>(boxB[(t - 1u - static_cast<uint32_t>(lenB)) & static_cast<uint32_t>(mask)]);
3627 else if (b < lenB) sumB -= static_cast<double>(boxB[(t - static_cast<uint32_t>(lenB)) & static_cast<uint32_t>(mask)]);
3628 lenA = a;
3629 lenB = b;
3630 length = next;
3631 zerosA = zerosB = 0;
3632 }
3633 }
3634
3636 [[nodiscard]] T process(T gr) noexcept
3637 {
3638 const auto m = static_cast<uint32_t>(mask);
3639 // The deepest of the last length + 1 (the gain changes share a sign: the largest magnitude).
3640 const T depth = std::abs(gr);
3641 while (count > 0 && std::abs(deepVal[static_cast<size_t>((head + count - 1) & mask)]) <= depth) --count;
3642 const auto at = static_cast<size_t>((head + count) & mask);
3643 deepVal[at] = gr;
3644 deepPos[at] = t;
3645 ++count;
3646 while (t - deepPos[static_cast<size_t>(head)] > static_cast<uint32_t>(length))
3647 {
3648 head = (head + 1) & mask;
3649 --count;
3650 }
3651 const T deep = deepVal[static_cast<size_t>(head)];
3652 // Two moving averages; a sum that has seen nothing but zeros for its whole length is zero.
3653 sumA += static_cast<double>(deep) - static_cast<double>(boxA[(t - static_cast<uint32_t>(lenA)) & m]);
3654 boxA[t & m] = deep;
3655 zerosA = deep == T(0) ? std::min(zerosA + 1, lenA) : 0;
3656 if (zerosA >= lenA) sumA = 0.0;
3657 const T mid = static_cast<T>(sumA / lenA);
3658 sumB += static_cast<double>(mid) - static_cast<double>(boxB[(t - static_cast<uint32_t>(lenB)) & m]);
3659 boxB[t & m] = mid;
3660 zerosB = mid == T(0) ? std::min(zerosB + 1, lenB) : 0;
3661 if (zerosB >= lenB) sumB = 0.0;
3662 ++t;
3663 return static_cast<T>(sumB / lenB);
3664 }
3665 };
3666
3668 [[nodiscard]] T rampedIn(T grDb, int g, int length, bool run) noexcept
3669 {
3670 if (!run || g >= rampCount_) return grDb;
3671 auto& ramp = lookaheadRamps_[static_cast<size_t>(g)];
3672 ramp.setLength(length);
3673 return ramp.process(grDb);
3674 }
3675
3677 [[nodiscard]] SlidingDeepest* holdWindow(int ch) const noexcept
3678 {
3679 return (holdEveryPeak_ && holdWindows_) ? &holdWindows_[static_cast<size_t>(ch)] : nullptr;
3680 }
3681
3693 [[nodiscard]] static T holdAndRange(T targetGR_Db, T range, int holdSamples,
3694 T& held, int& counter, int soft = 0,
3695 SlidingDeepest* window = nullptr, int perSample = 1) noexcept
3696 {
3697 if (soft == static_cast<int>(RangeShape::Asymptotic) && range > T(0))
3698 {
3699 // g / (1 + (g / R)^4)^(1/4): g while it is small, R at most.
3700 const T x = targetGR_Db / range, x2 = x * x;
3701 targetGR_Db /= std::sqrt(std::sqrt(T(1) + x2 * x2));
3702 }
3703 else if (soft == static_cast<int>(RangeShape::Local) && range > T(0))
3704 {
3705 // A quadratic bend over a stretch centred on the range: the target
3706 // under it, the range over it, and the slope continuous at both ends.
3707 const T size = std::abs(targetGR_Db);
3708 const T stretch = std::min(static_cast<T>(kLocalRangeStretchDb), range);
3709 const T past = size - (range - stretch / T(2));
3710 if (past >= stretch) targetGR_Db = std::copysign(range, targetGR_Db);
3711 else if (past > T(0)) targetGR_Db = std::copysign(size - past * past / (T(2) * stretch), targetGR_Db);
3712 }
3713 else
3714 {
3715 targetGR_Db = std::clamp(targetGR_Db, -range, range);
3716 }
3717
3718 if (holdSamples > 0 && window != nullptr) return window->push(targetGR_Db, perSample);
3719 if (holdSamples > 0)
3720 {
3721 if (std::abs(targetGR_Db) >= std::abs(held))
3722 {
3723 held = targetGR_Db; // deeper action: re-arm the hold
3724 counter = holdSamples;
3725 }
3726 else if (counter > 0)
3727 {
3728 --counter; // shallower: freeze at held depth
3729 targetGR_Db = held;
3730 }
3731 else
3732 {
3733 held = targetGR_Db; // hold elapsed: track normally
3734 }
3735 }
3736 return targetGR_Db;
3737 }
3738
3746 [[nodiscard]] T makeupToGain(T makeupDb) noexcept
3747 {
3748 if (makeupDb != cachedMakeupDb_)
3749 {
3750 cachedMakeupDb_ = makeupDb;
3751 cachedMakeupLin_ = decibelsToGain(makeupDb);
3752 }
3753 return cachedMakeupLin_;
3754 }
3755
3756 // ---- Detectors ----
3757
3760 [[nodiscard]] static T detectorSafe(T x) noexcept
3761 {
3762 // |x| <= max is false for NaN and both infinities: the same test as
3763 // std::isfinite, as one compare (MSVC calls a library routine for it).
3764 return (std::abs(x) <= std::numeric_limits<T>::max()) ? x : T(0);
3765 }
3766
3769 double linkCorrelation(T keyL, T keyR) noexcept
3770 {
3771 const double l = static_cast<double>(keyL);
3772 const double r = static_cast<double>(keyR);
3773 linkLL_ += linkCoeff_ * (l * l - linkLL_);
3774 linkRR_ += linkCoeff_ * (r * r - linkRR_);
3775 linkLR_ += linkCoeff_ * (l * r - linkLR_);
3776 const double den = linkLL_ * linkRR_;
3777 return den > 1e-60 ? std::min(1.0, linkLR_ * linkLR_ / den) : 0.0;
3778 }
3779
3782 void flushLinkCovariance() noexcept
3783 {
3784 if (linkLL_ < 1e-30) linkLL_ = 0.0;
3785 if (linkRR_ < 1e-30) linkRR_ = 0.0;
3786 if (std::abs(linkLR_) < 1e-30) linkLR_ = 0.0;
3787 }
3788
3793 [[nodiscard]] static T dominantLevel(T levelL, T levelR, double rho2) noexcept
3794 {
3795 return dominantPairLevel(levelL, levelR, rho2);
3796 }
3797
3805 [[nodiscard]] T detectLevel(T sample, int ch, DetectorType detType) noexcept
3806 {
3807 return gainToDecibels(detectLevelLinear(sample, ch, detType));
3808 }
3809
3817 [[nodiscard]] T detectLevelLinear(T sample, int ch, DetectorType detType) noexcept
3818 {
3819 T level = std::abs(sample);
3820 switch (detType)
3821 {
3822 case DetectorType::Peak:
3823 break; // level already holds abs(sample)
3824
3825 case DetectorType::Rms:
3826 {
3827 T sq = sample * sample;
3828 auto& buf = rmsBuffers_[ch];
3829 auto& sum = rmsSums_[ch];
3830 auto& idx = rmsIndices_[ch];
3831 auto& recomputeCount = rmsRecomputeCounters_[ch];
3832 int len = rmsWindowSamples_;
3833
3834 if (len > 0 && len <= static_cast<int>(buf.size()))
3835 {
3836 sum -= buf[idx];
3837 buf[idx] = sq;
3838 sum += sq;
3839 if (++idx >= len) idx = 0; // branch beats an integer division per sample
3840
3841 // Periodic full re-summation to prevent floating-point drift
3842 if (++recomputeCount >= kRmsRecomputePeriod)
3843 {
3844 sum = T(0);
3845 for (int j = 0; j < len; ++j) sum += buf[j];
3846 recomputeCount = 0;
3847 }
3848
3849 level = std::sqrt(std::max(sum / static_cast<T>(len), T(0)));
3850 }
3851 break;
3852 }
3853
3855 level = truePeak_.processSample(sample, ch);
3856 break;
3857
3859 {
3860 T pos = std::max(sample, T(0));
3861 T neg = std::max(-sample, T(0));
3862
3863 T posCoeff = (pos > splitPosEnv_[ch]) ? splitDetAttCoeff_ : splitDetRelCoeff_;
3864 T negCoeff = (neg > splitNegEnv_[ch]) ? splitDetAttCoeff_ : splitDetRelCoeff_;
3865
3866 splitPosEnv_[ch] = pos + posCoeff * (splitPosEnv_[ch] - pos);
3867 splitNegEnv_[ch] = neg + negCoeff * (splitNegEnv_[ch] - neg);
3868
3869 level = std::max(splitPosEnv_[ch], splitNegEnv_[ch]);
3870 break;
3871 }
3872
3874 {
3875 // The analytic magnitude is the envelope of a sustained tone,
3876 // but the allpass pair takes part of a cycle to form it after
3877 // an onset; the rectified input is never above the envelope of
3878 // a steady tone, so the larger of the two keeps the ripple-free
3879 // level and catches a step as fast as the peak detector.
3880 const double mag = hilbertDetectors_[ch].magnitude(static_cast<double>(sample));
3881 level = static_cast<T>(std::max(mag, std::abs(static_cast<double>(sample))));
3882 break;
3883 }
3884
3886 {
3887 // The root of twice the mean square is the peak of a steady
3888 // tone; the rectified sample is over it only while the level
3889 // rises faster than the mean can.
3890 double& meanSq = hybridMeanSq_[static_cast<size_t>(ch)];
3891 const double x = static_cast<double>(sample);
3892 meanSq += hybridRate_ * (x * x - meanSq);
3893 level = static_cast<T>(std::max(std::sqrt(2.0 * meanSq), std::abs(x)));
3894 break;
3895 }
3896 }
3897 return level;
3898 }
3899
3900 // ---- The colour stage (setCharacterStage()) ----
3901
3907 void runStage(CharacterStage<T>& stage, double& weight, bool wanted, AudioBufferView<T> buffer) noexcept
3908 {
3909 if (!(sampleRate_ > 0) || stageFade_.empty()) return;
3910 const double target = wanted ? 1.0 : 0.0;
3911 if (weight == 0.0 && target == 0.0) return;
3912 if (weight == 0.0) stage.reset();
3913 if (weight == 1.0 && target == 1.0)
3914 {
3915 stage.process(buffer);
3916 return;
3917 }
3918 const int nCh = std::min(buffer.getNumChannels(), stageScratch_.getNumChannels());
3919 const int step = stageScratch_.getNumSamples();
3920 for (int off = 0; off < buffer.getNumSamples(); off += step)
3921 {
3922 const int m = std::min(step, buffer.getNumSamples() - off);
3923 auto part = buffer.getSubView(off, m);
3924 auto copy = stageScratch_.toView().getSubView(0, m);
3925 for (int ch = 0; ch < nCh; ++ch) std::copy_n(part.getChannel(ch), m, copy.getChannel(ch));
3926 stage.process(AudioBufferView<T>(copy));
3927 for (int i = 0; i < m; ++i)
3928 {
3929 weight = target > weight ? std::min(target, weight + stageFadeStep_)
3930 : std::max(target, weight - stageFadeStep_);
3931 stageFade_[static_cast<size_t>(i)] = weight;
3932 }
3933 for (int ch = 0; ch < nCh; ++ch)
3934 {
3935 T* y = part.getChannel(ch);
3936 const T* s = copy.getChannel(ch);
3937 for (int i = 0; i < m; ++i)
3938 y[i] += static_cast<T>(stageFade_[static_cast<size_t>(i)]) * (s[i] - y[i]);
3939 }
3940 }
3941 }
3942
3943 // ---- Characters as data ----
3944
3946 enum class Colour
3947 {
3948 None,
3949 SecondOrder,
3950 PushPull
3951 };
3952
3984
3985 static constexpr T kNoLimit = std::numeric_limits<T>::infinity();
3986
3987 // The three-stage cell of Opto (setOptoCell()). The memory share of 0.4
3988 // splits 0.625 / 0.375 between the medium stage (charge over one release
3989 // time, 30 ms to 1 s; release over five) and the deep one; with the fast
3990 // stage at 0.725 release times, a fully charged cell recovers half its
3991 // reduction in one release time: 0.6 e^(-1/0.725) + 0.4 (0.625 e^(-1/5)
3992 // + 0.375 e^(-1/25)) = 0.500.
3993 static constexpr double kOptoThreeFastRelease = 0.725;
3994 static constexpr double kOptoMidShare = 0.625;
3995 static constexpr double kOptoMidRelease = 5.0;
3996 static constexpr double kOptoMidCharge = 1.0;
3997 static constexpr double kOptoMidChargeFloorMs = 30.0;
3998 static constexpr double kOptoMidChargeCeilMs = 1000.0;
3999
4001 static constexpr std::array<CharacterProfile, 5> kProfiles { {
4002 // Clean: one envelope on the knobs.
4003 { T(0.01), kNoLimit, T(1), kNoLimit, T(1), T(1), kNoLimit, T(0), T(0), T(0), T(1),
4004 T(0), T(0), false, Colour::None, true, true,
4005 false, T(0), T(0), T(0), T(0), T(0), T(0), T(0) },
4006 // Opto: the release knob is the 50 % recovery time. With a 0.6/0.4
4007 // split, a fast stage of 0.61 times the release puts the half
4008 // recovery on the knob while the memory tail decays some 35 times
4009 // slower, up to the 5 s of the cell; the memory charges over four
4010 // release times (0.1 to 2 s), so only sustained compression builds
4011 // the long tail. The 10 ms attack floor is the cell's.
4012 { T(10), kNoLimit, T(1), kNoLimit, T(0.61), T(25), T(5000), T(4), T(100), T(2000), T(0.6),
4013 T(10), T(0), false, Colour::None, false, false,
4014 false, T(0), T(0), T(0), T(0), T(0), T(0), T(0) },
4015 // FET: knobs of 20 to 800 us and 50 to 1100 ms. With a 0.75/0.25
4016 // split the compound release passes its t63 at the knob, and a
4017 // 150 ms charge gives the tail that depends on the programme.
4018 { T(0.02), T(0.8), T(50), T(1100), T(0.7), T(2.5), kNoLimit, T(0), T(150), T(150), T(0.75),
4019 T(0), T(0), true, Colour::SecondOrder, false, false,
4020 false, T(0), T(0), T(0), T(0), T(0), T(0), T(0) },
4021 // Varimu: one envelope, a ratio that grows with the level, a knee
4022 // that cannot be hard, and the gain through a push-pull pair.
4023 { T(0.01), kNoLimit, T(1), kNoLimit, T(1), T(1), kNoLimit, T(0), T(0), T(0), T(1),
4024 T(10), T(40), false, Colour::PushPull, false, true,
4025 false, T(0), T(0), T(0), T(0), T(0), T(0), T(0) },
4026 // Layered: a levelling layer with half the slope from 6 dB under the
4027 // threshold, eight times the attack (30 ms at least) and six times
4028 // the release, under a layer on the knobs; both take twice as long
4029 // 12 dB (attack) or 6 dB (release) away from their target.
4030 { T(0.01), kNoLimit, T(1), kNoLimit, T(1), T(1), kNoLimit, T(0), T(0), T(0), T(1),
4031 T(6), T(0), false, Colour::None, false, false,
4032 true, T(0.5), T(6), T(8), T(30), T(6), T(12), T(6) },
4033 } };
4034
4036 [[nodiscard]] static constexpr CharacterProfile profileOf(Character type) noexcept
4037 {
4038 const int last = static_cast<int>(kProfiles.size()) - 1;
4039 return kProfiles[static_cast<size_t>(std::clamp(static_cast<int>(type), 0, last))];
4040 }
4041
4043 [[nodiscard]] static constexpr Topology topologyFor(const CharacterProfile& profile, Topology asked) noexcept
4044 {
4045 return profile.ownLoop ? Topology::FeedBack : (profile.forwardOnly ? Topology::FeedForward : asked);
4046 }
4047
4049 [[nodiscard]] static constexpr bool isLayered(const CharacterProfile& profile, Mode modeType) noexcept
4050 {
4051 return profile.levelShare > T(0) && modeType == Mode::Downward;
4052 }
4053
4055 [[nodiscard]] static constexpr DetectorType detectorFor(const CharacterProfile& profile, DetectorType asked) noexcept
4056 {
4057 return profile.ownLoop ? DetectorType::Peak : asked;
4058 }
4059
4060 // ---- Gain curves ----
4061
4068 [[nodiscard]] static T effectiveRatioFor(Character charType, T ratio, T excessDb) noexcept
4069 {
4070 // Progressive compression: a remote-cutoff tube's effective ratio
4071 // grows with the level above the threshold.
4072 const T growth = profileOf(charType).ratioGrowthDb;
4073 if (growth > T(0) && excessDb > T(0))
4074 return ratio * (T(1) + excessDb / growth);
4075 return ratio;
4076 }
4077
4079 [[nodiscard]] static T effectiveKneeFor(Character charType, T knee) noexcept
4080 {
4081 // Neither a remote-cutoff tube (Varimu) nor a photocell (Opto) can
4082 // form a hard corner: both transfers bend gradually over their whole
4083 // operating region, so the knee has a 10 dB physical floor.
4084 const T floor = profileOf(charType).kneeFloorDb;
4085 return (floor > T(0)) ? std::max(knee, floor) : knee;
4086 }
4087
4099 [[nodiscard]] T computeGain(T inputDb, T thresh, T ratio, T knee, Character charType, Mode modeType,
4100 T guardDb) const noexcept
4101 {
4102 if (modeType == Mode::Upward)
4103 return computeGainUpward(inputDb, thresh, ratio, knee, guardDb);
4104 if (modeType == Mode::Leveler)
4105 return levelerCurve(inputDb, thresh);
4106 const T down = downwardCurve(inputDb, thresh, ratio, knee, charType);
4107 return modeType == Mode::Both ? down + lift(inputDb, thresh, knee, guardDb) : down;
4108 }
4109
4112 [[nodiscard]] static constexpr Mode modeIn(Mode asked, Topology topoEff) noexcept
4113 {
4114 return (topoEff == Topology::FeedBack && asked != Mode::Upward) ? Mode::Downward : asked;
4115 }
4116
4118 [[nodiscard]] static constexpr bool reducesOnly(Mode modeType) noexcept
4119 {
4120 return modeType == Mode::Downward || modeType == Mode::Leveler;
4121 }
4122
4128 [[nodiscard]] static T levelerCurve(T inputDb, T thresh) noexcept
4129 {
4130 const T over = inputDb - thresh;
4131 if (over <= T(-120)) return T(0);
4132 return static_cast<T>(-20.0 / std::numbers::ln10) * std::log1p(decibelsToGain(over));
4133 }
4134
4136 [[nodiscard]] T lift(T inputDb, T thresh, T knee, T guardDb) const noexcept
4137 {
4138 return std::min(computeGainUpward(inputDb, thresh - liftBelowDb_, liftRatioIn_, knee, guardDb), liftRangeDb_);
4139 }
4140
4145 [[nodiscard]] static T downwardCurve(T inputDb, T thresh, T ratio, T knee, Character charType) noexcept
4146 {
4147 const CharacterProfile profile = profileOf(charType);
4148 if (profile.levelShare > T(0))
4149 {
4150 const Layers layers = layeredCurve(inputDb, thresh, ratio, knee, profile);
4151 return layers.level + layers.peak;
4152 }
4153 const T effectiveRatio = effectiveRatioFor(charType, ratio, inputDb - thresh);
4154 const T effectiveKnee = effectiveKneeFor(charType, knee);
4155 return kneeCurve(inputDb, thresh, T(1) - T(1) / effectiveRatio, effectiveKnee);
4156 }
4157
4162 [[nodiscard]] static T kneeCurve(T inputDb, T thresh, T slope, T knee) noexcept
4163 {
4164 // Branch-free pieces (the level crosses the threshold at random on
4165 // dense programme, where a branch per sample mispredicts): below the
4166 // threshold the linear piece is positive and min() returns 0.
4167 if (knee <= T(0))
4168 return std::min(thresh - inputDb, T(0)) * slope;
4169
4170 // Soft knee: the quadratic below the knee top never exceeds the
4171 // linear piece, and with x clamped to the knee width it is the larger
4172 // one above it, so min() picks the right piece on every side.
4173 const T halfKnee = knee / T(2);
4174 const T x = std::clamp(inputDb - (thresh - halfKnee), T(0), knee);
4175 const T quad = T(0) - slope * x * x / (T(2) * knee);
4176 return std::min((thresh - inputDb) * slope, quad);
4177 }
4178
4179 // ---- Layered characters ----
4180
4182 struct Layers
4183 {
4186 };
4187
4196 [[nodiscard]] static Layers layeredCurve(T inputDb, T thresh, T ratio, T knee,
4197 const CharacterProfile& profile) noexcept
4198 {
4199 const T slope = T(1) - T(1) / ratio;
4200 const T levelSlope = profile.levelShare * slope;
4201 const T lag = profile.levelLeadDb * profile.levelShare / (T(1) - profile.levelShare);
4202 return { kneeCurve(inputDb, thresh - profile.levelLeadDb, levelSlope, T(2) * profile.levelLeadDb),
4203 kneeCurve(inputDb, thresh + lag, slope - levelSlope, std::max(knee, profile.kneeFloorDb)) };
4204 }
4205
4218 [[nodiscard]] static double pacedStep(double envelope, double target, double attackRate, double releaseRate,
4219 double attackPace, double releasePace) noexcept
4220 {
4221 const double distance = envelope - target; // over zero: the gain has to fall
4222 const double gap = std::abs(distance);
4223 const double rate = (distance > 0.0) ? attackRate / (1.0 + gap / attackPace)
4224 : releaseRate / (1.0 + gap / releasePace);
4225 return target + fastDecay(rate) * distance;
4226 }
4227
4236 [[nodiscard]] double layeredStep(T inputDb, T thresh, T ratio, T knee, const CharacterProfile& profile,
4237 T range, int holdN, int soft, T& held, int& counter,
4238 double& level, double& peak, SlidingDeepest* window = nullptr) const noexcept
4239 {
4240 const Layers want = layeredCurve(inputDb, thresh, ratio, knee, profile);
4241 const T bounded = holdAndRange(want.level + want.peak, range, holdN, held, counter, soft, window);
4242 const double levelTarget = static_cast<double>(std::max(want.level, bounded));
4243 const double peakTarget = static_cast<double>(bounded) - levelTarget;
4244 level = pacedStep(level, levelTarget, layerAttRate_, layerRelRate_,
4245 static_cast<double>(profile.attackPaceDb), static_cast<double>(profile.releasePaceDb));
4246 peak = pacedStep(peak, peakTarget, peakAttRate_, peakRelRate_,
4247 static_cast<double>(profile.attackPaceDb), static_cast<double>(profile.releasePaceDb));
4248 if (atRest(level, levelTarget)) level = 0.0;
4249 if (atRest(peak, peakTarget)) peak = 0.0;
4250 // (While the layers trade places their sum could pass the range.)
4251 return std::max(level + peak, -static_cast<double>(range));
4252 }
4253
4258 void syncLayerState(bool layered) noexcept
4259 {
4260 if (layered && !layeredActive_)
4261 {
4262 const double share = static_cast<double>(profileOf(character_.load(std::memory_order_relaxed)).levelShare);
4263 for (int ch = 0; ch < kMaxChannels; ++ch)
4264 {
4265 const double shown = envFastDb_[static_cast<size_t>(ch)];
4266 layerLevelDb_[static_cast<size_t>(ch)] = share * shown;
4267 layerPeakDb_[static_cast<size_t>(ch)] = shown - share * shown;
4268 }
4269 }
4270 layeredActive_ = layered;
4271 }
4272
4273 // ---- The gain after the ballistics ----
4274
4293 [[nodiscard]] static T pushPullElement(T input, T gain, T amount) noexcept
4294 {
4295 if (!(gain > T(0)) || !(amount > T(0)) || !std::isfinite(input)) return input * gain;
4296 const double g = static_cast<double>(gain);
4297 const double slope = std::min(g, 1.0) * kPushPullRest;
4298 const double drive = kPushPullDrive * static_cast<double>(amount);
4299 // With e the exponential of the bias (the logistic of the bias is
4300 // the slope) and u that of the input, the difference of the two
4301 // halves is the logarithm of (1 + e u) / (1 + e / u): one
4302 // exponential and one logarithm per sample, exact for a small e too.
4303 const double e = slope / (1.0 - slope);
4304 const double u = std::exp(std::clamp(drive * static_cast<double>(input), -30.0, 30.0));
4305 const double pair = 0.5 * std::log1p(e * (u - 1.0 / u) / (1.0 + e / u));
4306 return static_cast<T>(pair * (g / slope) / drive);
4307 }
4308
4309 // ---- The audio path beyond the plain gain ----
4310
4312 [[nodiscard]] static bool rectifies(DetectorType detType) noexcept
4313 {
4314 return detType == DetectorType::Peak || detType == DetectorType::TruePeak || detType == DetectorType::Hybrid;
4315 }
4316
4323 bool syncAudioPath() noexcept
4324 {
4325 const T low = toneLowDb_.load(std::memory_order_relaxed), high = toneHighDb_.load(std::memory_order_relaxed);
4326 const bool tone = low != T(0) || high != T(0);
4327 if (tone && (!toneActive_ || low != toneLowIn_ || high != toneHighIn_))
4328 {
4330 static_cast<double>(low)));
4332 static_cast<double>(high)));
4333 if (!toneActive_)
4334 {
4335 toneLow_.reset();
4336 toneHigh_.reset();
4337 }
4338 toneLowIn_ = low;
4339 toneHighIn_ = high;
4340 }
4341 toneActive_ = tone;
4342
4343 // The leak starts from the gain that is sounding: switching it on leaves no thump.
4344 const T leak = controlLeak_.load(std::memory_order_relaxed);
4345 if (leak > T(0) && !(leakAmount_ > T(0)))
4346 leakBase_.fill(decibelsToGain(gainReductionDb_.load(std::memory_order_relaxed)));
4347 leakAmount_ = leak;
4348
4349 asymAmount_ = detectorAsymmetry_.load(std::memory_order_relaxed);
4350 driftAmount_ = detectorDrift_.load(std::memory_order_relaxed);
4352 return audioExtras_ || lopsidedDetector();
4353 }
4354
4356 [[nodiscard]] bool lopsidedDetector() const noexcept { return asymAmount_ != T(0) || driftAmount_ > T(0); }
4357
4363 [[nodiscard]] T gained(T input, T gain, int ch) noexcept
4364 {
4365 T wet = input * gain;
4366 if (toneActive_)
4367 {
4368 // y = x - (1 - g) F(x): at no reduction, the input itself.
4369 const T shaped = toneHigh_.processSample(
4370 toneLow_.processSample(std::isfinite(input) ? input : T(0), ch), ch);
4371 wet = input - (T(1) - gain) * shaped;
4372 }
4373 if (leakAmount_ > T(0))
4374 {
4375 // The gain through a high-pass: what it is over its own slow copy.
4376 T& base = leakBase_[static_cast<size_t>(ch)];
4377 const T moved = gain - base;
4378 if (std::abs(moved) < T(1e-7)) base = gain; // (end the tail: a settled gain adds exactly nothing)
4379 else
4380 {
4381 base += leakCoeff_ * moved;
4382 wet += leakAmount_ * static_cast<T>(kLeakLevel) * moved;
4383 }
4384 }
4385 return wet;
4386 }
4387
4392 [[nodiscard]] T asymmetric(T key, int ch) noexcept
4393 {
4394 const size_t c = static_cast<size_t>(ch);
4395 T& crest = asymCrest_[c];
4396 crest = std::max(std::abs(key), crest * asymDecay_);
4397 T amount = asymAmount_;
4398 if (driftAmount_ > T(0))
4399 {
4400 // One step of the channel's walk (this runs once per channel and
4401 // frame): a draw every kAsymDriftTick frames, followed in a line.
4402 AsymDrift& d = asymDrift_[c];
4403 if (d.tick == 0)
4404 {
4405 d.from = d.to;
4407 d.smooth += asymDriftRate_ * (d.wander - d.smooth);
4408 d.to = asymDriftScale_ * d.smooth;
4409 }
4410 const double t = static_cast<double>(d.tick + 1) / kAsymDriftTick;
4411 d.tick = (d.tick + 1 == kAsymDriftTick) ? 0 : d.tick + 1;
4412 const double wander = d.from + t * (d.to - d.from);
4413 amount = std::clamp(static_cast<T>(static_cast<double>(asymAmount_)
4414 + static_cast<double>(driftAmount_) * kAsymDrift * wander),
4415 T(-1), T(1));
4416 asymNow_[c] = amount;
4417 }
4418 return (key + amount * crest) / (T(1) + std::abs(amount));
4419 }
4420
4422 static double driftUniform(std::uint32_t& s) noexcept
4423 {
4424 s ^= s << 13; s ^= s >> 17; s ^= s << 5;
4425 return static_cast<double>(s) * (2.0 / 4294967296.0) - 1.0;
4426 }
4427
4429 [[nodiscard]] bool shapesGain() const noexcept
4430 {
4431 return gainSmoothRate_ > 0.0 || landingRate_ > 0.0 || networkShare_ < 1.0;
4432 }
4433
4439 [[nodiscard]] T smoothedGain(T grDb, int ch) noexcept
4440 {
4441 const size_t c = static_cast<size_t>(ch);
4442 double gain = static_cast<double>(grDb);
4443 if (landingRate_ > 0.0)
4444 {
4445 // At once while the gain change deepens or changes side; on the
4446 // way back, a follower that is slow near the gain it follows.
4447 double& heard = landingDb_[c];
4448 const double behind = std::abs(heard) - std::abs(gain);
4449 if (behind <= 0.0 || (heard > 0.0) != (gain > 0.0))
4450 heard = gain;
4451 else
4452 heard += std::min(1.0, landingRate_ * std::exp(std::min(behind * (1.0 / kLandingPaceDb), 40.0)))
4453 * (gain - heard);
4454 if (gain == 0.0 && std::abs(heard) < 1e-6) heard = 0.0;
4455 gain = heard;
4456 }
4457 if (networkShare_ < 1.0)
4458 {
4459 // A shelf: what is slow, whole; of what is fast, a share.
4460 double& low = networkLow_[c];
4461 low += networkRate_ * (gain - low);
4462 if (gain == 0.0 && std::abs(low) < 1e-6) low = 0.0;
4463 gain = low + networkShare_ * (gain - low);
4464 }
4465 if (gainSmoothRate_ > 0.0)
4466 {
4467 double& first = gainSmoothA_[c];
4468 double& second = gainSmoothB_[c];
4469 first += gainSmoothRate_ * (gain - first);
4470 second += gainSmoothRate_ * (first - second);
4471 // (End the asymptotic tail: 0 dB is exact again once it is reached.)
4472 if (gain == 0.0 && std::abs(first) < 1e-6 && std::abs(second) < 1e-6)
4473 {
4474 first = 0.0;
4475 second = 0.0;
4476 }
4477 gain = second;
4478 }
4479 return static_cast<T>(gain);
4480 }
4481
4486 void syncGainSmoothing(bool) noexcept
4487 {
4488 const bool smooth = gainSmoothRate_ > 0.0, landing = landingRate_ > 0.0, network = networkShare_ < 1.0;
4489 if ((smooth && !gainSmoothActive_) || (landing && !landingActive_) || (network && !networkActive_))
4490 {
4491 const double shown = static_cast<double>(gainReductionDb_.load(std::memory_order_relaxed));
4492 if (smooth && !gainSmoothActive_)
4493 {
4494 gainSmoothA_.fill(shown);
4495 gainSmoothB_.fill(shown);
4496 }
4497 if (landing && !landingActive_) landingDb_.fill(shown);
4498 if (network && !networkActive_) networkLow_.fill(shown);
4499 }
4500 gainSmoothActive_ = smooth;
4501 landingActive_ = landing;
4502 networkActive_ = network;
4503 }
4504
4515 [[nodiscard]] T computeGainUpward(T inputDb, T thresh, T ratio, T knee, T guardDb) const noexcept
4516 {
4517 T effectiveRatio = ratio;
4518 T boost;
4519 if (knee <= T(0))
4520 {
4521 if (inputDb >= thresh) return T(0);
4522 boost = (thresh - inputDb) * (T(1) - T(1) / effectiveRatio);
4523 }
4524 else
4525 {
4526 T halfKnee = knee / T(2);
4527 T lower = thresh - halfKnee;
4528 T upper = thresh + halfKnee;
4529
4530 if (inputDb >= upper) return T(0);
4531 if (inputDb <= lower)
4532 {
4533 boost = (thresh - inputDb) * (T(1) - T(1) / effectiveRatio);
4534 }
4535 else
4536 {
4537 T x = upper - inputDb;
4538 boost = (T(1) - T(1) / effectiveRatio) * x * x / (T(2) * knee);
4539 }
4540 }
4541
4542 const T silenceGuard = std::clamp((guardDb - (thresh - T(60))) / T(20), T(0), T(1));
4543 return boost * silenceGuard;
4544 }
4545
4546 // ---- Feedback law (element transfer solved from the observed curve) ----
4547
4550 {
4553 };
4554
4571 [[nodiscard]] static FeedbackLaw elementLaw(T eOut, T r, T w) noexcept
4572 {
4573 const T a = r - T(1);
4574 if (w <= T(0))
4575 {
4576 if (eOut <= T(0)) return { T(0), T(0) };
4577 return { -a * eOut, a };
4578 }
4579 const T halfW = w / T(2);
4580 if (eOut <= -halfW) return { T(0), T(0) };
4581 if (eOut >= halfW / r) return { -a * eOut, a };
4582 // Knee: invert eOut = u - W/2 - s u^2 / (2W) for the input-side
4583 // excess u in (0, W). s = 1 - 1/R is the feed-forward slope factor;
4584 // the slope denominator is analytically >= 1/R.
4585 const T s = a / r;
4586 const T b = eOut + halfW;
4587 const T z = std::min(T(2) * s * b / w, T(1));
4588 const T u = std::min(T(2) * b / (T(1) + std::sqrt(T(1) - z)), w);
4589 const T su = s * u / w;
4590 return { -s * u * u / (T(2) * w), su / std::max(T(1) - su, T(1) / r) };
4591 }
4592
4607 [[nodiscard]] FeedbackLaw computeGainFeedback(T outDb, T thresh, T ratio, T knee,
4608 Character charType) const noexcept
4609 {
4610 const T eOut = outDb - thresh;
4611 const T w = effectiveKneeFor(charType, knee);
4612 T r = std::max(effectiveRatioFor(charType, ratio, eOut), T(1));
4613 FeedbackLaw law = elementLaw(eOut, r, w);
4614 if (profileOf(charType).ratioGrowthDb > T(0))
4615 {
4616 for (int pass = 0; pass < 2; ++pass)
4617 {
4618 r = std::max(effectiveRatioFor(charType, ratio, eOut - law.target), T(1));
4619 law = elementLaw(eOut, r, w);
4620 }
4621 }
4622 return law;
4623 }
4624
4641 [[nodiscard]] static FeedbackLaw computeGainFeedbackUpward(T outDb, T thresh, T ratio, T knee,
4642 T guardDb) noexcept
4643 {
4644 const T r = std::max(ratio, T(1));
4645 const T a = r - T(1);
4646 const T guard = std::clamp((guardDb - (thresh - T(60))) / T(20), T(0), T(1));
4647 if (knee <= T(0))
4648 {
4649 const T e = thresh - outDb;
4650 if (e <= T(0)) return { T(0), T(0) };
4651 return { a * e * guard, a * guard };
4652 }
4653 const T s = a / r;
4654 const T eu = thresh + knee / T(2) - outDb; // distance below the knee top
4655 if (eu <= T(0)) return { T(0), T(0) };
4656 if (eu >= knee * (T(1) - s / T(2)))
4657 return { a * (thresh - outDb) * guard, a * guard };
4658 // Knee: invert upper - out = v - s v^2 / (2W) for the input-side
4659 // depth v in (0, W) (cancellation-free root).
4660 const T z = std::min(T(2) * s * eu / knee, T(1));
4661 const T v = std::min(T(2) * eu / (T(1) + std::sqrt(T(1) - z)), knee);
4662 const T sv = s * v / knee;
4663 return { s * v * v / (T(2) * knee) * guard, sv / std::max(T(1) - sv, T(1) / r) * guard };
4664 }
4665
4668 {
4671 };
4672
4694 [[nodiscard]] FeedbackSolve solveFeedbackGain(T inDb, T k, T effB, T thresh,
4695 T ratio, T knee, Character charType) const noexcept
4696 {
4697 const T r = std::max(effectiveRatioFor(charType, ratio, inDb - thresh), T(1));
4698 const T w = effectiveKneeFor(charType, knee);
4699 const T halfW = w / T(2);
4700 const T a = r - T(1);
4701
4702 // Piece 1: at or below the knee start the law is zero and G = k.
4703 T e = inDb + k - thresh;
4704 if (e <= ((w > T(0)) ? -halfW : T(0)))
4705 return { k, T(0) };
4706
4707 // Piece 3: linear region, target = -a * e at the solved level. With a
4708 // hard knee this piece always resolves (e scales by 1/(1 + effB a)).
4709 const T g3 = (k - effB * a * (inDb - thresh)) / (T(1) + effB * a);
4710 e = inDb + g3 - thresh;
4711 if (e >= ((w > T(0)) ? halfW / r : T(0)))
4712 return { g3, -a * e };
4713
4714 // Piece 2: quadratic knee. Substituting G = k + effB * gel into the
4715 // knee relation gives q u^2 - u + (d + W/2) = 0 with
4716 // q = (1 - effB) s / (2W); the cancellation-free smaller root is used.
4717 const T s = a / r;
4718 const T q = (T(1) - effB) * s / (T(2) * w);
4719 const T b = (inDb - thresh + k) + halfW;
4720 const T disc = std::max(T(1) - T(4) * q * b, T(0));
4721 T u = T(2) * b / (T(1) + std::sqrt(disc));
4722 u = std::clamp(u, T(0), w);
4723 const T target = -s * u * u / (T(2) * w);
4724 return { k + effB * target, target };
4725 }
4726
4742 [[nodiscard]] T applyBallisticsFeedbackImplicit(T inDb, int ch, Character charType,
4743 T thresh, T ratio, T knee) noexcept
4744 {
4747 return boundImplicit(stepImplicit(inDb, ch, charType, thresh, ratio, knee, coeffs), ch);
4748 }
4749
4752 {
4753 double attack;
4754 double release;
4755 double charge;
4757 double midCharge;
4758 double midRelease;
4759 };
4760
4763 [[nodiscard]] T stepImplicit(T inDb, int ch, Character charType, T thresh, T ratio, T knee,
4764 const LoopCoeffs& coeffs) noexcept
4765 {
4766 double& fast = envFastDb_[ch];
4767 double& slow = envSlowDb_[ch];
4768 const double wFast = static_cast<double>(charFastWeight_);
4769 const bool dual = wFast < 1.0;
4770
4771 if (dual)
4772 {
4773 // The memory stage tracks the REAL sustained gain reduction (the
4774 // static curve at the current input), never the element's
4775 // internal target: the loop gain scales that one by up to
4776 // (R - 1), and a memory charging toward the amplified signal
4777 // overshoots, drags the settled blend off the curve and smears
4778 // the observed attack. Advancing it first keeps the solve below
4779 // consistent with the state it blends against.
4780 const T range = rangeDb_.load(std::memory_order_relaxed);
4781 const T slowTarget = std::clamp(
4782 computeGain(inDb, thresh, ratio, knee, charType, Mode::Downward, T(0)),
4783 -range, range);
4784 const double st = static_cast<double>(slowTarget);
4785 if (threeStage_)
4786 {
4787 double& mid = envMidDb_[ch];
4788 double& deep = envDeepDb_[ch];
4789 mid = st + ((st < mid) ? coeffs.midCharge : coeffs.midRelease) * (mid - st);
4790 if (atRest(mid, st)) mid = 0.0;
4791 deep = st + ((st < deep) ? coeffs.charge : coeffs.slowRelease) * (deep - st);
4792 if (atRest(deep, st)) deep = 0.0;
4793 slow = kOptoMidShare * mid + (1.0 - kOptoMidShare) * deep;
4794 }
4795 else
4796 {
4797 const bool charging = st < slow;
4798 slow = st + (charging ? coeffs.charge : coeffs.slowRelease) * (slow - st);
4799 if (atRest(slow, st)) slow = 0.0;
4800 }
4801 }
4802
4803 // Branch on the direction the loop is about to move: attack while
4804 // the reduction deepens at the previous gain, release otherwise.
4805 const T shownPrev = static_cast<T>(dual ? wFast * fast + (1.0 - wFast) * slow : fast);
4806 const T probe = computeGainFeedback(inDb + shownPrev, thresh, ratio, knee, charType).target;
4807 const bool engaging = static_cast<double>(probe) < fast;
4808 const double coeff = engaging ? coeffs.attack : coeffs.release;
4809 const double beta = 1.0 - coeff;
4810
4811 const T k = static_cast<T>(dual ? wFast * coeff * fast + (1.0 - wFast) * slow : coeff * fast);
4812 const T effB = static_cast<T>(dual ? wFast * beta : beta);
4813 const auto sol = solveFeedbackGain(inDb, k, effB, thresh, ratio, knee, charType);
4814
4815 const double solT = static_cast<double>(sol.target);
4816 fast = solT + coeff * (fast - solT);
4817 if (atRest(fast, solT)) fast = 0.0;
4818 return static_cast<T>(dual ? wFast * fast + (1.0 - wFast) * slow : fast);
4819 }
4820
4830 [[nodiscard]] T boundImplicit(T shown, int ch) noexcept
4831 {
4832 const T bounded = applyHoldAndRange(shown, ch);
4833 if (bounded != shown)
4834 {
4835 const double wFast = static_cast<double>(charFastWeight_);
4836 const double sh = static_cast<double>(bounded);
4837 envFastDb_[ch] = (wFast < 1.0) ? (sh - (1.0 - wFast) * envSlowDb_[ch]) / wFast : sh;
4838 }
4839 return bounded;
4840 }
4841
4853 [[nodiscard]] static bool atRest(double envelope, double target) noexcept
4854 {
4855 return std::abs(envelope) < 1e-4 && std::abs(target) < 1e-4;
4856 }
4857
4858 // ---- Ballistics (log domain) ----
4859
4892 [[nodiscard]] T applyBallistics(T targetGrDb, int ch, bool splitAdaptive,
4893 T loopSlope = T(-1), double loopDelay = 0.0) noexcept
4894 {
4895 // Level-adaptive release for the SplitPolarity detector: full-scale
4896 // output halves the release time constant. Halving tau squares the
4897 // one-pole coefficient, so blending between the two valid endpoints
4898 // keeps the modulation on the exponential curve.
4899 double attCoeff = charAttCoeff_;
4900 double relCoeff = charRelCoeff_;
4901 if (splitAdaptive)
4902 {
4903 // Written so a non-finite previous output reads as full scale
4904 // instead of turning the coefficient (and the envelope) into NaN.
4905 const double lastOut = std::abs(static_cast<double>(fbLastOutput_[ch]));
4906 const double outputLevel = (lastOut < 1.0) ? lastOut : 1.0;
4907 relCoeff += outputLevel * (relCoeff * relCoeff - relCoeff);
4908 }
4909 if (loopSlope >= T(0))
4910 {
4911 // Cap the per-sample loop advance at 0.5 (half-deadbeat): the
4912 // one-sample delay then converges monotonically instead of
4913 // sustaining a marginal dance on the detector's residual ripple.
4914 // A detector with a delay (the RMS window) lowers the cap to the
4915 // critically damped advance of a loop around that delay. On a
4916 // level fall the window's mean square stays up until the old
4917 // loud samples leave it (a full window of delay); on a rise the
4918 // new loud samples dominate it within a fraction of the window,
4919 // so the attack side tolerates twice the advance (measured: no
4920 // over-compression at 2x, 0.07 dB at 2.5x).
4921 const double lim = (loopDelay > 0.0) ? 1.0 / (std::numbers::e * (1.0 + loopDelay)) : 0.5;
4922 const double attAdvance = std::min(0.5, 2.0 * lim);
4923 const double relAdvance = std::min(0.5, lim);
4924 const double loop = 1.0 + static_cast<double>(loopSlope);
4925 attCoeff = std::max(attCoeff, 1.0 - attAdvance / loop);
4926 relCoeff = std::max(relCoeff, 1.0 - relAdvance / loop);
4927 }
4928
4929 return static_cast<T>(ballisticsStep(static_cast<double>(targetGrDb), envFastDb_[ch], envSlowDb_[ch],
4930 envMidDb_[ch], envDeepDb_[ch], attCoeff, relCoeff));
4931 }
4932
4944 [[nodiscard]] static double branchingStep(double y, double tgt, double cDown, double cUp) noexcept
4945 {
4946 const double d = y - tgt;
4947 const double down = tgt + cDown * d;
4948 const double up = tgt + cUp * d;
4949 return (cDown <= cUp) ? std::min(down, up) : std::max(down, up);
4950 }
4951
4961 [[nodiscard]] double ballisticsStep(double tgt, double& fast, double& slow, double& mid, double& deep,
4962 double attCoeff, double relCoeff) const noexcept
4963 {
4964 return ballisticsCore(tgt, fast, slow, mid, deep, attCoeff, relCoeff, charChargeCoeff_, charSlowRelCoeff_,
4966 }
4967
4969 [[nodiscard]] double ballisticsCore(double tgt, double& fast, double& slow, double& mid, double& deep,
4970 double attCoeff, double relCoeff, double chargeCoeff,
4971 double slowRelCoeff, double midChargeCoeff,
4972 double midRelCoeff) const noexcept
4973 {
4974 fast = branchingStep(fast, tgt, attCoeff, relCoeff);
4975 if (atRest(fast, tgt)) fast = 0.0; // end the asymptotic dB tail
4976
4977 if (charFastWeight_ >= T(1)) // Clean / Varimu: single envelope
4978 return fast;
4979
4980 // Opto / FET memory stage: charges toward the target over the history
4981 // time constant and discharges with the slow release, so its level
4982 // encodes how long (and how deep) the compressor has been working.
4983 // The three-stage cell blends a medium and a deep memory there.
4984 if (threeStage_)
4985 {
4986 mid = branchingStep(mid, tgt, midChargeCoeff, midRelCoeff);
4987 if (atRest(mid, tgt)) mid = 0.0;
4988 deep = branchingStep(deep, tgt, chargeCoeff, slowRelCoeff);
4989 if (atRest(deep, tgt)) deep = 0.0;
4990 slow = kOptoMidShare * mid + (1.0 - kOptoMidShare) * deep;
4991 }
4992 else
4993 {
4994 slow = branchingStep(slow, tgt, chargeCoeff, slowRelCoeff);
4995 if (atRest(slow, tgt)) slow = 0.0;
4996 }
4997
4998 const double w = static_cast<double>(charFastWeight_);
4999 return w * fast + (1.0 - w) * slow;
5000 }
5001
5008 void syncAdaptiveMakeup(bool adaptive) noexcept
5009 {
5010 if (adaptive && !adaptiveMakeupActive_)
5011 autoMakeupEnv_ = gainReductionDb_.load(std::memory_order_relaxed);
5012 adaptiveMakeupActive_ = adaptive;
5013 }
5014
5021 [[nodiscard]] double feedbackDetectorDelay(DetectorType detType) const noexcept
5022 {
5023 return (detType == DetectorType::Rms || detType == DetectorType::Hybrid)
5024 ? static_cast<double>(rmsWindowSamples_) : 0.0;
5025 }
5026
5029 [[nodiscard]] bool useDecoupled(Character charType, Topology topoEff) const noexcept
5030 {
5031 return profileOf(charType).decoupled && topoEff == Topology::FeedForward
5032 && cleanBallistics_.load(std::memory_order_relaxed) == CleanBallistics::Decoupled;
5033 }
5034
5040 void syncDecoupledState(bool decoupled) noexcept
5041 {
5042 if (decoupled && !decoupledActive_)
5043 for (int ch = 0; ch < kMaxChannels; ++ch)
5044 envHoldDb_[static_cast<size_t>(ch)] = envFastDb_[static_cast<size_t>(ch)];
5045 decoupledActive_ = decoupled;
5046 }
5047
5081 [[nodiscard]] T applyBallisticsDecoupled(T targetGrDb, int ch, bool splitAdaptive) noexcept
5082 {
5083 double holdCoeff = decHoldCoeff_;
5084 if (splitAdaptive)
5085 {
5086 const double lastOut = std::abs(static_cast<double>(fbLastOutput_[ch]));
5087 const double outputLevel = (lastOut < 1.0) ? lastOut : 1.0;
5088 holdCoeff += outputLevel * (holdCoeff * holdCoeff - holdCoeff);
5089 }
5090
5091 return static_cast<T>(decoupledStep(static_cast<double>(targetGrDb), envHoldDb_[ch],
5092 envFastDb_[ch], holdCoeff));
5093 }
5094
5096 [[nodiscard]] double decoupledStep(double tgt, double& hold, double& fast,
5097 double holdCoeff) const noexcept
5098 {
5099 return decoupledCore(tgt, hold, fast, holdCoeff, charAttCoeff_, decSmoothCoeff_);
5100 }
5101
5103 [[nodiscard]] static double decoupledCore(double tgt, double& hold, double& fast, double holdCoeff,
5104 double attCoeff, double smoothCoeff) noexcept
5105 {
5106 // Hold stage: a deeper (lower) target is taken at once; otherwise
5107 // release toward the target. Same direction rule as the branching
5108 // ballistics: a falling gain is the attack side in both modes.
5109 hold = std::min(tgt, tgt + holdCoeff * (hold - tgt));
5110 if (atRest(hold, tgt)) hold = 0.0; // end the asymptotic dB tail
5111
5112 // Smoothing stage: the attack pole while the held gain is below the
5113 // output (deepening), the release-side pole otherwise (never slower
5114 // than the attack, see updateTimeConstants).
5115 fast = branchingStep(fast, hold, attCoeff, smoothCoeff);
5116 if (atRest(fast, hold)) fast = 0.0;
5117 return fast;
5118 }
5119
5129 [[nodiscard]] static double decoupledHoldTau(double releaseMs, double smoothMs) noexcept
5130 {
5131 const double target = std::exp(-1.0);
5132 auto remaining = [&](double tau1) {
5133 const double t = releaseMs, t2 = smoothMs;
5134 if (std::abs(tau1 - t2) < 1e-9 * t)
5135 return (1.0 + t / t2) * std::exp(-t / t2);
5136 return (tau1 * std::exp(-t / tau1) - t2 * std::exp(-t / t2)) / (tau1 - t2);
5137 };
5138 double lo = 1e-6 * releaseMs, hi = releaseMs;
5139 for (int it = 0; it < 48; ++it)
5140 {
5141 const double mid = 0.5 * (lo + hi);
5142 if (remaining(mid) < target) lo = mid; else hi = mid;
5143 }
5144 return 0.5 * (lo + hi);
5145 }
5146
5147 // ---- Precision of the control signal (setPrecision) ----
5148
5151 [[nodiscard]] bool usePrecision(Topology topoEff, bool fbImplicit, bool splitAdaptive) const noexcept
5152 {
5153 return precision_.load(std::memory_order_relaxed) == Precision::High && !splitAdaptive
5154 && (topoEff == Topology::FeedForward || fbImplicit);
5155 }
5156
5159 [[nodiscard]] static bool readsBetweenSamples(DetectorType detType) noexcept
5160 {
5161 return detType == DetectorType::Peak || detType == DetectorType::TruePeak;
5162 }
5163
5169 void syncPrecisionState(bool precise) noexcept
5170 {
5171 if (precise && !precisionActive_)
5172 {
5173 const double w = static_cast<double>(charFastWeight_);
5174 for (size_t ch = 0; ch < static_cast<size_t>(kMaxChannels); ++ch)
5175 {
5176 interp_[ch] = {};
5177 precLevel_[ch] = -100.0;
5178 precTarget_[ch] = (w < 1.0) ? w * envFastDb_[ch] + (1.0 - w) * envSlowDb_[ch]
5179 : envFastDb_[ch];
5180 }
5181 }
5182 precisionActive_ = precise;
5183 }
5184
5198 void detectorPoints(T sample, int ch, T* points) noexcept
5199 {
5200 auto& h = interp_[static_cast<size_t>(ch)];
5201 // Mirrored ring: the window of the last kInterpTaps samples is
5202 // contiguous, oldest first.
5203 h.x[h.at] = sample;
5204 h.x[h.at + kInterpTaps] = sample;
5205 const T* window = &h.x[h.at + 1];
5206 h.at = (h.at + 1) & (kInterpTaps - 1);
5207 for (int p = 0; p < kDetectorPoints - 1; ++p)
5208 points[p] = std::abs(simd::dotProduct(interpPhase_[p], window, kInterpTaps));
5209 points[kDetectorPoints - 1] = std::abs(window[kInterpTaps / 2]);
5210 }
5211
5214 [[nodiscard]] T heldBack(T grDb, int g, double delay, bool run) noexcept
5215 {
5216 if (!run) return grDb;
5217 auto& line = gainDelay_[static_cast<size_t>(g)];
5218 line.push(grDb);
5219 const int whole = static_cast<int>(delay);
5220 const T part = static_cast<T>(delay - static_cast<double>(whole));
5221 const T at = line.read(whole);
5222 return part > T(0) ? at + part * (line.read(whole + 1) - at) : at;
5223 }
5224
5231 [[nodiscard]] double slideGainDelay(int target) noexcept
5232 {
5233 const double goal = static_cast<double>(target);
5234 if (gainDelayNow_ < 0.0) gainDelayNow_ = goal;
5235 else if (gainDelayNow_ != goal)
5237 return gainDelayNow_;
5238 }
5239
5261 [[nodiscard]] T gainPathPrecise(const T* levelDb, int count, int ch, const GainPathConfig& cfg,
5262 T thresh, T ratio, T knee) noexcept
5263 {
5264 const int stepsEach = kSubsteps / count;
5265 const double share = 1.0 / stepsEach;
5266 const size_t c = static_cast<size_t>(ch);
5267 double sum = 0.0;
5268
5269 if (cfg.fbImplicit)
5270 {
5273 double last = precLevel_[c];
5274 T shown = T(0);
5275 for (int j = 0; j < count; ++j)
5276 {
5277 const double to = static_cast<double>(levelDb[j]);
5278 for (int s = 1; s <= stepsEach; ++s)
5279 {
5280 const double at = last + (to - last) * (s * share);
5281 shown = stepImplicit(static_cast<T>(at), ch, cfg.charType, thresh, ratio, knee, coeffs);
5282 sum += static_cast<double>(shown);
5283 }
5284 last = to;
5285 }
5286 precLevel_[c] = last;
5287 const T bounded = boundImplicit(shown, ch);
5288 return (bounded != shown) ? bounded : static_cast<T>(sum * (1.0 / kSubsteps));
5289 }
5290
5291 // Sustained-level guard of the Upward curve, on the frame's top level.
5292 T guardDb = levelDb[0];
5293 for (int j = 1; j < count; ++j) guardDb = std::max(guardDb, levelDb[j]);
5294 if (cfg.modeType == Mode::Upward || cfg.modeType == Mode::Both)
5295 {
5296 T& guard = upwardGuardDb_[c];
5297 guard = std::max(guardDb, guard - upwardGuardDecay_);
5298 guardDb = guard;
5299 }
5300
5301 const T range = rangeDb_.load(std::memory_order_relaxed);
5302 const int soft = rangeShape_.load(std::memory_order_relaxed);
5303 const int holdLength = holdSamples_ * count; // the hold counts levels here
5304 double last = precTarget_[c];
5305 double& hold = envHoldDb_[c];
5306 double& fast = envFastDb_[c];
5307 double& slow = envSlowDb_[c];
5308 double& mid = envMidDb_[c];
5309 double& deep = envDeepDb_[c];
5310 double targets[kDetectorPoints] = {};
5311 double deepest = 0.0;
5312 for (int j = 0; j < count; ++j)
5313 {
5314 targets[j] = static_cast<double>(holdAndRange(
5315 computeGain(levelDb[j], thresh, ratio, knee, cfg.charType, cfg.modeType, guardDb),
5316 range, holdLength, heldGrDb_[c], holdCounters_[c], soft, holdWindow(static_cast<int>(c)), count));
5317 deepest = (j == 0) ? targets[j] : std::min(deepest, targets[j]);
5318 }
5319 // Programme-dependent timing sets the two coefficients once per
5320 // frame, for steps of an eighth of a sample.
5321 double attack = subAttCoeff_, release = subRelCoeff_;
5322 if (cfg.program)
5323 {
5324 const ProgramCoeffs timed = programCoeffs(deepest, fast, programState_[c], balance_, 1.0 / kSubsteps);
5325 attack = timed.attack;
5326 release = timed.release;
5327 }
5328 for (int j = 0; j < count; ++j)
5329 {
5330 const double to = targets[j];
5331 for (int s = 1; s <= stepsEach; ++s)
5332 {
5333 const double at = last + (to - last) * (s * share);
5334 sum += cfg.decoupled
5336 : ballisticsCore(at, fast, slow, mid, deep, attack, release, subChargeCoeff_, subSlowRelCoeff_,
5338 }
5339 last = to;
5340 }
5341 precTarget_[c] = last;
5342 const double mean = sum * (1.0 / kSubsteps);
5343 return static_cast<T>(cfg.program ? programShape(mean, programState_[c]) : mean);
5344 }
5345
5346 // ---- Programme-dependent timing (setProgramRelease and the three after it) ----
5347
5350 {
5351 double release = 0.0;
5352 double attack = 0.0;
5353 double spectral = 0.0;
5354 double emphasis = 0.0;
5355 bool active = false;
5356 };
5357
5360 {
5361 double sustained = 0.0;
5362 double smoothed = 0.0;
5363 };
5364
5367 {
5368 double sub = 0.0;
5369 double low = 0.0;
5370 double mid = 0.0;
5371 double high = 0.0;
5372 };
5373
5376 {
5378 };
5379
5382 [[nodiscard]] ProgramTiming programTiming(Character charType, Topology topoEff, bool decoupled,
5383 bool splitAdaptive) const noexcept
5384 {
5385 ProgramTiming p;
5386 if (topoEff != Topology::FeedForward || decoupled || splitAdaptive
5387 || !profileOf(charType).programTiming)
5388 return p;
5389 p.release = static_cast<double>(programRelease_.load(std::memory_order_relaxed));
5390 p.attack = static_cast<double>(adaptiveAttack_.load(std::memory_order_relaxed));
5391 p.spectral = static_cast<double>(spectralTiming_.load(std::memory_order_relaxed));
5392 p.emphasis = static_cast<double>(attackEmphasis_.load(std::memory_order_relaxed));
5393 p.active = p.release > 0.0 || p.attack > 0.0 || p.spectral > 0.0 || p.emphasis != 0.0;
5394 return p;
5395 }
5396
5399 void syncProgramState(bool active) noexcept
5400 {
5401 if (active && !programActive_)
5402 for (size_t ch = 0; ch < static_cast<size_t>(kMaxChannels); ++ch)
5403 programState_[ch] = { std::abs(envFastDb_[ch]), envFastDb_[ch] };
5404 programActive_ = active;
5405 }
5406
5418 void balanceBands(T key, int ch, double& lowSq, double& highSq) noexcept
5419 {
5420 BalanceBands& b = balanceBands_[static_cast<size_t>(ch)];
5421 const double x = static_cast<double>(key);
5422 b.sub += subRate_ * (x - b.sub);
5423 b.low += lowRate_ * ((x - b.sub) - b.low);
5424 b.mid += midRate_ * (x - b.mid);
5425 b.high += highRate_ * ((x - b.mid) - b.high);
5426 lowSq += b.low * b.low;
5427 highSq += b.high * b.high;
5428 }
5429
5432 [[nodiscard]] double balanceAdvance(double lowSq, double highSq) noexcept
5433 {
5434 balanceLow_ += balanceRate_ * (lowSq - balanceLow_);
5435 balanceHigh_ += balanceRate_ * (highSq - balanceHigh_);
5436 const double sum = balanceLow_ + balanceHigh_;
5437 balance_ = (sum > kBalanceSilence) ? (balanceHigh_ - balanceLow_) / sum : 0.0;
5438 return balance_;
5439 }
5440
5451 [[nodiscard]] ProgramCoeffs programCoeffs(double target, double fast, ProgramState& state,
5452 double balance, double share) const noexcept
5453 {
5454 // How sustained the gain change is: a slow follower of its depth
5455 // against the depth itself.
5456 const double depth = std::abs(fast);
5457 state.sustained += sustainRate_ * (depth - state.sustained);
5458 // (Squared: a peak that came and went must count for next to nothing.)
5459 const double held = std::min(state.sustained / (depth + kSustainFloorDb), 1.0);
5460 const double sustain = held * held;
5461 // How close the target is: full at none, nothing from kFullAttackDb.
5462 const double excess = std::max(fast - target, 0.0);
5463 const double close = 1.0 - std::min(excess * (1.0 / kFullAttackDb), 1.0);
5464 // A bright key shortens both times and a dark one lengthens them.
5465 const double tilt = program_.spectral * balance;
5466 const double speed = share * (2.0 + tilt) / (2.0 - tilt);
5467 return { fastDecay(attackX_ * speed / (1.0 + kAttackStretch * program_.attack * close)),
5468 fastDecay(releaseX_ * speed / (1.0 + kReleaseStretch * program_.release * sustain)) };
5469 }
5470
5473 [[nodiscard]] double programShape(double gain, ProgramState& state) const noexcept
5474 {
5475 state.smoothed += emphasisRate_ * (gain - state.smoothed);
5476 return gain + program_.emphasis * std::min(gain - state.smoothed, 0.0);
5477 }
5478
5481 [[nodiscard]] double programStep(double target, double& fast, ProgramState& state,
5482 double balance) const noexcept
5483 {
5484 const ProgramCoeffs timed = programCoeffs(target, fast, state, balance, 1.0);
5485 fast = branchingStep(fast, target, timed.attack, timed.release);
5486 if (atRest(fast, target)) fast = 0.0;
5487 return programShape(fast, state);
5488 }
5489
5490 // ---- Analytic makeup ----
5491
5495 {
5496 T thresh = T(0);
5497 T ratio = T(1);
5498 T knee = T(0);
5499 T amount = T(1);
5500 T range = T(0);
5501 T fastWeight = T(1);
5502 T window = T(0);
5503 double attack = 0.0;
5504 double release = 0.0;
5505 double charge = 0.0;
5506 double slowRelease = 0.0;
5507 double midCharge = 0.0;
5508 double midRelease = 0.0;
5509 bool threeStage = false;
5510 double hold = 0.0;
5514 bool decoupled = false;
5515 bool loop = false;
5516 bool autoThreshold = false;
5517 int soft = 0;
5518 T liftBelow = T(0), liftRatio = T(1), liftRange = T(0);
5519 bool valid = false;
5520
5521 bool operator==(const MakeupModelKey&) const = default;
5522 };
5523
5528 [[nodiscard]] T analyticMakeupDb(Character charType, Mode modeType, DetectorType detType,
5529 bool decoupled, bool loop) noexcept
5530 {
5531 MakeupModelKey key;
5532 key.thresh = threshold_.load(std::memory_order_relaxed);
5533 key.ratio = std::max(ratio_.load(std::memory_order_relaxed), T(1));
5534 key.knee = std::max(kneeWidth_.load(std::memory_order_relaxed), T(0));
5535 key.amount = amount_.load(std::memory_order_relaxed);
5536 key.range = rangeDb_.load(std::memory_order_relaxed);
5538 key.window = rmsWindowMsAtomic_.load(std::memory_order_relaxed);
5539 key.attack = rawAttCoeff_;
5540 key.release = charRelCoeff_;
5545 key.threeStage = threeStage_;
5546 key.hold = decHoldCoeff_;
5547 key.charType = charType;
5548 key.modeType = modeType;
5549 key.detType = detType;
5550 key.decoupled = decoupled;
5551 key.loop = loop;
5552 key.autoThreshold = autoThreshold_.load(std::memory_order_relaxed);
5553 key.soft = rangeShape_.load(std::memory_order_relaxed);
5554 key.liftBelow = liftBelowDb_;
5555 key.liftRatio = liftRatioIn_;
5556 key.liftRange = liftRangeDb_;
5557 key.valid = true;
5558 if (!(key == makeupKey_))
5559 {
5560 makeupKey_ = key;
5562 }
5563 return makeupModelDb_;
5564 }
5565
5568 [[nodiscard]] T analyticTarget() noexcept
5569 {
5570 if (autoMakeupMode_.load(std::memory_order_relaxed) != AutoMakeupMode::Analytic) return T(0);
5571 const Character charType = character_.load(std::memory_order_relaxed);
5572 const CharacterProfile& profile = profileOf(charType);
5573 const Topology topoEff = topologyFor(profile, topology_.load(std::memory_order_relaxed));
5574 const DetectorType detType = detectorFor(profile, detectorType_.load(std::memory_order_relaxed));
5575 return analyticMakeupDb(charType, mode_.load(std::memory_order_relaxed), detType,
5576 useDecoupled(charType, topoEff), topoEff == Topology::FeedBack);
5577 }
5578
5595 [[nodiscard]] static double restingGain(const double* target, const double* weight, int count,
5596 double attackRate, double releaseRate) noexcept
5597 {
5598 double lo = target[0], hi = target[0];
5599 for (int i = 1; i < count; ++i)
5600 {
5601 lo = std::min(lo, target[i]);
5602 hi = std::max(hi, target[i]);
5603 }
5604 for (int pass = 0; pass < 48 && hi - lo > 1e-6; ++pass)
5605 {
5606 const double at = 0.5 * (lo + hi);
5607 double below = 0.0, above = 0.0;
5608 for (int i = 0; i < count; ++i)
5609 {
5610 const double d = target[i] - at;
5611 if (d < 0.0) below -= weight[i] * d;
5612 else above += weight[i] * d;
5613 }
5614 if (attackRate * below > releaseRate * above) hi = at;
5615 else lo = at;
5616 }
5617 return 0.5 * (lo + hi);
5618 }
5619
5629 [[nodiscard]] static double windowSpreadDb(double windowMs) noexcept
5630 {
5631 return 1.6 * std::cbrt(10.0 / std::clamp(windowMs, 1.0, 500.0));
5632 }
5633
5643 [[nodiscard]] static double referenceOverRmsDb(const MakeupModelKey& key) noexcept
5644 {
5645 switch (key.detType)
5646 {
5647 case DetectorType::Rms:
5648 {
5649 const double ms = std::clamp(static_cast<double>(key.window), 1.0, 500.0);
5650 return windowSpreadDb(ms) * 3.2 / (1.0 + ms / 130.0);
5651 }
5654 default: return kPeakReferenceDb;
5655 }
5656 }
5657
5679 [[nodiscard]] T solveMakeupModel(const MakeupModelKey& key) const noexcept
5680 {
5681 const double rmsDb = key.autoThreshold ? -referenceOverRmsDb(key) : kNominalRmsDb;
5682 const bool window = key.detType == DetectorType::Rms;
5683 const bool envelope = key.detType == DetectorType::Hilbert;
5684 const bool between = key.detType == DetectorType::TruePeak;
5685 const bool hybrid = key.detType == DetectorType::Hybrid;
5686 const double spread = window ? windowSpreadDb(static_cast<double>(key.window)) : 0.0;
5687 double target[kMakeupNodes], weight[kMakeupNodes];
5688 T held = T(0);
5689 int counter = 0;
5690 for (int i = 0; i < kMakeupNodes; ++i)
5691 {
5692 double levelDb = rmsDb;
5693 if (window)
5694 {
5695 // Equal steps of the level from -4 to +4 spreads; the mean of the squares stays the RMS.
5696 const double z = ((static_cast<double>(i) + 0.5) / kMakeupNodes - 0.5) * 8.0;
5697 weight[i] = std::exp(-0.5 * z * z);
5698 levelDb += spread * z - 0.1151 * spread * spread;
5699 }
5700 else
5701 {
5702 // In units of the RMS: the middle of each of the equal steps up to kMakeupReach.
5703 const double t = (static_cast<double>(i) + 0.5) * (kMakeupReach / kMakeupNodes);
5704 weight[i] = std::exp(-0.5 * t * t);
5705 if (envelope) weight[i] *= t;
5706 if (between)
5707 weight[i] *= std::pow(std::erf(t * 0.70710678118654752), kTruePeakSamples - 1.0);
5708 // Hybrid never reads under the root of twice the mean square.
5709 levelDb += 20.0 * std::log10(hybrid ? std::max(t, std::numbers::sqrt2) : t)
5710 + (envelope ? kEnvelopeLiftDb : 0.0);
5711 }
5712 const T gain = computeGain(static_cast<T>(levelDb), key.thresh, key.ratio, key.knee, key.charType,
5713 key.modeType, static_cast<T>(rmsDb + kSustainedOverRmsDb));
5714 target[i] = static_cast<double>(holdAndRange(gain, key.range, 0, held, counter, key.soft));
5715 }
5716
5717 const int count = kMakeupNodes;
5718 double settled = 0.0;
5719 if (key.decoupled)
5720 {
5721 settled = restingGain(target, weight, count, 1.0, 1.0 - key.hold);
5722 }
5723 else
5724 {
5725 settled = restingGain(target, weight, count, 1.0 - key.attack, 1.0 - key.release);
5726 const double w = static_cast<double>(key.fastWeight);
5727 if (w < 1.0)
5728 {
5729 const double memory = key.loop
5730 ? (1.0 - w) / (1.0 + w * (static_cast<double>(key.ratio) - 1.0)) : 1.0 - w;
5731 const double deep = restingGain(target, weight, count, 1.0 - key.charge, 1.0 - key.slowRelease);
5732 const double rest = key.threeStage
5733 ? kOptoMidShare * restingGain(target, weight, count, 1.0 - key.midCharge, 1.0 - key.midRelease)
5734 + (1.0 - kOptoMidShare) * deep
5735 : deep;
5736 settled = (1.0 - memory) * settled + memory * rest;
5737 }
5738 }
5739 const double makeup = -static_cast<double>(key.amount) * settled;
5740 return static_cast<T>(std::clamp(makeup, -kMakeupLimitDb, kMakeupLimitDb));
5741 }
5742
5743 // ---- Sidechain HPF ----
5744
5747 {
5748 // The setter rejects invalid cutoffs; the clamp keeps the coefficient
5749 // in the stable range even against a hostile in-memory value.
5750 const double scFreq = std::clamp(
5751 static_cast<double>(scHpfFreq_.load(std::memory_order_relaxed)),
5752 1.0, sampleRate_ * 0.45);
5753 scHpfB1_ = static_cast<T>(std::exp(-std::numbers::pi * 2.0 * scFreq / sampleRate_));
5754 scHpfA0_ = (T(1) + scHpfB1_) / T(2); // Normalization to prevent high-frequency boost
5755 }
5756
5763 [[nodiscard]] T applySidechainHPF(T input, int ch) noexcept
5764 {
5765 T& xp = scHpfPrev_[ch];
5766 T& yp = scHpfState_[ch];
5767 T output = scHpfA0_ * (input - xp) + scHpfB1_ * yp;
5768 xp = input;
5769 yp = output;
5770 return output;
5771 }
5772
5773 // ---- RMS Configuration ----
5774
5776 void updateRmsWindow() noexcept
5777 {
5778 if (sampleRate_ > 0)
5779 {
5780 int requestedSamples = static_cast<int>(sampleRate_ * static_cast<double>(rmsWindowMs_) / 1000.0);
5781
5782 // Limit the logical window to the LIVE element count. capacity()
5783 // can exceed size() after a re-prepare to a lower rate, and a
5784 // window reaching into the dead tail reads stale squares from the
5785 // previous stream (measured: audible gain reduction on silence).
5786 if (!rmsBuffers_[0].empty())
5787 {
5788 int maxLen = static_cast<int>(rmsBuffers_[0].size());
5789 rmsWindowSamples_ = std::clamp(requestedSamples, 1, maxLen);
5790 }
5791 else
5792 {
5793 rmsWindowSamples_ = std::max(1, requestedSamples);
5794 }
5795
5796 // The Hybrid detector's mean of the squares takes the same time.
5797 hybridRate_ = 1.0 - std::exp(-1.0 / (sampleRate_ * std::max(static_cast<double>(rmsWindowMs_), 1.0)
5798 / 1000.0));
5799
5800 for (int ch = 0; ch < kMaxChannels; ++ch)
5801 {
5802 // Clear the window contents too: stale squares from a previous
5803 // window length would otherwise be subtracted from the fresh
5804 // running sum (transient negative-sum glitch).
5805 std::fill(rmsBuffers_[ch].begin(), rmsBuffers_[ch].end(), T(0));
5806 rmsSums_[ch] = T(0);
5807 rmsIndices_[ch] = 0;
5808 rmsRecomputeCounters_[ch] = 0;
5809 }
5810 }
5811 }
5812
5813 // =========================================================================
5814 // Members & State
5815 // =========================================================================
5816
5818 double sampleRate_ = 0;
5819
5820 // User Parameters (Atomic for thread safety)
5821 std::atomic<T> threshold_ { T(-20) };
5822 std::atomic<T> ratio_ { T(4) };
5823 std::atomic<T> attackMs_ { T(5) };
5824 std::atomic<T> releaseMs_ { T(100) };
5825 std::atomic<T> kneeWidth_ { T(0) };
5826 std::atomic<T> makeupGain_ { T(0) };
5827 std::atomic<T> stereoLink_ { T(1) };
5828 std::atomic<LinkMode> linkMode_ { LinkMode::Loudest };
5829 double linkCoeff_ = 0.0;
5830 double linkLL_ = 0.0, linkRR_ = 0.0, linkLR_ = 0.0;
5831 std::atomic<T> mix_ { T(1) };
5832 std::atomic<T> lookaheadMs_ { T(0) };
5833 std::atomic<T> characterColor_ { T(0) };
5834 std::atomic<AutoMakeupMode> autoMakeupMode_ { AutoMakeupMode::Off };
5835
5836 std::atomic<DetectorType> detectorType_ { DetectorType::Peak };
5837 std::atomic<Topology> topology_ { Topology::FeedForward };
5838 std::atomic<Character> character_ { Character::Clean };
5839 std::atomic<OptoCell> optoCell_ { OptoCell::TwoStage };
5840 std::atomic<CleanBallistics> cleanBallistics_ { CleanBallistics::Branching };
5841 std::atomic<Mode> mode_ { Mode::Downward };
5842
5843 // Internal DSP Coefficients & State
5844 T autoMakeupCoeff_ = T(0.9995);
5848
5849 // Character ballistics coefficients (dB-domain one-poles, see
5850 // updateTimeConstants). charFastWeight_ == 1 selects the single-envelope
5851 // path (Clean/Varimu); Opto/FET blend fast and slow memory envelopes.
5852 std::atomic<bool> timeConstantsDirty_ { true };
5853 double charAttCoeff_ = 0.0;
5854 double charRelCoeff_ = 0.0;
5855 double charSlowRelCoeff_ = 0.0;
5856 double charMidRelCoeff_ = 0.0;
5857 double charMidChargeCoeff_ = 0.0;
5858 bool threeStage_ = false;
5859 double charChargeCoeff_ = 0.0;
5861
5868
5869 // FET colour: 2nd-order term gain at full colour, calibrated so limiting
5870 // at -6 dBFS program level measures within the 1176's published THD spec
5871 // (< 0.5%); the one-pole DC estimate AC-couples the squared term.
5872 static constexpr T kFetColorH2 = T(0.028);
5873 T fetDcCoeff_ = T(0);
5874 std::array<T, kMaxChannels> fetDcState_ {};
5875
5876 // Recursive dB envelopes are double for every T: in float a 3 s release
5877 // at 192 kHz parked 0.57 dB short of its target.
5878 std::array<double, kMaxChannels> envFastDb_ {};
5879 std::array<double, kMaxChannels> envSlowDb_ {};
5880 std::array<double, kMaxChannels> envMidDb_ {};
5881 std::array<double, kMaxChannels> envDeepDb_ {};
5882 std::array<double, kMaxChannels> envHoldDb_ {};
5883 double decHoldCoeff_ = 0.0;
5884 double decSmoothCoeff_ = 0.0;
5885 bool decoupledActive_ = false;
5886
5887 // Layered characters: the two layers and their rates (share of the
5888 // distance to the target per sample).
5889 std::array<double, kMaxChannels> layerLevelDb_ {};
5890 std::array<double, kMaxChannels> layerPeakDb_ {};
5891 double layerAttRate_ = 0.0, layerRelRate_ = 0.0, peakAttRate_ = 0.0, peakRelRate_ = 0.0;
5892 bool layeredActive_ = false;
5893
5894 // The push-pull element of Varimu: the slope of the pair at no reduction
5895 // and the level of full scale in units of its curve at amount 1.
5896 static constexpr double kPushPullRest = 0.98;
5897 static constexpr double kPushPullDrive = 2.0;
5898
5899 // The gain after the ballistics.
5900 std::atomic<T> gainSmoothMs_ { T(0) };
5901 double gainSmoothRate_ = 0.0;
5902 std::array<double, kMaxChannels> gainSmoothA_ {};
5903 std::array<double, kMaxChannels> gainSmoothB_ {};
5904 bool gainSmoothActive_ = false;
5905 static constexpr double kLandingPaceDb = 0.5;
5906 std::atomic<T> landingMs_ { T(0) };
5907 double landingRate_ = 0.0;
5908 std::array<double, kMaxChannels> landingDb_ {};
5909 bool landingActive_ = false;
5910 std::atomic<T> networkDepthDb_ { T(0) };
5911 std::atomic<T> networkCornerHz_ { T(10) };
5912 double networkShare_ = 1.0;
5913 double networkRate_ = 0.0;
5914 std::array<double, kMaxChannels> networkLow_ {};
5915 bool networkActive_ = false;
5916
5917 // The audio path beyond the plain gain.
5918 static constexpr double kLeakCornerHz = 5.0;
5919 static constexpr double kLeakLevel = 0.05;
5920 static constexpr double kAsymCrestSeconds = 0.05;
5921 std::atomic<T> toneLowDb_ { T(0) }, toneHighDb_ { T(0) };
5922 std::atomic<T> controlLeak_ { T(0) };
5923 std::atomic<T> detectorAsymmetry_ { T(0) };
5925 T toneLowIn_ = T(0), toneHighIn_ = T(0);
5926 bool toneActive_ = false;
5927 T leakAmount_ = T(0);
5928 T leakCoeff_ = T(0);
5929 std::array<T, kMaxChannels> leakBase_ {};
5930 T asymAmount_ = T(0);
5931 T asymDecay_ = T(0);
5932 std::array<T, kMaxChannels> asymCrest_ {};
5933 // The drift of the asymmetry (setDetectorDrift()).
5934 static constexpr double kAsymDrift = 0.1;
5935 static constexpr double kAsymDriftHz = 0.25;
5936 static constexpr int kAsymDriftTick = 64;
5939 {
5940 double wander = 0.0;
5941 double smooth = 0.0;
5942 double from = 0.0, to = 0.0;
5943 int tick = 0;
5944 std::uint32_t rng = 1u;
5945 };
5946 std::atomic<T> detectorDrift_ { T(0) };
5947 T driftAmount_ = T(0);
5948 double asymDriftRate_ = 0.0, asymDriftScale_ = 1.0;
5949 std::array<AsymDrift, kMaxChannels> asymDrift_ {};
5950 std::array<T, kMaxChannels> asymNow_ {};
5951 bool audioExtras_ = false;
5952
5953 // The routes of a pair (setRoute()).
5954 std::atomic<Route> route_ { Route::Stereo };
5955 std::atomic<T> midSideFocus_ { T(0) };
5956 // The weights of the two parts' heard gain in decibels across the block
5957 // being processed (MidSide with a focus; audio thread), from and to.
5958 std::array<T, 2> partFrom_ { T(1), T(1) }, partTo_ { T(1), T(1) };
5959 bool parted_ = false;
5961 bool routeWas_ = false;
5965
5966 // The upward half of Mode::Both (setLift()), and as the audio thread took it.
5967 std::atomic<T> liftBelow_ { T(30) }, liftRatio_ { T(2) }, liftRange_ { T(6) };
5968 T liftBelowDb_ = T(30), liftRatioIn_ = T(2), liftRangeDb_ = T(6);
5970 std::array<T, kMaxChannels> upwardGuardDb_ {};
5971 T upwardGuardDecay_ = T(0.00125);
5972 std::array<T, kMaxChannels> fbLastOutput_ {};
5974 std::array<std::array<T, 4>, kMaxChannels> pointLevelDb_ {};
5975
5976 std::array<RingBuffer<T>, kMaxChannels> lookaheadBuffers_ {};
5978
5979 std::array<HilbertIIR<double>, kMaxChannels> hilbertDetectors_ {};
5980
5981 // Sidechain Filtering
5982 std::atomic<bool> scHpfEnabled_ { false };
5983 std::atomic<T> scHpfFreq_ { T(80) };
5984 std::atomic<bool> scHpfDirty_ { true };
5985 T scHpfB1_ = T(0);
5986 T scHpfA0_ = T(0);
5987 std::array<T, kMaxChannels> scHpfState_ {};
5988 std::array<T, kMaxChannels> scHpfPrev_ {};
5991 static constexpr int kStageKeyRoom = 64;
5992 std::atomic<bool> scListen_ { false };
5993 std::atomic<bool> removalListen_ { false };
5994
5995 // Split-Polarity Detector State
5996 std::array<T, kMaxChannels> splitPosEnv_ {};
5997 std::array<T, kMaxChannels> splitNegEnv_ {};
5999 T splitDetRelCoeff_ = T(0.99);
6000
6001 // RMS Detector
6002 T rmsWindowMs_ = T(10);
6003 std::atomic<T> rmsWindowMsAtomic_ { T(10) };
6004 std::atomic<bool> rmsWindowDirty_ { false };
6006 std::array<std::vector<T>, kMaxChannels> rmsBuffers_;
6007 std::array<T, kMaxChannels> rmsSums_ {};
6008 std::array<int, kMaxChannels> rmsIndices_ {};
6009 static constexpr int kRmsRecomputePeriod = 4096;
6010 std::array<int, kMaxChannels> rmsRecomputeCounters_ {};
6011
6012 // Shared ITU-R BS.1770-4 true-peak detector (Core/TruePeakDetector.h).
6014
6015 // Hold & Range
6016 std::atomic<T> holdMs_ { T(0) };
6017 std::atomic<T> rangeDb_ { T(100) };
6019 std::array<int, kMaxChannels> holdCounters_ {};
6020 std::array<T, kMaxChannels> heldGrDb_ {};
6021 std::atomic<HoldMode> holdMode_ { HoldMode::Deepest };
6022 std::unique_ptr<SlidingDeepest[]> holdWindows_;
6024 bool holdEveryPeak_ = false;
6025
6026 // Automatic threshold, lookahead inside a fixed latency, amount, soft range.
6027 static constexpr double kAutoRefFallDb = 1.0;
6028 std::atomic<bool> autoThreshold_ { false };
6029 std::atomic<T> thresholdInUseDb_ { T(0) };
6030 std::array<double, kMaxChannels> autoRefDb_ {};
6031 double autoRefFall_ = 0.0;
6032 std::atomic<T> maxLookaheadMs_ { T(0) };
6034 std::array<RingBuffer<T>, kMaxChannels> gainDelay_ {};
6035 static constexpr double kGainDelaySlide = 0.25;
6036 double gainDelayNow_ = -1.0;
6037 bool latencyKept_ = false;
6038 std::atomic<LookaheadShape> lookaheadShape_ { LookaheadShape::Lead };
6039 std::atomic<bool> feedbackKeyed_ { false };
6040 std::vector<LookaheadRamp> lookaheadRamps_;
6041 int rampCount_ = 0;
6042 bool rampShape_ = false;
6043 bool rampActive_ = false;
6044 std::atomic<T> amount_ { T(1) };
6046 std::atomic<int> rangeShape_ { 0 };
6047 static constexpr double kLocalRangeStretchDb = 6.0;
6048
6049 // Precision of the control signal (setPrecision): the detector's points
6050 // between samples, the history of the steps and their coefficients.
6051 static constexpr int kSubsteps = 8;
6052 static constexpr int kDetectorPoints = 4;
6053 static constexpr int kInterpTaps = 16;
6054 static constexpr int kDetectorDelay = kInterpTaps / 2 - 1;
6055 static constexpr double kInterpBeta = 6.5;
6056 static_assert(kDetectorPoints == 4 && kSubsteps % kDetectorPoints == 0, "the steps divide among the points");
6059 {
6060 T x[2 * kInterpTaps] = {};
6061 int at = 0;
6062 };
6063 std::atomic<Precision> precision_ { Precision::Standard };
6064 bool precisionActive_ = false;
6065
6066 // The colour stage (setCharacterStage()).
6067 std::atomic<StagePosition> stagePosition_ { StagePosition::Off };
6071 std::vector<double> stageFade_;
6072 double stageFadeStep_ = 0.0;
6073 double stageWeightBefore_ = 0.0;
6074 double stageWeightAfter_ = 0.0;
6076 std::array<InterpHistory, kMaxChannels> interp_ {};
6077 std::array<double, kMaxChannels> precLevel_ {};
6078 std::array<double, kMaxChannels> precTarget_ {};
6079 double rawAttCoeff_ = 0.0;
6080 double subAttCoeff_ = 0.0;
6081 double subRelCoeff_ = 0.0;
6082 double subSlowRelCoeff_ = 0.0;
6083 double subChargeCoeff_ = 0.0;
6084 double subMidRelCoeff_ = 0.0;
6085 double subMidChargeCoeff_ = 0.0;
6086 double subDecHoldCoeff_ = 0.0;
6087 double subDecSmoothCoeff_ = 0.0;
6088
6089 // Programme-dependent timing (setProgramRelease() and the three after it).
6090 static constexpr double kSustainReleases = 15.0;
6091 static constexpr double kSustainFloorSeconds = 0.1;
6092 static constexpr double kSustainCeilSeconds = 60.0;
6093 static constexpr double kSustainFloorDb = 0.5;
6094 static constexpr double kReleaseStretch = 7.0;
6095 static constexpr double kAttackStretch = 3.0;
6096 static constexpr double kFullAttackDb = 6.0;
6097 static constexpr double kEmphasisAttacks = 6.0;
6098 static constexpr double kEmphasisFloorSeconds = 0.002;
6099 static constexpr double kEmphasisCeilSeconds = 0.5;
6100 static constexpr double kBalanceFloorHz = 30.0;
6101 static constexpr double kBalanceLowHz = 200.0;
6102 static constexpr double kBalanceHighHz = 2500.0;
6103 static constexpr double kBalanceCeilingHz = 16000.0;
6104 static constexpr double kBalanceSeconds = 0.05;
6105 static constexpr double kBalanceSilence = 1e-24;
6106 std::atomic<T> programRelease_ { T(0) };
6107 std::atomic<T> adaptiveAttack_ { T(0) };
6108 std::atomic<T> spectralTiming_ { T(0) };
6109 std::atomic<T> attackEmphasis_ { T(0) };
6111 bool programActive_ = false;
6112 std::array<ProgramState, kMaxChannels> programState_ {};
6113 std::array<BalanceBands, kMaxChannels> balanceBands_ {};
6114 double balanceLow_ = 0.0;
6115 double balanceHigh_ = 0.0;
6116 double balance_ = 0.0;
6117 double attackX_ = 0.0;
6118 double releaseX_ = 0.0;
6119 double subRate_ = 0.0;
6120 double lowRate_ = 0.0;
6121 double midRate_ = 0.0;
6122 double highRate_ = 0.0;
6123 double balanceRate_ = 0.0;
6124 double sustainRate_ = 0.0;
6125 double emphasisRate_ = 0.0;
6126
6127 // Hybrid detector: a one-pole mean of the squares per channel.
6128 std::array<double, kMaxChannels> hybridMeanSq_ {};
6129 double hybridRate_ = 0.0;
6130
6131 // Analytic makeup: the programme it assumes and its cached result.
6132 static constexpr int kMakeupNodes = 48;
6133 static constexpr double kMakeupReach = 4.8;
6134 static constexpr double kNominalRmsDb = -18.0;
6135 static constexpr double kSustainedOverRmsDb = 10.0;
6136 static constexpr double kPeakReferenceDb = 12.35;
6137 static constexpr double kTruePeakReferenceDb = 12.5;
6138 static constexpr double kEnvelopeReferenceDb = 13.2;
6139 static constexpr double kTruePeakSamples = 2.6;
6140 static constexpr double kEnvelopeLiftDb = 0.6;
6141 static constexpr double kMakeupLimitDb = 40.0;
6145
6146 std::atomic<T> gainReductionDb_ { T(0) };
6147};
6148
6149} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Owning audio buffer with contiguous, 32-byte aligned storage.
Biquad filter using Transposed Direct Form II (TDF-II) with thread-safe updates.
Definition Biquad.h:853
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
Emphasis, static saturators and de-emphasis, with drift, sag and noise.
High-fidelity modular compressor designed for real-time applications.
Definition Compressor.h:104
bool audioExtras_
The gain is not a plain product (tone or leak).
void flushLinkCovariance() noexcept
static constexpr double kSustainFloorSeconds
It is never shorter than this,.
StagePosition
Where the analog colour stage sits (see setCharacterStage()).
@ After
The output amplifier: the compressed signal is coloured.
@ Before
The input amplifier: coloured before it is compressed (and detected).
@ Off
No colour stage (the default).
std::array< double, kMaxChannels > layerLevelDb_
static constexpr double kOptoMidChargeCeilMs
MakeupModelKey makeupKey_
Settings of the cached result.
void setSoftRange(bool on) noexcept
Makes the gain change approach the range without a corner.
void setRoute(Route route) noexcept
Chooses what of a stereo pair is compressed, and from which part of the key.
Definition Compressor.h:947
static T detectorSafe(T x) noexcept
A non-finite sample reads as silence in the detector: it would otherwise latch in the recursive detec...
DetectorType
Level detection methodologies.
Definition Compressor.h:110
@ SplitPolarity
Separate envelopes for the positive and negative half-waves.
@ TruePeak
4x oversampled peak detection (ITU-R BS.1770-4 compliant).
@ Rms
Sliding-window Root-Mean-Square. Smoother, responds to average energy.
@ Peak
Instantaneous absolute value tracking. Fast and standard.
static constexpr double kBalanceSilence
Summed power under which the balance is 0.
static constexpr double kMakeupReach
They reach this many times its RMS.
static constexpr int kMaxChannels
T getControlNetworkDepth() const noexcept
Depth of the network in the control path, in dB (setControlNetwork()).
double subMidChargeCoeff_
Medium-memory charge coefficient of an eighth of a sample.
typename CharacterStage< T >::Settings StageSettings
The settings of the colour stage (Core/CharacterStage.h).
void setThreshold(T dB) noexcept
Sets the compression threshold in dB.
Definition Compressor.h:735
std::atomic< T > thresholdInUseDb_
With the automatic threshold, the threshold of the last sample (metering).
std::atomic< OptoCell > optoCell_
Cell of the Opto character.
void setHoldTime(T ms) noexcept
Sets the gain-reduction hold time.
std::array< RingBuffer< T >, kMaxChannels > lookaheadBuffers_
Lookahead delay lines.
void prepare(const AudioSpec &spec)
Allocates buffers and initializes internal DSP state.
Definition Compressor.h:275
StageSettings getCharacterStageSettings() const noexcept
The settings of the colour stage.
void setLookaheadShape(LookaheadShape shape) noexcept
Chooses how the lookahead brings a reduction in (Lead by default).
void setDetectorAsymmetry(T amount) noexcept
Makes the detector read the two halves of the wave differently (0, the default, is off).
void setLinkMode(LinkMode mode) noexcept
Chooses how a stereo pair is linked.
Definition Compressor.h:906
static constexpr double kTruePeakSamples
Independent samples the TruePeak reading is the largest of.
T asymmetric(T key, int ch) noexcept
The key with a share of its own crest added, scaled so that the half the share favours still reads th...
static constexpr double kReductionToneHighHz
Corner of its high shelf, in Hz.
std::array< T, kMaxChannels > heldGrDb_
std::atomic< bool > scHpfEnabled_
HPF toggle.
std::atomic< AutoMakeupMode > autoMakeupMode_
Auto-makeup behavior.
SmoothedValue< T > makeupSmooth_
De-zippered makeup gain (dB).
static double driftUniform(std::uint32_t &s) noexcept
A uniform draw in [-1, 1) (xorshift32).
double subRelCoeff_
Release coefficient of an eighth of a sample.
std::atomic< T > releaseMs_
Release time in milliseconds.
double landingRate_
Its coefficient when it is on the gain it follows (0: off).
double stageFadeStep_
Its change per sample (20 ms end to end).
std::array< double, kMaxChannels > envDeepDb_
Deep memory of the three-stage cell per channel (dB).
FeedbackSolve solveFeedbackGain(T inDb, T k, T effB, T thresh, T ratio, T knee, Character charType) const noexcept
Solves one feedback ballistics step against the current input.
void setAmount(T amount) noexcept
Sets how much of the gain change is applied, as a scale of its decibels.
static constexpr int kInterpTaps
Samples each point between samples is read from.
AudioBuffer< T > routeKey_
A key given apart, as its middle and its sides.
std::array< T, kMaxChannels > fetDcState_
Per-channel DC estimate of wet^2.
double networkShare_
Share of a fast move applied at once (1: off).
static constexpr double kAsymDrift
Deviation of the asymmetry at full drift.
std::atomic< LinkMode > linkMode_
What the linked level reads.
T getReductionToneHigh() const noexcept
Its gain over 4 kHz, in dB.
double feedbackDetectorDelay(DetectorType detType) const noexcept
Delay of the detector as an explicit feedback loop sees it, in samples: the RMS window (its reading o...
static constexpr double kPushPullDrive
std::atomic< T > stereoLink_
Stereo linking amount (0 to 1).
std::atomic< T > gainReductionDb_
Publicly readable Gain Reduction meter.
T getGainReductionDb() const noexcept
Returns current active gain reduction in dB (negative value).
static E clampEnum(E value, E last) noexcept
Clamps an enum to its valid [first, last] range.
std::array< int, kMaxChannels > holdCounters_
Character getCharacter() const noexcept
Returns the currently active character.
static T downwardCurve(T inputDb, T thresh, T ratio, T knee, Character charType) noexcept
Downward static curve with the character's knee floor and ratio law (see computeGain).
std::array< BalanceBands, kMaxChannels > balanceBands_
Bands of the key per channel.
T computeGainUpward(T inputDb, T thresh, T ratio, T knee, T guardDb) const noexcept
Upward compression curve calculation.
SmoothedValue< T > kneeSmooth_
De-zippered knee.
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
std::array< T, kMaxChannels > splitPosEnv_
Positive half-wave tracking.
void syncAdaptiveMakeup(bool adaptive) noexcept
The adaptive makeup envelope only runs while adaptive makeup is active; when it engages it starts fro...
int rampCount_
Ramps prepared.
double highRate_
Pole of the split at kBalanceCeilingHz.
std::atomic< bool > rmsWindowDirty_
Applied at the next block.
bool rampShape_
The shape as the audio thread took it.
LookaheadShape
How the lookahead brings a reduction in (see setLookaheadShape()).
Character
Time-constant behavior and release curve shape.
Definition Compressor.h:150
std::atomic< T > controlLeak_
setControlLeak().
ProgramCoeffs programCoeffs(double target, double fast, ProgramState &state, double balance, double share) const noexcept
The attack and release coefficients of a frame under programme-dependent timing, and the advance of i...
double attackX_
The attack as a decay per sample (-ln of its coefficient).
T getGainSmoothing() const noexcept
The smoothing of the gain after the ballistics, in milliseconds.
void setRelease(T ms) noexcept
Sets the release time in milliseconds (clamped to >= 1 ms: below that the envelope stops smoothing at...
Definition Compressor.h:777
T detectLevel(T sample, int ch, DetectorType detType) noexcept
Computes level detection in Decibels.
CharacterStage< T > stageBefore_
The input amplifier.
HoldMode getHoldMode() const noexcept
static T pushPullElement(T input, T gain, T amount) noexcept
The gain of a variable-mu stage applied by its own curve: two halves in push-pull,...
void setRemovalListen(bool on) noexcept
Removal listen: the output is what the compression takes out, the aligned input minus the compressed ...
static constexpr double kOptoThreeFastRelease
static constexpr DetectorType detectorFor(const CharacterProfile &profile, DetectorType asked) noexcept
The detector a character reads with when the user asks for one.
static constexpr double kLocalRangeStretchDb
Width of the bend of RangeShape::Local, at most.
void setAutoThreshold(bool on) noexcept
Makes the threshold count from the key's own recent peak instead of from full scale.
T scHpfB1_
HPF internal feedback coefficient.
static constexpr double kEnvelopeLiftDb
What the Hilbert detector reads over the envelope (dB).
std::atomic< Precision > precision_
How finely the control signal is computed.
double emphasisRate_
Pole of the smoothing the emphasis measures against.
SmoothedValue< T > analyticSmooth_
De-zippered analytic makeup (dB).
std::array< int, kMaxChannels > rmsIndices_
Write heads for RMS buffers.
T applySidechainHPF(T input, int ch) noexcept
Applies sidechain filtering for a specific channel.
double balanceLow_
Smoothed power of the low band.
void runStage(CharacterStage< T > &stage, double &weight, bool wanted, AudioBufferView< T > buffer) noexcept
Runs one place of the colour stage over a block, fading its share towards whether it is wanted (20 ms...
void balanceBands(T key, int ch, double &lowSq, double &highSq) noexcept
Feeds one channel's key to the two bands of the balance and adds their squares to the frame's.
static constexpr double kSustainFloorDb
Depth under which a reduction does not count as sustained.
static constexpr double kSustainReleases
Follower of the depth of the gain change, in release times.
std::array< ProgramState, kMaxChannels > programState_
Measures per gain computer.
double charAttCoeff_
Attack coefficient of the fast envelope.
static constexpr double kLeakLevel
What a gain that moves by 1 leaks, at an amount of 1.
double networkRate_
Coefficient of its low-pass.
void runGainRecursion(T *inDb, T *out, int m, int ch, const FeedForwardConfig &ff, const T *thr, const T *rat, const T *kn, const T *dryIn, const double *balance) noexcept
The serial part of the feed-forward path for one gain channel: Upward guard, static curve,...
void updateHpfCoefficients() noexcept
Updates the normalized DC-blocker / High-pass filter coefficients.
void setTopology(Topology topo) noexcept
Changes signal routing topology (FeedForward or FeedBack).
void setMakeupGain(T dB) noexcept
Sets manual static makeup gain in dB.
Definition Compressor.h:792
std::array< double, kMaxChannels > envFastDb_
Fast gain envelope per channel (dB).
Colour
The harmonic signature a character can add (setCharacterColor()).
@ SecondOrder
Second-order modulation of the element by the signal across it.
@ PushPull
The gain applied by the curve of a push-pull pair biased by it.
std::atomic< StagePosition > stagePosition_
std::atomic< Character > character_
Selected ballistics.
std::atomic< HoldMode > holdMode_
T getCharacterColor() const noexcept
Returns the character colour amount (see setCharacterColor).
void setDetectorDrift(T amount) noexcept
Lets the detector's asymmetry wander slowly at random, as the balance of a rectifier does with its te...
static constexpr double kNominalRmsDb
RMS the programme is taken at (dBFS).
std::array< T, 2 > partFrom_
static constexpr int kDetectorDelay
Samples those points are late.
T makeupModelDb_
The cached result (dB).
double decHoldCoeff_
Decoupled hold-stage release coefficient.
void setAutoMakeup(AutoMakeupMode mode) noexcept
Selects the automatic makeup behavior (default: Off).
Definition Compressor.h:822
std::array< T, 2 > partTo_
std::array< T, kMaxChannels > asymNow_
Each channel's asymmetry with its drift.
T gained(T input, T gain, int ch) noexcept
The gain on one sample of a channel when it is not a plain product: through the tone that follows the...
T getAdaptiveAttack() const noexcept
Weight of the target-dependent attack (see setAdaptiveAttack()).
std::array< double, kMaxChannels > precTarget_
Last gain target, after hold and range (dB).
KeyBand getSidechainBand(int band) const noexcept
The settings of a band of the key equalizer.
static constexpr double kOptoMidShare
static double decoupledHoldTau(double releaseMs, double smoothMs) noexcept
Time constant of the decoupled hold stage (ms) so that the series release of the hold stage and the s...
Route getRoute() const noexcept
What of a stereo pair is compressed (setRoute()).
Definition Compressor.h:950
std::atomic< bool > scHpfDirty_
Coefficients need a recompute.
T analyticTarget() noexcept
Target of the analytic makeup for the settings as they stand (0 dB when another makeup mode is select...
std::atomic< T > detectorAsymmetry_
setDetectorAsymmetry().
std::atomic< T > toneLowDb_
T getSpectralTiming() const noexcept
Weight of the spectral balance on the times (see setSpectralTiming()).
bool lopsidedDetector() const noexcept
Whether the detector reads the two halves of the wave differently (an asymmetry or its drift).
std::array< std::vector< T >, kMaxChannels > rmsBuffers_
Pre-allocated RMS sliding windows.
int holdWindowFor_
The hold length the windows are set for.
typename KeyEq::Band KeyBand
The settings of one band of the key equalizer.
SmoothedValue< T > thresholdSmooth_
De-zippered threshold.
T applyHoldAndRange(T targetGR_Db, int ch) noexcept
Applies the hold and range stages to the static gain target (dB).
T getReductionToneLow() const noexcept
Gain under 200 Hz of the tone that follows the reduction, in dB (setReductionTone()).
T getControlNetworkCorner() const noexcept
Corner of the network in the control path, in Hz (setControlNetwork()).
T cachedMakeupLin_
Its linear gain.
SmoothedValue< T > mixSmooth_
De-zippered parallel mix.
bool holdEveryPeak_
The hold mode as the audio thread took it.
std::array< double, kMaxChannels > autoRefDb_
That reference per channel (the linked one in slot 0), in dB.
T interpPhase_[kDetectorPoints - 1][kInterpTaps]
Interpolation phases (prepare()).
void setLookahead(T ms) noexcept
Sets lookahead time in ms (0 = off, max = 10ms).
Definition Compressor.h:982
ProgramTiming program_
The weights of the block (audio thread).
std::atomic< T > scHpfFreq_
HPF Cutoff frequency.
T getAttackEmphasis() const noexcept
Emphasis of the attack (see setAttackEmphasis()).
std::atomic< T > amount_
Share of the gain change that is applied, in dB.
bool routeWas_
The last block ran a route.
T computeGain(T inputDb, T thresh, T ratio, T knee, Character charType, Mode modeType, T guardDb) const noexcept
Calculates static target gain reduction based on knee and ratio.
void setAttackEmphasis(T amount) noexcept
Deepens or softens the gain change while it attacks.
double slideGainDelay(int target) noexcept
The delay of the gain line this frame. It slides to its target kGainDelaySlide of a sample per sample...
static double pacedStep(double envelope, double target, double attackRate, double releaseRate, double attackPace, double releasePace) noexcept
One step of a follower whose time grows with the distance to its target: far away it moves at a stead...
std::atomic< bool > autoThreshold_
The threshold counts from the key's own recent peak.
void setReductionTone(T lowDb, T highDb) noexcept
Makes the tone change with the reduction.
void setGainSmoothing(T ms) noexcept
Smooths the gain after the ballistics (milliseconds; 0, the default, is off).
std::atomic< T > networkDepthDb_
Depth of the network of the control path (0: off).
void setSpectralTiming(T amount) noexcept
Makes attack and release follow the spectral balance of the key.
T autoMakeupEnv_
Smoothed internal auto-makeup envelope.
void syncLayerState(bool layered) noexcept
Seats the two layers on the gain as it stands when a layered character engages. Audio thread only.
static T dominantLevel(T levelL, T levelR, double rho2) noexcept
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
double subChargeCoeff_
Memory-stage charge coefficient of an eighth of a sample.
T getDetectorAsymmetry() const noexcept
How differently the detector reads the two halves of the wave (setDetectorAsymmetry()).
T autoMakeupCoeff_
Auto-makeup tracking factor.
std::array< double, kMaxChannels > networkLow_
T getAmount() const noexcept
The share of the gain change that is applied (setAmount()).
std::array< T, kMaxChannels > scHpfState_
HPF y[n-1] state.
T getMidSideFocus() const noexcept
Definition Compressor.h:969
std::atomic< T > liftBelow_
void setDetector(DetectorType type) noexcept
Changes the level detection algorithm (Peak, RMS, TruePeak, SplitPolarity, Hilbert,...
static double branchingStep(double y, double tgt, double cDown, double cUp) noexcept
Branch-free branching one-pole step toward tgt: coefficient cDown while the state is above the target...
double charChargeCoeff_
History charge coefficient of the memory stage.
std::atomic< bool > timeConstantsDirty_
Coefficients need a recompute.
std::atomic< T > mix_
Wet/Dry mix (1 = full wet).
SmoothedValue< T > ratioSmooth_
De-zippered ratio.
static constexpr double kSustainCeilSeconds
nor longer than this.
static constexpr double kReductionToneLowHz
Corner of the low shelf of the tone that follows the reduction, in Hz (setReductionTone()).
std::atomic< T > attackEmphasis_
Emphasis of the attack.
T gainPath(T inputDb, int ch, const GainPathConfig &cfg, T thresh, T ratio, T knee) noexcept
Static curve plus character ballistics for one channel's state.
double subSlowRelCoeff_
Memory-stage release coefficient of an eighth of a sample.
bool useDecoupled(Character charType, Topology topoEff) const noexcept
The Clean character in feed-forward runs the decoupled detector when setCleanBallistics() selected it...
void applyGain(AudioBufferView< T > &audio, int ch, int i, T gainLin, T grDb, int activeLookahead, Character charType, T colorAmt, T makeupLin, T mixVal, T outLin) noexcept
Applies the frame's gain to one channel: lookahead, FET colour, feedback history, makeup and the para...
static constexpr double kOptoMidCharge
static constexpr double kEmphasisFloorSeconds
It is never shorter than this,.
static constexpr double kBalanceCeilingHz
And ends here.
void setAutoMakeup(bool on) noexcept
Convenience overload: true selects Adaptive, false turns auto makeup off.
Definition Compressor.h:829
static constexpr double kLeakCornerHz
High-pass the gain leaks through.
static constexpr double kOptoMidRelease
static T effectiveRatioFor(Character charType, T ratio, T excessDb) noexcept
Level-dependent effective ratio of the character (Varimu grows).
bool isSidechainListen() const noexcept
Whether the key is being played instead of the audio.
CleanBallistics
Ballistics of the Clean character in feed-forward (see setCleanBallistics).
Definition Compressor.h:219
T processSample(T input, int channel) noexcept
Processes a single sample on one channel.
Definition Compressor.h:445
static constexpr double kAutoRefFallDb
dB per second the reference of the automatic threshold falls.
std::array< RingBuffer< T >, kMaxChannels > gainDelay_
Holds the gain back while the lookahead is shorter than the latency.
T getThresholdInUseDb() const noexcept
The threshold in use, in dBFS (metering; any thread): the set one, or with setAutoThreshold() the key...
static bool atRest(double envelope, double target) noexcept
An envelope within 1e-4 dB of no gain change, heading there: it is put on it, to end the asymptotic t...
static constexpr double kGainDelaySlide
Samples per sample the gain line's delay moves to a new lookahead.
T driftAmount_
The drift as the audio thread took it.
static constexpr double kMakeupLimitDb
Bound of the result (dB).
std::atomic< T > liftRatio_
T smoothedGain(T grDb, int ch) noexcept
One frame of what stands between the ballistics and the gain on a channel (dB): the landing of the re...
RangeShape
How the gain change meets the range (see setRangeShape()).
@ Corner
Cut at the range (default).
@ Local
A bend in a stretch around the range; exact under it and over it.
@ Asymptotic
It bends from afar and never quite arrives: the curve of setSoftRange().
double subAttCoeff_
Attack coefficient of an eighth of a sample.
static constexpr double kInterpBeta
Kaiser window of the interpolation.
bool syncAudioPath() noexcept
Takes the settings of the audio path that are not the plain gain (the tone that follows the reduction...
Topology
Signal routing topology for the detector sidechain.
Definition Compressor.h:133
@ FeedForward
Detector reads uncompressed input (modern, precise, transparent).
static constexpr double kReleaseStretch
The release grows up to 1 + this.
static constexpr int kSubsteps
Steps of the ballistics per sample at Precision::High.
LookaheadShape getLookaheadShape() const noexcept
T getReleaseLanding() const noexcept
The landing of the release, in milliseconds (setReleaseLanding()).
void setRmsWindow(T ms) noexcept
Sets the RMS analysis window size in milliseconds.
T getLiftRatio() const noexcept
Ratio of the rise of Mode::Both (setLift()).
Definition Compressor.h:871
static double referenceOverRmsDb(const MakeupModelKey &key) noexcept
How far over the RMS of dense programme the reference of the automatic threshold rests,...
std::array< T, kMaxChannels > splitNegEnv_
Negative half-wave tracking.
T makeupToGain(T makeupDb) noexcept
Makeup dB to linear, cached: the makeup is shared by every channel of a frame and constant unless aut...
std::atomic< T > detectorDrift_
setDetectorDrift().
T heldBack(T grDb, int g, double delay, bool run) noexcept
The gain as it is heard with a latency kept for the lookahead: older by the difference (see setMaxLoo...
void syncProgramState(bool active) noexcept
Seats the measures on the gain that is sounding when the programme-dependent timing engages....
void setMaxLookahead(T ms) noexcept
Keeps a latency of its own for the lookahead, so the lookahead can move without the latency changing.
static constexpr double kPeakReferenceDb
Automatic-threshold reference over the RMS, rectified.
double rawAttCoeff_
Attack coefficient as it is observed (before a loop's own speed).
T getDetectorDrift() const noexcept
How far the detector's asymmetry wanders (setDetectorDrift()).
OptoCell
The optical cell of the Opto character (see setOptoCell()).
@ ThreeStage
A fast stage, a medium memory and a deep memory.
@ TwoStage
A fast stage and one memory stage (default).
static constexpr int kAsymDriftTick
Frames between draws.
static constexpr int kRmsRecomputePeriod
Re-summation interval to halt drift.
T rampedIn(T grDb, int g, int length, bool run) noexcept
A gain change through the lookahead's ramp of its gain computer, or as it came.
std::array< T, kMaxChannels > upwardGuardDb_
Peak-held sustained level (Upward guard).
double charSlowRelCoeff_
Release coefficient of the memory stage.
bool isRemovalListen() const noexcept
static constexpr double kAttackStretch
The attack grows up to 1 + this.
std::array< double, kMaxChannels > gainSmoothA_
static constexpr int kDetectorPoints
Points the rectifying detectors read per sample there.
void processFeedForward(AudioBufferView< T > &audio, AudioBufferView< T > &sidechain, int nCh, int nS, int scCh, const FeedForwardConfig &ff, const ChunkParams &constants) noexcept
Feed-forward block path, run in passes over chunks of frames.
static constexpr double kBalanceFloorHz
The low band of the balance starts here.
std::atomic< LookaheadShape > lookaheadShape_
static T holdAndRange(T targetGR_Db, T range, int holdSamples, T &held, int &counter, int soft=0, SlidingDeepest *window=nullptr, int perSample=1) noexcept
Hold and range on explicit state (shared by both block paths).
T solveMakeupModel(const MakeupModelKey &key) const noexcept
The analytic makeup: minus the gain the ballistics settle on over dense programme.
T charFastWeight_
Fast/slow blend (1 = single envelope).
AudioBuffer< T > stageScratch_
The coloured copy while a place fades.
static constexpr int kKeyBands
Bands of the key equalizer.
double balanceRate_
Pole of the smoothing of the two powers.
static constexpr double kAsymCrestSeconds
Fall of the crest the asymmetric detector adds.
double subDecHoldCoeff_
Decoupled hold coefficient of an eighth of a sample.
void detectorPoints(T sample, int ch, T *points) noexcept
The rectified key at kDetectorPoints points per sample.
void setMix(T dryWet) noexcept
Sets dry/wet balance for parallel (New York) compression (1.0 = fully wet).
Definition Compressor.h:972
void reset() noexcept
Resets all internal DSP history, states, and buffers to neutral.
Definition Compressor.h:645
void setLift(T belowDb, T ratio, T rangeDb) noexcept
Sets the upward half of Mode::Both: what lies under a second, lower threshold is raised.
Definition Compressor.h:859
KeyMonitor< T, 16 > keyMonitor_
The listened key: late by the latency, under full scale.
double releaseX_
The release as a decay per sample.
void setRatio(T ratio) noexcept
Sets the compression ratio (1.0 = off, >20.0 = limiting).
Definition Compressor.h:742
int latencySamples_
Delay of the audio in feed-forward (audio thread).
bool usePrecision(Topology topoEff, bool fbImplicit, bool splitAdaptive) const noexcept
Whether the control signal runs at Precision::High with this routing: feed-forward,...
std::atomic< T > adaptiveAttack_
Weight of the closeness of the target on the attack.
StagePosition getCharacterStage() const noexcept
Where the colour stage sits (see setCharacterStage()).
Route
What of a stereo pair the compressor works on (see setRoute()).
Definition Compressor.h:916
@ MidKeysSide
The sides, with the gain the middle of the key asks for.
@ SideKeysMid
The middle, with the gain the sides of the key ask for.
@ Mid
The middle only: the sides pass untouched.
@ Stereo
Left and right (default).
@ Side
The sides only: the middle passes untouched.
@ MidSide
The middle and the sides, each with its gain; setStereoLink() links the two.
double stageWeightBefore_
Share of the input stage (audio thread).
void setSidechainHPF(bool enabled, T cutoffHz=T(80)) noexcept
Toggles the internal sidechain high-pass filter.
static constexpr double kBalanceHighHz
The high band starts here.
double balanceHigh_
Smoothed power of the high band.
static constexpr int kMakeupNodes
Levels of the programme that are weighed.
T splitDetAttCoeff_
Detector attack coefficient (sample-rate derived).
std::atomic< T > gainSmoothMs_
Smoothing of the gain (0: off).
LinkMode getLinkMode() const noexcept
Definition Compressor.h:912
std::array< double, kMaxChannels > gainSmoothB_
double autoRefFall_
Its fall per sample, in dB.
std::atomic< DetectorType > detectorType_
Selected detection method.
double linkCoeff_
One-pole coefficient of the key's covariance (20 ms).
void setKnee(T dB) noexcept
Sets knee width in dB (0 = hard knee, >0 = soft knee).
Definition Compressor.h:785
double sampleRate_
Cached operating sample rate.
std::array< double, kMaxChannels > envHoldDb_
Decoupled hold stage per channel (dB).
T asymAmount_
The asymmetry as the audio thread took it.
FeedbackLaw computeGainFeedback(T outDb, T thresh, T ratio, T knee, Character charType) const noexcept
Feedback target for detectors with memory (explicit path).
bool decoupledActive_
The decoupled path ran last (audio thread).
bool isFeedbackKeyed() const noexcept
void setCharacterColor(T amount) noexcept
Sets the amount of the character's harmonic signature (0 to 1).
bool precisionActive_
The precise path ran last (audio thread).
double subRate_
Pole of the split at kBalanceFloorHz.
std::array< T, kMaxChannels > rmsSums_
Running sums for RMS.
T applyBallistics(T targetGrDb, int ch, bool splitAdaptive, T loopSlope=T(-1), double loopDelay=0.0) noexcept
Smooths the static gain target with the active character's ballistics.
std::atomic< T > lookaheadMs_
Lookahead latency target in ms.
void setCharacter(Character type) noexcept
Changes ballistics and envelope behavior character.
static constexpr double kTruePeakReferenceDb
The same for TruePeak.
SlidingDeepest * holdWindow(int ch) const noexcept
static bool rectifies(DetectorType detType) noexcept
Whether a detector rectifies the key (the ones an asymmetry makes sense for).
void syncDecoupledState(bool decoupled) noexcept
Seats the decoupled hold stage on the current gain when the decoupled path engages (character or topo...
double subDecSmoothCoeff_
Decoupled smoothing coefficient of an eighth of a sample.
T lift(T inputDb, T thresh, T knee, T guardDb) const noexcept
The upward half of Mode::Both: the rise under the lower threshold, up to its range.
std::unique_ptr< SlidingDeepest[]> holdWindows_
One window per gain computer (HoldMode::EveryPeak).
double decoupledStep(double tgt, double &hold, double &fast, double holdCoeff) const noexcept
One decoupled step on explicit state (see applyBallisticsDecoupled).
T detectLevelLinear(T sample, int ch, DetectorType detType) noexcept
Computes the detected level as a linear magnitude (>= 0).
void prepare(double sampleRate) noexcept
Prepares the compressor using sample rate only (backward compatibility).
Definition Compressor.h:381
void processBlockImpl(AudioBufferView< T > audio, AudioBufferView< T > sidechain) noexcept
Core DSP loop executing sidechain detection, linking, ballistics, and gain application.
static constexpr double kLandingPaceDb
Decibels behind that make the landing e times faster.
ProgramTiming programTiming(Character charType, Topology topoEff, bool decoupled, bool splitAdaptive) const noexcept
The weights for this routing: the Clean and Varimu characters in feed-forward with Branching ballisti...
std::array< AsymDrift, kMaxChannels > asymDrift_
double hybridRate_
Its pole (the time of the RMS window).
static bool readsBetweenSamples(DetectorType detType) noexcept
The detectors that rectify: at Precision::High they read the key between the samples too.
CharacterStage< T > stageAfter_
The output amplifier.
LinkMode
What the linked level of a stereo pair reads (see setLinkMode()).
Definition Compressor.h:885
@ Dominant
The level of the pair's dominant component, wherever it sits in the image.
@ Loudest
The louder channel's level (the default).
static constexpr T kFetColorH2
void setHoldMode(HoldMode mode) noexcept
Chooses what the hold keeps (Deepest by default).
void setRange(T dB) noexcept
Limits the maximum gain change the compressor may apply.
static constexpr T kNoLimit
double layeredStep(T inputDb, T thresh, T ratio, T knee, const CharacterProfile &profile, T range, int holdN, int soft, T &held, int &counter, double &level, double &peak, SlidingDeepest *window=nullptr) const noexcept
One frame of a layered character: hold and range on the whole target, each layer towards its part of ...
void setMidSideFocus(T focus) noexcept
In Route::MidSide, how the compression leans to the middle or to the sides, -1 to 1: at 0 (the defaul...
Definition Compressor.h:963
std::array< HilbertIIR< double >, kMaxChannels > hilbertDetectors_
Zero-latency analytic pairs for detection.
double ballisticsStep(double tgt, double &fast, double &slow, double &mid, double &deep, double attCoeff, double relCoeff) const noexcept
Branching ballistics on explicit state (shared by both block paths): the fast envelope,...
HoldMode
What the hold keeps (see setHoldMode()).
void setControlNetwork(T depthDb, T cornerHz=T(10)) noexcept
A lead-lag network in the control path: only a part of each fast move of the gain is applied at once.
static constexpr int kChunk
Frames per pass of the feed-forward path.
T toneHighIn_
The gains those were designed for.
static constexpr double kSustainedOverRmsDb
Its sustained level over the RMS (Upward guard, dB).
std::atomic< T > rangeDb_
Max |gain change| in dB.
std::array< T, kMaxChannels > fbLastOutput_
static constexpr double kEmphasisCeilSeconds
nor longer than this.
std::atomic< T > spectralTiming_
Weight of the balance of the key on both times.
double gainSmoothRate_
Coefficient of each of its two sections (0: off).
Topology getTopology() const noexcept
Returns the currently active topology.
std::atomic< T > toneHighDb_
setReductionTone().
T cachedMakeupDb_
Last makeup converted by makeupToGain().
std::atomic< T > attackMs_
Attack time in milliseconds.
bool latencyKept_
A latency is kept for the lookahead (audio thread).
double midRate_
Pole of the split at kBalanceHighHz.
T getControlLeak() const noexcept
How much of the moves of the gain leaks into the audio (setControlLeak()).
void setCharacterStage(StagePosition position) noexcept
Puts an analog colour stage before or after the compression.
std::array< InterpHistory, kMaxChannels > interp_
Their history per channel.
static T effectiveKneeFor(Character charType, T knee) noexcept
Physical knee floor of the character (dB).
std::atomic< T > landingMs_
Landing of the release (0: off).
T upwardGuardDecay_
Guard decay per sample (60 dB/s).
static constexpr CharacterProfile profileOf(Character type) noexcept
The profile of a character.
static constexpr Mode modeIn(Mode asked, Topology topoEff) noexcept
The mode a routing runs: the two-way and the levelling curves are feed-forward ones,...
T fetDcCoeff_
~10 Hz DC-tracking coefficient.
static double restingGain(const double *target, const double *weight, int count, double attackRate, double releaseRate) noexcept
Where a branching follower rests over a set of weighted targets.
void syncGainSmoothing(bool) noexcept
Seats each of those stages on the gain as it stands when it engages. Audio thread only.
AutoMakeupMode
Automatic makeup-gain behavior (Static and Adaptive apply in Downward mode).
Definition Compressor.h:230
@ Off
Manual makeup only (setMakeupGain).
int getLatency() const noexcept
Returns total processing latency in samples.
DetectorType getDetector() const noexcept
Returns the currently active detector type.
Precision getPrecision() const noexcept
How finely the control signal is computed (see setPrecision()).
std::atomic< T > networkCornerHz_
Its corner.
std::atomic< T > rmsWindowMsAtomic_
Control-thread published target.
T scHpfA0_
HPF normalized feedforward coefficient.
double programStep(double target, double &fast, ProgramState &state, double balance) const noexcept
One step of the branching follower with programme-dependent timing (the single envelope of Clean and ...
std::array< double, kMaxChannels > landingDb_
static constexpr double kAsymDriftHz
Corner of each of the walk's two smoothings.
void updateRmsWindow() noexcept
Safely recalculates the RMS window size ensuring zero heap allocations.
static constexpr double kOptoMidChargeFloorMs
bool layeredActive_
The layers ran last (audio thread).
typename KeyEq::Placement KeyPlacement
The part of a two-channel key a band of the key equalizer acts on.
T analyticMakeupDb(Character charType, Mode modeType, DetectorType detType, bool decoupled, bool loop) noexcept
Target of the analytic makeup, in dB, for a routing that is already known (the solve only runs when a...
static constexpr double kBalanceSeconds
Smoothing of the two powers.
std::atomic< T > liftRange_
AudioSpec spec_
Active audio environment specification.
std::atomic< Topology > topology_
Selected topology.
static constexpr double kEmphasisAttacks
Smoothing the emphasis of the attack measures against, in attack times.
std::array< double, kMaxChannels > envMidDb_
Medium memory of the three-stage cell per channel (dB).
T stepImplicit(T inDb, int ch, Character charType, T thresh, T ratio, T knee, const LoopCoeffs &coeffs) noexcept
One step of the semi-implicit loop on the channel's envelopes: the blended gain it leaves,...
T applyBallisticsFeedbackImplicit(T inDb, int ch, Character charType, T thresh, T ratio, T knee) noexcept
Feedback ballistics with the loop resolved semi-implicitly.
T getLiftBelow() const noexcept
Distance of the lower threshold of Mode::Both under the main one, in dB (setLift()).
Definition Compressor.h:868
std::array< double, kMaxChannels > hybridMeanSq_
Mean square of the key.
static FeedbackLaw elementLaw(T eOut, T r, T w) noexcept
Downward element law for feedback detection, per output level.
void setCleanBallistics(CleanBallistics mode) noexcept
Selects the Clean character's feed-forward ballistics.
double gainDelayNow_
The gain line's delay now, in samples (negative: not started).
std::atomic< Mode > mode_
Selected compression mode.
void setFeedbackKeyed(bool on) noexcept
In FeedBack, runs the loop on the key ahead of the audio.
double programShape(double gain, ProgramState &state) const noexcept
The gain with the emphasis of the attack: what it is under its own smoothed course while it falls,...
void setAdaptiveAttack(T amount) noexcept
Makes the attack depend on how far the target is.
std::array< int, kMaxChannels > rmsRecomputeCounters_
Re-summation counters.
double ballisticsCore(double tgt, double &fast, double &slow, double &mid, double &deep, double attCoeff, double relCoeff, double chargeCoeff, double slowRelCoeff, double midChargeCoeff, double midRelCoeff) const noexcept
ballisticsStep() with the coefficients of the memory stage given too.
static constexpr Topology topologyFor(const CharacterProfile &profile, Topology asked) noexcept
The topology a character runs in when the user asks for one.
void setProgramRelease(T amount) noexcept
Makes the release depend on how long the compressor has been working.
double charMidChargeCoeff_
Charge coefficient of the medium memory.
RingBuffer< T > routeDelay_
The part that is not treated waits here.
static constexpr double kFullAttackDb
Distance to the target from which the attack is the knob's.
bool programActive_
They acted last (audio thread).
T getMaxLookahead() const noexcept
The latency kept for the lookahead, in ms (0: none; see setMaxLookahead()).
OptoCell getOptoCell() const noexcept
void setOptoCell(OptoCell cell) noexcept
Chooses how the cell of the Opto character remembers.
static T weightedGain(T g, T w) noexcept
A linear gain with its decibels scaled by w: 1 at w = 0, itself at w = 1.
bool threeStage_
The audio thread runs the three-stage cell.
double balanceAdvance(double lowSq, double highSq) noexcept
Smooths the frame's two powers and returns the balance of the key: -1 all low, +1 all high,...
KeyEq::Response getSidechainResponse() const noexcept
The curve of the key equalizer, for a display: build it when the bands change and read each frequency...
static T levelerCurve(T inputDb, T thresh) noexcept
The levelling curve: the gain 1 / (1 + level / threshold), in decibels. Nothing far under the thresho...
std::array< T, kMaxChannels > asymCrest_
The crest of each channel's key.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio buffer in-place using its own signal as the sidechain.
Definition Compressor.h:391
CleanBallistics getCleanBallistics() const noexcept
Returns the Clean character's feed-forward ballistics.
bool isAutoThreshold() const noexcept
Whether the threshold counts from the key's recent peak (setAutoThreshold()).
std::array< double, kMaxChannels > envSlowDb_
Slow memory envelope per channel (dB).
typename KeyEq::Shape KeyShape
What a band of the key equalizer does.
T getProgramRelease() const noexcept
Weight of the programme-dependent release (see setProgramRelease()).
double sustainRate_
Pole of the follower of the depth.
T applyBallisticsDecoupled(T targetGrDb, int ch, bool splitAdaptive) noexcept
Decoupled ballistics for the Clean character in feed-forward operation (after the smooth decoupled pe...
std::atomic< T > midSideFocus_
std::vector< LookaheadRamp > lookaheadRamps_
One ramp per gain computer of the layout (LookaheadShape::Ramp).
std::atomic< T > kneeWidth_
Knee width in dB.
Biquad< T, kMaxChannels > toneHigh_
The filter F of the tone (audio thread).
void setReleaseLanding(T ms) noexcept
Makes the last decibels of a release come back slowly (milliseconds; 0, the default,...
static T kneeCurve(T inputDb, T thresh, T slope, T knee) noexcept
A threshold, a slope (1 - 1/ratio) and a quadratic knee: the gain change at a level,...
Precision
How finely the control signal is computed (see setPrecision()).
Definition Compressor.h:257
@ Standard
One value of the gain per sample (default).
bool isSoftRange() const noexcept
Whether the gain change meets the range without a corner (setSoftRange(), setRangeShape()).
std::array< double, kMaxChannels > precLevel_
Last level of the solved loop (dB).
static constexpr double kPushPullRest
std::atomic< T > programRelease_
Weight of the sustained reduction on the release.
void setMode(Mode mode) noexcept
Sets the curve of the gain computer (Downward, Upward, Both or Leveler).
Definition Compressor.h:835
double linkLR_
The key's covariance (dominant link).
int lookaheadSamples_
Active lookahead latency in samples.
static double decoupledCore(double tgt, double &hold, double &fast, double holdCoeff, double attCoeff, double smoothCoeff) noexcept
decoupledStep() with the coefficients of the smoothing stage given too.
TruePeakDetector< T, kMaxChannels > truePeak_
std::atomic< T > maxLookaheadMs_
Latency kept for the lookahead (0: the lookahead itself).
std::atomic< bool > removalListen_
The output is what the compression takes out.
std::atomic< T > threshold_
Threshold in dB.
SmoothedValue< T > amountSmooth_
De-zippered amount.
std::array< std::array< T, 4 >, kMaxChannels > pointLevelDb_
Detected level per channel and point of the frame (dB).
void setCharacterStageSettings(const StageSettings &settings) noexcept
Sets drive, emphasis, asymmetry, drift, sag and noise of the colour stage. Any thread.
void processBlock(AudioBufferView< T > audio, AudioBufferView< T > sidechain) noexcept
Processes audio with an independent external sidechain.
Definition Compressor.h:408
double subMidRelCoeff_
Medium-memory release coefficient of an eighth of a sample.
std::atomic< bool > feedbackKeyed_
A feedback loop runs on the key ahead of the audio.
void updateTimeConstants(T fs) noexcept
Pre-calculates recursive exponential decay coefficients.
T rmsWindowMs_
Active RMS length in ms (audio-thread copy).
std::vector< double > stageFade_
The share of the colour, per sample of the fade.
double lowRate_
Pole of the split at kBalanceLowHz.
void setControlLeak(T amount) noexcept
Lets the moves of the gain leak into the audio as low thumps (0, the default, is off).
bool shapesGain() const noexcept
Whether anything stands between the ballistics and the gain: the landing, the network or the smoothin...
std::atomic< bool > scListen_
The key goes out instead of the audio.
void setStereoLink(T amount) noexcept
Sets stereo linking amount (0.0 = unlinked dual mono, 1.0 = fully linked).
Definition Compressor.h:877
std::atomic< T > makeupGain_
Static makeup gain in dB.
bool toneActive_
The tone is in the path.
void syncPrecisionState(bool precise) noexcept
Seats the history of the precise path when it engages: it starts from the gain that is sounding and f...
T splitDetRelCoeff_
Detector release coefficient (sample-rate derived).
RangeShape getRangeShape() const noexcept
How the gain change meets the range (setRangeShape()).
T leakAmount_
The leak as the audio thread took it.
std::atomic< Route > route_
void setPrecision(Precision precision) noexcept
Selects how finely the control signal is computed (default: Standard).
static constexpr std::array< CharacterProfile, 5 > kProfiles
The characters, in the order of Character.
std::array< double, kMaxChannels > layerPeakDb_
bool rampActive_
The ramp ran in the last block.
Biquad< T, kMaxChannels > toneLow_
T getLiftRange() const noexcept
The most Mode::Both raises, in dB (setLift()).
Definition Compressor.h:874
static constexpr int kStageKeyRoom
Samples kept for the colour stage's latency in the listened key.
double balance_
Their balance, -1 to +1.
T gainPathPrecise(const T *levelDb, int count, int ch, const GainPathConfig &cfg, T thresh, T ratio, T knee) noexcept
The gain of one frame at Precision::High, for one gain computer.
T boundImplicit(T shown, int ch) noexcept
Hold and range of the semi-implicit loop.
std::atomic< T > holdMs_
Gain-hold time in ms (0 = off).
void setAttack(T ms) noexcept
Sets the attack time in milliseconds.
Definition Compressor.h:761
double charMidRelCoeff_
Release coefficient of the medium memory (three-stage cell).
static constexpr double kEnvelopeReferenceDb
The same for the Hilbert detector.
static constexpr double kBalanceLowHz
And ends here.
Route routeIn_
The route the states carry (audio thread).
void setSidechainListen(bool on) noexcept
Plays the key instead of the compressed audio.
void copyGainStateFromChannel0(int nCh) noexcept
Copies channel 0's gain-computer state to channels [1, nCh).
double linkCorrelation(T keyL, T keyR) noexcept
int rmsWindowSamples_
Active RMS length in samples.
void setSidechainBand(int band, const KeyBand &settings) noexcept
Sets a band of the equalizer of the key.
SmoothedValue< T > colorSmooth_
De-zippered character colour amount.
static Layers layeredCurve(T inputDb, T thresh, T ratio, T knee, const CharacterProfile &profile) noexcept
The curves of the two layers.
Mode
Processing direction.
Definition Compressor.h:198
@ Downward
Standard: Reduces dynamic range by attenuating signals above the threshold.
void setRangeShape(RangeShape shape) noexcept
Selects how the gain change meets the range.
double charRelCoeff_
Release coefficient (fast stage).
std::array< T, kMaxChannels > leakBase_
The slow copy of each channel's gain.
bool adaptiveMakeupActive_
Adaptive makeup ran last (audio thread).
double stageWeightAfter_
Share of the output stage (audio thread).
static constexpr bool isLayered(const CharacterProfile &profile, Mode modeType) noexcept
Whether a character runs its two layers: it has them, and the mode is Downward.
static constexpr bool reducesOnly(Mode modeType) noexcept
Whether a mode only ever takes level off (the automatic makeups that add it back apply).
std::atomic< T > characterColor_
Character harmonic amount (0 to 1).
~Compressor()=default
KeyEq keyEq_
Equalizer of the key, after the high-pass.
std::atomic< int > rangeShape_
How the gain change meets the range (a RangeShape).
double decSmoothCoeff_
Decoupled smoothing pole, release side.
std::atomic< CleanBallistics > cleanBallistics_
Clean feed-forward ballistics.
static FeedbackLaw computeGainFeedbackUpward(T outDb, T thresh, T ratio, T knee, T guardDb) noexcept
Upward element law for feedback detection, per output level.
bool gainSmoothActive_
The smoothing ran last (audio thread).
std::atomic< T > ratio_
Ratio (e.g., 4 = 4:1).
static double windowSpreadDb(double windowMs) noexcept
Spread of what an RMS window reads over dense programme: the standard deviation of its level,...
T partWeight(int ch, int idx, int n) const noexcept
std::array< T, kMaxChannels > scHpfPrev_
HPF x[n-1] state.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
void writeState(StateWriter &w, const char *prefix) const
Writes the bands under keys that start with a prefix ("<prefix><band>.shape", ".freq",...
bool sync() noexcept
Takes the settings published since the last call.
void processFrame(T *frame, int channels) noexcept
One frame of the key, every channel of it, in place.
Placement
The part of a two-channel key a band acts on (see processFrame()).
void advance(int samples) noexcept
Moves the equalizer on in time: the coefficients between two designs, the bands on the move to their ...
void reset() noexcept
Clears the memory of the filters (settings and glides are kept).
Response getResponse(Placement part=Placement::Stereo) const noexcept
The sections of the published bands, designed as the audio thread designs them, for a display.
static constexpr int kBands
Bands of the equalizer.
void readState(const StateReader &r, const char *prefix) noexcept
Reads the bands writeState() wrote (a band that is missing reads as Off, a placement that is missing ...
Shape
What a band does to the key.
Band getBand(int band) const noexcept
The published settings of a band (a band out of range reads as Off).
void setBand(int band, const Band &settings) noexcept
Publishes the settings of a band.
T processSample(T input, int channel) noexcept
One sample of one channel of the key through the equalizer.
bool isPlaced() const noexcept
Whether a band in the path is placed on the middle or on the sides: only processFrame() gives those t...
void prepare(double sampleRate) noexcept
Prepares the equalizer for a sample rate and clears its memory.
The key of a dynamics processor as it is listened to: late by the processor's latency and held under ...
void processFrame(T *frame, int channels, int delay) noexcept
One frame: the key of every channel goes in and comes out late and under the ceiling.
void prepare(double sampleRate, int maxDelaySamples) noexcept
Sets the rate and the longest delay (allocates).
void reset() noexcept
Clears the delay and lets the gain go.
Power-of-two circular buffer with compile-time interpolated read access.
Definition RingBuffer.h:64
Zero-allocation parameter smoother for real-time audio.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
Per-channel 4x-oversampled inter-sample peak estimator.
T processSample(T sample, int channel) noexcept
Feeds one sample and returns the local true-peak estimate.
void reset() noexcept
Clears all channel histories. Safe on the audio thread.
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
Definition SimdOps.h:644
Main namespace for the DSPark framework.
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 decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
T fastDecay(T x) noexcept
e^(-x) for x >= 0 by a rational approximation: the coefficient of a one-pole whose time changes every...
Definition DspMath.h:242
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
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
static BiquadCoeffs makeHighShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth high shelf (see makeLowShelfMatched()).
Definition Biquad.h:405
static BiquadCoeffs makeLowShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth low shelf (Vicanek, "Matched Two-Pole Digital Shelving Filters",...
Definition Biquad.h:399
The settings of the stage.
One channel's walk: smoothed draws, followed in a line between them.
std::uint32_t rng
The channel's source.
double smooth
And through the second.
double wander
The draws through one one-pole.
double to
The walk at the start and the end of the tick.
int tick
Frames into the tick.
State of the two bands the balance of one channel's key is read from.
double high
From there to kBalanceCeilingHz: the high band.
double low
From there to kBalanceLowHz: the low band.
double mid
Under kBalanceHighHz.
double sub
Under kBalanceFloorHz.
What makes a character: the numbers one engine reads.
T levelLeadDb
Decibels under the threshold where the levelling layer starts.
T attackCeilMs
Limits of the attack knob.
T chargeScale
Time the memory stage takes to charge, as a multiple of the release knob...
T levelShare
Share of the slope a levelling layer takes (0: one layer).
bool forwardOnly
It runs in feed-forward whatever Topology says.
T releasePaceDb
Decibels of distance to the target that double the time of a layer.
T ratioGrowthDb
Decibels over the threshold that double the ratio (0: a fixed ratio).
T releaseCeilMs
Limits of the release knob.
T fastRelease
Release of the fast stage, as a multiple of the knob.
T kneeFloorDb
Narrowest knee the element can form (0: any).
bool ownLoop
It detects on its own output with a peak rectifier, whatever Topology and Detector say.
T fastWeight
Share of the fast stage in the gain (1: no memory stage).
T slowReleaseCeilMs
Release of the memory stage: a multiple of the knob, up to a ceiling.
Colour colour
Its harmonic signature.
T levelRelease
Its release, as a multiple of the knob.
bool decoupled
setCleanBallistics() applies to it.
T levelAttackFloorMs
Its attack: a multiple of the knob, and the least it is.
bool programTiming
Programme-dependent timing applies to it.
Parameter values of a block whose smoothers are settled.
Per-block routing of the feed-forward block path.
bool gainSmooth
The gain is smoothed after the ballistics.
bool ramp
The lookahead brings the gain in along a ramp.
int gainDelay
Samples the gain is held back: the latency kept minus the lookahead.
bool autoThreshold
The threshold counts from the key's recent peak.
bool dominant
The pair links to its dominant component.
bool keyBalance
It reads the spectral balance of the key.
bool keyEq
The equalizer of the key has bands in the path.
bool program
Programme-dependent timing acts.
bool listen
The key goes out instead of the audio.
int listenDelay
Samples the listened key waits: the latency of the audio path.
bool gainLine
A latency is kept for the lookahead: the gain runs through its line.
bool layered
The character runs its two layers.
Element law result: static target (dB, <= 0) and its |slope|.
T slope
d|target| / d(level in dB): the incremental loop gain.
T target
Gain change the element commands at this output level.
Semi-implicit solve result: stepped gain and the law's target.
T target
The element law's static target at the solved level.
T gain
Blended gain (dB) after this sample's ballistics step.
Per-block routing of the gain path (see gainPath()).
double loopDelay
Detector delay seen by an explicit feedback loop (samples).
bool layered
The character runs its two layers (see layeredStep()).
bool program
Programme-dependent timing acts (see programTiming()).
History of the key of one channel, mirrored so its window is contiguous.
T x[2 *kInterpTaps]
Each sample twice, kInterpTaps apart.
int at
Where the next one goes.
What the two layers of a layered character ask for at a level (dB).
T level
The levelling layer.
T peak
The layer over it.
The lookahead as a ramp (LookaheadShape::Ramp).
T process(T gr) noexcept
One gain change in dB in, the ramped one out.
uint32_t t
Values taken so far (wraps).
std::vector< uint32_t > deepPos
When each queued value came.
void setLength(int wanted) noexcept
Moves the ramp's length to wanted, a sample at a time (the sums follow, each step in constant time).
std::vector< T > boxB
The queue of the sliding window; the histories of the two averages.
void prepare(int maxLength)
Allocates for a longest ramp.
Coefficients of one step of the semi-implicit loop.
double charge
Memory stage while it charges.
double midRelease
Medium memory while it discharges.
double release
Fast stage while it recovers.
double midCharge
Medium memory of the three-stage cell while it charges.
double slowRelease
Memory stage while it discharges.
double attack
Fast stage while the reduction deepens.
Everything the analytic makeup depends on: it is worked out again only when one of these changes.
T liftRange
The upward half of Mode::Both.
double release
Release coefficient.
double attack
Observed attack coefficient.
T fastWeight
Blend of the fast and memory stages.
double hold
Release coefficient of the decoupled hold stage.
bool valid
False until the first solve.
bool operator==(const MakeupModelKey &) const =default
double slowRelease
Release coefficient of the memory stage.
DetectorType detType
Effective detector.
double midCharge
Charge coefficient of the medium memory (three-stage cell).
int soft
How the target meets the range (a RangeShape).
double charge
Charge coefficient of the memory stage.
T window
Length of the RMS window (ms).
bool decoupled
Decoupled ballistics.
double midRelease
Release coefficient of the medium memory.
T range
Largest gain change (dB).
bool autoThreshold
The threshold counts from the key's peak.
bool threeStage
The memory stage is the three-stage cell.
T amount
Share of the gain change that is applied.
bool loop
The detector reads the output (feedback).
The two coefficients of a frame.
State of one gain computer under programme-dependent timing.
double smoothed
The gain smoothed over kEmphasisAttacks times the attack (dB).
double sustained
Slow follower of the depth of the gain change (dB).
The weights of a block (zero where the routing leaves the times fixed).
double spectral
Weight of the balance of the key on both.
double release
Weight of the sustained reduction on the release.
bool active
Any of them acts.
double emphasis
Emphasis of the attack, -1 to +1.
double attack
Weight of the closeness of the target on the attack.
The deepest gain change of a sliding window (HoldMode::EveryPeak).
std::array< T, kSlots > depth
T push(T gr, int perSample=1) noexcept
One value in, the deepest of the window out.
void configure(int windowSamples) noexcept
Sets the window in samples and empties it.
std::array< uint32_t, kSlots > block
static constexpr int kSlots
Room of the queue (a power of two, over kBlocks + 1).
static constexpr int kBlocks
Blocks the window is cut in, at most.