DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
TriggeredEnvelope.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
45#include "DspMath.h"
46
47#include <algorithm>
48#include <cmath>
49#include <cstdint>
50
51namespace dspark {
52
69template <FloatType T>
71{
72public:
74 enum class Trigger { Notes, Audio };
75
76 TriggeredEnvelope() noexcept { recalculate(); }
77
79 void prepare(double sampleRate) noexcept
80 {
81 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate)) return;
82 sampleRate_ = sampleRate;
83 recalculate();
84 }
85
86 // -- Times, levels and curves (owning thread) ------------------------------
87
89 void setDelay(T ms) noexcept { setTime(delayMs_, ms); }
91 void setAttack(T ms) noexcept { setTime(attackMs_, ms); }
93 void setHold(T ms) noexcept { setTime(holdMs_, ms); }
95 void setDecay(T ms) noexcept { setTime(decayMs_, ms); }
97 void setRelease(T ms) noexcept { setTime(releaseMs_, ms); }
98
100 void setTimes(T delayMs, T attackMs, T holdMs, T decayMs, T releaseMs) noexcept
101 {
102 setDelay(delayMs);
103 setAttack(attackMs);
104 setHold(holdMs);
105 setDecay(decayMs);
106 setRelease(releaseMs);
107 }
108
114 void setSustain(T level) noexcept
115 {
116 if (!std::isfinite(level)) return;
117 const double s = std::clamp(static_cast<double>(level), 0.0, 1.0);
118 if (s == sustain_) return;
119 const double now = value_;
120 sustain_ = s;
121 if (stage_ == Stage::Decay)
122 {
123 // Keep the phase: what is left of the decay goes to the new level.
124 const double f = shape(x_, decayCurve_);
125 if (f < 1.0 - 1e-12) from_ = (now - sustain_ * f) / (1.0 - f);
126 to_ = sustain_;
127 }
128 else if (stage_ == Stage::Sustain)
129 {
130 // Move there at the decay's pace.
131 from_ = now;
132 to_ = sustain_;
133 x_ = 0.0;
134 decayScale_ = std::abs(sustain_ - now);
135 stage_ = Stage::Decay;
136 curveNow_ = decayCurve_;
137 aim(stageSamples());
138 }
139 }
140
147 void setCurves(T attack, T decay, T release) noexcept
148 {
149 if (!std::isfinite(attack) || !std::isfinite(decay) || !std::isfinite(release)) return;
150 const double a = std::clamp(static_cast<double>(attack), -1.0, 1.0);
151 const double d = std::clamp(static_cast<double>(decay), -1.0, 1.0);
152 const double r = std::clamp(static_cast<double>(release), -1.0, 1.0);
153 const double* mine = curveOf(stage_, a, d, r);
154 if (mine != nullptr && *mine != curveNow_)
155 {
156 // The phase at which the new curve gives the output's place in the stage.
157 const double place = (to_ != from_) ? std::clamp((value_ - from_) / (to_ - from_), 0.0, 1.0) : 1.0;
158 x_ = inverse(place, *mine);
159 curveNow_ = *mine;
160 aim(stageSamples());
161 }
162 attackCurve_ = a;
163 decayCurve_ = d;
164 releaseCurve_ = r;
165 }
166
168 void setBipolar(bool on) noexcept { bipolar_ = on; }
169 [[nodiscard]] bool isBipolar() const noexcept { return bipolar_; }
170
171 // -- Trigger (owning thread) ------------------------------------------------
172
174 void setTrigger(Trigger trigger) noexcept { trigger_ = trigger; }
175 [[nodiscard]] Trigger getTrigger() const noexcept { return trigger_; }
176
178 void setThresholdDb(T db) noexcept
179 {
180 if (!std::isfinite(db)) return;
181 thresholdDb_ = std::clamp(static_cast<double>(db), -120.0, 24.0);
182 recalculateTrigger();
183 }
184
186 void setHysteresisDb(T db) noexcept
187 {
188 if (!std::isfinite(db)) return;
189 hysteresisDb_ = std::clamp(static_cast<double>(db), 0.0, 40.0);
190 recalculateTrigger();
191 }
192
194 void setReleaseWaitMs(T ms) noexcept
195 {
196 if (!(ms >= T(0)) || !std::isfinite(ms)) return;
197 waitMs_ = static_cast<double>(ms);
198 recalculateTrigger();
199 }
200
202 void noteOn() noexcept
203 {
204 held_ = value_;
205 x_ = 0.0;
206 stage_ = Stage::Delay;
207 if (delaySteps_ <= 0.0) enterAttack();
208 }
209
211 void noteOff() noexcept
212 {
213 if (stage_ == Stage::Idle || stage_ == Stage::Release) return;
214 enterRelease();
215 }
216
218 void reset() noexcept
219 {
220 stage_ = Stage::Idle;
221 value_ = 0.0;
222 x_ = 0.0;
223 gate_ = false;
224 level_ = 0.0;
225 below_ = 0;
226 }
227
228 [[nodiscard]] Stage getStage() const noexcept { return stage_; }
230 [[nodiscard]] T getValue() const noexcept { return static_cast<T>(value_); }
231 [[nodiscard]] bool isActive() const noexcept { return stage_ != Stage::Idle; }
232
233 // -- Processing (owning thread) ----------------------------------------------
234
239 T process(T key = T(0)) noexcept
240 {
241 if (trigger_ == Trigger::Audio) listen(static_cast<double>(key));
242 advance();
243 return output();
244 }
245
250 void processBlock(const T* key, T* out, int numSamples) noexcept
251 {
252 if (out == nullptr || numSamples <= 0) return;
253 for (int i = 0; i < numSamples; ++i)
254 out[i] = process(key != nullptr ? key[i] : T(0));
255 }
256
257private:
258 void setTime(double& slot, T ms) noexcept
259 {
260 if (!(ms >= T(0)) || !std::isfinite(ms)) return;
261 slot = static_cast<double>(ms);
262 recalculate();
263 }
264
265 [[nodiscard]] double samplesFor(double ms) const noexcept { return std::round(ms * 0.001 * sampleRate_); }
266
268 [[nodiscard]] double stageSamples() const noexcept
269 {
270 switch (stage_)
271 {
272 case Stage::Attack: return attackN_;
273 case Stage::Decay: return samplesFor(decayMs_ * decayScale_);
274 case Stage::Release: return releaseN_;
275 default: return 0.0;
276 }
277 }
278
281 void aim(double samples) noexcept
282 {
283 left_ = std::max<int64_t>(1, static_cast<int64_t>(std::llround((1.0 - x_) * samples)));
284 moveStep_ = (1.0 - x_) / static_cast<double>(left_);
285 }
286
287 void recalculate() noexcept
288 {
289 delaySteps_ = std::round(delayMs_ * 0.001 * sampleRate_);
290 holdSteps_ = std::round(holdMs_ * 0.001 * sampleRate_);
291 attackN_ = samplesFor(attackMs_);
292 releaseN_ = samplesFor(releaseMs_);
293 if (stage_ == Stage::Attack || stage_ == Stage::Decay || stage_ == Stage::Release) aim(stageSamples());
294 recalculateTrigger();
295 }
296
297 void recalculateTrigger() noexcept
298 {
299 threshold_ = std::pow(10.0, thresholdDb_ / 20.0);
300 lowLevel_ = std::pow(10.0, (thresholdDb_ - hysteresisDb_) / 20.0);
301 waitSamples_ = static_cast<int64_t>(std::llround(waitMs_ * 0.001 * sampleRate_));
302 levelFall_ = std::exp(-1.0 / (kDetectorReleaseSeconds * sampleRate_));
303 }
304
306 [[nodiscard]] static double shape(double x, double curve) noexcept
307 {
308 if (curve == 0.0) return x;
309 const double k = 6.0 * curve;
310 return std::expm1(-k * x) / std::expm1(-k);
311 }
312
314 [[nodiscard]] static double inverse(double y, double curve) noexcept
315 {
316 if (curve == 0.0) return y;
317 const double k = 6.0 * curve;
318 return std::clamp(-std::log1p(y * std::expm1(-k)) / k, 0.0, 1.0);
319 }
320
321 [[nodiscard]] const double* curveOf(Stage stage, const double& a, const double& d, const double& r) const noexcept
322 {
323 switch (stage)
324 {
325 case Stage::Attack: return &a;
326 case Stage::Decay: return &d;
327 case Stage::Release: return &r;
328 default: return nullptr;
329 }
330 }
331
332 void enterAttack() noexcept
333 {
334 stage_ = Stage::Attack;
335 from_ = 0.0;
336 to_ = 1.0;
337 curveNow_ = attackCurve_;
338 x_ = inverse(std::clamp(held_, 0.0, 1.0), curveNow_); // from where the output is
339 if (x_ >= 1.0) { enterHold(); return; }
340 aim(attackN_);
341 }
342
343 void enterHold() noexcept
344 {
345 value_ = 1.0;
346 stage_ = Stage::Hold;
347 x_ = 0.0;
348 if (holdSteps_ <= 0.0) enterDecay();
349 }
350
351 void enterDecay() noexcept
352 {
353 stage_ = Stage::Decay;
354 from_ = 1.0;
355 to_ = sustain_;
356 curveNow_ = decayCurve_;
357 decayScale_ = 1.0;
358 x_ = 0.0;
359 aim(stageSamples());
360 }
361
362 void enterRelease() noexcept
363 {
364 stage_ = Stage::Release;
365 from_ = 1.0;
366 to_ = 0.0;
367 curveNow_ = releaseCurve_;
368 x_ = inverse(1.0 - std::clamp(value_, 0.0, 1.0), curveNow_); // from where the output is
369 aim(releaseN_);
370 }
371
372 void advance() noexcept
373 {
374 switch (stage_)
375 {
376 case Stage::Idle:
377 value_ = 0.0;
378 return;
379 case Stage::Delay:
380 value_ = held_;
381 if (++x_ >= delaySteps_) enterAttack();
382 return;
383 case Stage::Hold:
384 value_ = 1.0;
385 if (++x_ >= holdSteps_) enterDecay();
386 return;
387 case Stage::Sustain:
388 value_ = sustain_;
389 return;
390 case Stage::Attack:
391 case Stage::Decay:
392 case Stage::Release:
393 break;
394 }
395 x_ += moveStep_;
396 if (--left_ <= 0)
397 {
398 value_ = to_;
399 if (stage_ == Stage::Attack) enterHold();
400 else if (stage_ == Stage::Decay) { stage_ = Stage::Sustain; value_ = sustain_; }
401 else { stage_ = Stage::Idle; value_ = 0.0; }
402 return;
403 }
404 value_ = from_ + (to_ - from_) * shape(x_, curveNow_);
405 }
406
408 void listen(double key) noexcept
409 {
410 const double a = std::isfinite(key) ? std::abs(key) : 0.0;
411 level_ = std::max(a, level_ * levelFall_);
412 if (!gate_)
413 {
414 if (level_ > threshold_)
415 {
416 gate_ = true;
417 below_ = 0;
418 noteOn();
419 }
420 return;
421 }
422 if (level_ >= lowLevel_) { below_ = 0; return; }
423 if (++below_ >= waitSamples_)
424 {
425 gate_ = false;
426 noteOff();
427 }
428 }
429
430 [[nodiscard]] T output() const noexcept
431 {
432 if (!bipolar_) return static_cast<T>(value_);
433 const double s = sustain_;
434 if (value_ >= s) return static_cast<T>(s < 1.0 ? (value_ - s) / (1.0 - s) : 0.0);
435 return static_cast<T>(s > 0.0 ? (value_ - s) / s : 0.0);
436 }
437
438 static constexpr double kDetectorReleaseSeconds = 0.01;
439
440 double sampleRate_ = 48000.0;
441 double delayMs_ = 0.0, attackMs_ = 10.0, holdMs_ = 0.0, decayMs_ = 100.0, releaseMs_ = 200.0;
442 double sustain_ = 0.7;
443 double attackCurve_ = 0.0, decayCurve_ = 0.0, releaseCurve_ = 0.0;
444 bool bipolar_ = false;
445
446 double delaySteps_ = 0.0, holdSteps_ = 0.0;
447 double attackN_ = 0.0, releaseN_ = 0.0;
448
449 Stage stage_ = Stage::Idle;
450 double value_ = 0.0;
451 double x_ = 0.0;
452 double from_ = 0.0, to_ = 0.0;
453 double curveNow_ = 0.0;
454 double moveStep_ = 0.0;
455 int64_t left_ = 0;
456 double decayScale_ = 1.0;
457 double held_ = 0.0;
458
459 Trigger trigger_ = Trigger::Notes;
460 double thresholdDb_ = -40.0, hysteresisDb_ = 6.0, waitMs_ = 50.0;
461 double threshold_ = 0.01, lowLevel_ = 0.005, levelFall_ = 0.99;
462 int64_t waitSamples_ = 2400;
463 bool gate_ = false;
464 double level_ = 0.0;
465 int64_t below_ = 0;
466};
467
468} // namespace dspark
DAHDSR envelope with bending curves, triggered by notes or by audio.
bool isBipolar() const noexcept
void processBlock(const T *key, T *out, int numSamples) noexcept
A block: key drives the audio trigger (may be null with the note trigger), the envelope goes to out.
Stage getStage() const noexcept
void setDelay(T ms) noexcept
Delay before the attack, in ms (>= 0; non-finite ignored).
void setThresholdDb(T db) noexcept
Level of the key above which the audio trigger starts the envelope, in dB (non-finite ignored).
void noteOn() noexcept
Starts the envelope (from where the output is).
void setReleaseWaitMs(T ms) noexcept
How long the key must stay below that before the release, in ms (>= 0; 50 by default).
bool isActive() const noexcept
void setSustain(T level) noexcept
The sustain level, 0..1 (non-finite ignored). During the decay the rest of the decay bends to it; dur...
void noteOff() noexcept
Lets the envelope go to its release (from where the output is).
T process(T key=T(0)) noexcept
One sample: the key (read by the audio trigger), then the output.
T getValue() const noexcept
The envelope now, 0..1 (before the bipolar mapping).
void prepare(double sampleRate) noexcept
Prepares for a sample rate (invalid rates are ignored).
void setDecay(T ms) noexcept
Decay, 1 to the sustain, in ms.
void setHysteresisDb(T db) noexcept
How far below the threshold the key must fall to let go, in dB (0..40; 6 by default).
void setHold(T ms) noexcept
Hold at the top, in ms.
void setAttack(T ms) noexcept
Attack, 0 to 1, in ms.
void setRelease(T ms) noexcept
Release, full scale to 0, in ms (from a lower value it arrives earlier).
void setTrigger(Trigger trigger) noexcept
Notes (noteOn()/noteOff()) or the audio of the key signal.
Trigger getTrigger() const noexcept
void setCurves(T attack, T decay, T release) noexcept
The curves of the attack, the decay and the release, -1 (slow start) to 1 (fast start),...
void setBipolar(bool on) noexcept
Output centred on the sustain (see the file notes).
void setTimes(T delayMs, T attackMs, T holdMs, T decayMs, T releaseMs) noexcept
All five times at once, in ms.
void reset() noexcept
Back to rest at 0, the trigger disarmed.
Main namespace for the DSPark framework.