DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
WaveshapeTable.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
41#include "DspMath.h"
42#include "AudioSpec.h"
43#include "AudioBuffer.h"
44#include "Oversampling.h"
45#include "Interpolation.h"
46
47#include <algorithm>
48#include <array>
49#include <cassert>
50#include <cmath>
51#include <functional>
52#include <memory>
53#include <vector>
54
55namespace dspark {
56
63template <FloatType T>
65{
66public:
71 {
72 buildFromFunction([](T x) { return x; }, 4);
73 }
74
89 void buildFromFunction(std::function<T(T)> func, int tableSize = 4096, T xMax = T(8))
90 {
91 assert(tableSize >= 4);
92 assert(xMax > T(0));
93
94 // Release-safe clamps: a tableSize below 4 makes process() compute
95 // negative table positions (out-of-bounds reads), and a huge one
96 // overflows the 32-bit size_t arithmetic on WASM. Invalid xMax
97 // (non-positive or NaN) falls back to the default half-range.
98 tableSize = std::clamp(tableSize, 4, 1 << 20);
99 if (!(xMax > T(0))) xMax = T(8);
100
101 tableSize_ = tableSize;
102 xMax_ = std::max(xMax, T(0.001));
103 invRange_ = T(1) / (T(2) * xMax_);
104
105 // Allocate tableSize + 3 to accommodate Hermite interpolation padding.
106 // This eliminates conditional branch bounds-checking in the DSP hot-path.
107 table_.resize(static_cast<size_t>(tableSize) + 3);
108
109 for (int i = 0; i < tableSize; ++i)
110 {
111 T x = -xMax_ + T(2) * xMax_ * static_cast<T>(i) / static_cast<T>(tableSize - 1);
112 table_[static_cast<size_t>(i + 1)] = func(x); // Offset by 1
113 }
114
115 // Pad boundaries for Hermite (mirroring endpoints)
116 table_[0] = table_[1];
117 table_[static_cast<size_t>(tableSize + 1)] = table_[static_cast<size_t>(tableSize)];
118 table_[static_cast<size_t>(tableSize + 2)] = table_[static_cast<size_t>(tableSize)];
119
120 // Antiderivative at every knot, integrating the interpolated curve
121 // segment by segment (exact for the Hermite cubic), in double: the
122 // ADAA difference quotient cancels most of its digits.
123 step_ = 2.0 * static_cast<double>(xMax_) / static_cast<double>(tableSize - 1);
124 integral_.assign(static_cast<size_t>(tableSize), 0.0);
125 for (int i = 0; i + 1 < tableSize; ++i)
126 integral_[static_cast<size_t>(i + 1)] = integral_[static_cast<size_t>(i)]
127 + step_ * segmentIntegral(i + 1, 1.0);
128 resetAntialiasing();
129 }
130
136 void buildTanh(int tableSize = 4096)
137 {
138 buildFromFunction([](T x) -> T { return std::tanh(x); }, tableSize);
139 }
140
146 void buildHardClip(T threshold = T(0.8), int tableSize = 4096)
147 {
148 buildFromFunction([threshold](T x) -> T {
149 return std::clamp(x, -threshold, threshold);
150 }, tableSize);
151 }
152
157 void buildSoftClip(int tableSize = 4096)
158 {
159 buildFromFunction([](T x) -> T {
160 if (x > T(1)) return T(2.0 / 3.0);
161 if (x < T(-1)) return T(-2.0 / 3.0);
162 return x - (x * x * x) / T(3);
163 }, tableSize);
164 }
165
170 void buildAsymmetric(int tableSize = 4096)
171 {
172 buildFromFunction([](T x) -> T {
173 return x >= T(0) ? std::tanh(x * T(1.2)) : std::tanh(x * T(0.8));
174 }, tableSize);
175 }
176
185 [[nodiscard]] inline T process(T input, T preGain = T(1), T postGain = T(1)) const noexcept
186 {
187 // The table spans [-xMax, xMax] (default 8), so realistic drive values
188 // keep tracing the curve instead of flattening at the old +-1 boundary.
189 // min/max are ordered so that a NaN (input or preGain) resolves to the
190 // upper table edge instead of reaching the int cast below (undefined)
191 // and indexing out of bounds: the output stays finite.
192 T driven = std::max(-xMax_, std::min(xMax_, input * preGain));
193
194 // Map to index range [0, tableSize - 1]
195 T pos = (driven + xMax_) * invRange_ * static_cast<T>(tableSize_ - 1);
196
197 int idx = static_cast<int>(pos);
198 T frac = pos - static_cast<T>(idx);
199
200 // Base index offset by +1 due to left-side padding
201 const T* t = table_.data() + idx + 1;
202
203 // Catmull-Rom smoothing via the shared Hermite kernel (Interpolation.h)
204 return interpolateHermite(t[-1], t[0], t[1], t[2], frac) * postGain;
205 }
206
218 void process(T* __restrict data, int numSamples, T preGain = T(1), T postGain = T(1)) const noexcept
219 {
220 for (int i = 0; i < numSamples; ++i)
221 data[i] = process(data[i], preGain, postGain);
222 }
223
224 // -- Lifecycle & Oversampling ---------------------------------------------
225
230 void prepare(const AudioSpec& spec)
231 {
232 spec_ = spec;
233 if (oversamplingAutomatic_)
234 applyOversampling(Oversampling<T>::factorForRate(spec.sampleRate, kAutomaticInternalRate));
235 else if (oversampler_)
236 oversampler_->prepare(spec);
237 }
238
244 void setOversampling(int factor)
245 {
246 assert(factor >= 1 && (factor & (factor - 1)) == 0);
247 oversamplingAutomatic_ = false;
248 applyOversampling(factor);
249 }
250
265 {
266 if (on == oversamplingAutomatic_) return;
267 oversamplingAutomatic_ = on;
268 if (on && spec_.sampleRate > 0)
269 applyOversampling(Oversampling<T>::factorForRate(spec_.sampleRate, kAutomaticInternalRate));
270 }
271
273 [[nodiscard]] bool isOversamplingAutomatic() const noexcept { return oversamplingAutomatic_; }
274
275private:
276 void applyOversampling(int factor)
277 {
278 if (factor > 1)
279 {
280 oversampler_ = std::make_unique<Oversampling<T>>(factor);
281 // Oversampling normalises invalid factors release-safe (rounds
282 // down to a power of two); mirror the value it actually adopted
283 // so getOversamplingFactor() never lies about the running rate.
284 oversamplingFactor_ = oversampler_->getFactor();
285 if (spec_.sampleRate > 0)
286 oversampler_->prepare(spec_);
287 }
288 else
289 {
290 oversamplingFactor_ = 1;
291 oversampler_.reset();
292 }
293 }
294
295public:
296 [[nodiscard]] int getOversamplingFactor() const noexcept { return oversamplingFactor_; }
297
304 void processBlock(AudioBufferView<T> buffer, T preGain = T(1), T postGain = T(1)) noexcept
305 {
306 const bool adaa = antialias_;
307
308 auto shape = [&](T* data, int n, int ch) {
309 if (adaa && ch < kAntialiasChannels)
310 processAntialiased(data, n, preGain, postGain, ch);
311 else
312 process(data, n, preGain, postGain);
313 };
314
315 if (oversamplingFactor_ > 1 && oversampler_)
316 {
317 auto upView = oversampler_->upsample(buffer);
318 for (int ch = 0; ch < upView.getNumChannels(); ++ch)
319 shape(upView.getChannel(ch), upView.getNumSamples(), ch);
320 oversampler_->downsample(buffer);
321 }
322 else
323 {
324 for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
325 shape(buffer.getChannel(ch), buffer.getNumSamples(), ch);
326 }
327 }
328
346 void setAntialiasing(bool enabled) noexcept
347 {
348 if (enabled && !antialias_) resetAntialiasing();
349 antialias_ = enabled;
350 }
351
353 [[nodiscard]] bool isAntialiasingEnabled() const noexcept { return antialias_; }
354
355 void reset() noexcept
356 {
357 if (oversampler_) oversampler_->reset();
358 resetAntialiasing();
359 }
360
361 [[nodiscard]] int getTableSize() const noexcept { return tableSize_; }
362 [[nodiscard]] bool isReady() const noexcept { return tableSize_ > 0; }
363
365 [[nodiscard]] T getInputRange() const noexcept { return xMax_; }
366
372 [[nodiscard]] int getLatency() const noexcept
373 {
374 return (oversampler_ && oversamplingFactor_ > 1) ? oversampler_->getLatency() : 0;
375 }
376
377private:
378 static constexpr int kAntialiasChannels = 16;
379
382 [[nodiscard]] double segmentIntegral(int i, double u) const noexcept
383 {
384 const double y0 = table_[static_cast<size_t>(i - 1)];
385 const double y1 = table_[static_cast<size_t>(i)];
386 const double y2 = table_[static_cast<size_t>(i + 1)];
387 const double y3 = table_[static_cast<size_t>(i + 2)];
388 // Same coefficients as interpolateHermite(): ((a u - b) u + c) u + y1.
389 const double c = (y2 - y0) * 0.5;
390 const double v = y1 - y2;
391 const double w = c + v;
392 const double a = w + v + (y3 - y1) * 0.5;
393 const double b = w + a;
394 return (((a * 0.25 * u - b / 3.0) * u + c * 0.5) * u + y1) * u;
395 }
396
399 [[nodiscard]] double antiderivative(double x) const noexcept
400 {
401 const double xMax = static_cast<double>(xMax_);
402 const int last = tableSize_ - 1;
403 if (x >= xMax)
404 return integral_[static_cast<size_t>(last)]
405 + static_cast<double>(table_[static_cast<size_t>(last + 1)]) * (x - xMax);
406 if (x <= -xMax)
407 return static_cast<double>(table_[1]) * (x + xMax);
408 const double pos = (x + xMax) / step_;
409 const int idx = std::min(static_cast<int>(pos), last - 1);
410 return integral_[static_cast<size_t>(idx)] + step_ * segmentIntegral(idx + 1, pos - idx);
411 }
412
413 void processAntialiased(T* data, int numSamples, T preGain, T postGain, int ch) noexcept
414 {
415 // Out-of-range drive keeps its finite linear continuation; NaN lands
416 // on the upper edge, as in process().
417 const double limit = 1.0e3 * static_cast<double>(xMax_);
418 const auto c = static_cast<size_t>(ch);
419 double x0 = adaaX_[c];
420 double f0 = adaaF_[c];
421 const double post = static_cast<double>(postGain);
422 for (int i = 0; i < numSamples; ++i)
423 {
424 const double x = std::max(-limit, std::min(limit, static_cast<double>(data[i] * preGain)));
425 const double f = antiderivative(x);
426 if (!adaaPrimed_[c]) // first input after a reset: nothing to average with yet
427 {
428 x0 = x;
429 f0 = f;
430 adaaPrimed_[c] = true;
431 }
432 const double dx = x - x0;
433 double y;
434 if (std::abs(dx) > 1.0e-6)
435 y = (f - f0) / dx;
436 else // ill-conditioned: the mean over a vanishing segment is its midpoint value
437 y = static_cast<double>(process(static_cast<T>(0.5 * (x + x0))));
438 data[i] = static_cast<T>(y * post);
439 x0 = x;
440 f0 = f;
441 }
442 adaaX_[c] = x0;
443 adaaF_[c] = f0;
444 }
445
446 void resetAntialiasing() noexcept { adaaPrimed_.fill(false); }
447
448 std::vector<T> table_;
449 std::vector<double> integral_;
450 double step_ = 1.0;
451 bool antialias_ = false;
452 std::array<double, kAntialiasChannels> adaaX_ {};
453 std::array<double, kAntialiasChannels> adaaF_ {};
454 std::array<bool, kAntialiasChannels> adaaPrimed_ {};
455 int tableSize_ = 0;
456 T xMax_ = T(8);
457 T invRange_ = T(1) / T(16);
458
459 AudioSpec spec_ {};
460 std::unique_ptr<Oversampling<T>> oversampler_;
461 int oversamplingFactor_ = 1;
462 bool oversamplingAutomatic_ = false;
463 static constexpr double kAutomaticInternalRate = 88200.0;
464};
465
466} // 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.
Power-of-two oversampling processor with polyphase anti-aliasing.
Zero-latency lookup-table waveshaper with RT-safe gain modulation.
void buildTanh(int tableSize=4096)
Builds a normalized tanh (soft clip) table.
bool isAntialiasingEnabled() const noexcept
True when processBlock() applies ADAA.
int getLatency() const noexcept
Reports the processing latency in samples.
void buildSoftClip(int tableSize=4096)
Builds a cubic soft-clip table.
int getTableSize() const noexcept
T process(T input, T preGain=T(1), T postGain=T(1)) const noexcept
Processes a single sample through the waveshaper with Hermite interpolation.
void buildAsymmetric(int tableSize=4096)
Builds an asymmetric clipping table for even-harmonic generation.
void prepare(const AudioSpec &spec)
Prepares the waveshaper for oversampled block processing.
void setAutomaticOversampling(bool on)
Lets the host rate choose the factor (allocates: not from the audio thread).
void buildHardClip(T threshold=T(0.8), int tableSize=4096)
Builds a hard-clip table.
bool isOversamplingAutomatic() const noexcept
Whether the factor follows the host rate (setAutomaticOversampling()).
WaveshapeTable()
Constructor. Initializes a safe passthrough table to prevent RT crashes.
bool isReady() const noexcept
void buildFromFunction(std::function< T(T)> func, int tableSize=4096, T xMax=T(8))
Builds the lookup table from an arbitrary transfer function.
void setAntialiasing(bool enabled) noexcept
Enables first-order antiderivative anti-aliasing (ADAA) in processBlock().
void setOversampling(int factor)
Enables oversampling.
void processBlock(AudioBufferView< T > buffer, T preGain=T(1), T postGain=T(1)) noexcept
Processes a buffer view with optional oversampling.
void process(T *__restrict data, int numSamples, T preGain=T(1), T postGain=T(1)) const noexcept
Processes a buffer in-place.
T getInputRange() const noexcept
Returns the half-range of the table's input domain.
int getOversamplingFactor() const noexcept
Main namespace for the DSPark framework.
T interpolateHermite(T y0, T y1, T y2, T y3, T frac) noexcept
4-point, 3rd-order Hermite interpolation (optimized x-form).
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45