DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
LoudnessNormalizer.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
48#include "../Core/AudioBuffer.h"
49#include "../Core/DenormalGuard.h"
50#include "../Core/DspMath.h"
51#include "../Core/TruePeakDetector.h"
52#include "LoudnessMeter.h"
53
54#include <algorithm>
55#include <atomic>
56#include <cmath>
57#include <cstdint>
58#include <limits>
59
60namespace dspark {
61
73template <FloatType T>
75{
76public:
78 enum class Status : std::uint8_t
79 {
80 Success,
86 };
87
89 struct Result
90 {
92 T measuredLUFS = T(-100);
93 T requestedGainDb = T(0);
94 T appliedGainDb = T(0);
95 T outLUFS = T(-100);
96 T outTruePeakDb = T(-100);
97 bool targetReached = false;
98 bool ceilingLimited = false;
99 };
100
101 // -- Parameters (control thread, between runs) ----------------------------
102
104 void setTargetLUFS(T target) noexcept
105 {
106 if (std::isfinite(target))
107 targetLUFS_.store(target, std::memory_order_relaxed);
108 }
109
111 [[nodiscard]] T getTargetLUFS() const noexcept
112 {
113 return targetLUFS_.load(std::memory_order_relaxed);
114 }
115
122 void setTruePeakCeilingDb(T ceilingDb) noexcept
123 {
124 if (std::isfinite(ceilingDb))
125 ceilingDb_.store(std::clamp(ceilingDb, T(-40), T(0)),
126 std::memory_order_relaxed);
127 }
128
130 [[nodiscard]] T getTruePeakCeilingDb() const noexcept
131 {
132 return ceilingDb_.load(std::memory_order_relaxed);
133 }
134
135 // -- Offline processing ---------------------------------------------------
136
148 template <int MaxChannels>
150 double sampleRate)
151 {
152 DenormalGuard guard;
153
154 Result out;
155 const int numChannels = audio.getNumChannels();
156 const int numSamples = audio.getNumSamples();
157 if (numChannels <= 0 || numSamples <= 0)
158 {
160 return out;
161 }
162 if (!std::isfinite(sampleRate) || sampleRate <= 0.0)
163 {
165 return out;
166 }
167
168 T maxAbsInput = T(0);
169 for (int channel = 0; channel < numChannels; ++channel)
170 {
171 const T* samples = audio.getChannel(channel);
172 for (int i = 0; i < numSamples; ++i)
173 {
174 const T sample = samples[i];
175 if (!std::isfinite(sample))
176 {
178 return out;
179 }
180 maxAbsInput = std::max(maxAbsInput, std::abs(sample));
181 }
182 }
183
184 const T measured = measureIntegrated(audio, sampleRate);
185 if (!meter_.isMeasurementValid())
186 {
188 return out;
189 }
190 const T inputTruePeak = measureTruePeakLinear(audio);
191 if (!std::isfinite(measured) || !std::isfinite(inputTruePeak)
192 || inputTruePeak < T(0))
193 {
195 return out;
196 }
197
198 if (measured <= kMeterFloorLUFS || !(inputTruePeak > T(0)))
199 {
200 out.measuredLUFS = measured;
202 out.outLUFS = measured;
203 out.outTruePeakDb = linearToDecibels(inputTruePeak, T(-100));
204 return out;
205 }
206
207 const T target = targetLUFS_.load(std::memory_order_relaxed);
208 const T ceilingDb = ceilingDb_.load(std::memory_order_relaxed);
209 const T requestedGainDb = gainReachingTarget(audio, sampleRate, target, measured);
210 const T requestedLinear = decibelsToLinear(requestedGainDb);
211 const T ceilingLinear = decibelsToLinear(ceilingDb);
212 const T ceilingSafeLinear = static_cast<T>(
213 static_cast<double>(ceilingLinear) * (1.0 - kCeilingAimMargin)
214 / static_cast<double>(inputTruePeak));
215 const T appliedLinear = std::min(requestedLinear, ceilingSafeLinear);
216 const T appliedGainDb = linearToDecibels(appliedLinear, T(0));
217
218 if (!std::isfinite(requestedGainDb) || !std::isfinite(requestedLinear)
219 || !std::isfinite(ceilingLinear)
220 || !std::isfinite(ceilingSafeLinear)
221 || !std::isfinite(appliedLinear) || !(appliedLinear > T(0))
222 || !std::isfinite(appliedGainDb)
223 || static_cast<long double>(maxAbsInput)
224 > static_cast<long double>(std::numeric_limits<T>::max())
225 / static_cast<long double>(appliedLinear))
226 {
228 return out;
229 }
230
231 out.measuredLUFS = measured;
232 out.requestedGainDb = requestedGainDb;
233 out.appliedGainDb = appliedGainDb;
234 out.ceilingLimited = ceilingSafeLinear < requestedLinear;
235
236 // This is the only caller-buffer mutation in the operation.
237 for (int channel = 0; channel < numChannels; ++channel)
238 {
239 T* samples = audio.getChannel(channel);
240 for (int i = 0; i < numSamples; ++i)
241 samples[i] = static_cast<T>(samples[i] * appliedLinear);
242 }
243
244 out.outLUFS = measureIntegrated(audio, sampleRate);
245 out.outTruePeakDb = linearToDecibels(measureTruePeakLinear(audio), T(-100));
246 out.targetReached = std::abs(out.outLUFS - target) <= kTargetToleranceLU;
248 return out;
249 }
250
251private:
252 static constexpr T kMeterFloorLUFS = T(-99);
253 static constexpr T kTargetToleranceLU = T(0.1);
254 static constexpr double kCeilingAimMargin = 1.0e-4;
255 static constexpr T kGainSettledLU = T(0.01);
256 static constexpr int kMaxGainPasses = 4;
257 static constexpr int kProbeFrames = 1024;
258
259 [[nodiscard]] static T decibelsToLinear(T decibels) noexcept
260 {
261 return static_cast<T>(
262 std::pow(10.0, static_cast<double>(decibels) / 20.0));
263 }
264
265 [[nodiscard]] static T linearToDecibels(T gain, T zeroSentinel) noexcept
266 {
267 return gain > T(0)
268 ? static_cast<T>(20.0 * std::log10(static_cast<double>(gain)))
269 : zeroSentinel;
270 }
271
272 template <int MaxChannels>
273 [[nodiscard]] T measureIntegrated(const AudioBuffer<T, MaxChannels>& audio,
274 double sampleRate) noexcept
275 {
276 const int numChannels = audio.getNumChannels();
277 meter_.prepare(sampleRate, std::min(numChannels, 2));
278 meter_.reset();
279 if (numChannels >= 2)
280 meter_.process(audio.getChannel(0), audio.getChannel(1),
281 audio.getNumSamples());
282 else
283 meter_.process(audio.getChannel(0), audio.getNumSamples());
284 return meter_.getIntegratedLUFS();
285 }
286
295 template <int MaxChannels>
296 [[nodiscard]] T gainReachingTarget(const AudioBuffer<T, MaxChannels>& audio,
297 double sampleRate, T target, T measured) noexcept
298 {
299 T gainDb = target - measured;
300 T bestGainDb = gainDb;
301 T bestMiss = std::numeric_limits<T>::infinity();
302 for (int pass = 0; pass < kMaxGainPasses; ++pass)
303 {
304 const T level = measureIntegrated(audio, sampleRate, decibelsToLinear(gainDb));
305 if (!std::isfinite(level) || level <= kMeterFloorLUFS) break;
306 const T miss = target - level;
307 if (std::abs(miss) < bestMiss)
308 {
309 bestMiss = std::abs(miss);
310 bestGainDb = gainDb;
311 }
312 if (std::abs(miss) <= kGainSettledLU) break;
313 gainDb += miss;
314 }
315 return bestGainDb;
316 }
317
319 template <int MaxChannels>
320 [[nodiscard]] T measureIntegrated(const AudioBuffer<T, MaxChannels>& audio,
321 double sampleRate, T gain) noexcept
322 {
323 const int numChannels = audio.getNumChannels();
324 const int numSamples = audio.getNumSamples();
325 meter_.prepare(sampleRate, std::min(numChannels, 2));
326 meter_.reset();
327 T left[kProbeFrames];
328 T right[kProbeFrames];
329 for (int first = 0; first < numSamples; first += kProbeFrames)
330 {
331 const int count = std::min(kProbeFrames, numSamples - first);
332 for (int i = 0; i < count; ++i)
333 left[i] = audio.getChannel(0)[first + i] * gain;
334 if (numChannels >= 2)
335 {
336 for (int i = 0; i < count; ++i)
337 right[i] = audio.getChannel(1)[first + i] * gain;
338 meter_.process(left, right, count);
339 }
340 else
341 meter_.process(left, count);
342 }
343 return meter_.getIntegratedLUFS();
344 }
345
346 template <int MaxChannels>
347 [[nodiscard]] static T measureTruePeakLinear(
348 const AudioBuffer<T, MaxChannels>& audio) noexcept
349 {
350 TruePeakDetector<T, MaxChannels> detector;
351 detector.reset();
352 T peak = T(0);
353 for (int channel = 0; channel < audio.getNumChannels(); ++channel)
354 {
355 const T* samples = audio.getChannel(channel);
356 for (int i = 0; i < audio.getNumSamples(); ++i)
357 peak = std::max(peak, detector.processSample(samples[i], channel));
358 for (int i = 0; i < TruePeakDetector<T, MaxChannels>::getTaps() - 1; ++i)
359 peak = std::max(peak, detector.processSample(T(0), channel));
360 }
361 return peak;
362 }
363
364 std::atomic<T> targetLUFS_ { T(-23) };
365 std::atomic<T> ceilingDb_ { T(-1) };
366 LoudnessMeter<T> meter_;
367};
368
369} // namespace dspark
Owning audio buffer with contiguous, 32-byte aligned storage.
int getNumChannels() const noexcept
Returns the number of active channels.
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
int getNumSamples() const noexcept
Returns the number of samples per channel.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Offline waveform-preserving LUFS normalizer with a hard true-peak ceiling.
void setTruePeakCeilingDb(T ceilingDb) noexcept
Sets the true-peak ceiling (default -1 dBTP).
void setTargetLUFS(T target) noexcept
Sets the target integrated loudness (default -23 LUFS).
T getTruePeakCeilingDb() const noexcept
Result normalize(AudioBuffer< T, MaxChannels > &audio, double sampleRate)
Normalizes audio in place with one validated constant gain.
Status
Completion or conservative no-mutation outcome.
Main namespace for the DSPark framework.
Measurements and the constant-gain decision for one run.
T appliedGainDb
One gain applied to every sample.
T outTruePeakDb
All-channel output true peak.
bool targetReached
Output is within 0.1 LU of target.
bool ceilingLimited
The ceiling selected the lower gain.
T outLUFS
Re-measured output loudness.
T measuredLUFS
Integrated loudness of the input.
T requestedGainDb
Gain needed to reach the target.