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"
102template <FloatType T>
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);
331 for (
int ch = 0; ch < kMaxChannels; ++ch) holdWindows_[static_cast<size_t>(ch)].configure(
holdSamples_);
339 lookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000));
341 maxLookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000)));
345 scHpfDirty_.store(
false, std::memory_order_relaxed);
349 int maxRmsSamples =
static_cast<int>(
sampleRate_ * 0.5) + 1;
352 buf.assign(
static_cast<size_t>(maxRmsSamples), T(0));
395 processRouted(buffer, buffer);
412 processRouted(audio, sidechain);
449 if (channel < 0 || channel >=
kMaxChannels)
return input;
464 const bool advanceShared = (channel == 0);
465 T thresh, ratio, knee, makeupDb, colorAmt, amount;
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);
513 modeType =
modeIn(modeType, topoEff);
520 &&
scHpfDirty_.exchange(
false, std::memory_order_acquire))
543 const bool layered =
isLayered(profile, modeType);
556 double lowSq = 0.0, highSq = 0.0;
562 T levelDb =
detectLevel(detectorRead, channel, detTypeEff);
564 const GainPathConfig cfg { charType, modeType, topoEff, fbImplicit, splitAdaptive, decoupled,
568 T threshNow = thresh;
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);
577 T smoothedGR_Db =
gainPath(levelDb, channel, cfg, threshNow, ratio, knee);
581 if (amount < T(1)) smoothedGR_Db *= amount;
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;
602 makeup +=
computeGain(T(0), thresh, ratio, knee, charType,
603 modeType, T(0)) * T(-0.5);
621 T output = pushPull ?
pushPullElement(input, smoothedGainLinear, colorAmt)
622 : (extras ?
gained(input, smoothedGainLinear, channel) : input * smoothedGainLinear);
626 const T sq = output * output;
628 if (std::isfinite(sq)) dc +=
fetDcCoeff_ * (sq - dc);
629 const T grDepth = std::clamp(-smoothedGR_Db * T(0.1), T(0), T(1));
630 output += colorAmt *
kFetColorH2 * grDepth * (sq - dc);
635 fbLastOutput_[channel] = (heardApart || extras) ? input * loopGainLinear : output;
639 return scListen_.load(std::memory_order_relaxed) ? detectorIn : output;
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);
665 for (
int ch = 0; ch < kMaxChannels; ++ch) holdWindows_[static_cast<size_t>(ch)].clear();
692 asymDrift_[ch].rng = 0x9E3779B9u *
static_cast<std::uint32_t
>(ch + 1) + 0x6A09E667u;
702 std::fill(buf.begin(), buf.end(), T(0));
703 for (
auto& sum :
rmsSums_) sum = T(0);
737 if (!std::isfinite(dB))
return;
738 threshold_.store(dB, std::memory_order_relaxed);
744 if (!std::isfinite(ratio))
return;
745 ratio_.store(std::max(ratio, T(1)), std::memory_order_relaxed);
763 if (!std::isfinite(ms))
return;
764 attackMs_.store(std::max(ms, T(0.01)), std::memory_order_relaxed);
779 if (!std::isfinite(ms))
return;
780 releaseMs_.store(std::max(ms, T(1)), std::memory_order_relaxed);
787 if (!std::isfinite(dB))
return;
788 kneeWidth_.store(std::max(dB, T(0)), std::memory_order_relaxed);
794 if (!std::isfinite(dB))
return;
825 std::memory_order_relaxed);
859 void setLift(T belowDb, T ratio, T rangeDb)
noexcept
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);
879 if (!std::isfinite(amount))
return;
880 stereoLink_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
965 if (std::isfinite(focus))
midSideFocus_.store(std::clamp(focus, T(-1), T(1)), std::memory_order_relaxed);
974 if (!std::isfinite(dryWet))
return;
975 mix_.store(std::clamp(dryWet, T(0), T(1)), std::memory_order_relaxed);
984 if (!std::isfinite(ms))
return;
985 lookaheadMs_.store(std::clamp(ms, T(0), T(10)), std::memory_order_relaxed);
1004 if (!std::isfinite(ms))
return;
1005 maxLookaheadMs_.store(std::clamp(ms, T(0), T(10)), std::memory_order_relaxed);
1104 if (!std::isfinite(amount))
return;
1105 amount_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1289 if (!std::isfinite(amount))
return;
1290 programRelease_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1313 if (!std::isfinite(amount))
return;
1314 adaptiveAttack_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1340 if (!std::isfinite(amount))
return;
1341 spectralTiming_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1365 if (!std::isfinite(amount))
return;
1366 attackEmphasis_.store(std::clamp(amount, T(-1), T(1)), std::memory_order_relaxed);
1390 if (!std::isfinite(ms))
return;
1391 holdMs_.store(std::clamp(ms, T(0), T(500)), std::memory_order_relaxed);
1431 if (!std::isfinite(dB))
return;
1432 rangeDb_.store(std::max(dB, T(0)), std::memory_order_relaxed);
1507 if (!std::isfinite(amount))
return;
1508 characterColor_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1526 if (!std::isfinite(ms))
return;
1527 gainSmoothMs_.store(std::clamp(ms, T(0), T(50)), std::memory_order_relaxed);
1552 if (!std::isfinite(ms))
return;
1553 landingMs_.store(std::clamp(ms, T(0), T(2000)), std::memory_order_relaxed);
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);
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);
1655 if (!std::isfinite(amount))
return;
1656 controlLeak_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1683 if (!std::isfinite(amount))
return;
1684 detectorAsymmetry_.store(std::clamp(amount, T(-1), T(1)), std::memory_order_relaxed);
1710 if (!std::isfinite(amount))
return;
1711 detectorDrift_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1768 if (std::isfinite(cutoffHz) && cutoffHz > T(0))
1769 scHpfFreq_.store(cutoffHz, std::memory_order_relaxed);
1771 scHpfDirty_.store(
true, std::memory_order_release);
1866 if (!std::isfinite(ms))
return;
1902 return gainPathLatency() + coloured;
1907 [[nodiscard]]
int gainPathLatency() const noexcept
1916 const bool layered =
isLayered(profile, mode);
1919 if (feedback && !
feedbackKeyed_.load(std::memory_order_relaxed))
return reading;
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;
1935 void processRouted(AudioBufferView<T> audio, AudioBufferView<T> sidechain)
noexcept
1937 const Route route =
route_.load(std::memory_order_relaxed);
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_)
1959 T*
const left = audio.getChannel(0) + off;
1960 T*
const right = audio.getChannel(1) + off;
1962 for (
int i = 0; i < m; ++i)
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);
1972 const T*
const kl = sidechain.getChannel(0) + off;
1973 const T*
const kr = (sidechain.getNumChannels() > 1 ? sidechain.getChannel(1) : sidechain.getChannel(0)) + off;
1976 for (
int i = 0; i < m; ++i)
1978 keyMid[i] = (kl[i] + kr[i]) * T(0.5);
1979 keySide[i] = (kl[i] - kr[i]) * T(0.5);
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);
1991 processBlockImpl(AudioBufferView<T>(pair, 2, m), AudioBufferView<T>(keys, 2, m));
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));
2004 const int late = std::min(gainPathLatency(),
routeReach_);
2005 const bool listening =
scListen_.load(std::memory_order_relaxed)
2007 for (
int i = 0; i < m; ++i)
2010 waiting[i] = listening ? T(0) :
routeDelay_.read(late);
2015 for (
int i = 0; i < m; ++i)
2017 const T mid = left[i], side = right[i];
2018 left[i] = mid + side;
2019 right[i] = mid - side;
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)));
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)));
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)));
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)));
2057 w.
write(
"mode",
static_cast<int32_t
>(
mode_.load(std::memory_order_relaxed)));
2059 w.
write(
"scHpfFreq",
static_cast<float>(
scHpfFreq_.load(std::memory_order_relaxed)));
2065 w.
write(
"amount",
static_cast<float>(
amount_.load(std::memory_order_relaxed)));
2068 w.
write(
"precision",
static_cast<int32_t
>(
precision_.load(std::memory_order_relaxed)));
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));
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)));
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)));
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)));
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)));
2111 const int amLegacy = r.
read(
"autoMakeup",
false) ? 2 : 0;
2113 std::clamp(r.
read(
"autoMakeupMode", amLegacy), 0, 3)));
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)));
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)));
2179 template <
typename E>
2182 const int v = std::clamp(
static_cast<int>(value), 0,
static_cast<int>(last));
2183 return static_cast<E
>(v);
2200 const int nCh = std::min(audio.getNumChannels(),
kMaxChannels);
2201 const int nS = audio.getNumSamples();
2204 const int scCh = (sidechain.getNumSamples() >= nS)
2205 ? sidechain.getNumChannels() : 0;
2219 &&
scHpfDirty_.exchange(
false, std::memory_order_acquire))
2222 const bool listen =
scListen_.load(std::memory_order_relaxed);
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);
2241 T sLink =
stereoLink_.load(std::memory_order_relaxed);
2250 modeType =
modeIn(modeType, topoEff);
2261 const bool layered =
isLayered(profile, modeType);
2264 const bool decoupled =
useDecoupled(charType, topoEff);
2266 const bool precise = !layered &&
usePrecision(topoEff, fbImplicit, splitAdaptive);
2279 const bool autoThr =
autoThreshold_.load(std::memory_order_relaxed);
2283 const bool ramp =
rampShape_ && activeLookahead > 0;
2290 const bool externalKey = scCh > 0 && nCh > 0 && sidechain.getChannel(0) != audio.getChannel(0);
2300 const bool shared = (sLink >= T(1)) && !splitAdaptive && nCh > 1 && !
parted_;
2302 const bool dominantLink = linkMode ==
LinkMode::Dominant && nCh == 2 && sLink > T(0);
2324 T staticMakeupDb = staticMakeup
2325 ?
computeGain(T(0), thresh, ratio, knee, charType, modeType, T(0)) * T(-0.5)
2329 const GainPathConfig cfg { charType, modeType, topoEff, fbImplicit, splitAdaptive, decoupled,
2343 if (feedForward && !precise && !element && !sampleWise && !keyFrames)
2346 activeLookahead, scHpf, shared, decoupled,
2347 splitAdaptive, staticMakeup, adaptiveMakeup,
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 };
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;
2368 for (
int i = 0; i < nS; ++i)
2382 staticMakeupDb =
computeGain(T(0), thresh, ratio, knee, charType,
2383 modeType, T(0)) * T(-0.5);
2390 T makeupDb = mkupBase + staticMakeupDb + analyticDb;
2400 double lowSq = 0.0, highSq = 0.0;
2409 const auto keyOf = [&](
int ch)
noexcept -> T {
2412 source = (scCh > 0) ? sidechain.getChannel(std::min(ch, scCh - 1))[i]
2413 : audio.getChannel(ch)[i];
2419 loopSource[ch] =
detectorSafe((scCh > 0) ? sidechain.getChannel(std::min(ch, scCh - 1))[i]
2420 : audio.getChannel(ch)[i]);
2424 source = fbImplicit ? audio.getChannel(ch)[i] :
fbLastOutput_[ch];
2426 if (keyBalance)
balanceBands(source, ch, lowSq, highSq);
2433 keyPair[0] = keyOf(0);
2434 keyPair[1] = keyOf(1);
2437 for (
int ch = 0; ch < nCh; ++ch)
2441 detectorIn = keyPair[ch];
2444 detectorIn = keyOf(ch);
2447 heard[ch] = detectorIn;
2448 if (lopsided) detectorIn =
asymmetric(detectorIn, ch);
2456 for (
int j = 0; j < count; ++j)
2458 linkedLin[j] = std::max(linkedLin[j], level[j]);
2461 if (dominantLink && ch < 2)
2462 for (
int j = 0; j < count; ++j) pairLevel[ch][j] = level[j];
2467 for (
int j = 0; j < count; ++j)
2468 linkedLin[j] =
dominantLevel(pairLevel[0][j], pairLevel[1][j], rho2);
2476 T threshNow = thresh;
2481 for (
int j = 0; j < count; ++j) top = std::max(top, linkedLin[j]);
2483 for (
int ch = 0; ch < nCh; ++ch) top = std::max(top, std::abs(loopSource[ch]));
2485 for (
int ch = 0; ch < nCh; ++ch) top = std::max(top, std::abs(
detectorSafe(audio.getChannel(ch)[i])));
2487 threshNow = thresh +
static_cast<T
>(
autoRefDb_[0]);
2496 const int rampLength = gainLine ? activeLookahead -
static_cast<int>(std::ceil(slide)) : activeLookahead;
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);
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;
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);
2514 for (
int ch = 0; ch < nCh; ++ch)
fbLastOutput_[ch] = loopSource[ch] * gainLin;
2519 for (
int j = 0; j < count; ++j)
2527 for (
int ch = 1; ch < nCh; ++ch) linkedDb[j] = std::max(linkedDb[j],
pointLevelDb_[ch][j]);
2529 for (
int ch = 0; ch < nCh; ++ch)
2532 for (
int j = 0; j < count; ++j)
2535 levelDb[j] = own + sLink * (linkedDb[j] - own);
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;
2543 T partMakeup = makeupLin;
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)
2565 for (
int ch = 0; ch < nCh; ++ch) audio.getChannel(ch)[i] = heard[ch];
2654 const int nGain = ff.shared ? 1 : nCh;
2656 if (!ff.paramsMoving)
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);
2668 for (
int o = 0; o < nS; o +=
kChunk)
2670 const int m = std::min(
kChunk, nS - o);
2674 if (ff.paramsMoving)
2676 for (
int k = 0; k < m; ++k)
2685 stMk[k] = (ff.staticMakeup
2686 ?
computeGain(T(0), thr[k], rat[k], kn[k], ff.charType, ff.modeType, T(0)) * T(-0.5)
2692 for (
int ch = 0; ch < nCh; ++ch)
2694 const T* src = ((scCh > 0) ? sidechain.getChannel(std::min(ch, scCh - 1))
2695 : audio.getChannel(ch)) + o;
2697 if (ff.detType ==
DetectorType::Peak && !ff.scHpf && !ff.keyEq && !ff.listen && !ff.dominant)
2699 for (
int k = 0; k < m; ++k) lv[k] = std::abs(
detectorSafe(src[k]));
2704 for (
int k = 0; k < m; ++k)
2717 double rho2[
kChunk] = {};
2719 for (
int k = 0; k < m; ++k) rho2[k] =
linkCorrelation(heard[0][k], heard[1][k]);
2727 for (
int ch = 0; ch < nCh; ++ch)
2729 const T* src = ((scCh > 0) ? sidechain.getChannel(std::min(ch, scCh - 1))
2730 : audio.getChannel(ch)) + o;
2733 for (
int k = 0; k < m; ++k) balance[k] =
balanceAdvance(lowSq[k], highSq[k]);
2741 if (ff.lookahead > 0)
2743 for (
int ch = 0; ch < nCh; ++ch)
2745 const T* src = audio.getChannel(ch) + o;
2746 for (
int k = 0; k < m; ++k)
2758 for (
int k = 0; k < m; ++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]);
2768 T dominantDb[
kChunk] = {};
2770 for (
int k = 0; k < m; ++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))
2776 for (
int k = 0; k < m; ++k)
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]);
2789 const T* thrUse = thr;
2790 if (ff.autoThreshold)
2793 for (
int k = 0; k < m; ++k)
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);
2809 for (
int g = 0; g < nGain; ++g)
2811 const T* dryIn = (ff.lookahead > 0) ? delayed[g] : audio.getChannel(g) + o;
2813 ff.splitAdaptive ? dryIn :
nullptr, balance);
2818 const bool scaled = ff.paramsMoving || constants.amount < T(1);
2819 if (ff.gainLine || scaled || ff.gainSmooth || ff.ramp)
2824 double slide[
kChunk] = {};
2826 for (
int k = 0; k < m; ++k) slide[k] =
slideGainDelay(ff.gainDelay);
2827 for (
int g = 0; g < nGain; ++g)
2831 for (
int k = 0; k < m; ++k)
2833 : ff.lookahead -
static_cast<int>(std::ceil(slide[k])),
true);
2834 if (ff.gainLine &&
atRest)
2836 auto& line =
gainDelay_[
static_cast<size_t>(g)];
2837 for (
int k = 0; k < m; ++k)
2840 gd[k] = line.read(ff.gainDelay);
2843 else if (ff.gainLine)
2844 for (
int k = 0; k < m; ++k) gd[k] =
heldBack(gd[k], g, slide[k],
true);
2846 for (
int k = 0; k < m; ++k)
2847 if (amt[k] < T(1)) gd[k] *= amt[k];
2849 for (
int k = 0; k < m; ++k) gd[k] =
smoothedGain(gd[k], g);
2851 if (ff.splitAdaptive)
2852 for (
int k = 0; k < m; ++k)
2860 for (
int g = 0; g < nGain; ++g)
2861 for (
int k = 0; k < m; ++k)
2865 if (ff.splitAdaptive) level[g][k] =
weightedGain(level[g][k], w);
2870 if (ff.adaptiveMakeup)
2873 for (
int k = 0; k < m; ++k)
2875 T blockGR = gain[0][k];
2876 for (
int g = 1; g < nGain; ++g) blockGR = std::min(blockGR, gain[g][k]);
2884 for (
int k = 0; k < m; ++k) mkLin[k] =
makeupToGain(mk[k] + stMk[k]);
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)
2890 for (
int g = 0; g < nGain; ++g)
2892 const T* gd = gain[g];
2895 for (
int k = 0; k < m; ++k) gl[k] = (gd[k] == T(0)) ? T(1) :
decibelsToGain(gd[k]);
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)
2905 T* data = audio.getChannel(ch) + o;
2906 const T* gl = level[ff.shared ? 0 : ch];
2909 const T* mkUse = mkLin;
2919 for (
int k = 0; k < m; ++k) data[k] = (data[k] * gl[k]) * mkUse[k];
2922 const T* dry = (ff.lookahead > 0) ? delayed[ch] : data;
2924 for (
int k = 0; k < m; ++k)
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);
2938 for (
int k = 0; k < m; ++k)
2941 for (
int ch = 0; ch < nCh; ++ch) frame[ch] = heard[ch][k];
2943 for (
int ch = 0; ch < nCh; ++ch) audio.getChannel(ch)[o + k] = frame[ch];
2956 for (
int ch = 1; ch < nCh; ++ch)
2977 for (
int ch = 1; ch < nCh; ++ch) holdWindows_[static_cast<size_t>(ch)] =
holdWindows_[0];
3001 const T* thr,
const T* rat,
const T* kn,
const T* dryIn,
3002 const double* balance)
noexcept
3012 const T range =
rangeDb_.load(std::memory_order_relaxed);
3013 const int soft =
rangeShape_.load(std::memory_order_relaxed);
3023 for (
int k = 0; k < m; ++k)
3031 for (
int k = 0; k < m; ++k)
3034 tgtA[k] =
downwardCurve(inDb[k], thr[k], rat[k], kn[k], ff.charType)
3035 +
lift(inDb[k], thr[k], kn[k], guard);
3040 for (
int k = 0; k < m; ++k) tgtA[k] =
levelerCurve(inDb[k], thr[k]);
3044 for (
int k = 0; k < m; ++k)
3045 tgtA[k] =
downwardCurve(inDb[k], thr[k], rat[k], kn[k], ff.charType);
3053 for (
int k = 0; k < m; ++k)
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);
3062 else if (dryIn !=
nullptr)
3067 for (
int k = 0; k < m; ++k)
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;
3076 y =
decoupledStep(
static_cast<double>(tgt), hold, fast, c + outputLevel * (c * c - c));
3082 c + outputLevel * (c * c - c));
3084 const T gr =
static_cast<T
>(y);
3088 lastWet = dryIn[k] * gl;
3091 else if (ff.program)
3094 for (
int k = 0; k < m; ++k)
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]));
3103 for (
int k = 0; k < m; ++k)
3105 const T tgt =
holdAndRange(tgtA[k], range, holdN, held, counter, soft, window);
3106 const double y = ff.decoupled
3109 out[k] =
static_cast<T
>(y);
3138 T thresh, T ratio, T knee)
noexcept
3142 T guardDb = inputDb;
3163 return applyBallistics(targetGR_Db, ch, cfg.splitAdaptive, law.slope, cfg.loopDelay);
3174 return static_cast<T
>(shown);
3177 T targetGR_Db =
computeGain(inputDb, thresh, ratio, knee, cfg.charType, cfg.modeType, guardDb);
3188 [[nodiscard]] T
partWeight(
int ch,
int idx,
int n)
const noexcept
3190 const auto c =
static_cast<std::size_t
>(std::clamp(ch, 0, 1));
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));
3207 int activeLookahead,
Character charType, T colorAmt, T makeupLin,
3208 T mixVal, T outLin)
noexcept
3210 T* data = audio.getChannel(ch);
3212 if (activeLookahead > 0)
3228 : (extras ?
gained(input, outLin, ch) : input * outLin);
3236 const T sq = wet * wet;
3238 if (std::isfinite(sq)) dc +=
fetDcCoeff_ * (sq - dc);
3239 const T grDepth = std::clamp(-grDb * T(0.1), T(0), T(1));
3240 wet += colorAmt *
kFetColorH2 * grDepth * (sq - dc);
3245 fbLastOutput_[ch] = (outLin == gainLin && !extras) ? wet : input * gainLin;
3253 data[i] =
removalListen_.load(std::memory_order_relaxed) ? input - kept
3254 : ((mixVal < T(1)) ? (input * (T(1) - mixVal) + wet * mixVal) : wet);
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));
3270 auto tc = [fs](T ms) {
return std::exp(-1.0 / (
static_cast<double>(fs) *
static_cast<double>(ms) / 1000.0)); };
3278 bool threeStageWanted =
false;
3301 if (threeStageWanted)
3315 const T smoothMs = std::min(std::max(relMs * T(0.1), attMs), relMs * T(0.5));
3318 static_cast<double>(relMs),
static_cast<double>(smoothMs))));
3324 const double perMs = 1000.0 /
static_cast<double>(fs);
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;
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);
3360 asymDriftScale_ = 1.0 / std::sqrt(r * r * r * r * (1.0 + a2) / (3.0 * (1.0 - a2) * (1.0 - a2) * (1.0 - a2)));
3369 const auto eighth = [](
double c) {
return std::pow(c, 1.0 /
kSubsteps); };
3385 const double w0 =
static_cast<double>(prevWeight);
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; }
3396 envMidDb_[
static_cast<size_t>(ch)] = shown;
3399 f = (shown - (1.0 - w1) * s) / w1;
3425 * (
static_cast<double>(std::max(
ratio_.load(std::memory_order_relaxed), T(1))) - 1.0);
3431 subAttCoeff_ = 1.0 - (1.0 - rhoSub) / (1.0 + rhoSub * loopGain);
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)); };
3457 const double attackSeconds =
static_cast<double>(std::clamp(attMs, profile.
attackFloorMs, profile.
attackCeilMs)) / 1000.0;
3467 fetDcCoeff_ = T(1) - std::exp(T(-2) * std::numbers::pi_v<T> * T(10) / fs);
3470 lookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000));
3472 maxLookaheadMs_.load(std::memory_order_relaxed), T(0), T(10)) / T(1000)));
3484 for (
int ch = 0; ch < kMaxChannels; ++ch) holdWindows_[static_cast<size_t>(ch)].configure(
holdSamples_);
3595 while (n <
static_cast<size_t>(std::max(0,
maxLength)) + 4) n <<= 1;
3597 boxA.assign(n, T(0));
3598 boxB.assign(n, T(0));
3600 mask =
static_cast<int>(n) - 1;
3607 std::fill(
boxA.begin(),
boxA.end(), T(0));
3608 std::fill(
boxB.begin(),
boxB.end(), T(0));
3618 wanted = std::clamp(wanted, 0,
mask - 3);
3622 const int a = (next + 2) / 2, b = next + 2 - a;
3640 const T depth = std::abs(gr);
3651 const T deep =
deepVal[
static_cast<size_t>(
head)];
3653 sumA +=
static_cast<double>(deep) -
static_cast<double>(
boxA[(
t -
static_cast<uint32_t>(
lenA)) & m]);
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]);
3663 return static_cast<T
>(
sumB /
lenB);
3668 [[nodiscard]] T
rampedIn(T grDb,
int g,
int length,
bool run)
noexcept
3672 ramp.setLength(length);
3673 return ramp.process(grDb);
3693 [[nodiscard]]
static T
holdAndRange(T targetGR_Db, T range,
int holdSamples,
3694 T& held,
int& counter,
int soft = 0,
3700 const T x = targetGR_Db / range, x2 = x * x;
3701 targetGR_Db /= std::sqrt(std::sqrt(T(1) + x2 * x2));
3707 const T size = std::abs(targetGR_Db);
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);
3715 targetGR_Db = std::clamp(targetGR_Db, -range, range);
3718 if (holdSamples > 0 && window !=
nullptr)
return window->push(targetGR_Db, perSample);
3719 if (holdSamples > 0)
3721 if (std::abs(targetGR_Db) >= std::abs(held))
3724 counter = holdSamples;
3726 else if (counter > 0)
3764 return (std::abs(x) <= std::numeric_limits<T>::max()) ? x : T(0);
3771 const double l =
static_cast<double>(keyL);
3772 const double r =
static_cast<double>(keyR);
3777 return den > 1e-60 ? std::min(1.0,
linkLR_ *
linkLR_ / den) : 0.0;
3819 T level = std::abs(sample);
3827 T sq = sample * sample;
3834 if (len > 0 && len <=
static_cast<int>(buf.size()))
3839 if (++idx >= len) idx = 0;
3845 for (
int j = 0; j < len; ++j) sum += buf[j];
3849 level = std::sqrt(std::max(sum /
static_cast<T
>(len), T(0)));
3860 T pos = std::max(sample, T(0));
3861 T neg = std::max(-sample, T(0));
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))));
3891 const double x =
static_cast<double>(sample);
3893 level =
static_cast<T
>(std::max(std::sqrt(2.0 * meanSq), std::abs(x)));
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)
3915 stage.process(buffer);
3918 const int nCh = std::min(buffer.getNumChannels(),
stageScratch_.getNumChannels());
3920 for (
int off = 0; off < buffer.getNumSamples(); off += step)
3922 const int m = std::min(step, buffer.getNumSamples() - off);
3923 auto part = buffer.getSubView(off, m);
3925 for (
int ch = 0; ch < nCh; ++ch) std::copy_n(part.getChannel(ch), m, copy.getChannel(ch));
3927 for (
int i = 0; i < m; ++i)
3929 weight = target > weight ? std::min(target, weight +
stageFadeStep_)
3933 for (
int ch = 0; ch < nCh; ++ch)
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]);
3985 static constexpr T
kNoLimit = std::numeric_limits<T>::infinity();
4001 static constexpr std::array<CharacterProfile, 5>
kProfiles { {
4003 { T(0.01),
kNoLimit, T(1),
kNoLimit, T(1), T(1),
kNoLimit, T(0), T(0), T(0), T(1),
4005 false, T(0), T(0), T(0), T(0), T(0), T(0), T(0) },
4012 { T(10),
kNoLimit, T(1),
kNoLimit, T(0.61), T(25), T(5000), T(4), T(100), T(2000), T(0.6),
4014 false, T(0), T(0), T(0), T(0), T(0), T(0), T(0) },
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),
4020 false, T(0), T(0), T(0), T(0), T(0), T(0), T(0) },
4023 { T(0.01),
kNoLimit, T(1),
kNoLimit, T(1), T(1),
kNoLimit, T(0), T(0), T(0), T(1),
4025 false, T(0), T(0), T(0), T(0), T(0), T(0), T(0) },
4030 { T(0.01),
kNoLimit, T(1),
kNoLimit, T(1), T(1),
kNoLimit, T(0), T(0), T(0), T(1),
4032 true, T(0.5), T(6), T(8), T(30), T(6), T(12), T(6) },
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))];
4073 if (growth > T(0) && excessDb > T(0))
4074 return ratio * (T(1) + excessDb / growth);
4085 return (floor > T(0)) ? std::max(knee, floor) : knee;
4100 T guardDb)
const noexcept
4106 const T down =
downwardCurve(inputDb, thresh, ratio, knee, charType);
4107 return modeType ==
Mode::Both ? down +
lift(inputDb, thresh, knee, guardDb) : down;
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));
4136 [[nodiscard]] T
lift(T inputDb, T thresh, T knee, T guardDb)
const noexcept
4155 return kneeCurve(inputDb, thresh, T(1) - T(1) / effectiveRatio, effectiveKnee);
4162 [[nodiscard]]
static T
kneeCurve(T inputDb, T thresh, T slope, T knee)
noexcept
4168 return std::min(thresh - inputDb, T(0)) * slope;
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);
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)) };
4218 [[nodiscard]]
static double pacedStep(
double envelope,
double target,
double attackRate,
double releaseRate,
4219 double attackPace,
double releasePace)
noexcept
4221 const double distance = envelope - target;
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;
4237 T range,
int holdN,
int soft, T& held,
int& counter,
4238 double& level,
double& peak,
SlidingDeepest* window =
nullptr) const noexcept
4242 const double levelTarget =
static_cast<double>(std::max(want.
level, bounded));
4243 const double peakTarget =
static_cast<double>(bounded) - levelTarget;
4248 if (
atRest(level, levelTarget)) level = 0.0;
4249 if (
atRest(peak, peakTarget)) peak = 0.0;
4251 return std::max(level + peak, -
static_cast<double>(range));
4265 const double shown =
envFastDb_[
static_cast<size_t>(ch)];
4267 layerPeakDb_[
static_cast<size_t>(ch)] = shown - share * shown;
4295 if (!(gain > T(0)) || !(amount > T(0)) || !std::isfinite(input))
return input * gain;
4296 const double g =
static_cast<double>(gain);
4298 const double drive =
kPushPullDrive *
static_cast<double>(amount);
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);
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);
4330 static_cast<double>(low)));
4332 static_cast<double>(high)));
4344 const T leak =
controlLeak_.load(std::memory_order_relaxed);
4363 [[nodiscard]] T
gained(T input, T gain,
int ch)
noexcept
4365 T wet = input * gain;
4371 wet = input - (T(1) - gain) * shaped;
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;
4394 const size_t c =
static_cast<size_t>(ch);
4396 crest = std::max(std::abs(key), crest *
asymDecay_);
4412 const double wander = d.
from + t * (d.
to - d.
from);
4413 amount = std::clamp(
static_cast<T
>(
static_cast<double>(
asymAmount_)
4418 return (key + amount * crest) / (T(1) + std::abs(amount));
4424 s ^= s << 13; s ^= s >> 17; s ^= s << 5;
4425 return static_cast<double>(s) * (2.0 / 4294967296.0) - 1.0;
4441 const size_t c =
static_cast<size_t>(ch);
4442 double gain =
static_cast<double>(grDb);
4448 const double behind = std::abs(heard) - std::abs(gain);
4449 if (behind <= 0.0 || (heard > 0.0) != (gain > 0.0))
4454 if (gain == 0.0 && std::abs(heard) < 1e-6) heard = 0.0;
4462 if (gain == 0.0 && std::abs(low) < 1e-6) low = 0.0;
4472 if (gain == 0.0 && std::abs(first) < 1e-6 && std::abs(second) < 1e-6)
4479 return static_cast<T
>(gain);
4491 const double shown =
static_cast<double>(
gainReductionDb_.load(std::memory_order_relaxed));
4517 T effectiveRatio = ratio;
4521 if (inputDb >= thresh)
return T(0);
4522 boost = (thresh - inputDb) * (T(1) - T(1) / effectiveRatio);
4526 T halfKnee = knee / T(2);
4527 T lower = thresh - halfKnee;
4528 T upper = thresh + halfKnee;
4530 if (inputDb >= upper)
return T(0);
4531 if (inputDb <= lower)
4533 boost = (thresh - inputDb) * (T(1) - T(1) / effectiveRatio);
4537 T x = upper - inputDb;
4538 boost = (T(1) - T(1) / effectiveRatio) * x * x / (T(2) * knee);
4542 const T silenceGuard = std::clamp((guardDb - (thresh - T(60))) / T(20), T(0), T(1));
4543 return boost * silenceGuard;
4573 const T a = r - T(1);
4576 if (eOut <= T(0))
return { T(0), T(0) };
4577 return { -a * eOut, a };
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 };
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) };
4610 const T eOut = outDb - thresh;
4614 if (
profileOf(charType).ratioGrowthDb > T(0))
4616 for (
int pass = 0; pass < 2; ++pass)
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));
4649 const T e = thresh - outDb;
4650 if (e <= T(0))
return { T(0), T(0) };
4651 return { a * e * guard, a * guard };
4654 const T eu = thresh + knee / T(2) - outDb;
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 };
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 };
4695 T ratio, T knee,
Character charType)
const noexcept
4699 const T halfW = w / T(2);
4700 const T a = r - T(1);
4703 T e = inDb + k - thresh;
4704 if (e <= ((w > T(0)) ? -halfW : T(0)))
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 };
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 };
4743 T thresh, T ratio, T knee)
noexcept
4769 const bool dual = wFast < 1.0;
4780 const T range =
rangeDb_.load(std::memory_order_relaxed);
4781 const T slowTarget = std::clamp(
4784 const double st =
static_cast<double>(slowTarget);
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;
4797 const bool charging = st < slow;
4798 slow = st + (charging ? coeffs.charge : coeffs.slowRelease) * (slow - st);
4799 if (
atRest(slow, st)) slow = 0.0;
4805 const T shownPrev =
static_cast<T
>(dual ? wFast * fast + (1.0 - wFast) * slow : fast);
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;
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);
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);
4833 if (bounded != shown)
4836 const double sh =
static_cast<double>(bounded);
4853 [[nodiscard]]
static bool atRest(
double envelope,
double target)
noexcept
4855 return std::abs(envelope) < 1e-4 && std::abs(target) < 1e-4;
4893 T loopSlope = T(-1),
double loopDelay = 0.0) noexcept
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);
4909 if (loopSlope >= T(0))
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);
4944 [[nodiscard]]
static double branchingStep(
double y,
double tgt,
double cDown,
double cUp)
noexcept
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);
4961 [[nodiscard]]
double ballisticsStep(
double tgt,
double& fast,
double& slow,
double& mid,
double& deep,
4962 double attCoeff,
double relCoeff)
const noexcept
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
4975 if (
atRest(fast, tgt)) fast = 0.0;
4987 if (
atRest(mid, tgt)) mid = 0.0;
4989 if (
atRest(deep, tgt)) deep = 0.0;
4995 if (
atRest(slow, tgt)) slow = 0.0;
4999 return w * fast + (1.0 - w) * slow;
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);
5097 double holdCoeff)
const noexcept
5103 [[nodiscard]]
static double decoupledCore(
double tgt,
double& hold,
double& fast,
double holdCoeff,
5104 double attCoeff,
double smoothCoeff)
noexcept
5109 hold = std::min(tgt, tgt + holdCoeff * (hold - tgt));
5110 if (
atRest(hold, tgt)) hold = 0.0;
5116 if (
atRest(fast, hold)) fast = 0.0;
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);
5138 double lo = 1e-6 * releaseMs, hi = releaseMs;
5139 for (
int it = 0; it < 48; ++it)
5141 const double mid = 0.5 * (lo + hi);
5142 if (remaining(mid) < target) lo = mid;
else hi = mid;
5144 return 0.5 * (lo + hi);
5174 for (
size_t ch = 0; ch < static_cast<size_t>(
kMaxChannels); ++ch)
5200 auto& h =
interp_[
static_cast<size_t>(ch)];
5205 const T* window = &h.x[h.at + 1];
5214 [[nodiscard]] T
heldBack(T grDb,
int g,
double delay,
bool run)
noexcept
5216 if (!run)
return grDb;
5217 auto& line =
gainDelay_[
static_cast<size_t>(g)];
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;
5233 const double goal =
static_cast<double>(target);
5262 T thresh, T ratio, T knee)
noexcept
5264 const int stepsEach =
kSubsteps / count;
5265 const double share = 1.0 / stepsEach;
5266 const size_t c =
static_cast<size_t>(ch);
5275 for (
int j = 0; j < count; ++j)
5277 const double to =
static_cast<double>(levelDb[j]);
5278 for (
int s = 1; s <= stepsEach; ++s)
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);
5288 return (bounded != shown) ? bounded :
static_cast<T
>(sum * (1.0 /
kSubsteps));
5292 T guardDb = levelDb[0];
5293 for (
int j = 1; j < count; ++j) guardDb = std::max(guardDb, levelDb[j]);
5301 const T range =
rangeDb_.load(std::memory_order_relaxed);
5302 const int soft =
rangeShape_.load(std::memory_order_relaxed);
5311 double deepest = 0.0;
5312 for (
int j = 0; j < count; ++j)
5315 computeGain(levelDb[j], thresh, ratio, knee, cfg.charType, cfg.modeType, guardDb),
5317 deepest = (j == 0) ? targets[j] : std::min(deepest, targets[j]);
5328 for (
int j = 0; j < count; ++j)
5330 const double to = targets[j];
5331 for (
int s = 1; s <= stepsEach; ++s)
5333 const double at = last + (to - last) * (s * share);
5334 sum += cfg.decoupled
5342 const double mean = sum * (1.0 /
kSubsteps);
5383 bool splitAdaptive)
const noexcept
5402 for (
size_t ch = 0; ch < static_cast<size_t>(
kMaxChannels); ++ch)
5421 const double x =
static_cast<double>(key);
5452 double balance,
double share)
const noexcept
5456 const double depth = std::abs(fast);
5457 state.sustained +=
sustainRate_ * (depth - state.sustained);
5459 const double held = std::min(state.sustained / (depth +
kSustainFloorDb), 1.0);
5460 const double sustain = held * held;
5462 const double excess = std::max(fast - target, 0.0);
5463 const double close = 1.0 - std::min(excess * (1.0 /
kFullAttackDb), 1.0);
5466 const double speed = share * (2.0 + tilt) / (2.0 - tilt);
5482 double balance)
const noexcept
5486 if (
atRest(fast, target)) fast = 0.0;
5529 bool decoupled,
bool loop)
noexcept
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));
5595 [[nodiscard]]
static double restingGain(
const double* target,
const double* weight,
int count,
5596 double attackRate,
double releaseRate)
noexcept
5598 double lo = target[0], hi = target[0];
5599 for (
int i = 1; i < count; ++i)
5601 lo = std::min(lo, target[i]);
5602 hi = std::max(hi, target[i]);
5604 for (
int pass = 0; pass < 48 && hi - lo > 1e-6; ++pass)
5606 const double at = 0.5 * (lo + hi);
5607 double below = 0.0, above = 0.0;
5608 for (
int i = 0; i < count; ++i)
5610 const double d = target[i] - at;
5611 if (d < 0.0) below -= weight[i] * d;
5612 else above += weight[i] * d;
5614 if (attackRate * below > releaseRate * above) hi = at;
5617 return 0.5 * (lo + hi);
5631 return 1.6 * std::cbrt(10.0 / std::clamp(windowMs, 1.0, 500.0));
5645 switch (key.detType)
5649 const double ms = std::clamp(
static_cast<double>(key.window), 1.0, 500.0);
5686 const double spread = window ?
windowSpreadDb(
static_cast<double>(key.window)) : 0.0;
5692 double levelDb = rmsDb;
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;
5704 weight[i] = std::exp(-0.5 * t * t);
5705 if (envelope) weight[i] *= t;
5707 weight[i] *= std::pow(std::erf(t * 0.70710678118654752),
kTruePeakSamples - 1.0);
5709 levelDb += 20.0 * std::log10(hybrid ? std::max(t, std::numbers::sqrt2) : t)
5712 const T gain =
computeGain(
static_cast<T
>(levelDb), key.thresh, key.ratio, key.knee, key.charType,
5714 target[i] =
static_cast<double>(
holdAndRange(gain, key.range, 0, held, counter, key.soft));
5718 double settled = 0.0;
5721 settled =
restingGain(target, weight, count, 1.0, 1.0 - key.hold);
5725 settled =
restingGain(target, weight, count, 1.0 - key.attack, 1.0 - key.release);
5726 const double w =
static_cast<double>(key.fastWeight);
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
5736 settled = (1.0 - memory) * settled + memory * rest;
5739 const double makeup = -
static_cast<double>(key.amount) * settled;
5750 const double scFreq = std::clamp(
5751 static_cast<double>(
scHpfFreq_.load(std::memory_order_relaxed)),
5788 int maxLen =
static_cast<int>(
rmsBuffers_[0].size());
6076 std::array<InterpHistory, kMaxChannels>
interp_ {};
Non-owning view over audio channel data.
Owning audio buffer with contiguous, 32-byte aligned storage.
Biquad filter using Transposed Direct Form II (TDF-II) with thread-safe updates.
void setCoeffsNow(const BiquadCoeffs &c) noexcept
Stream-owner direct set: makes c the active set immediately.
void reset() noexcept
Resets all per-channel filter states to zero to avoid ringing/clicks.
T processSample(T input, int channel) noexcept
Processes a single sample for a specific channel.
Emphasis, static saturators and de-emphasis, with drift, sag and noise.
High-fidelity modular compressor designed for real-time applications.
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.
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.
@ 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.
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.
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.
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.
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...
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.
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).
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()).
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).
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
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.
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).
T processSample(T input, int channel) noexcept
Processes a single sample on one channel.
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.
@ 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()).
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).
void reset() noexcept
Resets all internal DSP history, states, and buffers to neutral.
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.
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).
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()).
@ 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
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).
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).
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()).
@ 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...
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).
@ 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()).
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.
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()).
@ 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).
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.
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).
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()).
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.
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.
@ 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).
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.
Zero-allocation parameter smoother for real-time audio.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
bool isValid() const noexcept
uint32_t processorId() const noexcept
Serializes key/value parameters into a versioned blob.
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
void write(const char *key, float value)
Writes a float parameter.
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.
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...
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
T fastDecay(T x) noexcept
e^(-x) for x >= 0 by a rational approximation: the coefficient of a one-pole whose time changes every...
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Describes the audio environment for a DSP processor.
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
int maxBlockSize
Maximum number of samples per processing block.
double sampleRate
Sample rate in Hz.
static BiquadCoeffs makeHighShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth high shelf (see makeLowShelfMatched()).
static BiquadCoeffs makeLowShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth low shelf (Vicanek, "Matched Two-Pole Digital Shelving Filters",...
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.
T chargeCeilMs
...held to these.
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.
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
Character charType
Character.
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.