DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Delay.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
61#include "../Core/AudioBuffer.h"
62#include "../Core/AudioSpec.h"
63#include "../Core/BucketBrigade.h"
64#include "../Core/DspMath.h"
65#include "../Core/Interpolation.h"
66#include "../Core/Smoothers.h"
67#include "../Core/StateBlob.h"
68#include "../Core/TapeTransport.h"
69
70#include <algorithm>
71#include <array>
72#include <atomic>
73#include <cmath>
74#include <cstdint>
75#include <cstring>
76#include <vector>
77
78namespace dspark {
79
80template <typename SampleType>
81class Delay final
82{
83public:
89
91 enum class FeedbackMode
92 {
93 Clean,
96 Analog
99 };
100
102 void setFeedbackMode(FeedbackMode mode) noexcept
103 {
104 feedbackMode_.store(mode, std::memory_order_relaxed);
105 }
106
108 [[nodiscard]] FeedbackMode getFeedbackMode() const noexcept
109 {
110 return feedbackMode_.load(std::memory_order_relaxed);
111 }
112
114 enum class Interpolation
115 {
116 Hermite,
117 Sinc
120 };
121
123 void setInterpolation(Interpolation mode) noexcept
124 {
125 interpolation_.store(mode == Interpolation::Sinc ? Interpolation::Sinc : Interpolation::Hermite,
126 std::memory_order_relaxed);
127 }
128
130 [[nodiscard]] Interpolation getInterpolation() const noexcept
131 {
132 return interpolation_.load(std::memory_order_relaxed);
133 }
134
136 enum class Character
137 {
138 Clean,
139 Tape,
140 Bucket
141 };
142
144 void setCharacter(Character c) noexcept
145 {
146 const int v = std::clamp(static_cast<int>(c), 0, static_cast<int>(Character::Bucket));
147 character_.store(static_cast<Character>(v), std::memory_order_relaxed);
148 }
150 [[nodiscard]] Character getCharacter() const noexcept { return character_.load(std::memory_order_relaxed); }
151
156 void setWowFlutter(SampleType amount) noexcept
157 {
158 if (!std::isfinite(amount)) return;
159 wowFlutter_.store(std::clamp(amount, SampleType(0), SampleType(1)), std::memory_order_relaxed);
160 }
162 [[nodiscard]] SampleType getWowFlutter() const noexcept { return wowFlutter_.load(std::memory_order_relaxed); }
163
169 void setCharacterNoise(SampleType dbfs) noexcept
170 {
171 if (!std::isfinite(dbfs)) return;
172 characterNoiseDb_.store(std::clamp(dbfs, SampleType(-140), SampleType(-40)), std::memory_order_relaxed);
173 }
175 [[nodiscard]] SampleType getCharacterNoise() const noexcept { return characterNoiseDb_.load(std::memory_order_relaxed); }
176
177 // -- Lifecycle -----------------------------------------------------------
178
183 void prepare(const AudioSpec& spec)
184 {
186 }
187
196 void prepare(const AudioSpec& spec, double maxDelaySeconds)
197 {
198 if (!spec.isValid() || !(maxDelaySeconds >= 0.0)) return;
199 sampleRate_ = static_cast<SampleType>(spec.sampleRate);
200 // Clamp to the fixed per-channel state arrays (states_/writeIndices_ are
201 // kMaxChannels): maybeUpdateSmoothers()/updateSmootherTargets() iterate
202 // [0, numChannels_) and would otherwise read/write out of bounds.
203 numChannels_ = std::min(static_cast<int>(spec.numChannels), kMaxChannels);
204 blockSize_ = spec.maxBlockSize;
205
206 // Cap in double BEFORE the int cast: a huge request would otherwise be
207 // undefined behaviour in the cast, and nextPow2 past 2^29 overflows
208 // its shift. 2^29 samples is over 3 hours at 48 kHz.
209 const double capacityD =
210 std::min(std::ceil(maxDelaySeconds * spec.sampleRate) + blockSize_,
211 536870912.0); // 2^29
212 maxDelaySamples_ = nextPow2(static_cast<int>(capacityD));
213 bufferMask_ = maxDelaySamples_ - 1;
214
215 delayBuffer_.resize(numChannels_, maxDelaySamples_);
216 wetBuffer_.resize(numChannels_, blockSize_);
217 lastWetSamples_ = blockSize_; // full capacity until the first push
218 sinc_ = &sincTable(); // built here, on the setup thread, once per process
219
220 // The delay time and the feedback filter corners are kept in time and
221 // Hz: re-derive the sample-domain values for this rate.
222 if (const SampleType pending = pendingDelaySamples_.exchange(SampleType(-1), std::memory_order_relaxed);
223 pending >= SampleType(0))
224 delayMs_.store(pending * SampleType(1000) / sampleRate_, std::memory_order_relaxed);
225 globalDelay_.store(clampToCapacity(delayMs_.load(std::memory_order_relaxed) * sampleRate_ / SampleType(1000)),
226 std::memory_order_relaxed);
227 setFeedbackLpHz(fbLpHzShadow_.load(std::memory_order_relaxed));
228 setFeedbackHpHz(fbHpHzShadow_.load(std::memory_order_relaxed));
229
230 float timeMs = smoothingTimeMs_.load(std::memory_order_relaxed);
231 for (int ch = 0; ch < std::min(numChannels_, kMaxChannels); ++ch)
232 {
233 resetChannelSmoothers(states_[ch], timeMs, 0.0f);
234 writeIndices_[ch] = 0;
235 }
236
237 // The characters' engines: the tape transport (its nominal speed puts
238 // a 300 ms delay at 7.5 ips) and the bucket-brigade line.
239 tape_.resize(static_cast<size_t>(numChannels_));
240 bbd_.resize(static_cast<size_t>(numChannels_));
241 {
243 echo.speedUpSeconds = 0.25;
244 echo.slowDownSeconds = 0.4;
245 echo.restoreSeconds = 0.1;
246 echo.maxStep = 0.5;
247 echo.reel = 0.0;
248 echo.capstan = 0.0008;
249 echo.noise = 0.0006;
250 echo.scrape = 0.002;
251 for (auto& t : tape_)
252 {
253 t.prepare(spec.sampleRate, 0.3 * spec.sampleRate, 7.5, echo);
254 t.setLimits(3.0, static_cast<double>(maxDelaySamples_ - 1));
255 }
256 }
257 for (auto& b : bbd_) b.prepare(spec.sampleRate, kBucketStages, 0.45 * spec.sampleRate);
258 headCoeff_ = 1.0 - std::exp(-2.0 * 3.141592653589793 * std::min(kHeadLossHz, 0.45 * spec.sampleRate) / spec.sampleRate);
259 switchFade_ = std::max(1, static_cast<int>(kSwitchFadeSeconds * spec.sampleRate));
260
261 mixSmoother_.reset(spec.sampleRate, timeMs, 1.0f);
262 insertMixMaxStep_ = static_cast<SampleType>(1.0 / std::max(1.0, spec.sampleRate * 0.02));
263 reset();
264
265 prepared_.store(true, std::memory_order_release);
266 }
267
273 void prepareMs(const AudioSpec& spec, double maxDelayMs)
274 {
275 prepare(spec, maxDelayMs / 1000.0);
276 }
277
281 void reset() noexcept
282 {
283 delayBuffer_.clear();
284 wetBuffer_.clear();
285 for (int ch = 0; ch < kMaxChannels; ++ch)
286 {
287 writeIndices_[ch] = 0;
288 resetChannelState(states_[ch]);
289 }
290 for (auto& t : tape_) t.reset();
291 for (auto& b : bbd_) b.reset();
292 tapeSeeded_.fill(false);
293 bucketCornerFor_.fill(-1.0);
294 bucketTick_.fill(0);
295 switchLeft_.fill(0);
296 bucketHissCoeff_.fill(0.5);
297 hissDbFor_.fill(1.0); // not a level: the first hiss sample computes its gain
298 headLp_.fill(0.0);
299 hissLp_.fill(0.0);
300 for (int ch = 0; ch < kMaxChannels; ++ch)
301 hissRng_[static_cast<size_t>(ch)] = 0x3C6EF372u + 0x9E3779B9u * static_cast<uint32_t>(ch);
302 lastCharacter_ = character_.load(std::memory_order_relaxed);
303 mixSmoother_.skip();
304 insertMix_ = mix_.load(std::memory_order_relaxed); // no fade-in on start
305 snapNext_ = true; // the next call starts on the set delay, no glide
306 }
307
308 // -- Configuration -------------------------------------------------------
309
314 void setSmoother(SmootherType type) noexcept
315 {
316 smootherType_.store(type, std::memory_order_relaxed);
317 smootherDirty_.store(true, std::memory_order_release);
318 }
319
324 void setSmoothingTime(float ms) noexcept
325 {
326 if (!std::isfinite(ms)) return;
327 smoothingTimeMs_.store(std::max(0.0f, ms), std::memory_order_relaxed);
328 smootherDirty_.store(true, std::memory_order_release);
329 }
330
331 // -- Parameters ----------------------------------------------------------
332
339 void setDelaySamples(SampleType samples) noexcept
340 {
341 if (!std::isfinite(samples)) return;
342 samples = std::max(samples, SampleType(0));
343 if (prepared_.load(std::memory_order_acquire))
344 {
345 delayMs_.store(samples * SampleType(1000) / sampleRate_, std::memory_order_relaxed);
346 pendingDelaySamples_.store(SampleType(-1), std::memory_order_relaxed);
347 }
348 else
349 {
350 // No rate yet: prepare() reads the count at the rate it is given.
351 pendingDelaySamples_.store(samples, std::memory_order_relaxed);
352 }
353 globalDelay_.store(clampToCapacity(samples), std::memory_order_relaxed);
354 // Publish/apply pattern: the smoothers are NOT touched here (they are
355 // non-atomic audio-thread state - mutating them from a control thread
356 // raced against advanceSmoother). The audio thread applies the new
357 // target in maybeUpdateSmoothers() at the top of its next process call.
358 delayTargetDirty_.store(true, std::memory_order_release);
359 }
360
363 void setDelayMs(SampleType ms) noexcept
364 {
365 if (!std::isfinite(ms)) return;
366 ms = std::max(ms, SampleType(0));
367 delayMs_.store(ms, std::memory_order_relaxed);
368 pendingDelaySamples_.store(SampleType(-1), std::memory_order_relaxed);
369 globalDelay_.store(clampToCapacity(ms * sampleRate_ / SampleType(1000)), std::memory_order_relaxed);
370 delayTargetDirty_.store(true, std::memory_order_release);
371 }
372
374 void setDelaySeconds(SampleType secs) noexcept { setDelayMs(secs * SampleType(1000)); }
375
377 [[nodiscard]] SampleType getDelayMs() const noexcept
378 {
379 const SampleType pending = pendingDelaySamples_.load(std::memory_order_relaxed);
380 return pending >= SampleType(0) ? pending * SampleType(1000) / sampleRate_
381 : delayMs_.load(std::memory_order_relaxed);
382 }
383
385 [[nodiscard]] SampleType getCurrentDelaySamples() const noexcept { return globalDelay_.load(std::memory_order_relaxed); }
386
393 void setFeedback(SampleType gain) noexcept
394 {
395 if (!std::isfinite(gain)) return;
396 feedbackGain_.store(gain, std::memory_order_relaxed);
397 }
398
401 void setFeedbackLpHz(SampleType freq) noexcept
402 {
403 if (!std::isfinite(freq)) return;
404 fbLpCoef_.store((freq > 0) ? calcLpCoef(freq) : SampleType(0), std::memory_order_relaxed);
405 fbLpHzShadow_.store(freq, std::memory_order_relaxed); // serialization readback
406 }
407
410 void setFeedbackHpHz(SampleType freq) noexcept
411 {
412 if (!std::isfinite(freq)) return;
413 fbHpCoef_.store((freq > 0) ? calcHpCoef(freq) : SampleType(0), std::memory_order_relaxed);
414 fbHpHzShadow_.store(freq, std::memory_order_relaxed); // serialization readback
415 }
416
417 // -- Sample processing ---------------------------------------------------
418
425 SampleType processSample(int ch, SampleType input) noexcept
426 {
427 if (ch < 0 || ch >= numChannels_ || !prepared_.load(std::memory_order_acquire)) return input;
428 maybeUpdateSmoothers();
429
430 auto& s = states_[ch];
431 auto st = smootherType_.load(std::memory_order_relaxed);
432 SampleType delay = (st == SmootherType::None)
433 ? globalDelay_.load(std::memory_order_relaxed) : advanceSmoother(s, st);
434
435 SampleType out = processSampleInternal(ch, input, delay, s,
436 feedbackGain_.load(std::memory_order_relaxed),
437 fbLpCoef_.load(std::memory_order_relaxed),
438 fbHpCoef_.load(std::memory_order_relaxed));
439 advanceWriteIndexUnchecked(ch);
440 return out;
441 }
442
443 // -- Block processing ----------------------------------------------------
444
455 {
456 if (!prepared_.load(std::memory_order_acquire)) return;
457 maybeUpdateSmoothers();
458
459 const int nS = buffer.getNumSamples();
460 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
461 const auto smoothType = smootherType_.load(std::memory_order_relaxed);
462 const SampleType targetDelay = globalDelay_.load(std::memory_order_relaxed);
463 const SampleType fb = feedbackGain_.load(std::memory_order_relaxed);
464 const SampleType lpC = fbLpCoef_.load(std::memory_order_relaxed);
465 const SampleType hpC = fbHpCoef_.load(std::memory_order_relaxed);
466 const SampleType mixTarget = mix_.load(std::memory_order_relaxed);
467 const SampleType mixStart = insertMix_;
468 const bool pingPong = pingPong_.load(std::memory_order_relaxed) && nCh >= 2;
469
470 if (pingPong)
471 {
472 // The first two channels cross their feedback (the same wiring as
473 // processPingPong()); the blend is the insert's.
474 const bool analogFb = feedbackMode_.load(std::memory_order_relaxed) == FeedbackMode::Analog;
475 SampleType* L = buffer.getChannel(0);
476 SampleType* R = buffer.getChannel(1);
477 auto& sL = states_[0];
478 auto& sR = states_[1];
479 for (int i = 0; i < nS; ++i)
480 {
481 const SampleType currentDelay = (smoothType == SmootherType::None)
482 ? targetDelay : advanceSmoother(sL, smoothType);
483 advanceSmoother(sR, smoothType); // kept in step, as in processPingPong()
484 const SampleType dryL = L[i], dryR = R[i];
485 const SampleType outL = processSampleInternal(0, dryL + sL.pingPongFb, currentDelay, sL, SampleType(0), lpC, hpC, false);
486 const SampleType outR = processSampleInternal(1, dryR + sR.pingPongFb, currentDelay, sR, SampleType(0), lpC, hpC, false);
487 sR.pingPongFb = saturateFeedback(processFbFilters(1, outL * fb, lpC, hpC), analogFb);
488 sL.pingPongFb = saturateFeedback(processFbFilters(0, outR * fb, lpC, hpC), analogFb);
489 advanceWriteIndexUnchecked(0);
490 advanceWriteIndexUnchecked(1);
491 const SampleType m = moveTowards(mixStart, mixTarget,
492 insertMixMaxStep_ * static_cast<SampleType>(i + 1));
493 L[i] = dryL + (outL - dryL) * m;
494 R[i] = dryR + (outR - dryR) * m;
495 }
496 }
497
498 for (int ch = pingPong ? 2 : 0; ch < nCh; ++ch)
499 {
500 SampleType* data = buffer.getChannel(ch);
501 auto& s = states_[ch];
502 for (int i = 0; i < nS; ++i)
503 {
504 const SampleType currentDelay = (smoothType == SmootherType::None)
505 ? targetDelay : advanceSmoother(s, smoothType);
506 const SampleType dry = data[i];
507 const SampleType wet = processSampleInternal(ch, dry, currentDelay, s, fb, lpC, hpC);
508 advanceWriteIndexUnchecked(ch);
509 const SampleType m = moveTowards(mixStart, mixTarget,
510 insertMixMaxStep_ * static_cast<SampleType>(i + 1));
511 data[i] = dry + (wet - dry) * m;
512 }
513 }
514 insertMix_ = moveTowards(mixStart, mixTarget, insertMixMaxStep_ * static_cast<SampleType>(nS));
515 }
516
522 void setMix(SampleType mix) noexcept
523 {
524 if (!std::isfinite(mix)) return;
525 mix_.store(std::clamp(mix, SampleType(0), SampleType(1)), std::memory_order_relaxed);
526 }
527
529 [[nodiscard]] SampleType getMix() const noexcept { return mix_.load(std::memory_order_relaxed); }
530
539 void setPingPong(bool on) noexcept { pingPong_.store(on, std::memory_order_relaxed); }
540
542 [[nodiscard]] bool getPingPong() const noexcept { return pingPong_.load(std::memory_order_relaxed); }
543
545 [[nodiscard]] int getLatency() const noexcept { return 0; }
546
560 void processBlock(AudioBufferView<SampleType> buffer, SampleType delayMs,
561 SampleType feedback = 0, SampleType lpHz = 0, SampleType hpHz = 0) noexcept
562 {
563 if (!prepared_.load(std::memory_order_acquire)) return;
564
565 setDelayMs(delayMs);
566 setFeedback(feedback);
567 setFeedbackLpHz(lpHz);
568 setFeedbackHpHz(hpHz);
569 maybeUpdateSmoothers();
570
571 const int nS = buffer.getNumSamples();
572 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
573
574 // Cache atomic parameters to local stack for auto-vectorization & performance
575 const auto smoothType = smootherType_.load(std::memory_order_relaxed);
576 const SampleType targetDelay = globalDelay_.load(std::memory_order_relaxed);
577 const SampleType fb = feedbackGain_.load(std::memory_order_relaxed);
578 const SampleType lpC = fbLpCoef_.load(std::memory_order_relaxed);
579 const SampleType hpC = fbHpCoef_.load(std::memory_order_relaxed);
580
581 for (int ch = 0; ch < nCh; ++ch)
582 {
583 SampleType* data = buffer.getChannel(ch);
584 auto& s = states_[ch];
585
586 for (int i = 0; i < nS; ++i)
587 {
588 SampleType currentDelay = (smoothType == SmootherType::None) ? targetDelay : advanceSmoother(s, smoothType);
589 data[i] = processSampleInternal(ch, data[i], currentDelay, s, fb, lpC, hpC);
590 advanceWriteIndexUnchecked(ch);
591 }
592 }
593 }
594
598 void processChannel(AudioBufferView<SampleType> buffer, int ch, SampleType delayMs,
599 SampleType feedback = 0, SampleType lpHz = 0, SampleType hpHz = 0) noexcept
600 {
601 if (ch < 0 || ch >= numChannels_ || !prepared_.load(std::memory_order_acquire)) return;
602
603 setDelayMs(delayMs);
604 setFeedback(feedback);
605 setFeedbackLpHz(lpHz);
606 setFeedbackHpHz(hpHz);
607 maybeUpdateSmoothers();
608
609 SampleType* data = buffer.getChannel(ch);
610 const int nS = buffer.getNumSamples();
611
612 const auto smoothType = smootherType_.load(std::memory_order_relaxed);
613 const SampleType targetDelay = globalDelay_.load(std::memory_order_relaxed);
614 const SampleType fb = feedbackGain_.load(std::memory_order_relaxed);
615 const SampleType lpC = fbLpCoef_.load(std::memory_order_relaxed);
616 const SampleType hpC = fbHpCoef_.load(std::memory_order_relaxed);
617
618 auto& s = states_[ch];
619
620 for (int i = 0; i < nS; ++i)
621 {
622 SampleType currentDelay = (smoothType == SmootherType::None) ? targetDelay : advanceSmoother(s, smoothType);
623 data[i] = processSampleInternal(ch, data[i], currentDelay, s, fb, lpC, hpC);
624 advanceWriteIndexUnchecked(ch);
625 }
626 }
627
628 // -- Wet buffer processing -----------------------------------------------
629
632 {
633 pushDryToWetImpl([&](int ch) { return dry.getChannel(ch); }, dry.getNumChannels(), dry.getNumSamples());
634 }
635
638 {
639 pushDryToWetImpl([&](int ch) { return dry.getChannel(ch); }, dry.getNumChannels(), dry.getNumSamples());
640 }
641
647 void processWet(SampleType delayMs, SampleType feedback = 0, SampleType lpHz = 0, SampleType hpHz = 0) noexcept
648 {
649 processBlock(wetBuffer_.toView().getSubView(0, lastWetSamples_), delayMs, feedback, lpHz, hpHz);
650 }
651
660 void processPingPong(SampleType delayMs, SampleType feedback = 0, SampleType lpHz = 0, SampleType hpHz = 0) noexcept
661 {
662 if (wetBuffer_.getNumChannels() < 2 || !prepared_.load(std::memory_order_acquire)) return;
663
664 setDelayMs(delayMs);
665 setFeedback(feedback);
666 setFeedbackLpHz(lpHz);
667 setFeedbackHpHz(hpHz);
668 maybeUpdateSmoothers();
669
670 SampleType* L = wetBuffer_.getChannel(0);
671 SampleType* R = wetBuffer_.getChannel(1);
672 const int nS = std::min(lastWetSamples_, wetBuffer_.getNumSamples());
673
674 const auto smoothType = smootherType_.load(std::memory_order_relaxed);
675 const SampleType targetDelay = globalDelay_.load(std::memory_order_relaxed);
676 const SampleType fb = feedbackGain_.load(std::memory_order_relaxed);
677 const SampleType lpC = fbLpCoef_.load(std::memory_order_relaxed);
678 const SampleType hpC = fbHpCoef_.load(std::memory_order_relaxed);
679 const bool analogFb = feedbackMode_.load(std::memory_order_relaxed) == FeedbackMode::Analog;
680
681 for (int i = 0; i < nS; ++i)
682 {
683 auto& sL = states_[0];
684 auto& sR = states_[1];
685
686 SampleType currentDelay = (smoothType == SmootherType::None) ? targetDelay : advanceSmoother(sL, smoothType);
687 advanceSmoother(sR, smoothType); // Keep smoothers in sync
688
689 // s.pingPongFb holds what THIS channel receives next sample, i.e.
690 // the OTHER channel's previous output. (The original wiring
691 // consumed each channel's own stored value while storing f(other)
692 // into it: every echo regenerated into its own channel and the
693 // signal never crossed the stereo field at all.)
694 SampleType inL = L[i] + sL.pingPongFb;
695 SampleType inR = R[i] + sR.pingPongFb;
696
697 SampleType outL = processSampleInternal(0, inL, currentDelay, sL, SampleType(0), lpC, hpC, false);
698 SampleType outR = processSampleInternal(1, inR, currentDelay, sR, SampleType(0), lpC, hpC, false);
699
700 sR.pingPongFb = saturateFeedback(processFbFilters(1, outL * fb, lpC, hpC), analogFb); // L crosses to R
701 sL.pingPongFb = saturateFeedback(processFbFilters(0, outR * fb, lpC, hpC), analogFb); // R crosses to L
702
703 L[i] = outL;
704 R[i] = outR;
705 advanceWriteIndexUnchecked(0);
706 advanceWriteIndexUnchecked(1);
707 }
708 }
709
716 void mixWetToDry(AudioBufferView<SampleType> dry, SampleType mix) noexcept
717 {
718 // min/max with this argument order also resolves NaN to the dry bound.
719 mix = std::min(SampleType(1), std::max(SampleType(0), mix));
720 auto st = smootherType_.load(std::memory_order_relaxed);
721 if (st != SmootherType::None)
722 mixSmoother_.setTargetValue(static_cast<float>(mix));
723
724 const int nS = std::min(dry.getNumSamples(), wetBuffer_.getNumSamples());
725 const int nCh = std::min(dry.getNumChannels(), wetBuffer_.getNumChannels());
726
727 // Sample-outer loop: ONE smoother value per sample, shared by every
728 // channel. Advancing the smoother inside a channel-outer loop ran the
729 // ramp numChannels times too fast and, worse, gave each channel a
730 // different segment of it (channel 1 got the ramp a whole block ahead
731 // of channel 0), audibly tilting the stereo image on every mix change.
732 std::array<SampleType*, kMaxChannels> d {};
733 std::array<const SampleType*, kMaxChannels> w {};
734 for (int ch = 0; ch < nCh; ++ch)
735 {
736 d[ch] = dry.getChannel(ch);
737 w[ch] = wetBuffer_.getChannel(ch);
738 }
739 for (int i = 0; i < nS; ++i)
740 {
741 const SampleType m = (st != SmootherType::None)
742 ? static_cast<SampleType>(mixSmoother_.getNextValue()) : mix;
743 for (int ch = 0; ch < nCh; ++ch)
744 d[ch][i] = d[ch][i] * (SampleType(1) - m) + w[ch][i] * m;
745 }
746 }
747
749 AudioBufferView<SampleType> getWetView() noexcept { return wetBuffer_.toView(); }
750
752 [[nodiscard]] int getMaxDelaySamples() const noexcept { return maxDelaySamples_; }
753
754
756 [[nodiscard]] std::vector<uint8_t> getState() const
757 {
758 // The blob stores float: explicit casts, or Delay<double> would hand
759 // the writer a double that matches no overload unambiguously.
760 StateWriter w(stateId("DLAY"), 1);
761 w.write("delaySamples", static_cast<float>(globalDelay_.load(std::memory_order_relaxed)));
762 w.write("delayMs", static_cast<float>(getDelayMs()));
763 w.write("feedback", static_cast<float>(feedbackGain_.load(std::memory_order_relaxed)));
764 w.write("fbLpHz", static_cast<float>(fbLpHzShadow_.load(std::memory_order_relaxed)));
765 w.write("fbHpHz", static_cast<float>(fbHpHzShadow_.load(std::memory_order_relaxed)));
766 w.write("smoother", static_cast<int32_t>(smootherType_.load(std::memory_order_relaxed)));
767 w.write("smoothingMs", smoothingTimeMs_.load(std::memory_order_relaxed));
768 w.write("fbMode", static_cast<int32_t>(feedbackMode_.load(std::memory_order_relaxed)));
769 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
770 w.write("pingPong", static_cast<int32_t>(pingPong_.load(std::memory_order_relaxed) ? 1 : 0));
771 w.write("interp", static_cast<int32_t>(interpolation_.load(std::memory_order_relaxed)));
772 w.write("character", static_cast<int32_t>(character_.load(std::memory_order_relaxed)));
773 w.write("wowFlutter", static_cast<float>(wowFlutter_.load(std::memory_order_relaxed)));
774 w.write("charNoise", static_cast<float>(characterNoiseDb_.load(std::memory_order_relaxed)));
775 return w.blob();
776 }
777
779 bool setState(const uint8_t* data, size_t size)
780 {
781 StateReader r(data, size);
782 if (!r.isValid() || r.processorId() != stateId("DLAY")) return false;
783 // Prefer the time: a blob saved at another rate keeps its echo time.
784 // Older blobs carry only the sample count.
785 if (const float ms = r.read("delayMs", -1.0f); ms >= 0.0f)
786 setDelayMs(static_cast<SampleType>(ms));
787 else
788 setDelaySamples(static_cast<SampleType>(r.read("delaySamples", 0.0f)));
789 setFeedback(static_cast<SampleType>(r.read("feedback", 0.0f)));
790 setFeedbackLpHz(static_cast<SampleType>(r.read("fbLpHz", 0.0f)));
791 setFeedbackHpHz(static_cast<SampleType>(r.read("fbHpHz", 0.0f)));
792 // Enum fields clamped so a corrupt/foreign blob cannot install ids
793 // outside the ranges the switches expect.
794 setSmoother(static_cast<SmootherType>(std::clamp(r.read("smoother", 0), 0,
795 static_cast<int>(SmootherType::CriticallyDamped))));
796 setSmoothingTime(r.read("smoothingMs", 20.0f));
797 setFeedbackMode(static_cast<FeedbackMode>(std::clamp(r.read("fbMode", 1), 0,
798 static_cast<int>(FeedbackMode::Analog))));
799 setMix(static_cast<SampleType>(r.read("mix", 0.3f)));
800 setPingPong(r.read("pingPong", 0) != 0);
802 setCharacter(static_cast<Character>(std::clamp(r.read("character", 0), 0, static_cast<int>(Character::Bucket))));
803 setWowFlutter(static_cast<SampleType>(r.read("wowFlutter", 0.5f)));
804 setCharacterNoise(static_cast<SampleType>(r.read("charNoise", -84.0f)));
805 return true;
806 }
807
808protected:
809 static constexpr int kMaxChannels = 16;
810 static constexpr double kDefaultMaxDelaySeconds = 4.0;
811
829
830public:
836 void advanceWriteIndex(int ch) noexcept
837 {
838 if (ch < 0 || ch >= kMaxChannels) return;
839 advanceWriteIndexUnchecked(ch);
840 }
841
842private:
844 void advanceWriteIndexUnchecked(int ch) noexcept { writeIndices_[ch] = (writeIndices_[ch] + 1) & bufferMask_; }
845
849 [[nodiscard]] SampleType saturateFeedback(SampleType x, bool analog) const noexcept
850 {
851 return analog ? std::tanh(x) : std::clamp(x, SampleType(-2), SampleType(2));
852 }
853
854 template <typename ChannelFn>
855 void pushDryToWetImpl(ChannelFn&& getCh, int dryCh, int drySamples) noexcept
856 {
857 const int nCh = std::min(dryCh, wetBuffer_.getNumChannels());
858 const int nS = std::min(drySamples, wetBuffer_.getNumSamples());
859 for (int ch = 0; ch < nCh; ++ch)
860 std::memcpy(wetBuffer_.getChannel(ch), getCh(ch), static_cast<std::size_t>(nS) * sizeof(SampleType));
861 lastWetSamples_ = nS; // processWet()/processPingPong() run exactly this many
862 }
863
864 void resetChannelState(ChannelState& s) noexcept
865 {
866 s.fbLpZ1 = s.fbHpZ1 = s.lastFeedback = s.pingPongFb = 0;
867 s.currentDelay = s.targetDelay = 0;
868 }
869
870 void resetChannelSmoothers(ChannelState& s, float timeMs, float init) noexcept
871 {
872 double sr = static_cast<double>(sampleRate_);
873 s.lin.reset(sr, timeMs, init);
874 s.exp.reset(sr, timeMs, std::max(init, 1e-6f));
875 s.onePole.reset(sr, timeMs, init);
876 s.multi2.reset(sr, timeMs, init);
877 s.asym.reset(sr, timeMs / 5.0f, timeMs, init);
878 float timeSec = timeMs / 1000.0f;
879 float maxRate = static_cast<float>(maxDelaySamples_) / std::max(timeSec, 1e-6f);
880 s.slew.reset(sr, maxRate, init);
881 s.svf.reset(sr, timeMs, 0.707f, init);
882 s.butter.reset(sr, timeMs, init);
883 s.crit.reset(sr, timeMs, init);
884 }
885
886 void maybeUpdateSmoothers() noexcept
887 {
888 // First call after prepare()/reset(): every channel starts ON the set
889 // delay, so nothing glides in from zero (that glide swept the read
890 // point across the new input and played early copies of it).
891 if (snapNext_)
892 {
893 snapNext_ = false;
894 delayTargetDirty_.store(false, std::memory_order_relaxed);
895 smootherDirty_.store(false, std::memory_order_relaxed);
896 const SampleType target = globalDelay_.load(std::memory_order_acquire);
897 const float timeMs = smoothingTimeMs_.load(std::memory_order_relaxed);
898 for (int ch = 0; ch < numChannels_; ++ch)
899 {
900 auto& s = states_[ch];
901 resetChannelSmoothers(s, timeMs, static_cast<float>(target));
902 s.currentDelay = target;
903 setSmootherTarget(s, target);
904 }
905 mixSmoother_.reset(static_cast<double>(sampleRate_), timeMs, mixSmoother_.getCurrentValue());
906 return;
907 }
908
909 // Audio-thread application point for control-thread publications.
910 // A plain load first: the RMW is paid only when something is pending.
911 if (delayTargetDirty_.load(std::memory_order_relaxed)
912 && delayTargetDirty_.exchange(false, std::memory_order_acquire))
913 updateSmootherTargets(globalDelay_.load(std::memory_order_relaxed));
914
915 // exchange (not load+store: a publication between the two would be
916 // lost) with acquire, pairing with the setters' release stores so the
917 // freshly written type/time values are visible here.
918 if (!smootherDirty_.load(std::memory_order_relaxed)
919 || !smootherDirty_.exchange(false, std::memory_order_acquire)) return;
920 const float timeMs = smoothingTimeMs_.load(std::memory_order_relaxed);
921 const SampleType target = globalDelay_.load(std::memory_order_relaxed);
922 for (int ch = 0; ch < numChannels_; ++ch)
923 {
924 // Restart from where the read point is now, toward the set delay
925 // (currentDelay tracks the target under SmootherType::None too).
926 auto& s = states_[ch];
927 resetChannelSmoothers(s, timeMs, static_cast<float>(s.currentDelay));
928 setSmootherTarget(s, target);
929 }
930 mixSmoother_.reset(static_cast<double>(sampleRate_), timeMs, mixSmoother_.getCurrentValue());
931 }
932
933 void updateSmootherTargets(SampleType target) noexcept
934 {
935 const bool none = smootherType_.load(std::memory_order_relaxed) == SmootherType::None;
936 for (int ch = 0; ch < numChannels_; ++ch)
937 {
938 if (none)
939 {
940 // No smoother runs: keep the read point on record, so a
941 // later switch to a smoother starts from it.
942 states_[ch].targetDelay = target;
943 states_[ch].currentDelay = target;
944 }
945 else
946 {
947 setSmootherTarget(states_[ch], target);
948 }
949 }
950 }
951
953 [[nodiscard]] SampleType clampToCapacity(SampleType samples) const noexcept
954 {
955 samples = std::max(samples, SampleType(0));
956 return maxDelaySamples_ > 0 ? std::min(samples, static_cast<SampleType>(maxDelaySamples_ - 1))
957 : samples;
958 }
959
961 static const SincInterpolator<SampleType>& sincTable()
962 {
963 static const SincInterpolator<SampleType> table;
964 return table;
965 }
966
967 void setSmootherTarget(ChannelState& s, SampleType target) noexcept
968 {
969 s.targetDelay = target;
970 float t = static_cast<float>(target);
971 switch (smootherType_.load(std::memory_order_relaxed))
972 {
973 case SmootherType::Linear: s.lin.setTargetValue(t); break;
974 case SmootherType::Exponential: s.exp.setTargetValue(t); break;
975 case SmootherType::OnePole: s.onePole.setTargetValue(t); break;
976 case SmootherType::MultiPole2: s.multi2.setTargetValue(t); break;
977 case SmootherType::Asymmetric: s.asym.setTargetValue(t); break;
978 case SmootherType::SlewLimiter: s.slew.setTargetValue(t); break;
979 case SmootherType::StateVariable: s.svf.setTargetValue(t); break;
980 case SmootherType::Butterworth: s.butter.setTargetValue(t); break;
981 case SmootherType::CriticallyDamped:s.crit.setTargetValue(t); break;
982 default: break;
983 }
984 }
985
986 inline SampleType advanceSmoother(ChannelState& s, SmootherType st) noexcept
987 {
988 float val;
989 switch (st)
990 {
991 case SmootherType::Linear: val = s.lin.getNextValue(); break;
992 case SmootherType::Exponential: val = s.exp.getNextValue(); break;
993 case SmootherType::OnePole: val = s.onePole.getNextValue(); break;
994 case SmootherType::MultiPole2: val = s.multi2.getNextValue(); break;
995 case SmootherType::Asymmetric: val = s.asym.getNextValue(); break;
996 case SmootherType::SlewLimiter: val = s.slew.getNextValue(); break;
997 case SmootherType::StateVariable: val = s.svf.getNextValue(); break;
998 case SmootherType::Butterworth: val = s.butter.getNextValue(); break;
999 case SmootherType::CriticallyDamped:val = s.crit.getNextValue(); break;
1000 default: val = static_cast<float>(s.targetDelay);
1001 }
1002 s.currentDelay = static_cast<SampleType>(val);
1003 return s.currentDelay;
1004 }
1005
1006 inline SampleType processSampleInternal(int ch, SampleType input, SampleType delaySamples,
1007 ChannelState& s, SampleType fbMult,
1008 SampleType lpC, SampleType hpC,
1009 bool straightFeedback = true) noexcept
1010 {
1011 // Front-door non-finite guard: a NaN/Inf input, once written to the
1012 // ring and recirculated through the recursive feedback filters
1013 // (fbLpZ1/fbHpZ1) and the tanh saturator, poisons the delay line
1014 // permanently. Replace it with 0 before it enters any state. No-op on
1015 // finite input, so conformance metrics stay byte-identical. Shared by
1016 // every entry point (processBlock/Channel/Wet/PingPong/processSample).
1017 if (!std::isfinite(input)) input = SampleType(0);
1018
1019 // 4-point Hermite needs read positions at idx0-1, idx0, idx0+1, idx0+2.
1020 // The write index points to the slot we are about to write THIS sample.
1021 // Slots writeIdx, writeIdx+1, writeIdx+2 still hold stale data from
1022 // the previous ring-buffer wrap. To keep all 4 interpolation taps
1023 // inside the already-written history we need delaySamples >= 3.
1024 // Below that, samples idx1 / idx2 leak data ~bufferSize samples old
1025 // which manifests as audible clicks (notably when a binaural / Haas
1026 // panner crosses the centre). 3 samples ~ 62 us at 48 kHz -
1027 // imperceptible and the same on both channels, so spatial cues
1028 // (centre image, ITD ratios) are preserved.
1029 // The sinc reader needs SincInterpolator::kAfter + 1 = 17 written
1030 // samples after the read point by the same argument.
1031 constexpr SampleType kMinHermiteDelay = SampleType(3);
1032 const bool sinc = sinc_ && interpolation_.load(std::memory_order_relaxed) == Interpolation::Sinc;
1033 const SampleType minDelay = sinc ? SampleType(SincInterpolator<SampleType>::kAfter + 1)
1034 : kMinHermiteDelay;
1035 delaySamples = std::clamp(delaySamples, minDelay,
1036 static_cast<SampleType>(maxDelaySamples_ - 1));
1037
1038 const Character chr = character_.load(std::memory_order_relaxed);
1039 if (chr != lastCharacter_) [[unlikely]] switchCharacter(chr, delaySamples);
1040
1041 SampleType* data = delayBuffer_.getChannel(ch);
1042 const int writeIdx = writeIndices_[ch];
1043 const auto c = static_cast<size_t>(ch);
1044
1045 SampleType delayed;
1046 if (switchLeft_[c] > 0) [[unlikely]]
1047 {
1048 // A change of character: the incoming one runs from the change,
1049 // unheard until a bucket line has filled, then the two cross.
1050 const double outgoing = readCharacter(switchFrom_, ch, input, delaySamples, minDelay, sinc, s);
1051 const double incoming = readCharacter(lastCharacter_, ch, input, delaySamples, minDelay, sinc, s);
1052 const int left = switchLeft_[c]--;
1053 const double w = left > switchFade_ ? 0.0
1054 : static_cast<double>(switchFade_ - left + 1) / static_cast<double>(switchFade_);
1055 double y = outgoing + (incoming - outgoing) * w;
1056 const double hissOut = switchFrom_ != Character::Clean ? 1.0 - w : 0.0;
1057 const double hissIn = lastCharacter_ != Character::Clean ? w : 0.0;
1058 if (hissOut + hissIn > 0.0)
1059 {
1060 const Character heard = (w > 0.0 && lastCharacter_ != Character::Clean) || switchFrom_ == Character::Clean
1061 ? lastCharacter_ : switchFrom_;
1062 y += (hissOut + hissIn) * hiss(ch, hissCoeffOf(ch, heard));
1063 }
1064 delayed = static_cast<SampleType>(y);
1065 }
1066 else
1067 {
1068 // The character in play (a change waiting for another to end is not yet).
1069 const Character now = lastCharacter_;
1070 double y = readCharacter(now, ch, input, delaySamples, minDelay, sinc, s);
1071 if (now != Character::Clean) y += hiss(ch, hissCoeffOf(ch, now));
1072 delayed = static_cast<SampleType>(y);
1073 }
1074
1075 // Feedback processing. The filters run on every sample of the straight
1076 // path, silence and zero feedback included: skipping them froze their
1077 // state, which then played back as a step when the feedback (or the
1078 // signal) returned, and cut the filters' own decay short. The ping-pong
1079 // paths filter their cross-feed themselves (straightFeedback false).
1080 SampleType fbInput = SampleType(0);
1081 if (straightFeedback)
1082 {
1083 fbInput = processFbFilters(ch, delayed * fbMult, lpC, hpC);
1084 if (fbInput != SampleType(0))
1085 fbInput = saturateFeedback(fbInput,
1086 feedbackMode_.load(std::memory_order_relaxed) == FeedbackMode::Analog);
1087 }
1088 s.lastFeedback = fbInput;
1089
1090 data[writeIdx] = input + s.lastFeedback;
1091 return delayed;
1092 }
1093
1094 inline SampleType processFbFilters(int ch, SampleType sample, SampleType lpC, SampleType hpC) noexcept
1095 {
1096 auto& s = states_[ch];
1097 SampleType out = sample;
1098
1099 // Apply denormal prevention (1e-18f bias)
1100 out += SampleType(1e-18);
1101
1102 if (hpC > SampleType(0))
1103 {
1104 s.fbHpZ1 = out * (SampleType(1) - hpC) + s.fbHpZ1 * hpC;
1105 out -= s.fbHpZ1;
1106 }
1107 if (lpC > SampleType(0))
1108 {
1109 s.fbLpZ1 = out * (SampleType(1) - lpC) + s.fbLpZ1 * lpC;
1110 out = s.fbLpZ1;
1111 }
1112
1113 out -= SampleType(1e-18);
1114 return out;
1115 }
1116
1123 void switchCharacter(Character chr, SampleType delaySamples) noexcept
1124 {
1125 for (int ch = 0; ch < std::min(numChannels_, kMaxChannels); ++ch)
1126 if (switchLeft_[static_cast<size_t>(ch)] > 0) return;
1127 switchFrom_ = lastCharacter_;
1128 lastCharacter_ = chr;
1129 if (chr == Character::Tape) tapeSeeded_.fill(false);
1130 int fill = 0;
1131 if (chr == Character::Bucket)
1132 {
1133 for (auto& b : bbd_) b.reset();
1134 bucketCornerFor_.fill(-1.0);
1135 fill = static_cast<int>(delaySamples) + static_cast<int>(kBucketSettleSeconds * static_cast<double>(sampleRate_));
1136 }
1137 switchLeft_.fill(fill + switchFade_);
1138 }
1139
1141 SampleType readRing(int ch, SampleType delaySamples, bool sinc) noexcept
1142 {
1143 SampleType* data = delayBuffer_.getChannel(ch);
1144 const int writeIdx = writeIndices_[ch];
1145 // Read position writeIdx - delaySamples, split into an integer index
1146 // and a fraction in [0, 1] without ever forming the wrapped float
1147 // position: writeIdx - delay + size rounded up to exactly `size` when
1148 // the position fell a hair below 0, which masked the index to 0 while
1149 // the "fraction" became `size` (a Hermite blow-up, heard as random
1150 // zips on moving Haas/binaural delays).
1151 const int dInt = static_cast<int>(delaySamples); // >= 3
1152 const SampleType dFrac = delaySamples - static_cast<SampleType>(dInt);
1153 int idx0;
1154 SampleType frac;
1155 if (dFrac > SampleType(0))
1156 {
1157 idx0 = (writeIdx - dInt - 1) & bufferMask_;
1158 frac = SampleType(1) - dFrac;
1159 }
1160 else
1161 {
1162 idx0 = (writeIdx - dInt) & bufferMask_;
1163 frac = SampleType(0);
1164 }
1165 if (sinc)
1166 return sinc_->readRing(data, static_cast<int64_t>(bufferMask_), static_cast<int64_t>(idx0), static_cast<double>(frac));
1167 // 3rd-order Hermite interpolation (4-point).
1168 const int idxM1 = (idx0 - 1 + maxDelaySamples_) & bufferMask_;
1169 const int idx1 = (idx0 + 1) & bufferMask_;
1170 const int idx2 = (idx0 + 2) & bufferMask_;
1171 const SampleType ym1 = data[idxM1];
1172 const SampleType y0 = data[idx0];
1173 const SampleType y1 = data[idx1];
1174 const SampleType y2 = data[idx2];
1175 const SampleType c = (y1 - ym1) * SampleType(0.5);
1176 const SampleType v = y0 - y1;
1177 const SampleType w = c + v;
1178 const SampleType a = w + v + (y2 - y0) * SampleType(0.5);
1179 const SampleType b = w + a;
1180 return ((((a * frac) - b) * frac + c) * frac + y0);
1181 }
1182
1188 double readCharacter(Character chr, int ch, SampleType input, SampleType delaySamples, SampleType minDelay,
1189 bool sinc, ChannelState& s) noexcept
1190 {
1191 const auto c = static_cast<size_t>(ch);
1192 if (chr == Character::Bucket)
1193 return static_cast<double>(bucketRead(ch, input + s.lastFeedback, delaySamples));
1194 SampleType d = delaySamples;
1195 if (chr == Character::Tape)
1196 {
1197 // The tape reaches the set delay as a speed, with the motor's
1198 // inertia, and wanders by its wow and flutter.
1199 auto& tp = tape_[c];
1200 const double target = static_cast<double>(delaySamples);
1201 if (!tapeSeeded_[c])
1202 {
1203 tp.setTargetDelayNow(target);
1204 tapeSeeded_[c] = true;
1205 }
1206 else
1207 {
1208 tp.setTargetDelay(target);
1209 }
1210 d = std::clamp(static_cast<SampleType>(tp.next(static_cast<double>(wowFlutter_.load(std::memory_order_relaxed)))),
1211 minDelay, static_cast<SampleType>(maxDelaySamples_ - 1));
1212 }
1213 const double y = static_cast<double>(readRing(ch, d, sinc));
1214 if (chr != Character::Tape) return y;
1215 headLp_[c] += headCoeff_ * (y - headLp_[c]);
1216 return headLp_[c];
1217 }
1218
1224 SampleType bucketRead(int ch, SampleType in, SampleType delaySamples) noexcept
1225 {
1226 const auto c = static_cast<size_t>(ch);
1227 auto& b = bbd_[c];
1228 const double fs = static_cast<double>(sampleRate_);
1229 const double d = static_cast<double>(delaySamples);
1230 if (bucketCornerFor_[c] < 0.0 || ++bucketTick_[c] >= kBucketCornerGrid)
1231 {
1232 bucketTick_[c] = 0;
1233 const double corner = std::min(0.3 * b.clockFor(d / fs), 0.45 * fs);
1234 if (bucketCornerFor_[c] < 0.0) b.setCornersNow(corner, corner);
1235 else
1236 {
1237 // The line glides over the next 32 samples: to where the
1238 // corner will be at their end, if the delay goes on moving
1239 // as it did over the last 32.
1240 const double before = std::min(0.3 * b.clockFor(bucketCornerFor_[c] / fs), 0.45 * fs);
1241 const double ahead = std::clamp(2.0 * corner - before, 0.5 * corner, 2.0 * corner);
1242 b.setCorner(ahead);
1243 }
1244 bucketHissCoeff_[c] = 1.0 - std::exp(-2.0 * 3.141592653589793 * corner / fs);
1245 bucketCornerFor_[c] = d;
1246 }
1247 // The device's own delay (its filters, its hold) comes off the
1248 // chain's, so the echo lands on the time asked for.
1249 return b.processSample(in, b.delayFor(d / fs));
1250 }
1251
1257 [[nodiscard]] double hissCoeffOf(int ch, Character chr) const noexcept
1258 {
1259 return chr == Character::Tape ? headCoeff_ : bucketHissCoeff_[static_cast<size_t>(ch)];
1260 }
1261
1263 double hiss(int ch, double hissCoeff) noexcept
1264 {
1265 const auto c = static_cast<size_t>(ch);
1266 double y = 0.0;
1267 const double noiseDb = static_cast<double>(characterNoiseDb_.load(std::memory_order_relaxed));
1268 if (noiseDb > -120.0)
1269 {
1270 if (noiseDb != hissDbFor_[c] || hissCoeff != hissCoeffFor_[c]) [[unlikely]]
1271 {
1272 hissAmp_[c] = std::pow(10.0, noiseDb / 20.0) * 1.7320508075688772
1273 / std::sqrt(std::max(1e-9, hissCoeff / (2.0 - hissCoeff)));
1274 hissDbFor_[c] = noiseDb;
1275 hissCoeffFor_[c] = hissCoeff;
1276 }
1277 hissRng_[c] = hissRng_[c] * 1664525u + 1013904223u;
1278 const double n = static_cast<double>(hissRng_[c] >> 8) / 8388608.0 - 1.0;
1279 hissLp_[c] += hissCoeff * (n - hissLp_[c]);
1280 y = hissAmp_[c] * hissLp_[c];
1281 }
1282 return y;
1283 }
1284
1286 SampleType calcOnePoleCoef(SampleType freq) const noexcept { return std::exp(-twoPi<SampleType> * freq / sampleRate_); }
1287 SampleType calcLpCoef(SampleType freq) const noexcept { return calcOnePoleCoef(freq); }
1288 SampleType calcHpCoef(SampleType freq) const noexcept { return calcOnePoleCoef(freq); }
1289
1290 static int nextPow2(int v) noexcept
1291 {
1292 int r = 1;
1293 while (r < v) r <<= 1;
1294 return r;
1295 }
1296
1297 // -- Members -------------------------------------------------------------
1298 std::atomic<bool> prepared_{ false };
1299 AudioBuffer<SampleType> delayBuffer_, wetBuffer_;
1300 std::array<ChannelState, kMaxChannels> states_ {};
1301 std::array<int, kMaxChannels> writeIndices_ {};
1302
1303 int maxDelaySamples_ = 0, bufferMask_ = 0;
1304 int numChannels_ = 0, blockSize_ = 0;
1305 int lastWetSamples_ = 0;
1306 SampleType sampleRate_ = SampleType(48000);
1307
1308 std::atomic<SampleType> globalDelay_ { SampleType(0) };
1309 std::atomic<SampleType> delayMs_ { SampleType(0) };
1310 std::atomic<SampleType> pendingDelaySamples_ { SampleType(-1) };
1311 std::atomic<Interpolation> interpolation_ { Interpolation::Hermite };
1312 const SincInterpolator<SampleType>* sinc_ = nullptr;
1313 bool snapNext_ = true;
1314 std::atomic<SampleType> feedbackGain_ { SampleType(0) };
1315 std::atomic<SampleType> fbLpCoef_ { SampleType(0) };
1316 std::atomic<SampleType> fbLpHzShadow_ { SampleType(0) };
1317 std::atomic<SampleType> fbHpHzShadow_ { SampleType(0) };
1318 std::atomic<SampleType> fbHpCoef_ { SampleType(0) };
1319
1320 std::atomic<SmootherType> smootherType_ { SmootherType::Exponential };
1321 std::atomic<float> smoothingTimeMs_ { 20.0f };
1322 std::atomic<bool> smootherDirty_ { false };
1323 std::atomic<bool> delayTargetDirty_ { false };
1324 std::atomic<FeedbackMode> feedbackMode_ { FeedbackMode::Analog };
1325
1326 Smoothers::LinearSmoother mixSmoother_;
1327 std::atomic<SampleType> mix_ { SampleType(0.3) };
1328 std::atomic<bool> pingPong_ { false };
1329 SampleType insertMix_ = SampleType(0.3);
1330 SampleType insertMixMaxStep_ = SampleType(1.0 / 960.0);
1331
1332 // Characters.
1333 static constexpr int kBucketStages = 4096;
1334 static constexpr int kBucketCornerGrid = 32;
1335 static constexpr double kBucketSettleSeconds = 0.004;
1336 static constexpr double kSwitchFadeSeconds = 0.01;
1337 static constexpr double kHeadLossHz = 7000.0;
1338 std::atomic<Character> character_ { Character::Clean };
1339 std::atomic<SampleType> wowFlutter_ { SampleType(0.5) };
1340 std::atomic<SampleType> characterNoiseDb_ { SampleType(-84) };
1341 Character lastCharacter_ = Character::Clean;
1342 std::vector<TapeTransport<SampleType>> tape_;
1343 std::vector<BucketBrigade<SampleType>> bbd_;
1344 std::array<bool, kMaxChannels> tapeSeeded_ {};
1345 std::array<double, kMaxChannels> bucketCornerFor_ {};
1346 std::array<int, kMaxChannels> bucketTick_ {};
1347 std::array<int, kMaxChannels> switchLeft_ {};
1348 Character switchFrom_ = Character::Clean;
1349 int switchFade_ = 480;
1350 std::array<double, kMaxChannels> headLp_ {}, hissLp_ {}, bucketHissCoeff_ {};
1351 std::array<double, kMaxChannels> hissAmp_ {}, hissDbFor_ {}, hissCoeffFor_ {};
1352 std::array<uint32_t, kMaxChannels> hissRng_ {};
1353 double headCoeff_ = 0.5;
1354};
1355
1356} // 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.
AudioBufferView< T, MaxChannels > toView() noexcept
Returns a non-owning mutable view of this buffer. The view's channel capacity is propagated from MaxC...
int getNumChannels() const noexcept
Returns the number of active channels.
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
int getNumSamples() const noexcept
Returns the number of samples per channel.
void resize(int numChannels, int numSamples)
Allocates the buffer for the given dimensions.
void clear() noexcept
Clears all channels, including SIMD alignment padding. Ensures any SIMD over-read will consume pure z...
void setSmoothingTime(float ms) noexcept
Sets the smoothing transition time.
Definition Delay.h:324
Character getCharacter() const noexcept
Definition Delay.h:150
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition Delay.h:779
Interpolation
Fractional read kernel.
Definition Delay.h:115
@ Hermite
4-point cubic (default). Error -24 dB at 10 kHz on a moving read.
SampleType processSample(int ch, SampleType input) noexcept
Processes a single sample for a specific channel.
Definition Delay.h:425
AudioBufferView< SampleType > getWetView() noexcept
Exposes the internal wet buffer view.
Definition Delay.h:749
void setCharacter(Character c) noexcept
Selects the character. Thread-safe; out-of-range values are clamped.
Definition Delay.h:144
void setFeedback(SampleType gain) noexcept
Sets the global feedback amount.
Definition Delay.h:393
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition Delay.h:756
Character
Colour of the line (see the file comment).
Definition Delay.h:137
@ Tape
A tape loop: speed transport, wow and flutter, head loss, hiss.
@ Bucket
A bucket-brigade device of 4096 stages.
@ Clean
An interpolated delay line (default).
void mixWetToDry(AudioBufferView< SampleType > dry, SampleType mix) noexcept
Mixes the processed wet buffer back into the provided dry buffer.
Definition Delay.h:716
void pushDryToWet(AudioBufferView< SampleType > dry) noexcept
Copies a dry buffer into the internal wet buffer.
Definition Delay.h:637
int getMaxDelaySamples() const noexcept
Returns maximum capacity in samples.
Definition Delay.h:752
static constexpr double kDefaultMaxDelaySeconds
Definition Delay.h:810
Interpolation getInterpolation() const noexcept
Returns the fractional read kernel.
Definition Delay.h:130
SampleType getCurrentDelaySamples() const noexcept
Returns the current target delay time in samples.
Definition Delay.h:385
void setFeedbackHpHz(SampleType freq) noexcept
Sets the cutoff frequency for the feedback high-pass filter (0 to disable). Non-finite values are ign...
Definition Delay.h:410
void setMix(SampleType mix) noexcept
Sets the dry/wet blend of the insert-style processBlock(buffer).
Definition Delay.h:522
void prepareMs(const AudioSpec &spec, double maxDelayMs)
Prepares the delay with a maximum capacity in milliseconds.
Definition Delay.h:273
SampleType getCharacterNoise() const noexcept
Definition Delay.h:175
void prepare(const AudioSpec &spec, double maxDelaySeconds)
Prepares the delay structures and allocates memory. Must be called before processing.
Definition Delay.h:196
void processChannel(AudioBufferView< SampleType > buffer, int ch, SampleType delayMs, SampleType feedback=0, SampleType lpHz=0, SampleType hpHz=0) noexcept
Processes a single channel block in-place. Safe to call sequentially for different channels.
Definition Delay.h:598
FeedbackMode getFeedbackMode() const noexcept
Returns the active feedback mode.
Definition Delay.h:108
void processPingPong(SampleType delayMs, SampleType feedback=0, SampleType lpHz=0, SampleType hpHz=0) noexcept
Processes a true ping-pong delay (L feeds R, R feeds L) on the samples of the most recent pushDryToWe...
Definition Delay.h:660
void pushDryToWet(AudioBufferView< const SampleType > dry) noexcept
Copies a dry buffer into the internal wet buffer.
Definition Delay.h:631
void setWowFlutter(SampleType amount) noexcept
Wow and flutter of the tape character.
Definition Delay.h:156
void prepare(const AudioSpec &spec)
Prepares for insert use with the default capacity (4 seconds).
Definition Delay.h:183
void setSmoother(SmootherType type) noexcept
Sets the smoothing algorithm used for delay time changes.
Definition Delay.h:314
void setDelaySamples(SampleType samples) noexcept
Sets the delay time in samples.
Definition Delay.h:339
SampleType getWowFlutter() const noexcept
Definition Delay.h:162
void setFeedbackLpHz(SampleType freq) noexcept
Sets the cutoff frequency for the feedback low-pass filter (0 to disable). Non-finite values are igno...
Definition Delay.h:401
void setFeedbackMode(FeedbackMode mode) noexcept
Selects clean or analog feedback regeneration. Thread-safe.
Definition Delay.h:102
FeedbackMode
Feedback path colour.
Definition Delay.h:92
void setInterpolation(Interpolation mode) noexcept
Selects the fractional read kernel. Thread-safe.
Definition Delay.h:123
void setDelayMs(SampleType ms) noexcept
Sets the delay time in milliseconds (the stored form). Non-finite values are ignored.
Definition Delay.h:363
void setPingPong(bool on) noexcept
Ping-pong for the insert-style processBlock(buffer): the first two channels feed their echoes to each...
Definition Delay.h:539
SampleType getMix() const noexcept
Returns the insert dry/wet blend.
Definition Delay.h:529
void processBlock(AudioBufferView< SampleType > buffer) noexcept
Insert-style processing: the dry/wet blend, in place, with the stored parameters (setDelayMs(),...
Definition Delay.h:454
static constexpr int kMaxChannels
Definition Delay.h:809
void processBlock(AudioBufferView< SampleType > buffer, SampleType delayMs, SampleType feedback=0, SampleType lpHz=0, SampleType hpHz=0) noexcept
Processes a multi-channel block in-place.
Definition Delay.h:560
void setCharacterNoise(SampleType dbfs) noexcept
Hiss of the tape and bucket characters.
Definition Delay.h:169
SampleType getDelayMs() const noexcept
Returns the delay time in milliseconds.
Definition Delay.h:377
void advanceWriteIndex(int ch) noexcept
Advances the write index for a specific channel.
Definition Delay.h:836
bool getPingPong() const noexcept
True when the insert path runs as a ping-pong delay.
Definition Delay.h:542
void processWet(SampleType delayMs, SampleType feedback=0, SampleType lpHz=0, SampleType hpHz=0) noexcept
Processes the wet buffer in place with current settings. Processes exactly the samples of the most re...
Definition Delay.h:647
void setDelaySeconds(SampleType secs) noexcept
Sets the delay time in seconds.
Definition Delay.h:374
int getLatency() const noexcept
Latency in samples: none (the delay is the effect, not a latency).
Definition Delay.h:545
void reset() noexcept
Clears the delay buffers and resets all filter and feedback states.
Definition Delay.h:281
T readRing(const T *ring, int64_t mask, int64_t intPos, double frac) const noexcept
Reads a power-of-two ring buffer at intPos + frac.
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
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
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
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
Smoothers::ExponentialSmoother exp
Definition Delay.h:820
Smoothers::OnePoleSmoother onePole
Definition Delay.h:821
Smoothers::StateVariableSmoother svf
Definition Delay.h:825
Smoothers::ButterworthSmoother butter
Definition Delay.h:826
Smoothers::LinearSmoother lin
Definition Delay.h:819
Smoothers::CriticallyDampedSmoother crit
Definition Delay.h:827
Smoothers::SlewLimiter slew
Definition Delay.h:824
Smoothers::MultiPoleSmoother< 2 > multi2
Definition Delay.h:822
Smoothers::AsymmetricSmoother asym
Definition Delay.h:823
Smoother with asymmetric attack/release times.
Definition Smoothers.h:199
Butterworth low-pass smoother for maximally flat response.
Definition Smoothers.h:300
Critically damped smoother (no overshoot, exact Q=0.5).
Definition Smoothers.h:328
Exponential (multiplicative) smoother for natural, perceptual responses.
Definition Smoothers.h:111
Linear ramp smoother for predictable, uniform interpolation.
Definition Smoothers.h:60
void reset(double sampleRate, float rampTimeMilliseconds, float initialValue=0.0f) noexcept
Definition Smoothers.h:383
void setTargetValue(float newTarget) noexcept
Definition Smoothers.h:392
float getCurrentValue() const noexcept
Definition Smoothers.h:68
Templated cascaded multi-pole smoother for steeper roll-off.
Definition Smoothers.h:172
Authentic one-pole exponential IIR low-pass smoother.
Definition Smoothers.h:147
Rate limiter to cap maximum change per sample.
Definition Smoothers.h:230
Second-order state variable filter (SVF) smoother (TPT implementation).
Definition Smoothers.h:259
The transport's constants.
double restoreSeconds
Restoring time of the delay to the head distance.
double reel
Speed deviations at full depth and 15 ips:
double slowDownSeconds
... and when slowing down.
double speedUpSeconds
Inertia when speeding up.
double capstan
reel, capstan, its second harmonic's share,
double maxStep
Largest delay change per sample (bounds the pitch).