DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
CharacterStage.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
55#include "AudioBuffer.h"
56#include "AudioSpec.h"
57#include "DenormalGuard.h"
58#include "DspMath.h"
59#include "Oversampling.h"
60
61#include <algorithm>
62#include <atomic>
63#include <cmath>
64#include <cstddef>
65#include <cstdint>
66#include <memory>
67#include <vector>
68
69namespace dspark {
70
77template <FloatType T>
79{
80public:
82 struct Settings
83 {
84 T driveDb = T(6);
85 T emphasisDb = T(6);
86 T asymmetry = T(0.3);
87 T drift = T(0);
88 T sag = T(0);
89 T noiseDb = T(-140);
90 };
91
92 static constexpr int kMaxChannels = 16;
93
101 void prepare(const AudioSpec& spec)
102 {
103 if (!spec.isValid()) return;
104 sampleRate_ = spec.sampleRate;
105 maxBlock_ = spec.maxBlockSize;
106 numChannels_ = std::min(spec.numChannels, kMaxChannels);
107 factor_ = Oversampling<T>::factorForRate(sampleRate_);
108 if (factor_ > 1)
109 {
110 oversampler_ = std::make_unique<Oversampling<T>>(factor_, Oversampling<T>::Quality::High,
112 oversampler_->prepare(AudioSpec { sampleRate_, maxBlock_, numChannels_ });
113 }
114 else
115 {
116 oversampler_.reset();
117 }
118 const double fs = sampleRate_;
119 sagUp_ = 1.0 - std::exp(-1.0 / (0.030 * fs));
120 sagDown_ = 1.0 - std::exp(-1.0 / (0.300 * fs));
121 noiseRate_ = 1.0 - std::exp(-1.0 / (0.050 * fs));
122 dcPole_ = std::exp(-2.0 * 3.141592653589793 * 5.0 / fs);
123 driftRate_ = 1.0 - std::exp(-2.0 * 3.141592653589793 * kDriftHz * kDriftTick / fs);
124 // A one-pole of rate r over a uniform in [-1, 1) has a deviation of
125 // sqrt(r / (3 (2 - r))): scaled to about one.
126 driftScale_ = 1.0 / std::sqrt(driftRate_ / (3.0 * (2.0 - driftRate_)));
127 emphasisGlide_ = 1.0 - std::exp(-1.0 / (0.020 * fs));
128 ch_.assign(static_cast<size_t>(numChannels_), Channel {});
129 driveLin_.assign(static_cast<size_t>(numChannels_) * static_cast<size_t>(maxBlock_), 1.0);
130 biasNow_.assign(driveLin_.size(), 0.0);
131 reset();
132 }
133
135 void reset() noexcept
136 {
137 for (size_t ch = 0; ch < ch_.size(); ++ch)
138 {
139 Channel& c = ch_[ch];
140 c = Channel {};
141 c.rng = 0x9E3779B9u * static_cast<std::uint32_t>(ch + 1) + 0x7F4A7C15u;
142 c.driftTick = 0;
143 }
144 const Settings s = settings();
145 driveNow_ = static_cast<double>(s.driveDb);
146 emphasisNow_ = static_cast<double>(s.emphasisDb);
147 if (sampleRate_ > 0.0) designEmphasis(emphasisNow_);
148 if (oversampler_) oversampler_->reset();
149 }
150
152 void setSettings(const Settings& s) noexcept
153 {
154 store(driveDb_, s.driveDb, T(0), T(24));
155 store(emphasisDb_, s.emphasisDb, T(0), T(12));
156 store(asymmetry_, s.asymmetry, T(0), T(1));
157 store(drift_, s.drift, T(0), T(1));
158 store(sag_, s.sag, T(0), T(1));
159 store(noiseDb_, s.noiseDb, T(-140), T(-40));
160 }
161
163 [[nodiscard]] Settings settings() const noexcept
164 {
165 return { driveDb_.load(std::memory_order_relaxed), emphasisDb_.load(std::memory_order_relaxed),
166 asymmetry_.load(std::memory_order_relaxed), drift_.load(std::memory_order_relaxed),
167 sag_.load(std::memory_order_relaxed), noiseDb_.load(std::memory_order_relaxed) };
168 }
169
171 [[nodiscard]] int getLatency() const noexcept { return oversampler_ ? oversampler_->getLatency() : 0; }
172
174 [[nodiscard]] int getFactor() const noexcept { return factor_; }
175
185 void process(AudioBufferView<T> buffer) noexcept
186 {
187 if (!(sampleRate_ > 0.0) || maxBlock_ <= 0) return;
188 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
189 const int nS = buffer.getNumSamples();
190 if (nCh <= 0 || nS <= 0) return;
191 DenormalGuard guard;
192 T* channels[kMaxChannels] = {};
193 for (int off = 0; off < nS; off += maxBlock_)
194 {
195 const int m = std::min(maxBlock_, nS - off);
196 for (int ch = 0; ch < nCh; ++ch) channels[ch] = buffer.getChannel(ch) + off;
197 processPart(AudioBufferView<T>(channels, nCh, m));
198 }
199 }
200
201private:
202 struct Channel
203 {
204 double pre1 = 0.0;
205 double post1 = 0.0;
206 double sagEnv = 0.0;
207 double noiseEnv = 0.0;
208 double dcX1 = 0.0, dcY1 = 0.0;
209 double driftDb = 0.0, driftBias = 0.0;
210 double driftDbFrom = 0.0, driftBiasFrom = 0.0;
211 double driftDbTo = 0.0, driftBiasTo = 0.0;
212 double wanderDb = 0.0, wanderBias = 0.0;
213 int driftTick = 0;
214 std::uint32_t rng = 1u;
215 };
216
217 static constexpr double kEmphasisHz = 3000.0;
218 static constexpr double kSecond = 1.5;
219 static constexpr double kBias = 0.35;
220 static constexpr double kSagGain = 2.0;
221 static constexpr double kDriftDb = 1.5;
222 static constexpr double kDriftBias = 0.08;
223 static constexpr double kDriftHz = 0.3;
224 static constexpr int kDriftTick = 64;
225
226 static void store(std::atomic<T>& a, T v, T lo, T hi) noexcept
227 {
228 if (std::isfinite(v)) a.store(std::clamp(v, lo, hi), std::memory_order_relaxed);
229 }
230
232 static double uniform(std::uint32_t& s) noexcept
233 {
234 s ^= s << 13; s ^= s >> 17; s ^= s << 5;
235 return static_cast<double>(s) * (2.0 / 4294967296.0) - 1.0;
236 }
237
243 void designEmphasis(double db) noexcept
244 {
245 const double fsInt = sampleRate_ * factor_;
246 const double gain = std::pow(10.0, db / 20.0);
247 const double root = std::sqrt(gain);
248 const double kk = 2.0 * fsInt;
249 const double wz = kk * std::tan(3.141592653589793 * std::min(kEmphasisHz / root, 0.45 * fsInt) / fsInt);
250 const double wp = kk * std::tan(3.141592653589793 * std::min(kEmphasisHz * root, 0.45 * fsInt) / fsInt);
251 const double scale = wp / wz;
252 preB0_ = scale * (kk + wz) / (kk + wp);
253 preB1_ = scale * (wz - kk) / (kk + wp);
254 preA1_ = (wp - kk) / (kk + wp);
255 }
256
257 void processPart(AudioBufferView<T> part) noexcept
258 {
259 const int nCh = part.getNumChannels();
260 const int n = part.getNumSamples();
261 const Settings s = settings();
262
263 // The emphasis glides once per block towards its setting.
264 const double emphTarget = static_cast<double>(s.emphasisDb);
265 if (emphasisNow_ != emphTarget)
266 {
267 const double glide = 1.0 - std::pow(1.0 - emphasisGlide_, static_cast<double>(n));
268 emphasisNow_ += glide * (emphTarget - emphasisNow_);
269 if (std::abs(emphTarget - emphasisNow_) < 1e-4) emphasisNow_ = emphTarget;
270 designEmphasis(emphasisNow_);
271 }
272 const double driveFrom = driveNow_, driveTo = static_cast<double>(s.driveDb);
273 driveNow_ = driveTo;
274 const double asym = static_cast<double>(s.asymmetry) * kBias;
275 const double drift = static_cast<double>(s.drift);
276 const double sag = static_cast<double>(s.sag) * kSagGain;
277 const bool noisy = s.noiseDb > T(-140);
278 const double noiseGain = noisy ? std::pow(10.0, static_cast<double>(s.noiseDb) / 20.0) * 1.7320508075688772 : 0.0;
279
280 // Host rate: the envelopes and the drift, per sample, into arrays the
281 // internal rate reads (held across each group of factor_ samples).
282 for (int ch = 0; ch < nCh; ++ch)
283 {
284 Channel& c = ch_[static_cast<size_t>(ch)];
285 T* x = part.getChannel(ch);
286 double* drive = driveLin_.data() + static_cast<size_t>(ch) * static_cast<size_t>(maxBlock_);
287 double* bias = biasNow_.data() + static_cast<size_t>(ch) * static_cast<size_t>(maxBlock_);
288 for (int i = 0; i < n; ++i)
289 {
290 const T raw = x[i];
291 if (!std::isfinite(raw)) x[i] = T(0);
292 const double level = std::abs(static_cast<double>(x[i]));
293 c.sagEnv += (level > c.sagEnv ? sagUp_ : sagDown_) * (level - c.sagEnv);
294 c.noiseEnv += noiseRate_ * (level - c.noiseEnv);
295 if (c.driftTick == 0)
296 {
297 c.driftDbFrom = c.driftDbTo;
298 c.driftBiasFrom = c.driftBiasTo;
299 c.wanderDb += driftRate_ * (uniform(c.rng) - c.wanderDb);
300 c.wanderBias += driftRate_ * (uniform(c.rng) - c.wanderBias);
301 c.driftDbTo = driftScale_ * c.wanderDb;
302 c.driftBiasTo = driftScale_ * c.wanderBias;
303 }
304 const double t = static_cast<double>(c.driftTick + 1) / kDriftTick;
305 c.driftDb = c.driftDbFrom + t * (c.driftDbTo - c.driftDbFrom);
306 c.driftBias = c.driftBiasFrom + t * (c.driftBiasTo - c.driftBiasFrom);
307 c.driftTick = (c.driftTick + 1) % kDriftTick;
308
309 const double ramp = driveFrom + (driveTo - driveFrom) * (static_cast<double>(i + 1) / n);
310 const double db = ramp + drift * kDriftDb * std::clamp(c.driftDb, -1.0, 1.0);
311 drive[i] = std::pow(10.0, db / 20.0) * (1.0 + sag * c.sagEnv);
312 bias[i] = asym + drift * kDriftBias * std::clamp(c.driftBias, -1.0, 1.0);
313 }
314 }
315
316 // Internal rate: emphasis, saturators, de-emphasis.
317 AudioBufferView<T> work = oversampler_ ? oversampler_->upsample(part) : part;
318 const double invB0 = 1.0 / preB0_, postB1 = preA1_ * invB0, postA1 = preB1_ * invB0;
319 for (int ch = 0; ch < nCh; ++ch)
320 {
321 Channel& c = ch_[static_cast<size_t>(ch)];
322 T* u = work.getChannel(ch);
323 const double* drive = driveLin_.data() + static_cast<size_t>(ch) * static_cast<size_t>(maxBlock_);
324 const double* bias = biasNow_.data() + static_cast<size_t>(ch) * static_cast<size_t>(maxBlock_);
325 double pre1 = c.pre1, post1 = c.post1;
326 for (int i = 0, j = 0; i < n; ++i)
327 {
328 const double g = drive[i], b = bias[i];
329 const double tb = std::tanh(b);
330 const double back = 1.0 / (g * (1.0 - tb * tb)); // the chain's small-signal gain, undone
331 for (int k = 0; k < factor_; ++k, ++j)
332 {
333 const double in = static_cast<double>(u[j]);
334 // Emphasis, transposed direct form II.
335 const double e = preB0_ * in + pre1;
336 pre1 = preB1_ * in - preA1_ * e;
337 const double s1 = std::tanh(g * e + b) - tb;
338 const double y = std::tanh(kSecond * s1) * (back / kSecond);
339 // De-emphasis: the inverse of the emphasis.
340 const double d = invB0 * y + post1;
341 post1 = postB1 * y - postA1 * d;
342 u[j] = static_cast<T>(d);
343 }
344 }
345 if (!std::isfinite(pre1 + post1)) { pre1 = 0.0; post1 = 0.0; }
346 c.pre1 = pre1;
347 c.post1 = post1;
348 }
349 if (oversampler_) oversampler_->downsample(part);
350
351 // Host rate: the coupling high-pass and the noise floor.
352 for (int ch = 0; ch < nCh; ++ch)
353 {
354 Channel& c = ch_[static_cast<size_t>(ch)];
355 T* x = part.getChannel(ch);
356 double x1 = c.dcX1, y1 = c.dcY1, env = c.noiseEnv;
357 for (int i = 0; i < n; ++i)
358 {
359 const double v = static_cast<double>(x[i]);
360 const double hp = v - x1 + dcPole_ * y1;
361 x1 = v;
362 y1 = hp;
363 double out = hp;
364 if (noisy) out += noiseGain * env * uniform(c.rng);
365 x[i] = static_cast<T>(out);
366 }
367 if (!std::isfinite(x1 + y1)) { x1 = 0.0; y1 = 0.0; }
368 c.dcX1 = x1;
369 c.dcY1 = y1;
370 }
371 }
372
373 std::atomic<T> driveDb_ { T(6) };
374 std::atomic<T> emphasisDb_ { T(6) };
375 std::atomic<T> asymmetry_ { T(0.3) };
376 std::atomic<T> drift_ { T(0) };
377 std::atomic<T> sag_ { T(0) };
378 std::atomic<T> noiseDb_ { T(-140) };
379
380 double sampleRate_ = 0.0;
381 int maxBlock_ = 0;
382 int numChannels_ = 0;
383 int factor_ = 1;
384 std::unique_ptr<Oversampling<T>> oversampler_;
385 std::vector<Channel> ch_;
386 std::vector<double> driveLin_;
387 std::vector<double> biasNow_;
388
389 double preB0_ = 1.0, preB1_ = 0.0, preA1_ = 0.0;
390 double driveNow_ = 6.0, emphasisNow_ = 6.0;
391 double sagUp_ = 0.0, sagDown_ = 0.0, noiseRate_ = 0.0, dcPole_ = 0.0, driftRate_ = 0.0, emphasisGlide_ = 0.0;
392 double driftScale_ = 1.0;
393};
394
395} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Emphasis, static saturators and de-emphasis, with drift, sag and noise.
Settings settings() const noexcept
void process(AudioBufferView< T > buffer) noexcept
Colours a block in place.
void prepare(const AudioSpec &spec)
Allocates the oversampler and the scratch, and clears the state.
void setSettings(const Settings &s) noexcept
Sets every setting at once (clamped; non-finite fields are ignored). Any thread.
int getLatency() const noexcept
int getFactor() const noexcept
static constexpr int kMaxChannels
void reset() noexcept
Clears every memory and restarts the random sources. Audio thread.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Power-of-two oversampling processor with polyphase anti-aliasing.
static constexpr int factorForRate(double sampleRate, double minimumInternalRate=176400.0, int maxFactor=1<< kMaxStages) noexcept
The smallest factor that brings a host rate up to an internal rate.
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
The settings of the stage.
T driveDb
Gain into the saturators, [0, 24] dB (the level out does not follow it).
T sag
How much a slow envelope of the input raises the drive, [0, 1].
T asymmetry
Bias of the first saturator, [0, 1]: even harmonics.
T emphasisDb
High shelf before the saturators, undone after them, [0, 12] dB.
T drift
Slow random wander of drive (up to 1.5 dB) and bias, [0, 1].
T noiseDb
Noise relative to the input's envelope, [-140, -40] dB; -140 is none.