DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
NoiseGate.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
57#include "../Core/DspMath.h"
58#include "../Core/AudioSpec.h"
59#include "../Core/AudioBuffer.h"
60#include "../Core/DenormalGuard.h"
61#include "../Core/KeyEqualizer.h"
62#include "../Core/RingBuffer.h"
63#include "../Core/StateBlob.h"
64
65#include <algorithm>
66#include <array>
67#include <atomic>
68#include <cmath>
69#include <cstddef>
70#include <cstdint>
71#include <numbers>
72#include <utility>
73#include <vector>
74
75namespace dspark {
76
83template <FloatType T>
85{
86public:
87 ~NoiseGate() = default; // Removed virtual to prevent vptr injection in header-only DSP
88
90 enum class State
91 {
92 Closed,
93 Open,
94 Hold
95 };
96
98 enum class GateMode
99 {
100 Amplitude,
101 Frequency
102 };
103
115 void prepare(double sampleRate, int numChannels = 2) noexcept
116 {
117 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate)) return; // NaN/inf-safe gate
118 sampleRate_ = sampleRate;
119 lookaheadChannels_ = std::clamp(numChannels, 1, kMaxLookaheadChannels);
120 maxLookaheadSamples_ = static_cast<int>(std::ceil(sampleRate * kMaxLookaheadMs / 1000.0));
121 for (int ch = 0; ch < lookaheadChannels_; ++ch)
122 lookahead_[static_cast<size_t>(ch)].prepare(maxLookaheadSamples_ + 1);
123 keyEq_.prepare(sampleRate);
125 syncParams();
126 reset();
127 }
128
133 void prepare(const AudioSpec& spec) noexcept { prepare(spec.sampleRate, spec.numChannels); }
134
144 void processBlock(AudioBufferView<T> buffer) noexcept
145 {
146 DenormalGuard guard;
148
149 const int nCh = buffer.getNumChannels();
150 const int nS = buffer.getNumSamples();
151 if (nCh <= 0 || nS <= 0) return;
152
153 const bool freqMode = (cachedGateMode_ == GateMode::Frequency);
154 // A band of the key's equalizer on the middle or on the sides of a
155 // pair takes the key a frame at a time.
156 const bool keyFrames = keyOn_ && nCh == 2 && keyEq_.isPlaced();
157
158 for (int i = 0; i < nS; ++i)
159 {
160 // Stereo / N-channel linked detection: peak across ALL channels.
161 // The sidechain HPF runs per channel BEFORE the peak link; channels
162 // beyond the HPF state array are detected unfiltered (sharing a
163 // filter between channels would corrupt its history).
164 T level = T(0);
165 T det0 = T(0);
166 if (keyFrames)
167 level = placedKeyFrame([&](int ch) noexcept { return buffer.getChannel(ch)[i]; }, det0);
168 else
169 for (int ch = 0; ch < nCh; ++ch)
170 {
171 T s = detectorSafe(buffer.getChannel(ch)[i]);
173 s = applyScHpf(s, ch);
174 if (ch < kMaxScChannels)
175 {
176 if (keyOn_) s = keyEq_.processSample(s, ch);
177 heard_[static_cast<size_t>(ch)] = s;
178 }
179 if (ch == 0) det0 = s;
180 level = std::max(level, std::abs(s));
181 }
182 if (keyOn_) keyEq_.advance(1);
183
184 // Zero-crossing runs on the same (filtered) signal the detector
185 // sees, exactly like the per-sample path.
187
188 T envelope = computeEnvelopeFollower(level);
189 updateStateMachine(envelope);
190 T gain = getCurrentGain();
192
193 for (int ch = 0; ch < nCh; ++ch)
194 {
195 T* d = buffer.getChannel(ch);
196 const T x = delayed(d[i], ch);
197 // Frequency mode keeps per-channel filter state only for the first
198 // kMaxChannels; any extra channels fall back to amplitude gating.
199 d[i] = (freqMode && ch < kMaxChannels) ? applyFrequencyGate(x, ch)
200 : x * gain;
201 // Key listen: what the detector heard goes out instead.
202 if (listen_ && ch < kMaxScChannels) d[i] = heard_[static_cast<size_t>(ch)];
203 }
204 }
205 }
206
217 void processBlock(AudioBufferView<T> audio, AudioBufferView<T> sidechain) noexcept
218 {
219 // A sidechain shorter than the audio block (or with no channels)
220 // would be read past its end: key from the audio itself instead.
221 if (sidechain.getNumChannels() <= 0 || sidechain.getNumSamples() < audio.getNumSamples())
222 {
223 processBlock(audio);
224 return;
225 }
226
227 DenormalGuard guard;
229
230 const int nCh = audio.getNumChannels();
231 const int nS = audio.getNumSamples();
232 const int scCh = sidechain.getNumChannels();
233 if (nCh <= 0 || nS <= 0) return;
234
235 // NOTE: no std::assume_aligned - view pointers are not guaranteed 32-byte
236 // aligned (sub-views / driver buffers), and assuming so is UB. __restrict
237 // still conveys no-aliasing to the compiler for the mono fast path.
238 if (nCh == 1 && scCh == 1)
239 {
240 T* __restrict outL = audio.getChannel(0);
241 const T* __restrict scL = sidechain.getChannel(0);
242 for (int i = 0; i < nS; ++i)
243 outL[i] = processSampleInternal(outL[i], scL[i], 0);
244 }
245 else
246 {
247 const bool freqMode = (cachedGateMode_ == GateMode::Frequency);
248 const bool keyFrames = keyOn_ && scCh == 2 && keyEq_.isPlaced();
249
250 for (int i = 0; i < nS; ++i)
251 {
252 T scMax = T(0);
253 T det0 = T(0);
254 if (keyFrames)
255 scMax = placedKeyFrame([&](int c) noexcept { return sidechain.getChannel(c)[i]; }, det0);
256 else
257 for (int c = 0; c < scCh; ++c)
258 {
259 T s = detectorSafe(sidechain.getChannel(c)[i]);
261 s = applyScHpf(s, c);
262 if (c < kMaxScChannels)
263 {
264 if (keyOn_) s = keyEq_.processSample(s, c);
265 heard_[static_cast<size_t>(c)] = s;
266 }
267 if (c == 0) det0 = s;
268 T a = std::abs(s);
269 if (a > scMax) scMax = a;
270 }
271 if (keyOn_) keyEq_.advance(1);
272
274
275 T envelope = computeEnvelopeFollower(scMax);
276 updateStateMachine(envelope);
277 T gain = getCurrentGain();
279
280 for (int ch = 0; ch < nCh; ++ch)
281 {
282 T* d = audio.getChannel(ch);
283 const T x = delayed(d[i], ch);
284 d[i] = (freqMode && ch < kMaxChannels) ? applyFrequencyGate(x, ch)
285 : x * gain;
286 // Key listen: each channel plays its key (the last one when it has none).
287 if (listen_)
288 d[i] = heard_[static_cast<size_t>(std::min({ ch, scCh - 1, kMaxScChannels - 1 }))];
289 }
290 }
291 }
292 }
293
294 // -- Parameters (Thread-Safe Setters) -----------------------------------------
295
300 void setThreshold(T dB) noexcept
301 {
302 if (!std::isfinite(dB)) return;
303 threshold_.store(dB, std::memory_order_relaxed);
304 paramsDirty_.store(true, std::memory_order_release);
305 }
306
323 void setAutoThreshold(bool on) noexcept
324 {
325 autoThreshold_.store(on, std::memory_order_relaxed);
326 paramsDirty_.store(true, std::memory_order_release);
327 }
328
330 [[nodiscard]] bool isAutoThreshold() const noexcept { return autoThreshold_.load(std::memory_order_relaxed); }
331
336 void setHysteresis(T dB) noexcept
337 {
338 if (!std::isfinite(dB)) return;
339 hysteresis_.store(std::max(T(0), dB), std::memory_order_relaxed);
340 paramsDirty_.store(true, std::memory_order_release);
341 }
342
344 void setAttack(T ms) noexcept
345 {
346 if (!std::isfinite(ms)) return;
347 attackMs_.store(std::max(T(0.01), ms), std::memory_order_relaxed);
348 paramsDirty_.store(true, std::memory_order_release);
349 }
350
352 void setHold(T ms) noexcept
353 {
354 if (!std::isfinite(ms)) return;
355 holdMs_.store(std::max(T(0), ms), std::memory_order_relaxed);
356 paramsDirty_.store(true, std::memory_order_release);
357 }
358
360 void setRelease(T ms) noexcept
361 {
362 if (!std::isfinite(ms)) return;
363 releaseMs_.store(std::max(T(0.01), ms), std::memory_order_relaxed);
364 paramsDirty_.store(true, std::memory_order_release);
365 }
366
371 void setRange(T dB) noexcept
372 {
373 if (!std::isfinite(dB)) return;
374 rangeDb_.store(std::min(T(0), dB), std::memory_order_relaxed);
375 paramsDirty_.store(true, std::memory_order_release);
376 }
377
379 void setDuckMode(bool enabled) noexcept
380 {
381 duckMode_.store(enabled, std::memory_order_relaxed);
382 paramsDirty_.store(true, std::memory_order_release);
383 }
384
386 void setGateMode(GateMode mode) noexcept
387 {
388 const int m = std::clamp(static_cast<int>(mode), 0, static_cast<int>(GateMode::Frequency));
389 gateMode_.store(static_cast<GateMode>(m), std::memory_order_relaxed);
390 paramsDirty_.store(true, std::memory_order_release);
391 }
392
404 void setLookahead(T ms) noexcept
405 {
406 if (!std::isfinite(ms)) return;
407 lookaheadMs_.store(std::clamp(ms, T(0), static_cast<T>(kMaxLookaheadMs)), std::memory_order_relaxed);
408 paramsDirty_.store(true, std::memory_order_release);
409 }
410
412 [[nodiscard]] T getLookahead() const noexcept { return lookaheadMs_.load(std::memory_order_relaxed); }
413
415 [[nodiscard]] int getLatency() const noexcept
416 {
417 return lookaheadSamplesFor(lookaheadMs_.load(std::memory_order_relaxed));
418 }
419
421 void setAdaptiveHold(bool enabled) noexcept
422 {
423 adaptiveHold_.store(enabled, std::memory_order_relaxed);
424 paramsDirty_.store(true, std::memory_order_release);
425 }
426
437 void setSidechainHPF(bool enabled, double cutoffHz = 80.0) noexcept
438 {
439 scHpfEnabled_.store(enabled, std::memory_order_relaxed);
440 if (std::isfinite(cutoffHz) && cutoffHz > 0.0)
441 scHpfFreq_.store(static_cast<T>(cutoffHz), std::memory_order_relaxed);
442 paramsDirty_.store(true, std::memory_order_release);
443 }
444
448 using KeyBand = typename KeyEq::Band;
450 using KeyShape = typename KeyEq::Shape;
453
474 void setSidechainBand(int band, const KeyBand& settings) noexcept { keyEq_.setBand(band, settings); }
475
477 [[nodiscard]] KeyBand getSidechainBand(int band) const noexcept { return keyEq_.getBand(band); }
478
480 [[nodiscard]] typename KeyEq::Response getSidechainResponse() const noexcept { return keyEq_.getResponse(); }
481
491 void setSidechainListen(bool on) noexcept { scListen_.store(on, std::memory_order_relaxed); }
492
494 [[nodiscard]] bool isSidechainListen() const noexcept { return scListen_.load(std::memory_order_relaxed); }
495
496 // -- Single Sample Processing -------------------------------------------------
497
509 [[nodiscard]] T processSample(T input) noexcept
510 {
512 return processSampleInternal(input, input, 0);
513 }
514
521 [[nodiscard]] T processSampleWithSidechain(T input, T sidechain) noexcept
522 {
524 return processSampleInternal(input, sidechain, 0);
525 }
526
530 void reset() noexcept
531 {
534 envelopeState_ = T(0);
535 holdCounter_ = 0;
537 scHpfState_.fill(T(0));
538 scHpfPrev_.fill(T(0));
539 keyEq_.reset();
540 for (int ch = 0; ch < kMaxChannels; ++ch)
541 {
542 freqLpState_[ch] = T(0);
543 freqHpState_[ch] = T(0);
544 freqHpPrev_[ch] = T(0);
545 freqLpFreq_[ch] = T(20000);
546 freqHpFreq_[ch] = T(20);
547 }
548 zeroCrossCount_ = 0;
550 prevSign_ = false;
552 for (auto& line : lookahead_) line.reset();
554 }
555
556
558 [[nodiscard]] std::vector<uint8_t> getState() const
559 {
560 StateWriter w(stateId("GATE"), 1);
561 w.write("threshold", static_cast<float>(threshold_.load(std::memory_order_relaxed)));
562 w.write("hysteresis", static_cast<float>(hysteresis_.load(std::memory_order_relaxed)));
563 w.write("attack", static_cast<float>(attackMs_.load(std::memory_order_relaxed)));
564 w.write("hold", static_cast<float>(holdMs_.load(std::memory_order_relaxed)));
565 w.write("release", static_cast<float>(releaseMs_.load(std::memory_order_relaxed)));
566 w.write("range", static_cast<float>(rangeDb_.load(std::memory_order_relaxed)));
567 w.write("duck", duckMode_.load(std::memory_order_relaxed));
568 w.write("gateMode", static_cast<int32_t>(gateMode_.load(std::memory_order_relaxed)));
569 w.write("adaptiveHold", adaptiveHold_.load(std::memory_order_relaxed));
570 w.write("scHpf", scHpfEnabled_.load(std::memory_order_relaxed));
571 w.write("scHpfFreq", static_cast<float>(scHpfFreq_.load(std::memory_order_relaxed)));
572 w.write("lookahead", static_cast<float>(lookaheadMs_.load(std::memory_order_relaxed)));
573 w.write("autoThreshold", autoThreshold_.load(std::memory_order_relaxed));
574 keyEq_.writeState(w, "key");
575 return w.blob();
576 }
577
579 bool setState(const uint8_t* data, size_t size)
580 {
581 StateReader r(data, size);
582 if (!r.isValid() || r.processorId() != stateId("GATE")) return false;
583 setThreshold(static_cast<T>(r.read("threshold", -40.0f)));
584 setHysteresis(static_cast<T>(r.read("hysteresis", 4.0f)));
585 setAttack(static_cast<T>(r.read("attack", 0.5f)));
586 setHold(static_cast<T>(r.read("hold", 50.0f)));
587 setRelease(static_cast<T>(r.read("release", 100.0f)));
588 setRange(static_cast<T>(r.read("range", -80.0f)));
589 setDuckMode(r.read("duck", false));
590 setGateMode(static_cast<GateMode>(r.read("gateMode", 0)));
591 setAdaptiveHold(r.read("adaptiveHold", false));
592 setSidechainHPF(r.read("scHpf", false),
593 static_cast<double>(r.read("scHpfFreq", 80.0f)));
594 setLookahead(static_cast<T>(r.read("lookahead", 0.0f)));
595 setAutoThreshold(r.read("autoThreshold", false));
596 keyEq_.readState(r, "key");
597 return true;
598 }
599
600protected:
601 static constexpr int kMaxChannels = 2;
602
603 void syncParamsIfDirty() noexcept
604 {
605 // Plain load first: the exchange RMW is only paid when a publication
606 // is actually pending (this runs per sample in the per-sample path).
607 if (paramsDirty_.load(std::memory_order_acquire)
608 && paramsDirty_.exchange(false, std::memory_order_acquire))
609 syncParams();
610 // The equalizer of the key takes its settings here too.
611 keyOn_ = keyEq_.sync();
612 listen_ = scListen_.load(std::memory_order_relaxed);
613 }
614
615 void syncParams() noexcept
616 {
617 T fs = static_cast<T>(sampleRate_);
618 if (!(fs > T(0))) return; // NaN-safe (prepare() already gates the rate)
619
620 // Cache logical switches to prevent atomic loads in hot path
621 cachedDuck_ = duckMode_.load(std::memory_order_relaxed);
622 cachedGateMode_ = gateMode_.load(std::memory_order_relaxed);
623 cachedAdaptiveHold_ = adaptiveHold_.load(std::memory_order_relaxed);
624 cachedScHpfEnabled_ = scHpfEnabled_.load(std::memory_order_relaxed);
625 cachedAutoThreshold_ = autoThreshold_.load(std::memory_order_relaxed);
626 // The reference of the automatic threshold falls by a factor per
627 // sample (1 dB per second; a quarter of that while the key is quiet).
628 autoFall_ = std::pow(10.0, -kAutoRefFallDb / (20.0 * sampleRate_));
629 autoFallQuiet_ = std::pow(10.0, -kAutoRefFallDb * kAutoRefQuiet / (20.0 * sampleRate_));
630
631 // Compute thresholds in LINEAR domain to eliminate log10 in hot path
632 T thDb = threshold_.load(std::memory_order_relaxed);
633 T hystDb = hysteresis_.load(std::memory_order_relaxed);
636 cachedRangeLinear_ = decibelsToGain(rangeDb_.load(std::memory_order_relaxed));
637
638 T attMs = std::max(attackMs_.load(std::memory_order_relaxed), T(0.01));
639 T relMs = std::max(releaseMs_.load(std::memory_order_relaxed), T(0.01));
640 attackCoeff_ = T(1) - std::exp(T(-1) / (fs * attMs / T(1000)));
641 releaseCoeff_ = T(1) - std::exp(T(-1) / (fs * relMs / T(1000)));
642
643 // Fixed ~2ms release for the detector envelope (prevents bass chattering)
644 detectorReleaseCoeff_ = T(1) - std::exp(T(-1) / (fs * T(0.002)));
645
646 // Parameter smoothing coefficient for Frequency Mode (prevents hardcoded 0.001 dependency)
647 freqSmoothCoeff_ = T(1) - std::exp(T(-1) / (fs * T(0.02))); // 20ms smoothing
648
649 // Cap the sample count in double before the cast (a cast of an
650 // out-of-int-range double is undefined behaviour).
651 T hMs = std::max(holdMs_.load(std::memory_order_relaxed), T(0));
652 holdSamples_ = static_cast<int>(std::min(fs * static_cast<double>(hMs) / 1000.0, 1.0e9));
653
654 // The setter rejects invalid cutoffs; the clamp keeps the coefficient
655 // in the stable range even against a hostile in-memory value.
656 const double scFreq = std::clamp(
657 static_cast<double>(scHpfFreq_.load(std::memory_order_relaxed)),
658 1.0, sampleRate_ * 0.45);
659 scHpfCoeff_ = static_cast<T>(std::exp(-std::numbers::pi * 2.0 * scFreq / static_cast<double>(fs)));
660 scHpfA0_ = (T(1) + scHpfCoeff_) / T(2); // Normalization to prevent high-frequency boost
661
662 cachedNyquist_ = static_cast<T>(fs * 0.5);
663 cachedFsInvPi2_ = static_cast<T>(std::numbers::pi * 2.0 / fs);
664
665 lookaheadSamples_ = lookaheadSamplesFor(lookaheadMs_.load(std::memory_order_relaxed));
666 }
667
669 [[nodiscard]] int lookaheadSamplesFor(T ms) const noexcept
670 {
671 const double samples = std::round(static_cast<double>(ms) * sampleRate_ / 1000.0);
672 return std::clamp(static_cast<int>(std::min(samples, 1.0e9)), 0, maxLookaheadSamples_);
673 }
674
677 [[nodiscard]] inline T delayed(T x, int ch) noexcept
678 {
679 if (lookaheadSamples_ <= 0 || ch >= lookaheadChannels_) return x;
680 auto& line = lookahead_[static_cast<size_t>(ch)];
681 line.push(x);
682 return line.read(lookaheadSamples_);
683 }
684
688 [[nodiscard]] T computeEnvelopeFollower(T rawLevel) noexcept
689 {
690 if (rawLevel > envelopeState_)
691 envelopeState_ = rawLevel; // Instant attack for precise triggering
692 else
694
695 return envelopeState_;
696 }
697
698 void updateStateMachine(T envelopeLinear) noexcept
699 {
700 T openAt = cachedThresholdLinear_;
701 T closeAt = cachedCloseThresholdLinear_;
703 {
704 // The thresholds count from a reference that follows the level:
705 // up at once, down slowly, and a quarter as fast while the level
706 // is under the closing threshold.
707 const double level = static_cast<double>(envelopeLinear);
708 const bool quiet = level < static_cast<double>(closeAt) * autoRef_;
709 autoRef_ = std::max({ level, autoRef_ * (quiet ? autoFallQuiet_ : autoFall_), kAutoRefFloor });
710 openAt *= static_cast<T>(autoRef_);
711 closeAt *= static_cast<T>(autoRef_);
712 }
713 bool above = envelopeLinear > openAt;
714 bool below = envelopeLinear < closeAt;
715
716 if (cachedDuck_)
717 std::swap(above, below);
718
719 int effectiveHoldSamples = holdSamples_;
720 if (cachedAdaptiveHold_ && estimatedPeriod_ > effectiveHoldSamples)
721 effectiveHoldSamples = estimatedPeriod_;
722
723 switch (state_)
724 {
725 case State::Closed:
726 if (above) state_ = State::Open;
727 break;
728
729 case State::Open:
730 if (below)
731 {
733 holdCounter_ = effectiveHoldSamples;
734 }
735 break;
736
737 case State::Hold:
738 if (above)
739 {
741 }
742 else
743 {
744 --holdCounter_;
745 if (holdCounter_ <= 0)
747 }
748 break;
749 }
750 }
751
752 void updateZeroCrossing(T sample) noexcept
753 {
754 bool sign = sample >= T(0);
755 if (sign != prevSign_)
757 prevSign_ = sign;
758
761 {
762 if (zeroCrossCount_ > 0)
764 else
766
767 zeroCrossCount_ = 0;
769 }
770 }
771
772 [[nodiscard]] inline T getCurrentGain() noexcept
773 {
774 T targetGain = (state_ == State::Open || state_ == State::Hold) ? T(1) : cachedRangeLinear_;
775
776 // Fast path for established states to avoid unnecessary math
777 if (targetGain == gateGain_) return gateGain_;
778
779 T coeff = (targetGain > gateGain_) ? attackCoeff_ : releaseCoeff_;
780 gateGain_ += coeff * (targetGain - gateGain_);
781 return gateGain_;
782 }
783
784 [[nodiscard]] T applyFrequencyGate(T input, int ch) noexcept
785 {
786 // A non-finite sample passes through without touching the filter
787 // state, where it would latch for good.
788 if (!std::isfinite(input)) return input;
789 T gateOpenness = gateGain_;
790
791 T targetLp = T(20) + (cachedNyquist_ - T(20)) * gateOpenness;
792 T targetHp = T(20) + (cachedNyquist_ * T(0.4)) * (T(1) - gateOpenness);
793
794 freqLpFreq_[ch] += freqSmoothCoeff_ * (targetLp - freqLpFreq_[ch]);
795 freqHpFreq_[ch] += freqSmoothCoeff_ * (targetHp - freqHpFreq_[ch]);
796
797 // Bilinear/Euler approximation to avoid std::exp() in the audio inner loop
798 T lpCoeff = std::min(T(1), freqLpFreq_[ch] * cachedFsInvPi2_);
799 freqLpState_[ch] += lpCoeff * (input - freqLpState_[ch]);
800
801 T hpCoeff = T(1) - std::min(T(1), freqHpFreq_[ch] * cachedFsInvPi2_);
802 T hpOut = hpCoeff * (freqHpState_[ch] + freqLpState_[ch] - freqHpPrev_[ch]);
803
804 freqHpPrev_[ch] = freqLpState_[ch];
805 freqHpState_[ch] = hpOut;
806
807 return hpOut;
808 }
809
811 [[nodiscard]] T applyScHpf(T input, int ch) noexcept
812 {
813 T output = scHpfA0_ * (input - scHpfPrev_[ch]) + scHpfCoeff_ * scHpfState_[ch];
814 scHpfPrev_[ch] = input;
815 scHpfState_[ch] = output;
816 return output;
817 }
818
821 [[nodiscard]] static T detectorSafe(T x) noexcept { return std::isfinite(x) ? x : T(0); }
822
831 template <typename Sample>
832 [[nodiscard]] T placedKeyFrame(Sample sample, T& det0) noexcept
833 {
834 for (int ch = 0; ch < 2; ++ch)
835 {
836 T s = detectorSafe(sample(ch));
837 if (cachedScHpfEnabled_) s = applyScHpf(s, ch);
838 heard_[static_cast<size_t>(ch)] = s;
839 }
840 keyEq_.processFrame(heard_.data(), 2);
841 det0 = heard_[0];
842 return std::max(std::abs(heard_[0]), std::abs(heard_[1]));
843 }
844
845 [[nodiscard]] T processSampleInternal(T input, T sidechain, int ch) noexcept
846 {
847 sidechain = detectorSafe(sidechain);
849 sidechain = applyScHpf(sidechain, ch);
850 if (keyOn_ && ch < kMaxScChannels)
851 {
852 // The equalizer's clock moves once per frame, on channel 0.
853 if (ch == 0) keyEq_.advance(1);
854 sidechain = keyEq_.processSample(sidechain, ch);
855 }
856
857 T rawLevel = std::abs(sidechain);
858
860 updateZeroCrossing(sidechain);
861
862 T envelope = computeEnvelopeFollower(rawLevel);
863 updateStateMachine(envelope);
864 input = delayed(input, ch);
865
866 // The listened key: late by the lookahead and under full scale.
868
870 {
871 (void)getCurrentGain();
872 const T shaped = applyFrequencyGate(input, ch);
873 return listen_ ? sidechain : shaped;
874 }
875
876 const T gated = input * getCurrentGain();
877 return listen_ ? sidechain : gated;
878 }
879
880 double sampleRate_ = 48000.0;
881
882 std::atomic<T> threshold_ { T(-40) };
883 std::atomic<T> hysteresis_ { T(4) };
884 std::atomic<T> attackMs_ { T(0.5) };
885 std::atomic<T> holdMs_ { T(50) };
886 std::atomic<T> releaseMs_ { T(100) };
887 std::atomic<T> rangeDb_ { T(-80) };
888 std::atomic<bool> duckMode_ { false };
889 std::atomic<GateMode> gateMode_ { GateMode::Amplitude };
890 std::atomic<bool> adaptiveHold_ { false };
891 std::atomic<bool> paramsDirty_ { true };
892
893 std::atomic<bool> scHpfEnabled_ { false };
894 std::atomic<T> scHpfFreq_ { T(80) };
895
896 // Lookahead (audio delayed; detection runs on the undelayed signal).
897 static constexpr double kMaxLookaheadMs = 10.0;
898 static constexpr int kMaxLookaheadChannels = 16;
899 std::atomic<T> lookaheadMs_ { T(0) };
903 std::array<RingBuffer<T>, kMaxLookaheadChannels> lookahead_ {};
904
905 // Cached internal variables
908 T cachedRangeLinear_ = T(0.0001);
909 bool cachedDuck_ = false;
913 T cachedNyquist_ = T(24000);
915
916 static constexpr int kMaxScChannels = 16;
917 T scHpfCoeff_ = T(0.995);
918 T scHpfA0_ = T(0.9975);
919 std::array<T, kMaxScChannels> scHpfState_ {};
920 std::array<T, kMaxScChannels> scHpfPrev_ {};
923 std::atomic<bool> scListen_ { false };
924 bool keyOn_ = false;
925 bool listen_ = false;
926 std::array<T, kMaxScChannels> heard_ {};
927
928 T attackCoeff_ = T(0);
931
932 // Automatic threshold (setAutoThreshold()).
933 static constexpr double kAutoRefFallDb = 1.0;
934 static constexpr double kAutoRefQuiet = 0.25;
935 static constexpr double kAutoRefFloor = 1e-5;
936 std::atomic<bool> autoThreshold_ { false };
939 double autoFall_ = 1.0;
940 double autoFallQuiet_ = 1.0;
941
942 // Fast Envelope Follower State
945
947 T gateGain_ = T(0);
949
951 std::array<T, kMaxChannels> freqLpState_ {};
952 std::array<T, kMaxChannels> freqHpState_ {};
953 std::array<T, kMaxChannels> freqHpPrev_ {};
954 std::array<T, kMaxChannels> freqLpFreq_ {};
955 std::array<T, kMaxChannels> freqHpFreq_ {};
956
957 static constexpr int kZeroCrossWindow = 2048;
960 bool prevSign_ = false;
962};
963
964} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
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.
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.
High-performance noise gate with state machine, hysteresis, and zero-allocation processing.
Definition NoiseGate.h:85
T getLookahead() const noexcept
Returns the lookahead in milliseconds.
Definition NoiseGate.h:412
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition NoiseGate.h:579
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an AudioBufferView in-place.
Definition NoiseGate.h:144
int getLatency() const noexcept
Latency in samples (the lookahead), correct right after setLookahead().
Definition NoiseGate.h:415
void prepare(double sampleRate, int numChannels=2) noexcept
Prepares the noise gate for processing.
Definition NoiseGate.h:115
std::array< T, kMaxScChannels > scHpfPrev_
Definition NoiseGate.h:920
static constexpr double kAutoRefFloor
The reference never goes under -100 dBFS.
Definition NoiseGate.h:935
std::array< T, kMaxChannels > freqLpState_
Definition NoiseGate.h:951
KeyEq keyEq_
Equalizer of the key, after the high-pass.
Definition NoiseGate.h:921
T applyFrequencyGate(T input, int ch) noexcept
Definition NoiseGate.h:784
T processSample(T input) noexcept
Processes a single mono sample.
Definition NoiseGate.h:509
void setLookahead(T ms) noexcept
Sets the lookahead: the audio is delayed so the gate opens (and closes) ahead of it....
Definition NoiseGate.h:404
void setSidechainHPF(bool enabled, double cutoffHz=80.0) noexcept
Configures sidechain High-Pass filter.
Definition NoiseGate.h:437
void setRange(T dB) noexcept
Sets maximum attenuation range.
Definition NoiseGate.h:371
int lookaheadChannels_
Channels with a prepared delay line.
Definition NoiseGate.h:902
static T detectorSafe(T x) noexcept
Non-finite detector samples read as silence (they would latch in the envelope and filter state).
Definition NoiseGate.h:821
std::array< T, kMaxScChannels > scHpfState_
Definition NoiseGate.h:919
std::atomic< bool > autoThreshold_
The thresholds count from the key's recent level.
Definition NoiseGate.h:936
void processBlock(AudioBufferView< T > audio, AudioBufferView< T > sidechain) noexcept
Processes audio with an external sidechain signal.
Definition NoiseGate.h:217
T processSampleWithSidechain(T input, T sidechain) noexcept
Processes a mono sample using an external sidechain.
Definition NoiseGate.h:521
KeyMonitor< T, 16 > keyMonitor_
The listened key: late by the lookahead, under full scale.
Definition NoiseGate.h:922
std::array< RingBuffer< T >, kMaxLookaheadChannels > lookahead_
Definition NoiseGate.h:903
static constexpr int kZeroCrossWindow
Definition NoiseGate.h:957
void setAttack(T ms) noexcept
Sets attack time in milliseconds. Non-finite values are ignored.
Definition NoiseGate.h:344
void updateStateMachine(T envelopeLinear) noexcept
Definition NoiseGate.h:698
std::atomic< T > lookaheadMs_
Definition NoiseGate.h:899
bool keyOn_
The equalizer has bands in the path (audio thread).
Definition NoiseGate.h:924
bool listen_
scListen_ as the audio thread took it.
Definition NoiseGate.h:925
void setRelease(T ms) noexcept
Sets release time in milliseconds. Non-finite values are ignored.
Definition NoiseGate.h:360
void prepare(const AudioSpec &spec) noexcept
Prepares from AudioSpec (unified API).
Definition NoiseGate.h:133
static constexpr int kMaxChannels
Definition NoiseGate.h:601
std::atomic< T > threshold_
Definition NoiseGate.h:882
void setHold(T ms) noexcept
Sets hold time in milliseconds. Non-finite values are ignored.
Definition NoiseGate.h:352
std::array< T, kMaxChannels > freqLpFreq_
Definition NoiseGate.h:954
void setGateMode(GateMode mode) noexcept
Selects the processing mode (Amplitude or Frequency; wild enum values clamp).
Definition NoiseGate.h:386
void updateZeroCrossing(T sample) noexcept
Definition NoiseGate.h:752
std::atomic< bool > scListen_
The key goes out instead of the audio.
Definition NoiseGate.h:923
GateMode
Operating mode for the gate processing.
Definition NoiseGate.h:99
@ Frequency
Gatelope-style: narrows bandpass dynamically instead of direct gain reduction.
@ Amplitude
Standard amplitude gain reduction (default).
~NoiseGate()=default
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition NoiseGate.h:558
KeyBand getSidechainBand(int band) const noexcept
The settings of a band of the key equalizer.
Definition NoiseGate.h:477
T placedKeyFrame(Sample sample, T &det0) noexcept
One frame of a two-channel key whose equalizer has bands on the middle or the sides: both channels ma...
Definition NoiseGate.h:832
std::array< T, kMaxScChannels > heard_
The key of each channel in this frame.
Definition NoiseGate.h:926
std::array< T, kMaxChannels > freqHpState_
Definition NoiseGate.h:952
double autoFallQuiet_
The same while the key is quiet.
Definition NoiseGate.h:940
void syncParamsIfDirty() noexcept
Definition NoiseGate.h:603
double autoFall_
Its fall per sample (a factor).
Definition NoiseGate.h:939
bool isAutoThreshold() const noexcept
Whether the threshold counts from the key's recent level (see setAutoThreshold()).
Definition NoiseGate.h:330
std::atomic< T > holdMs_
Definition NoiseGate.h:885
T processSampleInternal(T input, T sidechain, int ch) noexcept
Definition NoiseGate.h:845
std::atomic< T > releaseMs_
Definition NoiseGate.h:886
typename KeyEq::Shape KeyShape
What a band of the key equalizer does.
Definition NoiseGate.h:450
T getCurrentGain() noexcept
Definition NoiseGate.h:772
bool isSidechainListen() const noexcept
Whether the key is being played instead of the audio.
Definition NoiseGate.h:494
std::atomic< GateMode > gateMode_
Definition NoiseGate.h:889
std::array< T, kMaxChannels > freqHpFreq_
Definition NoiseGate.h:955
KeyEq::Response getSidechainResponse() const noexcept
The curve of the key equalizer, for a display.
Definition NoiseGate.h:480
State
Gate state machine phases.
Definition NoiseGate.h:91
@ Closed
Gate is fully closed (applying range attenuation).
@ Hold
Gate is open but counting down hold time before closing.
@ Open
Gate is fully open (passing audio).
static constexpr double kMaxLookaheadMs
Definition NoiseGate.h:897
bool cachedAutoThreshold_
Definition NoiseGate.h:937
std::atomic< T > rangeDb_
Definition NoiseGate.h:887
int lookaheadSamplesFor(T ms) const noexcept
Definition NoiseGate.h:669
GateMode cachedGateMode_
Definition NoiseGate.h:910
std::atomic< T > attackMs_
Definition NoiseGate.h:884
T computeEnvelopeFollower(T rawLevel) noexcept
Updates envelope state to prevent intra-cycle chattering.
Definition NoiseGate.h:688
typename KeyEq::Band KeyBand
The settings of one band of the key equalizer.
Definition NoiseGate.h:448
static constexpr int kMaxScChannels
Definition NoiseGate.h:916
std::atomic< T > hysteresis_
Definition NoiseGate.h:883
void setHysteresis(T dB) noexcept
Sets the hysteresis amount (gap between open and close thresholds).
Definition NoiseGate.h:336
static constexpr double kAutoRefFallDb
dB per second its reference falls.
Definition NoiseGate.h:933
T applyScHpf(T input, int ch) noexcept
Per-channel one-pole sidechain high-pass (unity gain at Nyquist).
Definition NoiseGate.h:811
void setThreshold(T dB) noexcept
Sets the opening threshold.
Definition NoiseGate.h:300
std::atomic< T > scHpfFreq_
Definition NoiseGate.h:894
void setAutoThreshold(bool on) noexcept
Counts the threshold from the key's own recent level.
Definition NoiseGate.h:323
void setDuckMode(bool enabled) noexcept
Toggles ducking mode (invert gate logic).
Definition NoiseGate.h:379
std::array< T, kMaxChannels > freqHpPrev_
Definition NoiseGate.h:953
void setSidechainBand(int band, const KeyBand &settings) noexcept
Sets a band of the equalizer of the key.
Definition NoiseGate.h:474
int maxLookaheadSamples_
Allocated delay (0 before prepare()).
Definition NoiseGate.h:901
void reset() noexcept
Resets DSP state (clears filters, sets state to Closed).
Definition NoiseGate.h:530
static constexpr double kAutoRefQuiet
Share of that fall while the key is under the closing threshold.
Definition NoiseGate.h:934
void setAdaptiveHold(bool enabled) noexcept
Toggles adaptive hold based on zero-crossing rate.
Definition NoiseGate.h:421
std::atomic< bool > paramsDirty_
Definition NoiseGate.h:891
std::atomic< bool > duckMode_
Definition NoiseGate.h:888
void setSidechainListen(bool on) noexcept
Plays the key instead of the gated audio.
Definition NoiseGate.h:491
static constexpr int kMaxLookaheadChannels
Definition NoiseGate.h:898
int lookaheadSamples_
Audio-side value (consumed in syncParams()).
Definition NoiseGate.h:900
double autoRef_
The reference (linear).
Definition NoiseGate.h:938
void syncParams() noexcept
Definition NoiseGate.h:615
std::atomic< bool > adaptiveHold_
Definition NoiseGate.h:890
typename KeyEq::Placement KeyPlacement
The part of a two-channel key a band of the key equalizer acts on.
Definition NoiseGate.h:452
T delayed(T x, int ch) noexcept
Definition NoiseGate.h:677
std::atomic< bool > scHpfEnabled_
Definition NoiseGate.h:893
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
Main namespace for the DSPark framework.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37