DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
EnvelopeGenerator.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
17#include "DspMath.h"
18#include "AudioSpec.h"
19
20#include <algorithm>
21#include <cmath>
22
23namespace dspark {
24
55template <FloatType T>
57{
58public:
59 enum class State { Idle, Attack, Decay, Sustain, Release };
60
61 ADSREnvelope() noexcept { recalculate(); }
62
67 void prepare(double sampleRate) noexcept
68 {
69 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate)) return;
70 sampleRate_ = sampleRate;
71 recalculate();
72 }
73
78 void prepare(const AudioSpec& spec) noexcept { prepare(spec.sampleRate); }
79
80 // -- Parameters (in milliseconds) ------------------------------------------
81
82 // Non-finite values are ignored: the stages are recursive, so one NaN
83 // would hold the output at NaN until reset().
84
86 void setAttack(T ms) noexcept
87 {
88 if (!std::isfinite(ms)) return;
89 attackMs_ = std::max(ms, T(0.01));
90 recalculate();
91 }
92
94 void setDecay(T ms) noexcept
95 {
96 if (!std::isfinite(ms)) return;
97 decayMs_ = std::max(ms, T(0.01));
98 recalculate();
99 }
100
102 void setSustain(T level) noexcept
103 {
104 if (std::isfinite(level)) sustainLevel_ = std::clamp(level, T(0), T(1));
105 }
106
108 void setRelease(T ms) noexcept
109 {
110 if (!std::isfinite(ms)) return;
111 releaseMs_ = std::max(ms, T(0.01));
112 recalculate();
113 }
114
122 void setParameters(T attackMs, T decayMs, T sustain, T releaseMs) noexcept
123 {
124 if (!std::isfinite(attackMs) || !std::isfinite(decayMs)
125 || !std::isfinite(sustain) || !std::isfinite(releaseMs)) return;
126 attackMs_ = std::max(attackMs, T(0.01));
127 decayMs_ = std::max(decayMs, T(0.01));
128 sustainLevel_ = std::clamp(sustain, T(0), T(1));
129 releaseMs_ = std::max(releaseMs, T(0.01));
130 recalculate();
131 }
132
137 void setCurvature(T curve) noexcept
138 {
139 if (!std::isfinite(curve)) return;
140 curve = std::clamp(curve, T(0.1), T(10));
141 attackCurve_ = decayCurve_ = releaseCurve_ = curve;
142 recalculate();
143 }
144
155 void setCurvature(T attackCurve, T decayCurve, T releaseCurve) noexcept
156 {
157 if (!std::isfinite(attackCurve) || !std::isfinite(decayCurve)
158 || !std::isfinite(releaseCurve)) return;
159 attackCurve_ = std::clamp(attackCurve, T(0.1), T(10));
160 decayCurve_ = std::clamp(decayCurve, T(0.1), T(10));
161 releaseCurve_ = std::clamp(releaseCurve, T(0.1), T(10));
162 recalculate();
163 }
164
165 // -- Trigger ---------------------------------------------------------------
166
168 void noteOn() noexcept
169 {
170 state_ = State::Attack;
171 }
172
174 void noteOff() noexcept
175 {
176 if (state_ != State::Idle)
177 state_ = State::Release;
178 }
179
181 void reset() noexcept
182 {
183 state_ = State::Idle;
184 currentValue_ = 0.0;
185 }
186
187 // -- Processing ------------------------------------------------------------
188
193 [[nodiscard]] T getNextValue() noexcept
194 {
195 switch (state_)
196 {
197 case State::Idle:
198 return T(0);
199
200 case State::Attack:
201 currentValue_ += attackRate_ * (1.0 + kAttack_ - currentValue_);
202 if (currentValue_ >= 1.0)
203 {
204 currentValue_ = 1.0;
205 state_ = State::Decay;
206 }
207 break;
208
209 case State::Decay:
210 {
211 const double s = static_cast<double>(sustainLevel_);
212 const double prev = currentValue_;
213 currentValue_ += decayRate_ * (s - (1.0 - s) * kDecay_ - currentValue_);
214 if (currentValue_ <= s)
215 {
216 // Normal completion (crossed from above): land exactly on s.
217 // Sustain raised above the current value mid-decay: keep the
218 // value and let the Sustain chase close the gap click-free.
219 if (prev >= s)
220 currentValue_ = s;
221 state_ = State::Sustain;
222 }
223 break;
224 }
225
226 case State::Sustain:
227 // Chases sustain changes at the decay rate (dynamic modulation).
228 currentValue_ += decayRate_ * (static_cast<double>(sustainLevel_) - currentValue_);
229 break;
230
231 case State::Release:
232 currentValue_ += releaseRate_ * (-kRelease_ - currentValue_);
233 if (currentValue_ <= kSilence)
234 {
235 currentValue_ = 0.0;
236 state_ = State::Idle;
237 }
238 break;
239 }
240
241 return static_cast<T>(currentValue_);
242 }
243
253 void processBlock(T* output, int numSamples) noexcept
254 {
255 // Each stage runs as a tight loop on locals (stage constants hoisted,
256 // recursion state in a register): no state dispatch or member traffic
257 // per sample. Arithmetic is sample-exact with getNextValue().
258 int i = 0;
259 while (i < numSamples)
260 {
261 switch (state_)
262 {
263 case State::Idle:
264 while (i < numSamples)
265 output[i++] = T(0);
266 break;
267
268 case State::Attack:
269 {
270 const double target = 1.0 + kAttack_;
271 const double r = attackRate_;
272 double v = currentValue_;
273 while (i < numSamples)
274 {
275 v += r * (target - v);
276 if (v >= 1.0)
277 {
278 v = 1.0;
279 state_ = State::Decay;
280 output[i++] = T(1);
281 break;
282 }
283 output[i++] = static_cast<T>(v);
284 }
285 currentValue_ = v;
286 break;
287 }
288
289 case State::Decay:
290 {
291 const double s = static_cast<double>(sustainLevel_);
292 const double target = s - (1.0 - s) * kDecay_;
293 const double r = decayRate_;
294 double v = currentValue_;
295 while (i < numSamples)
296 {
297 const double prev = v;
298 v += r * (target - v);
299 if (v <= s)
300 {
301 if (prev >= s)
302 v = s;
303 state_ = State::Sustain;
304 output[i++] = static_cast<T>(v);
305 break;
306 }
307 output[i++] = static_cast<T>(v);
308 }
309 currentValue_ = v;
310 break;
311 }
312
313 case State::Sustain:
314 {
315 const double s = static_cast<double>(sustainLevel_);
316 const double r = decayRate_;
317 double v = currentValue_;
318 while (i < numSamples)
319 {
320 v += r * (s - v);
321 output[i++] = static_cast<T>(v);
322 }
323 currentValue_ = v;
324 break;
325 }
326
327 case State::Release:
328 {
329 const double target = -kRelease_;
330 const double r = releaseRate_;
331 double v = currentValue_;
332 while (i < numSamples)
333 {
334 v += r * (target - v);
335 if (v <= kSilence)
336 {
337 v = 0.0;
338 state_ = State::Idle;
339 output[i++] = T(0);
340 break;
341 }
342 output[i++] = static_cast<T>(v);
343 }
344 currentValue_ = v;
345 break;
346 }
347 }
348 }
349 }
350
351 // -- Getters ---------------------------------------------------------------
352
354 [[nodiscard]] T getCurrentValue() const noexcept { return static_cast<T>(currentValue_); }
355
357 [[nodiscard]] State getState() const noexcept { return state_; }
358
360 [[nodiscard]] bool isActive() const noexcept { return state_ != State::Idle; }
361
362private:
363 // Release ends when the value falls below this floor (about -80 dB);
364 // the strictly negative release target guarantees it is crossed.
365 static constexpr double kSilence = 1e-4;
366
367 void recalculate() noexcept
368 {
369 // Asymptotic one-pole stage design. With ov = exp(-curve), running the
370 // recursion v += rate * (target - v) for exactly `samples` steps
371 // multiplies the distance to the target by ov. Overshooting the stage
372 // endpoint by k = ov / (1 - ov) OF THE STAGE DEPTH makes the endpoint
373 // land exactly on the last step, for any curvature:
374 //
375 // endpoint = target + depth_to_target * ov with target = end + k*depth
376 //
377 // (A first-order shortcut like target = end + ov breaks the timing
378 // contract: at curve 0.1 the stages run ~7x their parameter, and a
379 // fixed absolute overshoot makes decay/release durations drift with
380 // the sustain level.)
381 auto stage = [this](T timeMs, T curve, double& rate, double& k) noexcept {
382 const double c = static_cast<double>(curve);
383 const double ov = std::exp(-c);
384 k = ov / (1.0 - ov);
385 const double samples = std::max(sampleRate_ * 0.001 * static_cast<double>(timeMs), 1.0);
386 rate = 1.0 - std::exp(-c / samples);
387 };
388
389 stage(attackMs_, attackCurve_, attackRate_, kAttack_);
390 stage(decayMs_, decayCurve_, decayRate_, kDecay_);
391 stage(releaseMs_, releaseCurve_, releaseRate_, kRelease_);
392 }
393
394 double sampleRate_ = 48000.0;
395
396 T attackMs_ = T(10);
397 T decayMs_ = T(100);
398 T sustainLevel_ = T(0.7);
399 T releaseMs_ = T(200);
400 T attackCurve_ = T(3.0);
401 T decayCurve_ = T(3.0);
402 T releaseCurve_ = T(3.0);
403
404 // Stage coefficients and overshoot fractions (see recalculate()).
405 double attackRate_ = 0.0;
406 double decayRate_ = 0.0;
407 double releaseRate_ = 0.0;
408 double kAttack_ = 0.0;
409 double kDecay_ = 0.0;
410 double kRelease_ = 0.0;
411
412 double currentValue_ = 0.0;
413 State state_ = State::Idle;
414};
415
416} // namespace dspark
Classic ADSR envelope generator with exponential curves.
void setRelease(T ms) noexcept
Sets release time in milliseconds (full scale -> silence).
void setCurvature(T attackCurve, T decayCurve, T releaseCurve) noexcept
Sets independent curvatures per stage.
void noteOn() noexcept
Triggers the attack phase (note on). Legato: continues from the current value.
T getNextValue() noexcept
Returns the next envelope value and advances the state machine.
void setDecay(T ms) noexcept
Sets decay time in milliseconds (1 -> sustain).
void prepare(double sampleRate) noexcept
Prepares the envelope for the given sample rate.
void setCurvature(T curve) noexcept
Sets the curvature of all exponential stages at once.
void setSustain(T level) noexcept
Sets sustain level (0.0 to 1.0).
void setAttack(T ms) noexcept
Sets attack time in milliseconds (0 -> 1).
T getCurrentValue() const noexcept
Returns the current envelope value.
void noteOff() noexcept
Triggers the release phase (note off).
State getState() const noexcept
Returns the current state.
bool isActive() const noexcept
Returns true if the envelope is actively producing output.
void setParameters(T attackMs, T decayMs, T sustain, T releaseMs) noexcept
Sets all ADSR parameters at once.
void reset() noexcept
Resets the envelope to idle with zero output.
void prepare(const AudioSpec &spec) noexcept
Prepares from AudioSpec (unified API).
void processBlock(T *output, int numSamples) noexcept
Fills a buffer with envelope values.
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37