DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
TransientDesigner.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
46#include "../Core/DspMath.h"
47#include "../Core/AudioSpec.h"
48#include "../Core/AudioBuffer.h"
49#include "../Core/DenormalGuard.h"
50#include "../Core/Hilbert.h"
51#include "../Core/StateBlob.h"
52
53#include <algorithm>
54#include <array>
55#include <atomic>
56#include <cmath>
57#include <cstddef>
58#include <cstdint>
59#include <vector>
60
61namespace dspark {
62
73template <FloatType T>
75{
76public:
77 ~TransientDesigner() = default; // non-virtual: leaf class (no virtual dispatch)
78
79 // -- Lifecycle -----------------------------------------------------------
80
85 void prepare(const AudioSpec& spec) noexcept
86 {
87 if (!spec.isValid()) return;
88 prepare(spec.sampleRate);
89 }
90
98 void prepare(double sampleRate) noexcept
99 {
100 if (!std::isfinite(sampleRate) || sampleRate <= 0.0) return;
101 sampleRate_ = sampleRate;
102 updateCoefficients();
103 reset();
104 }
105
110 void processBlock(AudioBufferView<T> buffer) noexcept
111 {
112 DenormalGuard guard;
113 const int nCh = std::min(buffer.getNumChannels(), kMaxChannels);
114 const int nS = buffer.getNumSamples();
115
116 const T attAmt = attackAmount_.load(std::memory_order_relaxed);
117 const T susAmt = sustainAmount_.load(std::memory_order_relaxed);
118 const bool odr = outputDepRecovery_.load(std::memory_order_relaxed);
119
120 // Amount changes ramp at a fixed rate (a unit change over 10 ms) so a
121 // setAttack()/setSustain() during a transient cannot step the gain by
122 // up to 24 dB in one sample. The ramp is closed-form in the samples
123 // elapsed since the change, so every channel sees the same values and
124 // the result does not depend on the block partition.
125 if (attAmt != rampToAttack_ || susAmt != rampToSustain_)
126 {
127 const T done = static_cast<T>(rampStep_ * rampPos_);
128 rampFromAttack_ = moveTowards(rampFromAttack_, rampToAttack_, done);
129 rampFromSustain_ = moveTowards(rampFromSustain_, rampToSustain_, done);
130 rampToAttack_ = attAmt;
131 rampToSustain_ = susAmt;
132 rampPos_ = 0.0;
133 }
134 const bool ramping = (rampFromAttack_ != attAmt) || (rampFromSustain_ != susAmt);
135 const T att0 = rampFromAttack_, sus0 = rampFromSustain_;
136 const double pos0 = rampPos_;
137
138 // Constants for VCA log-domain emulation
139 constexpr T noiseFloor = T(1e-5); // -100 dB floor avoids log(0) and denormals
140 constexpr T maxGainLog = T(2.77258); // approx +24dB max gain change
141
142 // Outer loop: channels (state stays in registers)
143 for (int ch = 0; ch < nCh; ++ch)
144 {
145 T* const channelData = buffer.getChannel(ch);
146 auto& analytic = analytic_[static_cast<size_t>(ch)];
147 T fast = envFast_[ch];
148 T slow = envSlow_[ch];
149 T lastOut = lastOutput_[ch];
150
151 // Inner loop: serial envelope recursion per sample, fed in chunks
152 // by the analytic magnitude (computed section by section).
153 for (int i = 0; i < nS; ++i)
154 {
155 if (i % kDetChunk == 0)
156 {
157 const int n = std::min(kDetChunk, nS - i);
158 for (int j = 0; j < n; ++j)
159 {
160 // Non-finite samples read as silence in the detector
161 // (they would latch in the envelopes and the allpasses).
162 const T x = channelData[i + j];
163 detIn_[static_cast<size_t>(j)] = std::isfinite(x) ? static_cast<double>(x) : 0.0;
164 }
165 analytic.magnitudeBlock(detIn_.data(), detMag_.data(), n);
166 }
167 T sample = channelData[i];
168 const T envelopeLevel = std::max(
169 static_cast<T>(std::abs(detIn_[static_cast<size_t>(i % kDetChunk)])),
170 static_cast<T>(detMag_[static_cast<size_t>(i % kDetChunk)]));
171 T absSample = envelopeLevel + noiseFloor;
172
173 // 1. Fast envelope (Peak)
174 T fastCoeff = (absSample > fast) ? fastAttackCoeff_ : fastReleaseCoeff_;
175 fast += fastCoeff * (absSample - fast);
176
177 // 2. Slow envelope (Sustain/RMS tracker)
178 T currentSlowRelCoeff = slowReleaseCoeff_;
179
180 if (odr)
181 {
182 // Corrected ODR: Higher output = LARGER coefficient = Faster release
183 T modifier = T(1) + std::abs(lastOut) * T(2.0);
184 currentSlowRelCoeff = std::min(fastReleaseCoeff_, currentSlowRelCoeff * modifier);
185 }
186
187 T slowCoeff = (absSample > slow) ? slowAttackCoeff_ : currentSlowRelCoeff;
188 slow += slowCoeff * (absSample - slow);
189
190 // 3. Log-domain VCA computation (fastLog/fastExp: relative
191 // error < 2e-7 - far below audibility, ~3x faster than libm)
192 T diffLog = fastLog(fast) - fastLog(slow);
193
194 // Attack kicks in when fast > slow (diffLog > 0). Sustain when slow > fast (diffLog < 0)
195 const T stepNow = static_cast<T>(rampStep_ * (pos0 + static_cast<double>(i + 1)));
196 const T att = ramping ? moveTowards(att0, attAmt, stepNow) : attAmt;
197 const T sus = ramping ? moveTowards(sus0, susAmt, stepNow) : susAmt;
198 T gainLog = (diffLog > T(0)) ? (diffLog * att) : (-diffLog * sus);
199
200 gainLog = std::clamp(gainLog, -maxGainLog, maxGainLog);
201
202 T gain = fastExp(gainLog);
203
204 const T out = sample * gain;
205 lastOut = std::isfinite(out) ? out : T(0);
206 channelData[i] = out;
207 }
208
209 // Save state
210 envFast_[ch] = fast;
211 envSlow_[ch] = slow;
212 lastOutput_[ch] = lastOut;
213 }
214 if (ramping)
215 {
216 rampPos_ += static_cast<double>(nS);
217 if (rampStep_ * rampPos_ >= 2.0) // the whole [-1, 1] span has elapsed
218 {
219 rampFromAttack_ = attAmt;
220 rampFromSustain_ = susAmt;
221 rampPos_ = 0.0;
222 }
223 }
224 }
225
226 // -- Parameters ----------------------------------------------------------
227 // All setters ignore non-finite values: a NaN amount used to storm the
228 // output for as long as it was published, and under output-dependent
229 // recovery the NaN last-output silently switched the slow envelope to the
230 // fast release, leaving the envelope history diverged after recovery.
231
236 void setAttack(T amount) noexcept
237 {
238 if (!std::isfinite(amount)) return;
239 attackAmount_.store(std::clamp(amount, T(-100), T(100)) / T(100), std::memory_order_relaxed);
240 }
241
246 void setSustain(T amount) noexcept
247 {
248 if (!std::isfinite(amount)) return;
249 sustainAmount_.store(std::clamp(amount, T(-100), T(100)) / T(100), std::memory_order_relaxed);
250 }
251
256 void setOutputDepRecovery(bool enabled) noexcept
257 {
258 outputDepRecovery_.store(enabled, std::memory_order_relaxed);
259 }
260
265 void setCharacter(T amount) noexcept
266 {
267 if (!std::isfinite(amount)) return;
268 T c = std::clamp(amount, T(-1), T(1));
269 attackAmount_.store(c, std::memory_order_relaxed);
270 sustainAmount_.store(-c * T(0.5), std::memory_order_relaxed);
271 }
272
276 void reset() noexcept
277 {
278 envFast_.fill(T(1e-5)); // Init to noise floor
279 envSlow_.fill(T(1e-5));
280 lastOutput_.fill(T(0));
281 for (auto& a : analytic_) a.reset();
282 rampFromAttack_ = rampToAttack_ = attackAmount_.load(std::memory_order_relaxed);
283 rampFromSustain_ = rampToSustain_ = sustainAmount_.load(std::memory_order_relaxed);
284 rampPos_ = 0.0;
285 }
286
287
289 [[nodiscard]] std::vector<uint8_t> getState() const
290 {
291 StateWriter w(stateId("TDES"), 1);
292 // static_cast<float>: the blob stores float (percent units), and
293 // StateWriter's overload set is ambiguous for a double argument.
294 w.write("attack", static_cast<float>(attackAmount_.load(std::memory_order_relaxed)) * 100.0f);
295 w.write("sustain", static_cast<float>(sustainAmount_.load(std::memory_order_relaxed)) * 100.0f);
296 w.write("outputDep", outputDepRecovery_.load(std::memory_order_relaxed));
297 return w.blob();
298 }
299
301 bool setState(const uint8_t* data, size_t size)
302 {
303 StateReader r(data, size);
304 if (!r.isValid() || r.processorId() != stateId("TDES")) return false;
305 setAttack(static_cast<T>(r.read("attack", 0.0f)));
306 setSustain(static_cast<T>(r.read("sustain", 0.0f)));
307 setOutputDepRecovery(r.read("outputDep", false));
308 return true;
309 }
310
311private:
312 static constexpr int kMaxChannels = 16;
313
314 void updateCoefficients() noexcept
315 {
316 if (!(sampleRate_ > 0.0)) return;
317 T fs = static_cast<T>(sampleRate_);
318 fastAttackCoeff_ = T(1) - std::exp(T(-1) / (fs * T(0.0001)));
319 fastReleaseCoeff_ = T(1) - std::exp(T(-1) / (fs * T(0.005)));
320 slowAttackCoeff_ = T(1) - std::exp(T(-1) / (fs * T(0.020)));
321 slowReleaseCoeff_ = T(1) - std::exp(T(-1) / (fs * T(0.200)));
322 rampStep_ = 1.0 / (sampleRate_ * 0.010); // a unit amount change over 10 ms
323 }
324
325 double sampleRate_ = 48000.0;
326
327 // Atomic parameters (Lock-free thread safety)
328 std::atomic<T> attackAmount_ { T(0) };
329 std::atomic<T> sustainAmount_ { T(0) };
330 std::atomic<bool> outputDepRecovery_ { false };
331
332 // Envelope coefficients (written by prepare/updateCoefficients on the
333 // setup thread, read by the audio thread)
334 T fastAttackCoeff_ = T(0), fastReleaseCoeff_ = T(0);
335 T slowAttackCoeff_ = T(0), slowReleaseCoeff_ = T(0);
336 // Amount ramp (audio thread): from/to values and samples since the change.
337 double rampStep_ = 1.0;
338 double rampPos_ = 0.0;
339 T rampFromAttack_ = T(0), rampToAttack_ = T(0);
340 T rampFromSustain_ = T(0), rampToSustain_ = T(0);
341
342 // Per-channel state (scalar recursion; no SIMD kernel touches these)
343 std::array<T, kMaxChannels> envFast_ {};
344 std::array<T, kMaxChannels> envSlow_ {};
345 std::array<T, kMaxChannels> lastOutput_ {};
346 std::array<HilbertIIR<double>, kMaxChannels> analytic_ {};
347 static constexpr int kDetChunk = 64;
348 std::array<double, kDetChunk> detIn_ {};
349 std::array<double, kDetChunk> detMag_ {};
350};
351
352} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
Zero-allocation, thread-safe transient shaper.
void reset() noexcept
Clears all internal buffers and state. Must be lock-free.
void setSustain(T amount) noexcept
Sets sustain (body) emphasis.
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
void setOutputDepRecovery(bool enabled) noexcept
Enables output-dependent recovery (ODR).
void prepare(double sampleRate) noexcept
Prepares the processor with a specific sample rate.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio buffer in-place.
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
void prepare(const AudioSpec &spec) noexcept
Prepares the processor with the current audio specification.
void setAttack(T amount) noexcept
Sets attack (transient) emphasis.
void setCharacter(T amount) noexcept
Sets character as a single macro-knob (overwrites attack AND sustain).
Main namespace for the DSPark framework.
T moveTowards(T from, T to, T maxDelta) noexcept
Moves a value toward a target by at most a given distance.
Definition DspMath.h:137
T fastLog(T x) noexcept
Fast natural logarithm approximation.
Definition DspMath.h:393
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
T fastExp(T x) noexcept
e^x via std::exp2, using the identity e^x = 2^(x * log2(e)).
Definition DspMath.h:220
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37