DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
EnvelopeFollower.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
44#include "../Core/AudioBuffer.h"
45#include "../Core/AudioSpec.h"
46#include "../Core/DspMath.h"
47#include "../Core/Hilbert.h"
48
49#include <algorithm>
50#include <array>
51#include <atomic>
52#include <cmath>
53#include <cstddef>
54
55namespace dspark {
56
64template <FloatType T, int MaxChannels = 16>
66{
67public:
69 enum class Mode { Peak, RMS };
70
71 EnvelopeFollower() noexcept { updateCoeffs(); }
72
73 // -- Lifecycle ---------------------------------------------------------------
74
82 void prepare(const AudioSpec& spec) noexcept
83 {
84 if (!spec.isValid() || !std::isfinite(spec.sampleRate)) return;
85 sampleRate_.store(spec.sampleRate, std::memory_order_relaxed);
86 numChannels_.store(std::clamp(spec.numChannels, 1, MaxChannels),
87 std::memory_order_relaxed);
88 updateCoeffs();
89 reset();
90 }
91
99 void reset() noexcept
100 {
101 for (auto& s : state_) s = 0.0;
102 for (auto& e : published_) e.store(T(0), std::memory_order_relaxed);
103 }
104
105 // -- Parameters ----------------------------------------------------------------
106
109 void setAttack(T ms) noexcept
110 {
111 const double v = static_cast<double>(ms);
112 if (!std::isfinite(v)) return;
113 attackMs_.store(std::max(v, 0.01), std::memory_order_relaxed);
114 updateCoeffs();
115 }
116
119 void setRelease(T ms) noexcept
120 {
121 const double v = static_cast<double>(ms);
122 if (!std::isfinite(v)) return;
123 releaseMs_.store(std::max(v, 0.01), std::memory_order_relaxed);
124 updateCoeffs();
125 }
126
128 void setMode(Mode m) noexcept
129 {
130 const int v = std::clamp(static_cast<int>(m), 0, 1);
131 mode_.store(static_cast<Mode>(v), std::memory_order_relaxed);
132 }
133
134 // -- Processing -------------------------------------------------------------------
135
142 {
143 const int nCh = std::min(buffer.getNumChannels(),
144 numChannels_.load(std::memory_order_relaxed));
145 const int nS = buffer.getNumSamples();
146 const double aAtt = attackA_.load(std::memory_order_relaxed);
147 const double aRel = releaseA_.load(std::memory_order_relaxed);
148 const bool peak = mode_.load(std::memory_order_relaxed) == Mode::Peak;
149
150 for (int ch = 0; ch < nCh; ++ch)
151 {
152 const T* d = buffer.getChannel(ch);
153 double env = state_[static_cast<size_t>(ch)];
154 if (peak)
155 {
156 for (int i = 0; i < nS; ++i)
157 {
158 const double x = std::abs(static_cast<double>(d[i]));
159 const double a = (x > env) ? aAtt : aRel;
160 env = a * env + (1.0 - a) * x;
161 }
162 }
163 else
164 {
165 for (int i = 0; i < nS; ++i)
166 {
167 const double x = static_cast<double>(d[i]) * d[i];
168 const double a = (x > env) ? aAtt : aRel;
169 env = a * env + (1.0 - a) * x;
170 }
171 }
172 // Publish-time guard: a non-finite sample would park NaN in the
173 // recursion for good (the branch comparison goes false forever),
174 // so the poisoned channel restarts and re-measures on the next
175 // block. The same test flushes fully decayed envelopes to true
176 // zero (~-1000 dBFS) before they walk into double denormals.
177 if (!std::isfinite(env) || env < 1e-100) env = 0.0;
178 state_[static_cast<size_t>(ch)] = env;
179 published_[static_cast<size_t>(ch)].store(readout(env, peak),
180 std::memory_order_relaxed);
181 }
182 }
183
192 [[nodiscard]] T processSample(T input) noexcept
193 {
194 const double aAtt = attackA_.load(std::memory_order_relaxed);
195 const double aRel = releaseA_.load(std::memory_order_relaxed);
196 const bool peak = mode_.load(std::memory_order_relaxed) == Mode::Peak;
197 double env = state_[0];
198 const double x = peak ? std::abs(static_cast<double>(input))
199 : static_cast<double>(input) * input;
200 const double a = (x > env) ? aAtt : aRel;
201 env = a * env + (1.0 - a) * x;
202 if (!std::isfinite(env) || env < 1e-100) env = 0.0;
203 state_[0] = env;
204 const T out = readout(env, peak);
205 published_[0].store(out, std::memory_order_relaxed);
206 return out;
207 }
208
209 // -- Readout (lock-free, any thread) ------------------------------------------------
210
212 [[nodiscard]] T getEnvelope(int channel = 0) const noexcept
213 {
214 const int n = numChannels_.load(std::memory_order_relaxed);
215 channel = std::clamp(channel, 0, n - 1);
216 return published_[static_cast<size_t>(channel)].load(std::memory_order_relaxed);
217 }
218
220 [[nodiscard]] T getEnvelopeMax() const noexcept
221 {
222 const int n = numChannels_.load(std::memory_order_relaxed);
223 T m = T(0);
224 for (int ch = 0; ch < n; ++ch)
225 m = std::max(m, published_[static_cast<size_t>(ch)].load(std::memory_order_relaxed));
226 return m;
227 }
228
230 [[nodiscard]] T getEnvelopeDb(int channel = 0) const noexcept
231 {
232 const double e = static_cast<double>(getEnvelope(channel));
233 return static_cast<T>(20.0 * std::log10(std::max(e, 1e-6)));
234 }
235
243 [[nodiscard]] T getEnvelopeNormalized(int channel = 0, T floorDb = T(-60)) const noexcept
244 {
245 const double floor = std::isfinite(floorDb) ? std::clamp(static_cast<double>(floorDb), -120.0, -1.0) : -60.0;
246 const double db = static_cast<double>(getEnvelopeDb(channel));
247 return static_cast<T>(std::clamp((db - floor) / -floor, 0.0, 1.0));
248 }
249
251 [[nodiscard]] T getAttack() const noexcept
252 {
253 return static_cast<T>(attackMs_.load(std::memory_order_relaxed));
254 }
255
257 [[nodiscard]] T getRelease() const noexcept
258 {
259 return static_cast<T>(releaseMs_.load(std::memory_order_relaxed));
260 }
261
263 [[nodiscard]] Mode getMode() const noexcept
264 {
265 return mode_.load(std::memory_order_relaxed);
266 }
267
268private:
269 static_assert(MaxChannels >= 1, "EnvelopeFollower needs at least one channel");
270
271 [[nodiscard]] T readout(double env, bool peak) const noexcept
272 {
273 return static_cast<T>(peak ? env : std::sqrt(std::max(env, 0.0)));
274 }
275
276 void updateCoeffs() noexcept
277 {
278 const double fs = sampleRate_.load(std::memory_order_relaxed);
279 attackA_.store(std::exp(-1.0 / (attackMs_.load(std::memory_order_relaxed) * 0.001 * fs)),
280 std::memory_order_relaxed);
281 releaseA_.store(std::exp(-1.0 / (releaseMs_.load(std::memory_order_relaxed) * 0.001 * fs)),
282 std::memory_order_relaxed);
283 }
284
285 std::atomic<double> sampleRate_ { 48000.0 };
286 std::atomic<int> numChannels_ { 1 };
287 std::atomic<double> attackMs_ { 10.0 };
288 std::atomic<double> releaseMs_ { 150.0 };
289 std::atomic<double> attackA_ { 0.99 };
290 std::atomic<double> releaseA_ { 0.999 };
291 std::atomic<Mode> mode_ { Mode::Peak };
292
293 std::array<double, MaxChannels> state_ {};
294 std::array<std::atomic<T>, MaxChannels> published_ {};
295};
296
319template <FloatType T>
321{
322public:
323 TransientFollower() noexcept { prepare(48000.0); }
324
326 void prepare(double sampleRate) noexcept
327 {
328 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0)) return;
329 fs_ = sampleRate;
330 const auto coeff = [this](double ms) { return std::exp(-1.0 / (ms * 0.001 * fs_)); };
331 fastAttack_ = coeff(0.5);
332 slowAttack_ = coeff(30.0);
333 followRelease_ = coeff(100.0);
334 reset();
335 }
336
338 void reset() noexcept
339 {
340 fast_ = 0.0;
341 slow_ = 0.0;
342 out_ = 0.0;
343 holdLeft_ = 0;
344 for (auto& h : analytic_) h.reset();
345 value_.store(T(0), std::memory_order_relaxed);
346 }
347
349 void setRange(T dB) noexcept
350 {
351 if (std::isfinite(dB)) range_.store(std::clamp(dB, T(3), T(40)), std::memory_order_relaxed);
352 }
354 void setHold(T ms) noexcept
355 {
356 if (std::isfinite(ms)) holdMs_.store(std::clamp(ms, T(0), T(500)), std::memory_order_relaxed);
357 }
359 void setRelease(T ms) noexcept
360 {
361 if (std::isfinite(ms)) releaseMs_.store(std::clamp(ms, T(1), T(2000)), std::memory_order_relaxed);
362 }
363
364 [[nodiscard]] T getRange() const noexcept { return range_.load(std::memory_order_relaxed); }
365 [[nodiscard]] T getHold() const noexcept { return holdMs_.load(std::memory_order_relaxed); }
366 [[nodiscard]] T getRelease() const noexcept { return releaseMs_.load(std::memory_order_relaxed); }
367
369 [[nodiscard]] T getValue() const noexcept { return value_.load(std::memory_order_relaxed); }
370
372 [[nodiscard]] T processSample(T input) noexcept
373 {
374 const Timing t = timing();
375 const double x = static_cast<double>(input);
376 const T v = step(analytic_[0].magnitude(std::isfinite(x) ? x : 0.0), t);
377 value_.store(v, std::memory_order_relaxed);
378 return v;
379 }
380
387 void processBlock(AudioBufferView<T> buffer, T* out = nullptr) noexcept
388 {
389 const Timing t = timing();
390 const int nCh = std::min(buffer.getNumChannels(), kChannels), nS = buffer.getNumSamples();
391 T v = value_.load(std::memory_order_relaxed);
392 for (int i = 0; i < nS; ++i)
393 {
394 double top = 0.0;
395 for (int ch = 0; ch < nCh; ++ch)
396 {
397 const double x = static_cast<double>(buffer.getChannel(ch)[i]);
398 top = std::max(top, analytic_[static_cast<size_t>(ch)].magnitude(std::isfinite(x) ? x : 0.0));
399 }
400 v = step(top, t);
401 if (out) out[i] = v;
402 }
403 value_.store(v, std::memory_order_relaxed);
404 }
405
406private:
407 struct Timing
408 {
409 double range;
410 int hold;
411 double release;
412 };
413
414 [[nodiscard]] Timing timing() const noexcept
415 {
416 return { static_cast<double>(range_.load(std::memory_order_relaxed)),
417 static_cast<int>(static_cast<double>(holdMs_.load(std::memory_order_relaxed)) * 0.001 * fs_),
418 std::exp(-1.0 / (static_cast<double>(releaseMs_.load(std::memory_order_relaxed)) * 0.001 * fs_)) };
419 }
420
421 [[nodiscard]] T step(double x, const Timing& t) noexcept
422 {
423 const double level = std::isfinite(x) ? std::abs(x) : 0.0;
424 fast_ = level + ((level > fast_) ? fastAttack_ : followRelease_) * (fast_ - level);
425 slow_ = level + ((level > slow_) ? slowAttack_ : followRelease_) * (slow_ - level);
426 double raw = 0.0;
427 if (slow_ > 1e-6 && fast_ > 1e-6)
428 raw = std::clamp((20.0 * std::log10(fast_ / slow_) - kDeadZoneDb) / t.range, 0.0, 1.0);
429 else if (fast_ > 1e-6)
430 raw = 1.0;
431 if (fast_ < 1e-12) fast_ = 0.0;
432 if (slow_ < 1e-12) slow_ = 0.0;
433 if (raw >= out_)
434 {
435 out_ = raw;
436 holdLeft_ = t.hold;
437 }
438 else if (holdLeft_ > 0)
439 {
440 --holdLeft_;
441 }
442 else
443 {
444 out_ = raw + t.release * (out_ - raw);
445 }
446 return static_cast<T>(out_);
447 }
448
449 static constexpr double kDeadZoneDb = 0.5;
450 static constexpr int kChannels = 16;
451
452 std::array<HilbertIIR<double>, kChannels> analytic_ {};
453
454 std::atomic<T> range_ { T(12) };
455 std::atomic<T> holdMs_ { T(20) };
456 std::atomic<T> releaseMs_ { T(80) };
457 std::atomic<T> value_ { T(0) };
458
459 double fs_ = 48000.0;
460 double fastAttack_ = 0.0, slowAttack_ = 0.0, followRelease_ = 0.0;
461 double fast_ = 0.0, slow_ = 0.0, out_ = 0.0;
462 int holdLeft_ = 0;
463};
464
465} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
int getNumSamples() const noexcept
Returns the number of samples per channel.
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
Attack/release envelope detector (Peak or RMS).
T processSample(T input) noexcept
Single-sample path on channel 0 (for embedding in processors).
void setAttack(T ms) noexcept
Attack time in milliseconds (default 10, floor 0.01; non-finite values are ignored).
void setRelease(T ms) noexcept
Release time in milliseconds (default 150, floor 0.01; non-finite values are ignored).
T getAttack() const noexcept
T getEnvelopeDb(int channel=0) const noexcept
T getRelease() const noexcept
void prepare(const AudioSpec &spec) noexcept
Prepares the follower. Allocation-free.
Mode getMode() const noexcept
T getEnvelopeNormalized(int channel=0, T floorDb=T(-60)) const noexcept
T getEnvelope(int channel=0) const noexcept
void processBlock(AudioBufferView< const T > buffer) noexcept
Analyzes a block (read-only) and updates per-channel envelopes.
T getEnvelopeMax() const noexcept
void setMode(Mode m) noexcept
Peak (default) or RMS detection. Out-of-range values clamp.
void reset() noexcept
Clears all envelopes.
How sudden the signal is, 0..1, whatever its level.
T getRelease() const noexcept
void prepare(double sampleRate) noexcept
Prepares for a sample rate (an invalid one is ignored) and clears.
void setRelease(T ms) noexcept
Time constant of the fall after the hold, 1 to 2000 ms (default 80).
void setHold(T ms) noexcept
Time the value is held at a peak, 0 to 500 ms (default 20).
void setRange(T dB) noexcept
Range in dB that maps to the full value, 3 to 40 (default 12).
void processBlock(AudioBufferView< T > buffer, T *out=nullptr) noexcept
Follows a block (the loudest channel per frame); the audio is not touched.
T getRange() const noexcept
T getValue() const noexcept
The value after the last sample (any thread).
void reset() noexcept
Clears the followers and the output.
T processSample(T input) noexcept
One sample (already the loudest channel's, or mono); returns the value.
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37