DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
LevelFollower.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
54#include "../Core/AudioBuffer.h"
55#include "../Core/AudioSpec.h"
56#include "../Core/DspMath.h"
57
58#include <algorithm>
59#include <array>
60#include <atomic>
61#include <cmath>
62#include <type_traits>
63
64namespace dspark {
65
81template <FloatType T, int MaxChannels = 16>
83{
84public:
94 void prepare(const AudioSpec& spec) noexcept
95 {
96 if (!spec.isValid())
97 return;
98
99 sampleRate_ = spec.sampleRate;
100 numChannels_ = std::min(spec.numChannels, MaxChannels);
101 updateCoefficients();
102 // The needle depends on the rate only (setup thread).
103 vuG_ = std::tan(3.141592653589793 * kVuHz / sampleRate_);
104 vuA1_ = 1.0 / (1.0 + vuG_ * (vuG_ + 2.0 * kVuDamping));
105 reset();
106 }
107
113 void setAttackMs(float ms) noexcept
114 {
115 if (!std::isfinite(ms))
116 return;
117 attackMs_.store(std::max(T(0.001), static_cast<T>(ms)), std::memory_order_relaxed);
118 updateCoefficients();
119 }
120
126 void setReleaseMs(float ms) noexcept
127 {
128 if (!std::isfinite(ms))
129 return;
130 releaseMs_.store(std::max(T(0.001), static_cast<T>(ms)), std::memory_order_relaxed);
131 updateCoefficients();
132 }
133
144 void setRmsWindowMs(float ms) noexcept
145 {
146 if (!std::isfinite(ms))
147 return;
148 rmsWindowMs_.store(std::max(T(0.001), static_cast<T>(ms)), std::memory_order_relaxed);
149 updateCoefficients();
150 }
151
153 [[nodiscard]] T getAttackMs() const noexcept
154 {
155 return attackMs_.load(std::memory_order_relaxed);
156 }
157
159 [[nodiscard]] T getReleaseMs() const noexcept
160 {
161 return releaseMs_.load(std::memory_order_relaxed);
162 }
163
165 [[nodiscard]] T getRmsWindowMs() const noexcept
166 {
167 return rmsWindowMs_.load(std::memory_order_relaxed);
168 }
169
174 void setVuEnabled(bool on) noexcept { vuOn_.store(on, std::memory_order_relaxed); }
176 [[nodiscard]] bool isVuEnabled() const noexcept { return vuOn_.load(std::memory_order_relaxed); }
177
179 void reset() noexcept
180 {
181 for (auto& s : state_)
182 {
183 s.peak.store(T(0), std::memory_order_relaxed);
184 s.rmsAccum.store(T(0), std::memory_order_relaxed);
185 s.vu.store(T(0), std::memory_order_relaxed);
186 s.vuS1 = s.vuS2 = 0.0;
187 }
188 }
189
198 void process(AudioBufferView<const T> buffer) noexcept
199 {
200 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
201 const int nS = buffer.getNumSamples();
202
203 // Constant offset that keeps the decay recursions out of the
204 // subnormal range (CPU spikes). Its equilibrium floor is
205 // kAntiDenormal / (1 - coeff): with the float offset at 1e-15 a 3 s
206 // RMS window at 192 kHz settled at -92.5 dB in silence, above the
207 // -100 dB readout floor. 1e-20 is still 18 decades above the float
208 // subnormal range.
209 static constexpr T kAntiDenormal = std::is_same_v<T, float> ? T(1e-20) : T(1e-30);
210
211 // One relaxed load per block; the per-sample loop runs on locals.
212 const T attackCoeff = attackCoeff_.load(std::memory_order_relaxed);
213 const T releaseCoeff = releaseCoeff_.load(std::memory_order_relaxed);
214 const T rmsCoeff = rmsCoeff_.load(std::memory_order_relaxed);
215 const bool vu = vuOn_.load(std::memory_order_relaxed);
216
217 for (int ch = 0; ch < nCh; ++ch)
218 {
219 const T* data = buffer.getChannel(ch);
220 auto& s = state_[ch];
221
222 // Local copies to avoid atomic operations per sample
223 T localPeak = s.peak.load(std::memory_order_relaxed);
224 T localRms = s.rmsAccum.load(std::memory_order_relaxed);
225
226 for (int i = 0; i < nS; ++i)
227 {
228 const T absSample = std::abs(data[i]);
229
230 // Branchless attack/release selector (avoids per-sample
231 // branch mispredictions; the recursion itself is serial)
232 const T isAttack = static_cast<T>(absSample > localPeak);
233 const T peakCoeff = isAttack * attackCoeff + (T(1) - isAttack) * releaseCoeff;
234
235 localPeak = absSample + peakCoeff * (localPeak - absSample) + kAntiDenormal;
236
237 // Symmetric one-pole lowpass over x^2 (exponential RMS)
238 const T squared = data[i] * data[i];
239 localRms = squared + rmsCoeff * (localRms - squared) + kAntiDenormal;
240 }
241
242 // A non-finite input would otherwise stick in the recursions
243 // forever (the one-pole never drains a NaN); a meter must report
244 // the signal as it is now, so sanitize at publish time and start
245 // clean on the next block.
246 if (!std::isfinite(localPeak)) localPeak = T(0);
247 if (!std::isfinite(localRms)) localRms = T(0);
248
249 // Publish final states for the UI thread once per block
250 s.peak.store(localPeak, std::memory_order_relaxed);
251 s.rmsAccum.store(localRms, std::memory_order_relaxed);
252
253 if (vu)
254 {
255 // The needle: |x| scaled so a sine reads its RMS, through a
256 // second-order low-pass (state-variable, trapezoidal).
257 double s1 = s.vuS1, s2 = s.vuS2;
258 for (int i = 0; i < nS; ++i)
259 {
260 const double x = kVuSineToRms * std::abs(static_cast<double>(data[i]));
261 const double v1 = vuA1_ * (s1 + vuG_ * (x - s2));
262 const double v2 = s2 + vuG_ * v1;
263 s1 = 2.0 * v1 - s1;
264 s2 = 2.0 * v2 - s2;
265 }
266 if (!std::isfinite(s1) || !std::isfinite(s2)) s1 = s2 = 0.0;
267 s.vuS1 = s1;
268 s.vuS2 = s2;
269 s.vu.store(static_cast<T>(std::max(0.0, s2)), std::memory_order_relaxed);
270 }
271 }
272 }
273
279 [[nodiscard]] T getVuLevel(int channel) const noexcept
280 {
281 if (channel < 0 || channel >= MaxChannels) return T(0);
282 return state_[channel].vu.load(std::memory_order_relaxed);
283 }
284
286 [[nodiscard]] T getVuLevelDb(int channel) const noexcept { return gainToDecibels(getVuLevel(channel)); }
287
293 [[nodiscard]] T getPeakLevel(int channel) const noexcept
294 {
295 if (channel < 0 || channel >= MaxChannels) return T(0);
296 return state_[channel].peak.load(std::memory_order_relaxed);
297 }
298
304 [[nodiscard]] T getRmsLevel(int channel) const noexcept
305 {
306 if (channel < 0 || channel >= MaxChannels) return T(0);
307 const T squaredRms = state_[channel].rmsAccum.load(std::memory_order_relaxed);
308 return std::sqrt(std::max(squaredRms, T(0)));
309 }
310
316 [[nodiscard]] T getPeakLevelDb(int channel) const noexcept
317 {
318 return gainToDecibels(getPeakLevel(channel));
319 }
320
326 [[nodiscard]] T getRmsLevelDb(int channel) const noexcept
327 {
328 if (channel < 0 || channel >= MaxChannels) return T(-100);
329 const T squaredRms = state_[channel].rmsAccum.load(std::memory_order_relaxed);
330
331 // Fast path: avoid std::sqrt by using 10*log10(x^2) instead of 20*log10(x)
332 if (squaredRms <= T(1e-10)) return T(-100);
333 return T(10) * std::log10(squaredRms);
334 }
335
336private:
337 void updateCoefficients() noexcept
338 {
339 if (!(sampleRate_ > 0.0))
340 return;
341 const auto fs = static_cast<T>(sampleRate_);
342
343 const T attackMs = attackMs_.load(std::memory_order_relaxed);
344 const T releaseMs = releaseMs_.load(std::memory_order_relaxed);
345 const T rmsMs = rmsWindowMs_.load(std::memory_order_relaxed);
346
347 attackCoeff_.store(std::exp(T(-1) / (fs * attackMs / T(1000))), std::memory_order_relaxed);
348 releaseCoeff_.store(std::exp(T(-1) / (fs * releaseMs / T(1000))), std::memory_order_relaxed);
349 rmsCoeff_.store(std::exp(T(-1) / (fs * rmsMs / T(1000))), std::memory_order_relaxed);
350 }
351
354 static constexpr double kVuHz = 2.1504;
355 static constexpr double kVuDamping = 0.8127;
357 static constexpr double kVuSineToRms = 1.1107207345395915;
358
359 struct ChannelState
360 {
361 // Written once per block by the audio thread, read at UI rate:
362 // contention is negligible, so no cache-line padding is needed.
363 std::atomic<T> peak{ T(0) };
364 std::atomic<T> rmsAccum{ T(0) };
365 std::atomic<T> vu{ T(0) };
366 double vuS1 = 0.0, vuS2 = 0.0;
367 };
368
369 double sampleRate_ = 44100.0;
370 int numChannels_ = 0;
371
372 std::atomic<T> attackMs_ { T(1) };
373 std::atomic<T> releaseMs_ { T(100) };
374 std::atomic<T> rmsWindowMs_ { T(300) };
375
376 std::atomic<T> attackCoeff_ { T(0) };
377 std::atomic<T> releaseCoeff_ { T(0) };
378 std::atomic<T> rmsCoeff_ { T(0) };
379 std::atomic<bool> vuOn_ { false };
380 double vuG_ = 0.0, vuA1_ = 1.0;
381
382 std::array<ChannelState, MaxChannels> state_{};
383};
384
385} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Per-channel peak and RMS envelope follower with lock-free readout.
T getAttackMs() const noexcept
Returns the peak attack time in milliseconds.
T getRmsWindowMs() const noexcept
Returns the RMS integration time constant in milliseconds.
void setVuEnabled(bool on) noexcept
Runs the volume-unit needle too (see the file notes; off by default, when it costs nothing)....
void prepare(const AudioSpec &spec) noexcept
Prepares the follower for the given audio environment.
T getRmsLevelDb(int channel) const noexcept
Returns the current RMS level in decibels (optimized).
void setReleaseMs(float ms) noexcept
Sets the release time for peak metering.
void setRmsWindowMs(float ms) noexcept
Sets the integration time constant for RMS metering.
T getPeakLevelDb(int channel) const noexcept
Returns the current peak level in decibels.
void process(AudioBufferView< const T > buffer) noexcept
Processes a block of audio and updates level tracking.
T getVuLevelDb(int channel) const noexcept
The needle in decibels (floored at -100).
T getPeakLevel(int channel) const noexcept
Returns the current peak level for the given channel safely.
void setAttackMs(float ms) noexcept
Sets the attack time for peak metering.
void reset() noexcept
Resets all envelope states to zero safely.
T getVuLevel(int channel) const noexcept
The volume-unit needle (setVuEnabled()), linear: a steady sine reads its RMS.
T getRmsLevel(int channel) const noexcept
Returns the current RMS level for the given channel safely.
T getReleaseMs() const noexcept
Returns the peak release time in milliseconds.
bool isVuEnabled() const noexcept
Main namespace for the DSPark framework.
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37