DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Expander.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
48#include "../Core/DspMath.h"
49#include "../Core/AudioSpec.h"
50#include "../Core/AudioBuffer.h"
51#include "../Core/DenormalGuard.h"
52#include "../Core/Hilbert.h"
53#include "../Core/KeyEqualizer.h"
54#include "../Core/RingBuffer.h"
55#include "../Core/StateBlob.h"
56
57#include <algorithm>
58#include <array>
59#include <atomic>
60#include <cmath>
61#include <cstddef>
62#include <cstdint>
63#include <numbers>
64#include <vector>
65
66namespace dspark {
67
74template <FloatType T>
76{
77public:
78 ~Expander() = default; // non-virtual: leaf class (no virtual dispatch)
79
80 enum class State { Closed, Open, Hold };
81
82 // -- Lifecycle -----------------------------------------------------------
83
91 void prepare(double sampleRate, int numChannels = 2) noexcept
92 {
93 if (!std::isfinite(sampleRate) || sampleRate <= 0.0) return;
94 sampleRate_ = sampleRate;
95 lookaheadChannels_ = std::clamp(numChannels, 1, MAX_CHANNELS);
96 maxLookaheadSamples_ = static_cast<int>(std::ceil(sampleRate * kMaxLookaheadMs / 1000.0));
97 for (int ch = 0; ch < lookaheadChannels_; ++ch)
98 lookahead_[static_cast<size_t>(ch)].prepare(maxLookaheadSamples_ + 1);
99 keyEq_.prepare(sampleRate);
102 // Re-derive the hold counter for the (possibly new) rate: it used to
103 // be computed only inside setHold() with the rate of that moment, so
104 // the default 50 ms hold was silently ZERO until setHold was called,
105 // and a re-prepare at a new rate kept stale hold lengths.
106 setHold(holdMs_.load(std::memory_order_relaxed));
107 reset();
108 prepared_ = true;
109 }
110
115 void prepare(const AudioSpec& spec) noexcept
116 {
117 if (!spec.isValid()) return;
118 prepare(spec.sampleRate, spec.numChannels);
119 }
120
125 void processBlock(AudioBufferView<T> buffer) noexcept
126 {
127 if (!prepared_) return;
128 DenormalGuard guard;
129 cacheParams();
130
132 processBlockInternal<true, false>(buffer, nullptr);
133 else
134 processBlockInternal<false, false>(buffer, nullptr);
135 }
136
147 void processBlock(AudioBufferView<T> buffer, AudioBufferView<T> sidechain) noexcept
148 {
149 if (!prepared_) return;
150 DenormalGuard guard;
151 cacheParams();
152
153 if (sidechain.getNumChannels() <= 0 ||
154 sidechain.getNumSamples() < buffer.getNumSamples())
155 {
157 processBlockInternal<true, false>(buffer, nullptr);
158 else
159 processBlockInternal<false, false>(buffer, nullptr);
160 return;
161 }
162
164 processBlockInternal<true, true>(buffer, &sidechain);
165 else
166 processBlockInternal<false, true>(buffer, &sidechain);
167 }
168
169 // -- Parameters ----------------------------------------------------------
170 // All setters ignore non-finite values (NaN attack/release/ratio used to
171 // poison the gain smoother permanently through max()'s first-argument
172 // NaN pass-through).
173
175 void setThreshold(T dB) noexcept
176 {
177 if (!std::isfinite(dB)) return;
178 threshold_.store(dB, std::memory_order_relaxed);
179 }
180
182 void setRatio(T ratio) noexcept
183 {
184 if (!std::isfinite(ratio)) return;
185 ratio_.store(std::max(ratio, T(1)), std::memory_order_relaxed);
186 }
187
189 void setHysteresis(T dB) noexcept
190 {
191 if (!std::isfinite(dB)) return;
192 hysteresis_.store(std::max(dB, T(0)), std::memory_order_relaxed);
193 }
194
196 void setRange(T dB) noexcept
197 {
198 if (!std::isfinite(dB)) return;
199 const T r = std::min(dB, T(0));
200 rangeDb_.store(r, std::memory_order_relaxed);
201 rangeLinear_.store(decibelsToGain(r), std::memory_order_relaxed);
202 }
203
205 void setAttack(T ms) noexcept
206 {
207 if (!std::isfinite(ms)) return;
208 attackMs_.store(std::max(ms, T(0.01)), std::memory_order_relaxed);
210 }
211
213 void setHold(T ms) noexcept
214 {
215 if (!std::isfinite(ms)) return;
216 holdMs_.store(std::max(ms, T(0)), std::memory_order_relaxed);
217 if (sampleRate_ > 0.0)
218 {
219 // Capped in double before the int cast (a huge finite hold time
220 // would otherwise be a UB float-to-int conversion).
221 const double h = std::min(
222 sampleRate_ * static_cast<double>(holdMs_.load(std::memory_order_relaxed)) / 1000.0,
223 1.0e9);
224 holdSamples_.store(static_cast<int>(h), std::memory_order_relaxed);
225 }
226 }
227
229 void setRelease(T ms) noexcept
230 {
231 if (!std::isfinite(ms)) return;
232 releaseMs_.store(std::max(ms, T(0.01)), std::memory_order_relaxed);
234 }
235
247 void setSidechainHPF(bool enabled, double cutoffHz = 80.0) noexcept
248 {
249 scHpfEnabled_.store(enabled, std::memory_order_relaxed);
250 if (std::isfinite(cutoffHz) && cutoffHz > 0.0)
251 scHpfFreqHz_.store(static_cast<T>(cutoffHz), std::memory_order_relaxed);
253 }
254
258 using KeyBand = typename KeyEq::Band;
260 using KeyShape = typename KeyEq::Shape;
263
283 void setSidechainBand(int band, const KeyBand& settings) noexcept { keyEq_.setBand(band, settings); }
284
286 [[nodiscard]] KeyBand getSidechainBand(int band) const noexcept { return keyEq_.getBand(band); }
287
289 [[nodiscard]] typename KeyEq::Response getSidechainResponse() const noexcept { return keyEq_.getResponse(); }
290
301 void setSidechainListen(bool on) noexcept { scListen_.store(on, std::memory_order_relaxed); }
302
304 [[nodiscard]] bool isSidechainListen() const noexcept { return scListen_.load(std::memory_order_relaxed); }
305
317 void setLookahead(T ms) noexcept
318 {
319 if (!std::isfinite(ms)) return;
320 lookaheadMs_.store(std::clamp(ms, T(0), static_cast<T>(kMaxLookaheadMs)), std::memory_order_relaxed);
321 }
322
324 [[nodiscard]] T getLookahead() const noexcept { return lookaheadMs_.load(std::memory_order_relaxed); }
325
342 void setAutoThreshold(bool on) noexcept { autoThreshold_.store(on, std::memory_order_relaxed); }
343
345 [[nodiscard]] bool isAutoThreshold() const noexcept { return autoThreshold_.load(std::memory_order_relaxed); }
346
348 [[nodiscard]] int getLatency() const noexcept
349 {
350 return lookaheadSamplesFor(lookaheadMs_.load(std::memory_order_relaxed));
351 }
352
353 // -- Queries -------------------------------------------------------------
354
361 [[nodiscard]] State getGateState() const noexcept
362 {
363 return publishedState_.load(std::memory_order_relaxed);
364 }
365
369 [[nodiscard]] T getCurrentGainDb() const noexcept
370 {
371 return gainToDecibels(publishedGateGain_.load(std::memory_order_relaxed));
372 }
373
375 void reset() noexcept
376 {
378 gateGain_ = rangeLinear_.load(std::memory_order_relaxed);
379 envelope_ = T(0);
380 holdCounter_ = 0;
381 autoRefDb_ = -100.0;
382 thresholdNow_ = threshold_.load(std::memory_order_relaxed);
384
385 std::fill(scHpfState_.begin(), scHpfState_.end(), T(0));
386 std::fill(scHpfPrev_.begin(), scHpfPrev_.end(), T(0));
387 keyEq_.reset();
389 for (auto& line : lookahead_) line.reset();
390 for (auto& a : analytic_) a.reset();
391 }
392
393
395 [[nodiscard]] std::vector<uint8_t> getState() const
396 {
397 StateWriter w(stateId("XPND"), 1);
398 // static_cast<float>: the blob stores float, and StateWriter's
399 // overload set is ambiguous for a double argument.
400 w.write("threshold", static_cast<float>(threshold_.load(std::memory_order_relaxed)));
401 w.write("ratio", static_cast<float>(ratio_.load(std::memory_order_relaxed)));
402 w.write("hysteresis", static_cast<float>(hysteresis_.load(std::memory_order_relaxed)));
403 w.write("attack", static_cast<float>(attackMs_.load(std::memory_order_relaxed)));
404 w.write("hold", static_cast<float>(holdMs_.load(std::memory_order_relaxed)));
405 w.write("release", static_cast<float>(releaseMs_.load(std::memory_order_relaxed)));
406 w.write("rangeDb", static_cast<float>(rangeDb_.load(std::memory_order_relaxed)));
407 w.write("scHpf", scHpfEnabled_.load(std::memory_order_relaxed));
408 w.write("scHpfFreq", static_cast<float>(scHpfFreqHz_.load(std::memory_order_relaxed)));
409 w.write("lookahead", static_cast<float>(lookaheadMs_.load(std::memory_order_relaxed)));
410 w.write("autoThreshold", autoThreshold_.load(std::memory_order_relaxed));
411 keyEq_.writeState(w, "key");
412 return w.blob();
413 }
414
416 bool setState(const uint8_t* data, size_t size)
417 {
418 StateReader r(data, size);
419 if (!r.isValid() || r.processorId() != stateId("XPND")) return false;
420 setThreshold(static_cast<T>(r.read("threshold", -40.0f)));
421 setRatio(static_cast<T>(r.read("ratio", 4.0f)));
422 setHysteresis(static_cast<T>(r.read("hysteresis", 4.0f)));
423 setAttack(static_cast<T>(r.read("attack", 0.5f)));
424 setHold(static_cast<T>(r.read("hold", 50.0f)));
425 setRelease(static_cast<T>(r.read("release", 100.0f)));
426 setRange(static_cast<T>(r.read("rangeDb", -80.0f)));
427 setSidechainHPF(r.read("scHpf", false),
428 static_cast<double>(r.read("scHpfFreq", 80.0f)));
429 setLookahead(static_cast<T>(r.read("lookahead", 0.0f)));
430 setAutoThreshold(r.read("autoThreshold", false));
431 keyEq_.readState(r, "key");
432 return true;
433 }
434
435protected:
436 void cacheParams() noexcept
437 {
438 cachedThreshold_ = threshold_.load(std::memory_order_relaxed);
439 cachedRatio_ = ratio_.load(std::memory_order_relaxed);
440 cachedHysteresis_ = hysteresis_.load(std::memory_order_relaxed);
441 cachedRangeLinear_ = rangeLinear_.load(std::memory_order_relaxed);
442 cachedAttackCoeff_ = attackCoeff_.load(std::memory_order_relaxed);
443 cachedReleaseCoeff_ = releaseCoeff_.load(std::memory_order_relaxed);
444 cachedHoldSamples_ = holdSamples_.load(std::memory_order_relaxed);
445 cachedScHpfEnabled_ = scHpfEnabled_.load(std::memory_order_relaxed);
446 cachedDetRelCoeff_ = detRelCoeff_.load(std::memory_order_relaxed);
447 cachedScHpfCoeff_ = scHpfCoeff_.load(std::memory_order_relaxed);
448 cachedScHpfA0_ = scHpfA0_.load(std::memory_order_relaxed);
449 cachedLookahead_ = lookaheadSamplesFor(lookaheadMs_.load(std::memory_order_relaxed));
450 cachedAutoThreshold_ = autoThreshold_.load(std::memory_order_relaxed);
452 keyOn_ = keyEq_.sync();
453 listen_ = scListen_.load(std::memory_order_relaxed);
454 }
455
457 [[nodiscard]] int lookaheadSamplesFor(T ms) const noexcept
458 {
459 const double samples = std::round(static_cast<double>(ms) * sampleRate_ / 1000.0);
460 return std::clamp(static_cast<int>(std::min(samples, 1.0e9)), 0, maxLookaheadSamples_);
461 }
462
467 template <bool UseHPF>
468 [[nodiscard]] T keyInput(T raw, int ch) noexcept
469 {
470 T input = std::isfinite(raw) ? raw : T(0); // non-finite would latch
471 if constexpr (UseHPF)
472 {
473 // One-pole HPF on the raw bipolar signal per channel,
474 // normalized for unity gain at Nyquist (the unnormalized
475 // form boosted the detected HF slightly).
476 T output = cachedScHpfA0_ * (input - scHpfPrev_[ch]) + cachedScHpfCoeff_ * scHpfState_[ch];
477 scHpfPrev_[ch] = input;
478 scHpfState_[ch] = output;
479 input = output;
480 }
481 return input;
482 }
483
491 template <bool UseHPF, bool UseSc>
493 const AudioBufferView<T>* sidechain) noexcept
494 {
495 const int nCh = buffer.getNumChannels();
496 const int nS = buffer.getNumSamples();
497 // Detector channel count is capped by the per-channel HPF state
498 // arrays; the scalar gain below is applied to ALL audio channels.
499 const int detCh = UseSc ? std::min(sidechain->getNumChannels(), MAX_CHANNELS)
500 : std::min(nCh, MAX_CHANNELS);
501
502 for (int c0 = 0; c0 < nS; c0 += kDetChunk)
503 {
504 const int m = std::min(kDetChunk, nS - c0);
505 std::fill(detLevel_.begin(), detLevel_.begin() + m, T(0));
506
507 // A band of the key's equalizer on the middle or on the sides of a
508 // pair takes the key a frame at a time, before each channel is read.
509 const bool keyFrames = keyOn_ && detCh == 2 && keyEq_.isPlaced();
510 if (keyFrames)
511 {
512 for (int ch = 0; ch < 2; ++ch)
513 {
514 const T* src = (UseSc ? sidechain->getChannel(ch) : buffer.getChannel(ch)) + c0;
515 for (int j = 0; j < m; ++j)
516 heard_[static_cast<size_t>(ch)][static_cast<size_t>(j)] = keyInput<UseHPF>(src[j], ch);
517 }
518 for (int j = 0; j < m; ++j)
519 {
520 T pair[2] = { heard_[0][static_cast<size_t>(j)], heard_[1][static_cast<size_t>(j)] };
521 keyEq_.processFrame(pair, 2);
522 heard_[0][static_cast<size_t>(j)] = pair[0];
523 heard_[1][static_cast<size_t>(j)] = pair[1];
524 }
525 }
526
527 // 1. Detector key per channel: sanitised, high-passed, then the larger
528 // of the rectified sample and the analytic magnitude (computed
529 // section by section over the chunk, like DynamicEQ).
530 for (int ch = 0; ch < detCh; ++ch)
531 {
532 const T* src = (UseSc ? sidechain->getChannel(ch) : buffer.getChannel(ch)) + c0;
533 for (int j = 0; j < m; ++j)
534 {
535 T input;
536 if (keyFrames) input = heard_[static_cast<size_t>(ch)][static_cast<size_t>(j)];
537 else
538 {
539 input = keyInput<UseHPF>(src[j], ch);
540 if (keyOn_) input = keyEq_.processSample(input, ch);
541 if (listen_) heard_[static_cast<size_t>(ch)][static_cast<size_t>(j)] = input;
542 }
543 detIn_[static_cast<size_t>(j)] = static_cast<double>(input);
544 }
545 analytic_[static_cast<size_t>(ch)].magnitudeBlock(detIn_.data(), detMag_.data(), m);
546 for (int j = 0; j < m; ++j)
547 {
548 const T level = static_cast<T>(std::max(std::abs(detIn_[static_cast<size_t>(j)]),
549 detMag_[static_cast<size_t>(j)]));
550 if (level > detLevel_[static_cast<size_t>(j)]) detLevel_[static_cast<size_t>(j)] = level;
551 }
552 }
553 if (keyOn_) keyEq_.advance(m);
554
555 for (int j = 0; j < m; ++j)
556 {
557 const int i = c0 + j;
558 const T sc = detLevel_[static_cast<size_t>(j)];
559
560 // 2. Peak envelope: instant attack (the analytic magnitude is
561 // already ripple-free on steady tones), sample-rate derived 5 ms
562 // release.
563 if (sc > envelope_) envelope_ = sc;
564 else envelope_ += cachedDetRelCoeff_ * (sc - envelope_);
565
566 // 3. Gain Calculation (Converting envelope to dB only once)
567 T levelDb = gainToDecibels(envelope_ + T(1e-9));
568
569 // The automatic threshold counts from a reference that follows
570 // the level: up at once, down slowly, and a quarter as fast
571 // while the level is under the closing threshold.
574 {
575 const double closing = autoRefDb_ + static_cast<double>(cachedThreshold_ - cachedHysteresis_);
576 const double fall = (static_cast<double>(levelDb) < closing) ? autoRefFall_ * kAutoRefQuiet
577 : autoRefFall_;
578 autoRefDb_ = std::max(static_cast<double>(levelDb), autoRefDb_ - fall);
579 thresholdNow_ = cachedThreshold_ + static_cast<T>(autoRefDb_);
580 }
581
582 updateStateMachine(levelDb);
583 T gain = computeGain(levelDb);
584
585 // The listened key: late by the lookahead and under full scale.
586 if (listen_)
587 {
588 T frame[MAX_CHANNELS];
589 for (int ch = 0; ch < detCh; ++ch) frame[ch] = heard_[static_cast<size_t>(ch)][static_cast<size_t>(j)];
591 for (int ch = 0; ch < detCh; ++ch) heard_[static_cast<size_t>(ch)][static_cast<size_t>(j)] = frame[ch];
592 }
593
594 // 4. Apply Gain (to the lookahead-delayed audio when enabled)
595 for (int ch = 0; ch < nCh; ++ch)
596 {
597 T& x = buffer.getChannel(ch)[i];
598 if (cachedLookahead_ > 0 && ch < lookaheadChannels_)
599 {
600 auto& line = lookahead_[static_cast<size_t>(ch)];
601 line.push(x);
602 x = line.read(cachedLookahead_);
603 }
604 x *= gain;
605 // Key listen: what the detector heard goes out instead.
606 if (listen_)
607 x = heard_[static_cast<size_t>(std::min(ch, detCh - 1))][static_cast<size_t>(j)];
608 }
609 }
610 }
611
613 }
614
622 void publishMeters() noexcept
623 {
624 publishedState_.store(state_, std::memory_order_relaxed);
625 publishedGateGain_.store(gateGain_, std::memory_order_relaxed);
626 }
627
628 void updateStateMachine(T levelDb) noexcept
629 {
630 T openThresh = thresholdNow_;
631 T closeThresh = thresholdNow_ - cachedHysteresis_;
632
633 switch (state_)
634 {
635 case State::Closed:
636 if (levelDb > openThresh) state_ = State::Open;
637 break;
638 case State::Open:
639 if (levelDb < closeThresh)
640 {
643 }
644 break;
645 case State::Hold:
646 if (levelDb > openThresh)
648 else if (--holdCounter_ <= 0)
650 break;
651 }
652 }
653
654 [[nodiscard]] T computeGain(T levelDb) noexcept
655 {
656 T targetGain;
657
659 {
660 targetGain = T(1);
661 }
662 else
663 {
664 T underDb = thresholdNow_ - levelDb;
665 // Downward-expander law: the transfer slope below threshold is the
666 // ratio R (out = thr + R*(in - thr)), so the attenuation applied is
667 // underDb*(R-1). As R -> inf this approaches full closure, i.e. the
668 // gate the class documents itself as a generalization of. (The prior
669 // (1 - 1/R) was the *compressor* law and made the expander ~R too
670 // gentle -- e.g. 5 dB instead of 10 dB of extra attenuation 10 dB
671 // below threshold at R=2, and it could never approach a gate.)
672 T reductionDb = underDb * (cachedRatio_ - T(1));
673
674 // Optimization note: replace decibelsToGain with fast_exp10 if available
675 T expandedGain = decibelsToGain(-reductionDb);
676 targetGain = std::max(expandedGain, cachedRangeLinear_);
677 }
678
679 // Apply smoothing to the linear gain
680 T coeff = (targetGain > gateGain_) ? cachedAttackCoeff_ : cachedReleaseCoeff_;
681 gateGain_ += coeff * (targetGain - gateGain_);
682
683 return gateGain_;
684 }
685
686 void updateCoefficients() noexcept
687 {
688 if (!(sampleRate_ > 0.0)) return;
689 T fs = static_cast<T>(sampleRate_);
690 attackCoeff_.store(T(1) - std::exp(T(-1) / (fs * attackMs_.load(std::memory_order_relaxed) / T(1000))),
691 std::memory_order_relaxed);
692 releaseCoeff_.store(T(1) - std::exp(T(-1) / (fs * releaseMs_.load(std::memory_order_relaxed) / T(1000))),
693 std::memory_order_relaxed);
694
695 // Detector release (~5 ms), sample-rate aware; the attack is instant.
696 detRelCoeff_.store(T(1) - std::exp(T(-1) / (fs * T(0.005))), std::memory_order_relaxed);
697
698 // Recompute the sidechain HPF for the (possibly new) sample rate.
699 // Design clamp [1, 0.45 * fs] keeps the one-pole stable; the atomic
700 // stores make this publication safe from any thread (the coefficient
701 // used to be a plain member written cross-thread).
702 const double scFreq = std::clamp(
703 static_cast<double>(scHpfFreqHz_.load(std::memory_order_relaxed)),
704 1.0, sampleRate_ * 0.45);
705 const T c = static_cast<T>(std::exp(-std::numbers::pi * 2.0 * scFreq / sampleRate_));
706 scHpfCoeff_.store(c, std::memory_order_relaxed);
707 scHpfA0_.store((T(1) + c) / T(2), std::memory_order_relaxed);
708 }
709
710 double sampleRate_ = 48000.0;
711 bool prepared_ = false;
712
713 std::atomic<T> threshold_ { T(-40) };
714 std::atomic<T> ratio_ { T(4) };
715 std::atomic<T> hysteresis_ { T(4) };
716 std::atomic<T> attackMs_ { T(0.5) };
717 std::atomic<T> holdMs_ { T(50) };
718 std::atomic<T> releaseMs_ { T(100) };
719 std::atomic<T> rangeDb_ { T(-80) };
720 std::atomic<T> rangeLinear_ { T(0.0001) };
721
722 std::atomic<bool> scHpfEnabled_ { false };
723 std::atomic<T> scHpfFreqHz_ { T(80) };
724 std::atomic<T> scHpfCoeff_ { T(0.995) };
725 std::atomic<T> scHpfA0_ { T(0.9975) };
726
727 // Per-channel sidechain HPF state (16 = detector channel cap).
728 static constexpr int MAX_CHANNELS = 16;
729 std::array<T, MAX_CHANNELS> scHpfState_{};
730 std::array<T, MAX_CHANNELS> scHpfPrev_{};
733 std::atomic<bool> scListen_ { false };
734 bool keyOn_ = false;
735 bool listen_ = false;
736
737 // Lookahead (audio delayed; detection runs on the undelayed signal).
738 static constexpr double kMaxLookaheadMs = 10.0;
739 std::atomic<T> lookaheadMs_ { T(0) };
743 std::array<RingBuffer<T>, MAX_CHANNELS> lookahead_ {};
744
745 std::atomic<T> attackCoeff_ { T(0) };
746 std::atomic<T> releaseCoeff_ { T(0) };
747 std::atomic<T> detRelCoeff_ { T(0.001) };
748 std::atomic<int> holdSamples_ { 0 };
749
750 // Cached per-block
752 T cachedRatio_ = T(4);
754 T cachedRangeLinear_ = T(0.0001);
757 T cachedDetRelCoeff_ = T(0.001);
758 T cachedScHpfCoeff_ = T(0.995);
759 T cachedScHpfA0_ = T(0.9975);
762
763 // Automatic threshold (setAutoThreshold()).
764 static constexpr double kAutoRefFallDb = 1.0;
765 static constexpr double kAutoRefQuiet = 0.25;
766 std::atomic<bool> autoThreshold_ { false };
768 double autoRefDb_ = -100.0;
769 double autoRefFall_ = 0.0;
770 T thresholdNow_ = T(-40);
771
773 T gateGain_ = T(0);
774 // Cross-thread metering readouts of the two audio-thread words above.
775 std::atomic<State> publishedState_ { State::Closed };
776 std::atomic<T> publishedGateGain_ { T(0) };
777 T envelope_ = T(0);
779
780 // Analytic detector (per detector channel) and its chunk scratch.
781 static constexpr int kDetChunk = 64;
782 std::array<HilbertIIR<double>, MAX_CHANNELS> analytic_ {};
783 std::array<double, kDetChunk> detIn_ {};
784 std::array<double, kDetChunk> detMag_ {};
785 std::array<T, kDetChunk> detLevel_ {};
786 std::array<std::array<T, kDetChunk>, MAX_CHANNELS> heard_ {};
787};
788
789} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Downward expander with ratio control, hysteresis, and sidechain.
Definition Expander.h:76
void publishMeters() noexcept
Publishes the metering words for cross-thread readout.
Definition Expander.h:622
void setHysteresis(T dB) noexcept
Sets the hysteresis gap in decibels to prevent chattering.
Definition Expander.h:189
typename KeyEq::Shape KeyShape
What a band of the key equalizer does.
Definition Expander.h:260
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition Expander.h:416
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition Expander.h:395
void setRange(T dB) noexcept
Sets the maximum gain reduction limit in decibels (<= 0).
Definition Expander.h:196
std::atomic< T > hysteresis_
Definition Expander.h:715
void updateStateMachine(T levelDb) noexcept
Definition Expander.h:628
std::atomic< T > rangeDb_
Definition Expander.h:719
typename KeyEq::Placement KeyPlacement
The part of a two-channel key a band of the key equalizer acts on.
Definition Expander.h:262
std::atomic< T > scHpfA0_
Definition Expander.h:725
std::atomic< T > holdMs_
Definition Expander.h:717
typename KeyEq::Band KeyBand
The settings of one band of the key equalizer.
Definition Expander.h:258
KeyBand getSidechainBand(int band) const noexcept
The settings of a band of the key equalizer.
Definition Expander.h:286
void reset() noexcept
Resets all internal DSP states to prevent clicks on playback start.
Definition Expander.h:375
std::atomic< bool > scListen_
The key goes out instead of the audio.
Definition Expander.h:733
double autoRefDb_
The reference (dB).
Definition Expander.h:768
static constexpr double kAutoRefFallDb
dB per second its reference falls.
Definition Expander.h:764
static constexpr int kDetChunk
Definition Expander.h:781
void setRatio(T ratio) noexcept
Sets the expansion ratio (e.g., 4.0 for 4:1).
Definition Expander.h:182
void cacheParams() noexcept
Definition Expander.h:436
bool cachedScHpfEnabled_
Definition Expander.h:761
State getGateState() const noexcept
Definition Expander.h:361
std::atomic< State > publishedState_
Definition Expander.h:775
std::array< std::array< T, kDetChunk >, MAX_CHANNELS > heard_
The key of each channel in this chunk.
Definition Expander.h:786
bool listen_
scListen_ as the audio thread took it.
Definition Expander.h:735
T computeGain(T levelDb) noexcept
Definition Expander.h:654
bool isSidechainListen() const noexcept
Whether the key is being played instead of the audio.
Definition Expander.h:304
int maxLookaheadSamples_
Allocated delay (0 before prepare()).
Definition Expander.h:741
std::atomic< T > releaseCoeff_
Definition Expander.h:746
std::array< T, MAX_CHANNELS > scHpfPrev_
Definition Expander.h:730
std::array< T, MAX_CHANNELS > scHpfState_
Definition Expander.h:729
void setRelease(T ms) noexcept
Sets the release time in milliseconds.
Definition Expander.h:229
std::atomic< bool > scHpfEnabled_
Definition Expander.h:722
bool keyOn_
The equalizer has bands in the path (audio thread).
Definition Expander.h:734
double autoRefFall_
Its fall per sample (dB).
Definition Expander.h:769
std::array< double, kDetChunk > detIn_
Definition Expander.h:783
void setAutoThreshold(bool on) noexcept
Counts the threshold from the key's own recent level.
Definition Expander.h:342
std::array< HilbertIIR< double >, MAX_CHANNELS > analytic_
Definition Expander.h:782
void setThreshold(T dB) noexcept
Sets the threshold in decibels.
Definition Expander.h:175
std::atomic< T > publishedGateGain_
Definition Expander.h:776
T getCurrentGainDb() const noexcept
Definition Expander.h:369
std::atomic< T > rangeLinear_
Definition Expander.h:720
void setSidechainListen(bool on) noexcept
Plays the key instead of the expanded audio.
Definition Expander.h:301
std::atomic< T > attackCoeff_
Definition Expander.h:745
~Expander()=default
void setAttack(T ms) noexcept
Sets the attack time in milliseconds.
Definition Expander.h:205
static constexpr double kAutoRefQuiet
Share of that fall while the key is under the closing threshold.
Definition Expander.h:765
void setHold(T ms) noexcept
Sets the hold time in milliseconds before release begins.
Definition Expander.h:213
void processBlockInternal(AudioBufferView< T > buffer, const AudioBufferView< T > *sidechain) noexcept
Internal processing loop templated on HPF/sidechain to avoid branching.
Definition Expander.h:492
void setLookahead(T ms) noexcept
Sets the lookahead: the audio is delayed so the gain moves ahead of it. 0 (default) is latency-free.
Definition Expander.h:317
int getLatency() const noexcept
Latency in samples (the lookahead), correct right after setLookahead().
Definition Expander.h:348
std::atomic< bool > autoThreshold_
The threshold counts from the key's recent level.
Definition Expander.h:766
std::atomic< T > releaseMs_
Definition Expander.h:718
std::array< RingBuffer< T >, MAX_CHANNELS > lookahead_
Definition Expander.h:743
std::atomic< T > scHpfFreqHz_
Definition Expander.h:723
static constexpr double kMaxLookaheadMs
Definition Expander.h:738
std::atomic< T > detRelCoeff_
Definition Expander.h:747
std::array< double, kDetChunk > detMag_
Definition Expander.h:784
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio block in place (internal detector key).
Definition Expander.h:125
KeyEq::Response getSidechainResponse() const noexcept
The curve of the key equalizer, for a display.
Definition Expander.h:289
int lookaheadChannels_
Channels with a prepared delay line.
Definition Expander.h:742
int lookaheadSamplesFor(T ms) const noexcept
Definition Expander.h:457
double sampleRate_
Definition Expander.h:710
std::atomic< T > scHpfCoeff_
Definition Expander.h:724
std::atomic< T > ratio_
Definition Expander.h:714
bool cachedAutoThreshold_
Definition Expander.h:767
KeyEq keyEq_
Equalizer of the key, after the high-pass.
Definition Expander.h:731
std::atomic< T > threshold_
Definition Expander.h:713
void prepare(const AudioSpec &spec) noexcept
Initializes the expander using an AudioSpec struct.
Definition Expander.h:115
void processBlock(AudioBufferView< T > buffer, AudioBufferView< T > sidechain) noexcept
Processes an audio block in place, keyed by an external sidechain.
Definition Expander.h:147
std::atomic< int > holdSamples_
Definition Expander.h:748
std::atomic< T > lookaheadMs_
Definition Expander.h:739
int cachedLookahead_
Audio-side samples (per block).
Definition Expander.h:740
void prepare(double sampleRate, int numChannels=2) noexcept
Initializes the expander with a specific sample rate.
Definition Expander.h:91
std::array< T, kDetChunk > detLevel_
Definition Expander.h:785
static constexpr int MAX_CHANNELS
Definition Expander.h:728
bool isAutoThreshold() const noexcept
Whether the threshold counts from the key's recent level (see setAutoThreshold()).
Definition Expander.h:345
std::atomic< T > attackMs_
Definition Expander.h:716
T keyInput(T raw, int ch) noexcept
One sample of a channel's key before its equalizer: made finite and, when UseHPF, through the sidecha...
Definition Expander.h:468
T thresholdNow_
Threshold of the frame (dB).
Definition Expander.h:770
T getLookahead() const noexcept
Returns the lookahead in milliseconds.
Definition Expander.h:324
KeyMonitor< T, 16 > keyMonitor_
The listened key: late by the lookahead, under full scale.
Definition Expander.h:732
void updateCoefficients() noexcept
Definition Expander.h:686
void setSidechainHPF(bool enabled, double cutoffHz=80.0) noexcept
Enables and configures the sidechain high-pass filter.
Definition Expander.h:247
void setSidechainBand(int band, const KeyBand &settings) noexcept
Sets a band of the equalizer of the key.
Definition Expander.h:283
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.
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
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37