DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Dither.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
20#include <algorithm>
21#include <array>
22#include <atomic>
23#include <cmath>
24#include <cstdint>
25#include <limits>
26#include <type_traits>
27
28namespace dspark {
29
67template <typename T>
68class Dither
69{
70 static_assert(std::is_floating_point_v<T>, "Dither requires a floating-point sample type");
71
72public:
74 enum class Shaper
75 {
78 };
79
89 explicit Dither(int targetBits = 16, bool noiseShaping = false) noexcept
90 : noiseShaping_(noiseShaping)
91 {
92 static std::atomic<uint32_t> seedGenerator{ 0x193A6B54u };
93 // Increment by golden ratio to ensure diverse initial states across instances
94 rngState_ = seedGenerator.fetch_add(0x9E3779B9u, std::memory_order_relaxed);
95 // xorshift32 has a fixed point at 0: if the rolling seed ever lands
96 // there, the dither would fall silent for that instance.
97 if (rngState_ == 0) rngState_ = 1;
98
99 setTargetBitDepth(targetBits);
100 }
101
106 void setTargetBitDepth(int bits) noexcept
107 {
108 // float (32-bit IEEE 754) only has 24 bits of mantissa precision.
109 constexpr int maxBits = (sizeof(T) == 4) ? 24 : 32;
110 targetBits_ = std::clamp(bits, 8, maxBits);
111
112 // Levels per unit: 2^(N-1). The representable grid is asymmetric,
113 // [-levels, levels - 1], mirroring the signed-integer formats.
114 int64_t levels = int64_t(1) << (targetBits_ - 1);
115
116 quantScale_ = static_cast<T>(levels);
117 quantStep_ = T(1) / quantScale_;
118 loLevel_ = -quantScale_;
119 hiLevel_ = quantScale_ - T(1);
120 // Feedback cap: a legitimate shaping error never exceeds 1.5 LSB
121 // (TPDF within (-1, 1] LSB + quantiser within +-0.5 LSB); see
122 // processSampleInternal for why the cap is needed at all.
123 errorCap_ = T(2) * quantStep_;
124 }
125
127 void setNoiseShaping(bool enabled) noexcept { noiseShaping_ = enabled; }
128
130 void setShaper(Shaper shaper) noexcept
131 {
133 }
134
136 [[nodiscard]] Shaper getShaper() const noexcept { return shaper_; }
137
139 void reset() noexcept
140 {
141 for (auto& h : errorState_) h.fill(T(0));
142 }
143
151 [[nodiscard]] T processSample(T input, int channel = 0) noexcept
152 {
153 if (noiseShaping_ && channel >= 0 && channel < kMaxChannels)
154 return shaper_ == Shaper::Lipshitz5 ? processSampleInternal<5>(input, channel)
155 : processSampleInternal<1>(input, channel);
156 return processSampleInternal<0>(input, channel);
157 }
158
169 void processBlock(T* data, int numSamples, int channel = 0) noexcept
170 {
171 if (noiseShaping_ && channel >= 0 && channel < kMaxChannels)
172 {
173 if (shaper_ == Shaper::Lipshitz5)
174 for (int i = 0; i < numSamples; ++i)
175 data[i] = processSampleInternal<5>(data[i], channel);
176 else
177 for (int i = 0; i < numSamples; ++i)
178 data[i] = processSampleInternal<1>(data[i], channel);
179 }
180 else
181 {
182 for (int i = 0; i < numSamples; ++i)
183 data[i] = processSampleInternal<0>(data[i], channel);
184 }
185 }
186
187 [[nodiscard]] int getTargetBitDepth() const noexcept { return targetBits_; }
188 [[nodiscard]] T getQuantisationStep() const noexcept { return quantStep_; }
189
190private:
191 static constexpr int kMaxChannels = 16;
192 static constexpr int kMaxOrder = 5;
193
195 static constexpr T kLipshitz5[kMaxOrder] = { T(2.033), T(-2.165), T(1.959), T(-1.590), T(0.6149) };
196
201 template <int Order>
202 [[nodiscard]] inline T processSampleInternal(T input, int channel) noexcept
203 {
204 // Sanitise on entry: NaN would pass every clamp below and park in the
205 // error feedback for good. Values beyond +-2 quantise exactly like
206 // +-2 (the level clamp and the error cap both bind), so clamping
207 // there changes no output, and it turns infinities into full scale.
208 if (input != input) input = T(0);
209 input = std::clamp(input, T(-2), T(2));
210
211 // 2 LSB peak-to-peak TPDF noise
212 const T noise = (nextRandom() + nextRandom()) * quantStep_;
213
214 T preQuantise = input;
215
216 if constexpr (Order == 1)
217 {
218 preQuantise -= errorState_[static_cast<size_t>(channel)][0];
219 }
220 else if constexpr (Order == kMaxOrder)
221 {
222 const auto& e = errorState_[static_cast<size_t>(channel)];
223 preQuantise -= kLipshitz5[0] * e[0] + kLipshitz5[1] * e[1] + kLipshitz5[2] * e[2]
224 + kLipshitz5[3] * e[3] + kLipshitz5[4] * e[4];
225 }
226
227 // Add dither to the signal (w[n] = v[n] + d[n])
228 const T dithered = preQuantise + noise;
229
230 // Quantise on the integer level grid and clamp to the representable
231 // range of the target depth. Ties are broken by the dither, so the
232 // rounding mode of nearbyint (default round-to-nearest) is fine and
233 // compiles to a single instruction on SSE4.1/NEON.
234 const T level = std::clamp(std::nearbyint(dithered * quantScale_), loLevel_, hiLevel_);
235 const T quantised = level * quantStep_;
236
237 if constexpr (Order > 0)
238 {
239 // Feed back the TOTAL requantisation error e[n] = y[n] - v[n]
240 // (dither + quantiser), the classic error-feedback structure
241 // with the dither inside the loop: the whole noise floor is
242 // shaped, not just the quantiser error.
243 // The cap bounds the loop when the level clamp engages (input at
244 // or beyond positive full scale): without it the clip error
245 // accumulates sample after sample and pins the output at full
246 // scale long after the overload has passed.
247 auto& e = errorState_[static_cast<size_t>(channel)];
248 const T err = std::clamp(quantised - preQuantise, -errorCap_, errorCap_);
249 if constexpr (Order == kMaxOrder)
250 {
251 e[4] = e[3]; e[3] = e[2]; e[2] = e[1]; e[1] = e[0];
252 }
253 e[0] = err;
254 }
255
256 return quantised;
257 }
258
263 [[nodiscard]] inline T nextRandom() noexcept
264 {
265 rngState_ ^= rngState_ << 13;
266 rngState_ ^= rngState_ >> 17;
267 rngState_ ^= rngState_ << 5;
268
269 constexpr T scale = T(1) / static_cast<T>(std::numeric_limits<uint32_t>::max());
270 return static_cast<T>(rngState_) * scale - T(0.5);
271 }
272
273 int targetBits_ = 16;
274 T quantStep_ = T(1) / T(32768);
275 T quantScale_ = T(32768);
276 T loLevel_ = T(-32768);
277 T hiLevel_ = T(32767);
278 T errorCap_ = T(2) / T(32768);
279 bool noiseShaping_ = false;
280 Shaper shaper_ = Shaper::FirstOrder;
281 uint32_t rngState_;
282 std::array<std::array<T, kMaxOrder>, kMaxChannels> errorState_{};
283};
284
285} // namespace dspark
TPDF dithering processor with optional noise shaping.
Definition Dither.h:69
T processSample(T input, int channel=0) noexcept
Applies TPDF dither and quantises a single sample.
Definition Dither.h:151
T getQuantisationStep() const noexcept
Definition Dither.h:188
Shaper getShaper() const noexcept
Returns the selected noise-shaping filter.
Definition Dither.h:136
void setShaper(Shaper shaper) noexcept
Selects the noise-shaping filter (used while shaping is enabled).
Definition Dither.h:130
int getTargetBitDepth() const noexcept
Definition Dither.h:187
Shaper
Error-feedback filter used when noise shaping is enabled.
Definition Dither.h:75
@ Lipshitz5
5-tap psychoacoustic shaping for 44.1 kHz (Lipshitz et al. 1991).
@ FirstOrder
(1 - z^-1) shaping of the whole noise floor (default).
Dither(int targetBits=16, bool noiseShaping=false) noexcept
Constructs a dithering processor.
Definition Dither.h:89
void reset() noexcept
Resets the noise shaping state. Call this when playback stops or flushes.
Definition Dither.h:139
void setNoiseShaping(bool enabled) noexcept
Enables or disables noise shaping.
Definition Dither.h:127
void processBlock(T *data, int numSamples, int channel=0) noexcept
Applies dithering to an entire audio buffer in-place.
Definition Dither.h:169
void setTargetBitDepth(int bits) noexcept
Sets the target bit depth and recalculates scaling factors.
Definition Dither.h:106
Main namespace for the DSPark framework.