DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Chorus.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
74#include "../Core/RingBuffer.h"
75#include "../Core/Oscillator.h"
76#include "../Core/DryWetMixer.h"
77#include "../Core/DspMath.h"
78#include "../Core/AudioSpec.h"
79#include "../Core/AudioBuffer.h"
80#include "../Core/DenormalGuard.h"
81#include "../Core/Interpolation.h"
82#include "../Core/StateBlob.h"
83#include "../Core/BucketBrigade.h"
84#include "../Core/Biquad.h"
85
86#include <algorithm>
87#include <array>
88#include <atomic>
89#include <cmath>
90#include <cstddef>
91#include <cstdint>
92#include <vector>
93
94namespace dspark {
95
102template <FloatType T>
104{
105public:
106 ~Chorus() = default; // non-virtual: leaf class, no virtual dispatch (framework policy)
107
108 static constexpr int kMaxVoices = 4;
109 static constexpr int kMaxChannels = 16;
110
112 enum class Interpolation
113 {
114 Hermite,
115 Sinc,
117 Linear
120 };
121
123 enum class Model
124 {
125 Digital,
126 Analog
127 };
128
130 enum class AnalogMode
131 {
132 Slow,
133 Fast,
134 Vibrato
135 };
136
137 // -- Lifecycle --------------------------------------------------------------
138
147 void prepare(const AudioSpec& spec)
148 {
149 if (!spec.isValid()) return; // release-safe: keep previous state
150
151 spec_ = spec;
152 mixer_.prepare(spec);
153
154 // Max delay: 30ms center + 20ms depth = 50ms total safety margin.
155 // The +4 pad keeps the interpolator's read window (intDelay + 2)
156 // strictly inside the ring even when the requested size lands exactly
157 // on a power of two (RingBuffer rounds its capacity up to one).
158 // The sinc reader also needs SincInterpolator::kBefore + 1 samples
159 // behind its read point: a +20 pad covers both readers.
160 maxDelaySamples_ = static_cast<int>(spec.sampleRate * 0.05) + 1;
161
162 for (int ch = 0; ch < spec.numChannels && ch < kMaxChannels; ++ch)
164 sinc_ = &sincTable(); // built on this setup thread, once per process
165 voiceFadeStep_ = static_cast<T>(1.0 / std::max(1.0, spec.sampleRate * 0.05));
166
167 for (int ch = 0; ch < kMaxChannels; ++ch)
168 {
169 for (int v = 0; v < kMaxVoices; ++v)
170 {
171 lfos_[ch][v].prepare(spec.sampleRate);
172 // LFO duty: keep the waveforms inside [-1, 1] (no minBLEP overshoot).
173 lfos_[ch][v].setAntiAliasing(Oscillator<T>::AntiAliasing::PolyBLEP);
174 lfos_[ch][v].setWaveform(lfoWaveform_.load(std::memory_order_relaxed));
175 }
176 }
177
178 // Initialize smoothing states
179 smoothedCenterSamples_ = centerDelayMs_.load(std::memory_order_relaxed) * static_cast<T>(spec.sampleRate) / T(1000);
180 smoothedDepthSamples_ = depthMs_.load(std::memory_order_relaxed) * static_cast<T>(spec.sampleRate) / T(1000);
181
182 // The analog engine: at half the rate from 176.4 kHz; below 88.2 kHz
183 // its lines run at twice the rate, so the images of their clock are
184 // filtered as in the device instead of folding into the band.
185 halfRate_ = spec.sampleRate >= 176400.0;
186 engineRate_ = halfRate_ ? 0.5 * spec.sampleRate : spec.sampleRate;
187 const int lineFactor = engineRate_ < 88200.0 ? 2 : 1;
188 for (auto& b : bbd_)
189 {
190 b.setPrecision(BucketBrigade<T>::Precision::High);
191 b.prepare(engineRate_, kAnalogStages, 4000.0, lineFactor);
192 }
193 hissHpCoeff_ = std::exp(-2.0 * 3.141592653589793 * kHissHighPassHz / engineRate_);
194 switchBuffer_.resize(spec.numChannels, spec.maxBlockSize);
195 switchFade_ = std::max(1, static_cast<int>(kSwitchFadeSeconds * spec.sampleRate));
196 analogCornerFor_ = -1.0;
197 analogGlide_ = 1.0 - std::exp(-1.0 / (kAnalogGlideSeconds * engineRate_));
198 {
199 static constexpr double kQ4[2] = { 0.5411961001461970, 1.3065629648763764 };
200 for (int k = 0; k < 2; ++k)
201 decimate_[static_cast<size_t>(k)] = BiquadCoeffs::makeLowPass(spec.sampleRate, std::min(20000.0, 0.2 * spec.sampleRate), kQ4[k]);
202 }
203 hpCoeff_ = std::exp(-2.0 * 3.141592653589793 * 5.0 / spec.sampleRate);
204 noiseCoeff_ = 0.0;
205
207 reset();
208 }
209
217 void processBlock(AudioBufferView<T> buffer) noexcept
218 {
219 if (maxDelaySamples_ <= 0) return; // not prepared: pass through
220 DenormalGuard denormalGuard;
221
222 // Front-door non-finite guard: a single NaN/Inf input sample would
223 // recirculate through the recursive fbState_ path (fastTanh passes
224 // NaN) and mute the voice forever. Replace non-finite input with 0 before
225 // it reaches the dry snapshot or any delay/feedback state. No-op on finite
226 // input, so conformance metrics stay byte-identical.
227 const int nS = buffer.getNumSamples();
228 for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
229 {
230 T* d = buffer.getChannel(ch);
231 for (int i = 0; i < nS; ++i)
232 if (!std::isfinite(d[i])) d[i] = T(0);
233 }
234
235 // The dry/wet mixer holds one prepared block: a longer host block runs
236 // in prepared-size slices so its tail is mixed too.
237 for (int offset = 0; offset < nS; offset += spec_.maxBlockSize)
238 processChunk(buffer.getSubView(offset, std::min(spec_.maxBlockSize, nS - offset)));
239 }
240
244 void reset() noexcept
245 {
246 for (int ch = 0; ch < kMaxChannels; ++ch)
247 {
248 delayLines_[ch].reset();
249 fbState_[ch] = T(0);
250 }
251 mixer_.reset();
252 for (auto& b : bbd_) b.reset();
253 analogPhase_ = 0.0;
254 analogPrimed_ = false;
255 hpX1_ = hpY1_ = 0.0;
256 for (auto& s : decimateState_) s = {};
257 engineOut_ = {};
258 engineLast_ = {};
259 noiseLp_ = {};
260 hissHpX_ = {};
261 hissHpY_ = {};
262 decimatePhase_ = 0;
263 switching_ = false;
264 playing_ = model_.load(std::memory_order_relaxed);
265 // A reset starts on the target layout: phases set, voices at level.
266 const int nv = numVoices_.load(std::memory_order_relaxed);
267 for (int v = 0; v < kMaxVoices; ++v)
268 voiceGain_[static_cast<size_t>(v)] = v < nv ? T(1) : T(0);
270 }
271
273 void setInterpolation(Interpolation mode) noexcept
274 {
276 std::memory_order_relaxed);
277 }
278
280 [[nodiscard]] Interpolation getInterpolation() const noexcept
281 {
282 return interpolation_.load(std::memory_order_relaxed);
283 }
284
285 // -- Parameters ------------------------------------------------------------- // -- Parameters -------------------------------------------------------------
286
291 void setRate(T hz) noexcept
292 {
293 if (!std::isfinite(hz)) return;
294 rate_.store(std::clamp(hz, T(0.01), T(20)), std::memory_order_relaxed);
295 }
296
301 void setDepthMs(T ms) noexcept
302 {
303 if (!std::isfinite(ms)) return;
304 depthMs_.store(std::clamp(ms, T(0), T(20)), std::memory_order_relaxed);
305 }
306
312 void setMix(T dryWet) noexcept
313 {
314 if (!std::isfinite(dryWet)) return;
315 mix_.store(std::clamp(dryWet, T(0), T(1)), std::memory_order_relaxed);
316 }
317
322 void setVoices(int count) noexcept
323 {
324 numVoices_.store(std::clamp(count, 1, kMaxVoices), std::memory_order_relaxed);
325 lfoPhaseDirty_.store(true, std::memory_order_release); // recomputed on audio thread
326 }
327
333 void setFeedback(T amount) noexcept
334 {
335 if (!std::isfinite(amount)) return;
336 feedback_.store(std::clamp(amount, T(-0.99), T(0.99)), std::memory_order_relaxed);
337 }
338
343 void setCenterDelay(T ms) noexcept
344 {
345 if (!std::isfinite(ms)) return;
346 centerDelayMs_.store(std::clamp(ms, T(0.1), T(30)), std::memory_order_relaxed);
347 }
348
353 void setStereoSpread(T amount) noexcept
354 {
355 if (!std::isfinite(amount)) return;
356 stereoSpread_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
357 }
358
363 void setAutoDepth(bool enabled) noexcept { autoDepth_.store(enabled, std::memory_order_relaxed); }
364
371 void setModWaveform(typename Oscillator<T>::Waveform wf) noexcept
372 {
373 // Publish only; the audio thread reapplies it (the oscillators are not
374 // thread-safe, so we must not write their state from the control thread).
375 const int w = std::clamp(static_cast<int>(wf), 0,
376 static_cast<int>(Oscillator<T>::Waveform::Triangle));
377 lfoWaveform_.store(static_cast<typename Oscillator<T>::Waveform>(w),
378 std::memory_order_relaxed);
379 waveformDirty_.store(true, std::memory_order_release);
380 }
381
382
384 void setModel(Model m) noexcept
385 {
386 model_.store(m == Model::Analog ? Model::Analog : Model::Digital, std::memory_order_relaxed);
387 }
389 [[nodiscard]] Model getModel() const noexcept { return model_.load(std::memory_order_relaxed); }
390
392 [[nodiscard]] T getRate() const noexcept { return rate_.load(std::memory_order_relaxed); }
394 [[nodiscard]] T getDepthMs() const noexcept { return depthMs_.load(std::memory_order_relaxed); }
396 [[nodiscard]] T getCenterDelay() const noexcept { return centerDelayMs_.load(std::memory_order_relaxed); }
397
406 void setAnalogMode(AnalogMode mode) noexcept
407 {
408 const int m = std::clamp(static_cast<int>(mode), 0, 2);
409 analogMode_.store(m, std::memory_order_relaxed);
410 static constexpr float kRate[3] = { 0.5f, 0.85f, 7.0f };
411 static constexpr float kDepth[3] = { 1.6f, 1.6f, 0.25f };
412 static constexpr float kCentre[3] = { 5.0f, 5.0f, 7.0f };
413 setRate(static_cast<T>(kRate[m]));
414 setDepthMs(static_cast<T>(kDepth[m]));
415 setCenterDelay(static_cast<T>(kCentre[m]));
416 setAnalogTapPhase(m == 2 ? T(0) : T(180));
417 }
419 [[nodiscard]] AnalogMode getAnalogMode() const noexcept { return static_cast<AnalogMode>(analogMode_.load(std::memory_order_relaxed)); }
420
427 void setAnalogNoise(T dB) noexcept
428 {
429 if (std::isfinite(dB)) analogNoiseDb_.store(std::clamp(dB, T(-200), T(-40)), std::memory_order_relaxed);
430 }
432 [[nodiscard]] T getAnalogNoise() const noexcept { return analogNoiseDb_.load(std::memory_order_relaxed); }
433
440 void setAnalogTapPhase(T degrees) noexcept
441 {
442 if (std::isfinite(degrees)) analogTapPhase_.store(std::clamp(degrees, T(0), T(180)), std::memory_order_relaxed);
443 }
445 [[nodiscard]] T getAnalogTapPhase() const noexcept { return analogTapPhase_.load(std::memory_order_relaxed); }
446
453 void setAnalogTone(T tone) noexcept
454 {
455 if (std::isfinite(tone)) analogTone_.store(std::clamp(tone, T(-1), T(1)), std::memory_order_relaxed);
456 }
458 [[nodiscard]] T getAnalogTone() const noexcept { return analogTone_.load(std::memory_order_relaxed); }
459
465 void setAnalogCircuitFilters(bool on) noexcept { analogCircuit_.store(on, std::memory_order_relaxed); }
467 [[nodiscard]] bool getAnalogCircuitFilters() const noexcept { return analogCircuit_.load(std::memory_order_relaxed); }
468
470 void setMixRule(typename DryWetMixer<T>::MixRule rule) noexcept { mixer_.setMixRule(rule); }
472 [[nodiscard]] typename DryWetMixer<T>::MixRule getMixRule() const noexcept { return mixer_.getMixRule(); }
473
475 [[nodiscard]] std::vector<uint8_t> getState() const
476 {
477 // The blob stores float: the casts keep the double instantiation
478 // compiling (a double matches no StateWriter overload unambiguously).
479 StateWriter w(stateId("CHOR"), 1);
480 w.write("rate", static_cast<float>(rate_.load(std::memory_order_relaxed)));
481 w.write("depthMs", static_cast<float>(depthMs_.load(std::memory_order_relaxed)));
482 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
483 w.write("feedback", static_cast<float>(feedback_.load(std::memory_order_relaxed)));
484 w.write("centerDelay", static_cast<float>(centerDelayMs_.load(std::memory_order_relaxed)));
485 w.write("spread", static_cast<float>(stereoSpread_.load(std::memory_order_relaxed)));
486 w.write("voices", numVoices_.load(std::memory_order_relaxed));
487 w.write("autoDepth", autoDepth_.load(std::memory_order_relaxed));
488 w.write("waveform",
489 static_cast<int32_t>(lfoWaveform_.load(std::memory_order_relaxed)));
490 w.write("interp", static_cast<int32_t>(interpolation_.load(std::memory_order_relaxed)));
491 w.write("model", static_cast<int32_t>(getModel()));
492 w.write("analogMode", analogMode_.load(std::memory_order_relaxed));
493 w.write("analogNoise", static_cast<float>(getAnalogNoise()));
494 w.write("analogTapPhase", static_cast<float>(getAnalogTapPhase()));
495 w.write("analogTone", static_cast<float>(getAnalogTone()));
496 w.write("analogCircuit", getAnalogCircuitFilters());
497 w.write("mixRule", static_cast<int32_t>(getMixRule()));
498 return w.blob();
499 }
500
502 bool setState(const uint8_t* data, size_t size)
503 {
504 StateReader r(data, size);
505 if (!r.isValid() || r.processorId() != stateId("CHOR")) return false;
506 setRate(static_cast<T>(r.read("rate", 1.0f)));
507 setDepthMs(static_cast<T>(r.read("depthMs", 3.5f)));
508 setMix(static_cast<T>(r.read("mix", 0.5f)));
509 setFeedback(static_cast<T>(r.read("feedback", 0.0f)));
510 setCenterDelay(static_cast<T>(r.read("centerDelay", 7.0f)));
511 setStereoSpread(static_cast<T>(r.read("spread", 0.5f)));
512 setVoices(r.read("voices", 2));
513 setAutoDepth(r.read("autoDepth", false));
514 setModWaveform(static_cast<typename Oscillator<T>::Waveform>(
515 r.read("waveform", 0)));
516 setInterpolation(static_cast<Interpolation>(r.read("interp", 0)));
517 setModel(r.read("model", 0) == 1 ? Model::Analog : Model::Digital);
518 // The preset index only (rate, depth and centre were read above).
519 analogMode_.store(std::clamp(static_cast<int>(r.read("analogMode", 0)), 0, 2), std::memory_order_relaxed);
520 setAnalogNoise(static_cast<T>(r.read("analogNoise", -84.0f)));
521 // A state without the offset takes the one of its preset.
522 setAnalogTapPhase(static_cast<T>(r.read("analogTapPhase", analogMode_.load(std::memory_order_relaxed) == 2 ? 0.0f : 180.0f)));
523 setAnalogTone(static_cast<T>(r.read("analogTone", 0.0f)));
524 setAnalogCircuitFilters(r.read("analogCircuit", false));
525 setMixRule(static_cast<typename DryWetMixer<T>::MixRule>(std::clamp(static_cast<int>(r.read("mixRule", 0)), 0, 2)));
526 return true;
527 }
528
529protected:
530
532 [[nodiscard]] T targetPhase(int ch, int v, int nv, T spread) const noexcept
533 {
534 // Spread spans half a cycle across the prepared channels: 1.0 puts the
535 // first and last channel 180 degrees apart (a stereo pair).
536 const int lastCh = std::max(1, std::min(spec_.numChannels, kMaxChannels) - 1);
537 const T chOffset = static_cast<T>(ch) * spread / (T(2) * static_cast<T>(lastCh));
538 const T phase = static_cast<T>(v) / static_cast<T>(std::max(1, nv)) + chOffset;
539 return phase - std::floor(phase);
540 }
541
546 void updateLfoPhases() noexcept
547 {
548 const int nv = numVoices_.load(std::memory_order_relaxed);
549 const T spreadVal = stereoSpread_.load(std::memory_order_relaxed);
550 lastSpread_ = spreadVal;
551 for (int ch = 0; ch < kMaxChannels; ++ch)
552 for (int v = 0; v < kMaxVoices; ++v)
553 lfos_[ch][v].setPhase(targetPhase(ch, v, nv, spreadVal));
554 }
555
558 {
559 static const SincInterpolator<T> table;
560 return table;
561 }
562
565 [[nodiscard]] T readSinc(const RingBuffer<T>& ring, T delay) const noexcept
566 {
567 const int dInt = static_cast<int>(delay);
568 const double dFrac = static_cast<double>(delay) - static_cast<double>(dInt);
569 const int64_t newest = static_cast<int64_t>(ring.getWritePosition()) - 1;
570 const int64_t intPos = newest - dInt - (dFrac > 0.0 ? 1 : 0);
571 return sinc_->readRing(ring.data(), static_cast<int64_t>(ring.getCapacity() - 1), intPos,
572 dFrac > 0.0 ? 1.0 - dFrac : 0.0);
573 }
574
576 [[nodiscard]] T readTap(const RingBuffer<T>& ring, T delay, Interpolation interp) const noexcept
577 {
578 if (interp == Interpolation::Sinc) return readSinc(ring, delay);
579 if (interp == Interpolation::Linear) return ring.template readInterpolated<InterpMethod::Linear>(delay);
580 return ring.readInterpolated(delay);
581 }
582
584 void processChunk(AudioBufferView<T> buffer) noexcept
585 {
586 // Clamp to the PREPARED channel count: delay lines beyond
587 // spec_.numChannels were never allocated and would read as silence.
588 const int nCh = std::min({ buffer.getNumChannels(), spec_.numChannels, kMaxChannels });
589 const int nS = buffer.getNumSamples();
590
591 const T mixVal = mix_.load(std::memory_order_relaxed);
592
593 mixer_.pushDry(buffer);
594 const Model wanted = model_.load(std::memory_order_relaxed);
595 if (!switching_ && wanted != playing_) startSwitch(wanted);
596 if (switching_) processSwitch(buffer, nCh, nS);
597 else runEngine(playing_, buffer, nCh, nS);
598 mixer_.mixWet(buffer, mixVal);
599 }
600
601 void runEngine(Model engine, AudioBufferView<T> buffer, int nCh, int nS) noexcept
602 {
603 if (engine == Model::Analog) processAnalog(buffer, nCh, nS);
604 else processDigital(buffer, nCh, nS);
605 }
606
608 void startSwitch(Model to) noexcept
609 {
610 switching_ = true;
611 incoming_ = to;
612 const double reach = static_cast<double>(centerDelayMs_.load(std::memory_order_relaxed) + depthMs_.load(std::memory_order_relaxed)) * 1e-3;
613 if (to == Model::Analog)
614 {
615 for (auto& b : bbd_) b.reset();
616 analogPrimed_ = false;
617 analogCornerFor_ = -1.0;
618 hpX1_ = hpY1_ = 0.0;
619 for (auto& s : decimateState_) s = {};
620 engineOut_ = {};
621 engineLast_ = {};
622 noiseLp_ = {};
623 hissHpX_ = {};
624 hissHpY_ = {};
625 // The line, its filters and their settling.
626 fillLeft_ = static_cast<int>((reach + kSwitchSettleSeconds) * spec_.sampleRate);
627 }
628 else
629 {
630 for (int ch = 0; ch < kMaxChannels; ++ch) fbState_[ch] = T(0);
631 fillLeft_ = static_cast<int>(reach * spec_.sampleRate) + 4;
632 }
634 }
635
637 void processSwitch(AudioBufferView<T> buffer, int nCh, int nS) noexcept
638 {
639 auto incoming = switchBuffer_.toView().getSubView(0, nS);
640 for (int ch = 0; ch < nCh; ++ch) std::copy_n(buffer.getChannel(ch), nS, incoming.getChannel(ch));
641 runEngine(playing_, buffer, nCh, nS);
642 T* scratch[kMaxChannels] = {};
643 for (int ch = 0; ch < nCh; ++ch) scratch[ch] = incoming.getChannel(ch);
644 runEngine(incoming_, AudioBufferView<T>(scratch, nCh, nS), nCh, nS);
645 const int fill = fillLeft_, fade = fadeLeft_;
646 for (int ch = 0; ch < nCh; ++ch)
647 {
648 T* out = buffer.getChannel(ch);
649 const T* in = incoming.getChannel(ch);
650 int f = fill, g = fade;
651 for (int i = 0; i < nS; ++i)
652 {
653 if (f > 0) { --f; continue; }
654 if (g > 0) --g;
655 const T w = T(1) - static_cast<T>(g) / static_cast<T>(switchFade_);
656 out[i] += (in[i] - out[i]) * w;
657 }
658 }
659 const int filled = std::min(fillLeft_, nS);
660 fillLeft_ -= filled;
661 fadeLeft_ = std::max(0, fadeLeft_ - (nS - filled));
662 if (fillLeft_ == 0 && fadeLeft_ == 0)
663 {
665 switching_ = false;
666 }
667 }
668
670 void processDigital(AudioBufferView<T> buffer, int nCh, int nS) noexcept
671 {
672 T targetRate = rate_.load(std::memory_order_relaxed);
673 T targetDepth = depthMs_.load(std::memory_order_relaxed);
674 T targetCenter = centerDelayMs_.load(std::memory_order_relaxed);
675 T fbVal = feedback_.load(std::memory_order_relaxed);
676 int nVoices = numVoices_.load(std::memory_order_relaxed);
677 bool autoD = autoDepth_.load(std::memory_order_relaxed);
678 Interpolation interp = interpolation_.load(std::memory_order_relaxed);
679 if (interp == Interpolation::Sinc && !sinc_) interp = Interpolation::Hermite;
680
681 // Deferred LFO config on the AUDIO thread (setters only publish). A
682 // voice-count change needs no phase reset: the glide below moves the
683 // LFOs to the new layout.
684 (void)lfoPhaseDirty_.exchange(false, std::memory_order_acquire);
685 if (waveformDirty_.exchange(false, std::memory_order_acquire))
686 {
687 const auto wf = lfoWaveform_.load(std::memory_order_relaxed);
688 for (int ch = 0; ch < kMaxChannels; ++ch)
689 for (int v = 0; v < kMaxVoices; ++v)
690 lfos_[ch][v].setWaveform(wf);
691 }
692 const T spreadVal = stereoSpread_.load(std::memory_order_relaxed);
693 lastSpread_ = spreadVal;
694
695 // Target calculations
696 T targetCenterSamples = targetCenter * static_cast<T>(spec_.sampleRate) / T(1000);
697 T targetDepthSamples = targetDepth * static_cast<T>(spec_.sampleRate) / T(1000);
698
699 if (autoD && targetRate > T(0.01))
700 targetDepthSamples /= std::sqrt(targetRate);
701
702 // Keep depth <= center - 2 samples: a deeper sweep would flatten
703 // against the 1-sample read floor, squaring off the modulation shape.
704 targetDepthSamples = std::min(targetDepthSamples,
705 std::max(T(0), targetCenterSamples - T(2)));
706
707 // Voices: a voice joining starts silent on its target phase; a voice
708 // leaving keeps running until its fade reaches zero.
709 std::array<T, kMaxVoices> gainStart {};
710 std::array<T, kMaxVoices> gainTarget {};
711 int nRun = 0;
712 bool fading = false;
713 for (int v = 0; v < kMaxVoices; ++v)
714 {
715 const size_t vi = static_cast<size_t>(v);
716 gainTarget[vi] = v < nVoices ? T(1) : T(0);
717 gainStart[vi] = voiceGain_[vi];
718 if (gainStart[vi] == T(0) && gainTarget[vi] > T(0))
719 for (int ch = 0; ch < kMaxChannels; ++ch)
720 lfos_[ch][v].setPhase(T(lfos_[0][0].getPhase()) + targetPhase(ch, v, nVoices, spreadVal));
721 if (gainStart[vi] > T(0) || gainTarget[vi] > T(0)) nRun = v + 1;
722 fading = fading || gainStart[vi] != gainTarget[vi];
723 }
724 const T voiceNorm = T(1) / std::sqrt(static_cast<T>(nVoices));
725
726 // Update LFO frequencies. Channel 0 / voice 0 is the phase reference;
727 // every other LFO that sits off its target phase runs slightly faster
728 // or slower until it arrives (a continuous phase glide: no jump in the
729 // delay time, so no click). The offset is bounded to half a cycle per
730 // second and never overshoots within one block.
731 const T blockSeconds = static_cast<T>(nS) / static_cast<T>(spec_.sampleRate);
732 const T glideTime = std::max(T(0.1), blockSeconds);
733 const T refPhase = lfos_[0][0].getPhase();
734 for (int ch = 0; ch < nCh; ++ch)
735 for (int v = 0; v < nRun; ++v)
736 {
737 T freq = targetRate;
738 if (ch != 0 || v != 0)
739 {
740 T err = targetPhase(ch, v, nVoices, spreadVal)
741 - (lfos_[ch][v].getPhase() - refPhase);
742 err -= std::floor(err + T(0.5)); // signed, in [-0.5, 0.5)
743 if (std::abs(err) > T(1e-5)) // settled LFOs run untouched
744 freq += std::clamp(err / glideTime, -kMaxGlideHz, kMaxGlideHz);
745 }
746 lfos_[ch][v].setFrequency(freq);
747 }
748
749 // One-pole smoothing coefficient, sample-rate invariant: 240/fs gives
750 // the same ~4.2 ms time constant at any rate (and is bit-identical to
751 // the historical 0.005 at 48 kHz; the old fixed value made parameter
752 // glides twice as fast at 96 kHz as at 48 kHz).
753 T smoothCoeff = std::min(T(1), T(240) / static_cast<T>(spec_.sampleRate));
754 const T minDelay = interp == Interpolation::Sinc ? T(SincInterpolator<T>::kAfter) : T(1);
755
756 // 2. Channel outer, sample inner (cache-friendly per-channel state)
757 for (int ch = 0; ch < nCh; ++ch)
758 {
759 auto* channelData = buffer.getChannel(ch);
760 auto& ring = delayLines_[ch];
761
762 // Local channel copies of the smoothing state (kept in registers)
763 T centerSamples = smoothedCenterSamples_;
764 T depthSamples = smoothedDepthSamples_;
765
766 for (int i = 0; i < nS; ++i)
767 {
768 // Smooth parameters per sample
769 centerSamples += (targetCenterSamples - centerSamples) * smoothCoeff;
770 depthSamples += (targetDepthSamples - depthSamples) * smoothCoeff;
771
772 T input = channelData[i];
773
774 // Saturating analog-style feedback to prevent harsh digital
775 // clipping. fastTanh is internally clamped; at typical levels
776 // |argument| < 1, where its error is < 0.05%.
777 T feedbackSig = fastTanh(fbState_[ch] * fbVal);
778 ring.push(input + feedbackSig);
779
780 T wetRaw = T(0);
781
782 if (!fading)
783 {
784 // Voice accumulation (steady voice count)
785 for (int v = 0; v < nVoices; ++v)
786 {
787 T lfoVal = lfos_[ch][v].getNextSample();
788 T rawDelay = centerSamples + lfoVal * depthSamples;
789
790 // Safety clamp against ring buffer limits
791 T delay = std::clamp(rawDelay, minDelay, static_cast<T>(maxDelaySamples_ - 2));
792 wetRaw += readTap(ring, delay, interp);
793 }
794 fbState_[ch] = wetRaw / static_cast<T>(nVoices);
795 channelData[i] = wetRaw * voiceNorm;
796 continue;
797 }
798
799 T gainSum = T(0);
800 T powerSum = T(0);
801
802 // Voice accumulation while voices fade in or out
803 for (int v = 0; v < nRun; ++v)
804 {
805 const size_t vi = static_cast<size_t>(v);
806 const T g = moveTowards(gainStart[vi], gainTarget[vi],
807 voiceFadeStep_ * static_cast<T>(i + 1));
808 T lfoVal = lfos_[ch][v].getNextSample();
809 T rawDelay = centerSamples + lfoVal * depthSamples;
810
811 // Safety clamp against ring buffer limits
812 T delay = std::clamp(rawDelay, minDelay, static_cast<T>(maxDelaySamples_ - 2));
813
814 const T tap = readTap(ring, delay, interp);
815 wetRaw += g == T(1) ? tap : g * tap;
816 gainSum += g;
817 powerSum += g * g;
818 }
819
820 // Equal-power sum, normalised by the voices actually sounding
821 // (1/sqrt(N) once every fade is complete).
822 fbState_[ch] = wetRaw / std::max(gainSum, T(1e-6));
823 channelData[i] = wetRaw / std::sqrt(std::max(powerSum, T(1e-12)));
824 }
825
826 // Save state back for the next block (only done by channel 0 to keep channels synced)
827 if (ch == 0)
828 {
829 smoothedCenterSamples_ = centerSamples;
830 smoothedDepthSamples_ = depthSamples;
831 }
832 }
833
834 for (int v = 0; v < kMaxVoices; ++v)
835 {
836 const size_t vi = static_cast<size_t>(v);
837 voiceGain_[vi] = moveTowards(gainStart[vi], gainTarget[vi],
838 voiceFadeStep_ * static_cast<T>(nS));
839 }
840 }
841
842 [[nodiscard]] static T moveTowards(T from, T to, T delta) noexcept
843 {
844 return from < to ? std::min(to, from + delta) : std::max(to, from - delta);
845 }
846
864 void processAnalog(AudioBufferView<T> buffer, int nCh, int nS) noexcept
865 {
866 const double rate = static_cast<double>(rate_.load(std::memory_order_relaxed));
867 const double centreSet = static_cast<double>(centerDelayMs_.load(std::memory_order_relaxed)) * 1e-3;
868 const double depthSet = std::min(static_cast<double>(depthMs_.load(std::memory_order_relaxed)) * 1e-3, 0.9 * centreSet);
869 const double offsetSet = static_cast<double>(analogTapPhase_.load(std::memory_order_relaxed)) / 360.0;
870 if (!analogPrimed_)
871 {
872 centreFrom_ = centreNow_ = centreSet;
873 depthFrom_ = depthNow_ = depthSet;
874 offsetNow_ = offsetSet;
875 analogPrimed_ = true;
876 }
877 // The filters sit at their fixed corners, lower only when the slowest
878 // clock the sweep needs (where it is or where it is going, whichever
879 // is longer) would leave the input filter too high for it.
880 // The corner moves at most an octave in a quarter of a second: a jump
881 // of the filters' coefficients would leave a step in their output.
882 const double reach = std::max(centreNow_ + std::min(depthNow_, 0.9 * centreNow_), centreSet + depthSet);
883 double slowest = reach > 0.0 ? static_cast<double>(kAnalogStages) / (2.0 * reach) : 1e5;
884 if (analogCornerFor_ > 0.0)
885 {
886 const double most = std::exp2(static_cast<double>(nS) / (kCornerOctaveSeconds * spec_.sampleRate));
887 slowest = std::clamp(slowest, analogCornerFor_ / most, analogCornerFor_ * most);
888 }
889 const double tone = static_cast<double>(analogTone_.load(std::memory_order_relaxed));
890 if (std::abs(slowest - analogCornerFor_) > 1e-3 * slowest || tone != analogToneFor_
891 || analogCircuit_.load(std::memory_order_relaxed) != circuitFor_)
892 {
893 const bool circuit = analogCircuit_.load(std::memory_order_relaxed);
894 if (circuit != circuitFor_)
895 {
896 for (auto& b : bbd_) b.setShape(circuit ? BucketBrigade<T>::Shape::Chorus : BucketBrigade<T>::Shape::Butterworth);
897 circuitFor_ = circuit;
898 }
899 const double inputHz = circuit ? kCircuitInputHz : kAnalogCornerHz;
900 const double outputHz = circuit ? kCircuitOutputHz : kAnalogCornerHz;
901 const double input = std::min(inputHz, (circuit ? kCircuitClockShare : kAnalogClockShare) * slowest);
902 const double output = input * (outputHz / inputHz) * std::exp2(tone);
903 for (auto& b : bbd_) b.setCorners(input, output);
904 const double heard = bbd_[0].getOutputCorner();
905 noiseCoeff_ = 1.0 - std::exp(-2.0 * 3.141592653589793 * std::min(heard, 0.45 * engineRate_) / engineRate_);
906 analogCornerFor_ = slowest;
907 analogToneFor_ = tone;
908 }
909 const T noiseDb = analogNoiseDb_.load(std::memory_order_relaxed);
910 // White noise through a one-pole at the corner, scaled by that
911 // filter's own gain: the same level (and density) at any rate.
912 const double noiseAmp = noiseDb > T(-120)
913 ? std::pow(10.0, static_cast<double>(noiseDb) / 20.0)
914 * 1.7320508075688772 / std::sqrt(std::max(1e-9, noiseCoeff_ / (2.0 - noiseCoeff_)))
915 : 0.0;
916 const double step = rate / engineRate_;
917 const auto triangle = [](double p) noexcept {
918 p -= std::floor(p);
919 return p < 0.5 ? 4.0 * p - 1.0 : 3.0 - 4.0 * p;
920 };
921 const auto glide = [this](double& now, double goal) noexcept {
922 now += analogGlide_ * (goal - now);
923 if (std::abs(goal - now) < 1e-12) now = goal;
924 };
925 const double perSample = 1.0 / static_cast<double>(std::max(1, nS));
926 const int channels = std::max(1, nCh);
927 for (int i = 0; i < nS; ++i)
928 {
929 double mono = 0.0;
930 for (int ch = 0; ch < nCh; ++ch) mono += static_cast<double>(buffer.getChannel(ch)[i]);
931 mono /= channels;
932 const double hp = mono - hpX1_ + hpCoeff_ * hpY1_;
933 hpX1_ = mono;
934 hpY1_ = hp;
935 double x = hp;
936 bool run = true;
937 if (halfRate_)
938 {
939 for (size_t k = 0; k < 2; ++k)
940 {
941 auto& s = decimateState_[k];
942 const auto& c = decimate_[k];
943 const double y = c.b0 * x + s[0];
944 s[0] = c.b1 * x - c.a1 * y + s[1];
945 s[1] = c.b2 * x - c.a2 * y;
946 x = y;
947 }
948 decimatePhase_ ^= 1;
949 run = decimatePhase_ == 1;
950 }
951 if (run)
952 {
953 const double u = static_cast<double>(i + 1) * perSample;
954 glide(centreNow_, centreFrom_ + u * (centreSet - centreFrom_));
955 glide(depthNow_, depthFrom_ + u * (depthSet - depthFrom_));
956 glide(offsetNow_, offsetSet);
957 advanceAnalogPhase(step);
958 const double centre = centreNow_;
959 const double depth = std::min(depthNow_, 0.9 * centre);
960 const double d[2] = { centre + depth * triangle(analogPhase_),
961 centre + depth * triangle(analogPhase_ + offsetNow_) };
962 double y[2];
963 bbd_[0].processPair(bbd_[1], static_cast<T>(x), d[0], d[1], y[0], y[1]);
964 for (size_t k = 0; k < 2; ++k)
965 {
966 if (noiseAmp > 0.0)
967 {
968 noiseRng_ = noiseRng_ * 1664525u + 1013904223u;
969 const double n = static_cast<double>(noiseRng_ >> 8) / 8388608.0 - 1.0;
970 // A hiss without lows: a high-pass, then the low-pass at the corner.
971 const double hissHp = hissHpCoeff_ * (hissHpY_[k] + n - hissHpX_[k]);
972 hissHpX_[k] = n;
973 hissHpY_[k] = hissHp;
974 noiseLp_[k] += noiseCoeff_ * (hissHp - noiseLp_[k]);
975 y[k] += noiseAmp * (d[k] / std::max(centre, 1e-4)) * noiseLp_[k];
976 }
977 engineLast_[k] = engineOut_[k];
978 engineOut_[k] = y[k];
979 }
980 }
981 for (int ch = 0; ch < nCh; ++ch)
982 {
983 const size_t k = static_cast<size_t>(ch & 1);
984 const double out = (halfRate_ && run) ? 0.5 * (engineOut_[k] + engineLast_[k]) : engineOut_[k];
985 buffer.getChannel(ch)[i] = static_cast<T>(out);
986 }
987 }
988 centreFrom_ = centreSet;
989 depthFrom_ = depthSet;
990 }
991
998 void advanceAnalogPhase(double step) noexcept
999 {
1000 double t = step;
1001 for (int edge = 0; edge < 4 && t > 0.0; ++edge)
1002 {
1003 const bool rising = analogPhase_ < 0.5;
1004 const double speed = rising ? 0.5 / kRise : 0.5 / (1.0 - kRise);
1005 const double need = ((rising ? 0.5 : 1.0) - analogPhase_) / speed;
1006 if (t < need)
1007 {
1008 analogPhase_ += t * speed;
1009 return;
1010 }
1011 t -= need;
1012 analogPhase_ = rising ? 0.5 : 0.0;
1013 }
1014 }
1015
1016 static constexpr int kAnalogStages = 512;
1017 static constexpr double kRise = 0.53;
1018 static constexpr double kAnalogGlideSeconds = 0.05;
1019 static constexpr double kCornerOctaveSeconds = 0.25;
1020 static constexpr double kAnalogCornerHz = 7000.0;
1021 static constexpr double kAnalogClockShare = 0.2;
1022 static constexpr double kCircuitInputHz = 8000.0;
1023 static constexpr double kCircuitOutputHz = 5600.0;
1024 static constexpr double kCircuitClockShare = 0.23;
1025 static constexpr double kHissHighPassHz = 200.0;
1026 static constexpr double kSwitchFadeSeconds = 0.01;
1027 static constexpr double kSwitchSettleSeconds = 0.003;
1028
1029 static constexpr T kMaxGlideHz = T(0.5);
1030
1033
1034 // Atomic parameters (updated via UI thread)
1035 std::atomic<T> rate_ { T(1) };
1036 std::atomic<T> depthMs_ { T(3.5) };
1037 std::atomic<T> mix_ { T(0.5) };
1038 std::atomic<T> feedback_ { T(0) };
1039 std::atomic<T> centerDelayMs_ { T(7) };
1040 std::atomic<T> stereoSpread_ { T(0.5) };
1041 std::atomic<int> numVoices_ { 2 };
1042 std::atomic<bool> autoDepth_ { false };
1043
1044 T lastSpread_ { T(0.5) };
1045 std::atomic<typename Oscillator<T>::Waveform> lfoWaveform_ { Oscillator<T>::Waveform::Sine };
1046 std::atomic<bool> lfoPhaseDirty_ { false }; // voices changed -> recompute phases (audio thread)
1047 std::atomic<bool> waveformDirty_ { false }; // waveform changed -> reapply (audio thread)
1048
1049 // Smoothed internal state variables (Audio thread only)
1052
1053 // Processing arrays
1054 std::array<RingBuffer<T>, kMaxChannels> delayLines_ {};
1055 // 2D Array: Avoids dynamic phase calculations in the hot loop
1056 std::array<std::array<Oscillator<T>, kMaxVoices>, kMaxChannels> lfos_ {};
1057 std::array<T, kMaxChannels> fbState_ {};
1058 std::array<T, kMaxVoices> voiceGain_ {};
1060 std::atomic<Interpolation> interpolation_ { Interpolation::Hermite };
1061 const SincInterpolator<T>* sinc_ = nullptr;
1062
1064
1065 // The analog model.
1066 std::atomic<Model> model_ { Model::Digital };
1067 std::atomic<int> analogMode_ { 0 };
1068 std::atomic<T> analogNoiseDb_ { T(-84) };
1069 std::atomic<T> analogTapPhase_ { T(180) };
1070 std::atomic<T> analogTone_ { T(0) };
1071 std::atomic<bool> analogCircuit_ { false };
1072 bool circuitFor_ = false;
1073 double analogToneFor_ = 0.0, hissHpCoeff_ = 0.0;
1074 std::array<double, 2> hissHpX_ {}, hissHpY_ {};
1075 // A change of engine.
1077 bool switching_ = false;
1078 int fillLeft_ = 0, fadeLeft_ = 0, switchFade_ = 480;
1080 std::array<BucketBrigade<T>, 2> bbd_ {};
1081 bool halfRate_ = false;
1082 double engineRate_ = 48000.0, analogCornerFor_ = -1.0, hpCoeff_ = 0.0, noiseCoeff_ = 0.0;
1083 double analogPhase_ = 0.0, hpX1_ = 0.0, hpY1_ = 0.0;
1084 double analogGlide_ = 1.0, centreNow_ = 0.0, depthNow_ = 0.0, offsetNow_ = 0.5;
1085 double centreFrom_ = 0.0, depthFrom_ = 0.0;
1086 bool analogPrimed_ = false;
1087 std::array<BiquadCoeffs, 2> decimate_ {};
1088 std::array<std::array<double, 2>, 2> decimateState_ {};
1089 std::array<double, 2> engineOut_ {}, engineLast_ {}, noiseLp_ {};
1091 uint32_t noiseRng_ = 0x6B43A9u;
1092};
1093
1094} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Owning audio buffer with contiguous, 32-byte aligned storage.
One bucket-brigade delay line (one channel).
Multi-voice chorus/flanger with true stereo spread and smooth parameter handling.
Definition Chorus.h:104
double centreNow_
Definition Chorus.h:1084
static constexpr int kAnalogStages
Stages of each analog line.
Definition Chorus.h:1016
static const SincInterpolator< T > & sincTable()
The shared sinc table (built on first use: prepare() calls it).
Definition Chorus.h:557
T readTap(const RingBuffer< T > &ring, T delay, Interpolation interp) const noexcept
One modulated read with the selected kernel.
Definition Chorus.h:576
void processAnalog(AudioBufferView< T > buffer, int nCh, int nS) noexcept
The analog model on one block: the mono sum, high-passed, into two bucket-brigade lines (sharing thei...
Definition Chorus.h:864
~Chorus()=default
void setModWaveform(typename Oscillator< T >::Waveform wf) noexcept
Sets the oscillator waveform for all voices.
Definition Chorus.h:371
std::atomic< int > analogMode_
Definition Chorus.h:1067
std::atomic< T > rate_
Definition Chorus.h:1035
static constexpr double kCircuitInputHz
The circuit pair: the input filter's corner.
Definition Chorus.h:1022
double analogToneFor_
Definition Chorus.h:1073
AnalogMode
Presets of the analog model (setAnalogMode()).
Definition Chorus.h:131
@ Fast
0.85 Hz, the same depth and centre.
@ Slow
0.5 Hz, 1.6 ms of depth about 5 ms, taps in opposition.
T smoothedCenterSamples_
Definition Chorus.h:1050
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition Chorus.h:475
std::atomic< bool > autoDepth_
Definition Chorus.h:1042
void setAnalogNoise(T dB) noexcept
Hiss of the analog lines: its RMS level in dBFS at the centre delay (it grows in proportion to the de...
Definition Chorus.h:427
bool switching_
Definition Chorus.h:1077
void setMix(T dryWet) noexcept
Sets the wet/dry mix ratio.
Definition Chorus.h:312
void setModel(Model m) noexcept
Selects the engine (see Model). Thread-safe; the change fills the incoming engine,...
Definition Chorus.h:384
double noiseCoeff_
Definition Chorus.h:1082
std::atomic< typename Oscillator< T >::Waveform > lfoWaveform_
Definition Chorus.h:1045
void advanceAnalogPhase(double step) noexcept
Moves the sweep's phase by step periods of time: the phase runs at 0.5 / kRise per period on its risi...
Definition Chorus.h:998
static T moveTowards(T from, T to, T delta) noexcept
Definition Chorus.h:842
std::atomic< int > numVoices_
Definition Chorus.h:1041
static constexpr double kCircuitClockShare
The circuit pair's input corner at most this share of the slowest clock.
Definition Chorus.h:1024
double analogGlide_
Definition Chorus.h:1084
std::array< double, 2 > engineLast_
Definition Chorus.h:1089
double hpX1_
Definition Chorus.h:1083
T getAnalogNoise() const noexcept
Definition Chorus.h:432
std::atomic< T > depthMs_
Definition Chorus.h:1036
std::array< BiquadCoeffs, 2 > decimate_
Definition Chorus.h:1087
void setAnalogTapPhase(T degrees) noexcept
The offset between the analog model's two taps, 0 to 180 degrees of the sweep (180 in opposition,...
Definition Chorus.h:440
std::atomic< T > mix_
Definition Chorus.h:1037
std::atomic< Interpolation > interpolation_
Definition Chorus.h:1060
void processDigital(AudioBufferView< T > buffer, int nCh, int nS) noexcept
The digital engine on one block (wet only).
Definition Chorus.h:670
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio block in-place.
Definition Chorus.h:217
int maxDelaySamples_
Definition Chorus.h:1032
std::array< RingBuffer< T >, kMaxChannels > delayLines_
Definition Chorus.h:1054
void setStereoSpread(T amount) noexcept
Sets the stereo spread amount.
Definition Chorus.h:353
double engineRate_
Definition Chorus.h:1082
void processSwitch(AudioBufferView< T > buffer, int nCh, int nS) noexcept
A block of a change of engine: both run; the incoming one is heard once its line is full.
Definition Chorus.h:637
bool circuitFor_
Definition Chorus.h:1072
std::atomic< T > analogTapPhase_
Definition Chorus.h:1069
std::atomic< bool > waveformDirty_
Definition Chorus.h:1047
AudioSpec spec_
Definition Chorus.h:1031
T getAnalogTapPhase() const noexcept
Definition Chorus.h:445
void reset() noexcept
Resets delay lines and LFO phases.
Definition Chorus.h:244
void setInterpolation(Interpolation mode) noexcept
Selects the fractional read kernel. Thread-safe; an out-of-range value reads as Hermite.
Definition Chorus.h:273
double depthNow_
Definition Chorus.h:1084
std::array< T, kMaxVoices > voiceGain_
Voice fades (audio thread).
Definition Chorus.h:1058
static constexpr double kCornerOctaveSeconds
The analog filters' corner moves an octave in this time at most.
Definition Chorus.h:1019
T getRate() const noexcept
Definition Chorus.h:392
void setVoices(int count) noexcept
Sets the number of active voices per channel.
Definition Chorus.h:322
void setAnalogMode(AnalogMode mode) noexcept
Loads a preset of the analog model: rate, depth and centre (through their setters) and whether the ta...
Definition Chorus.h:406
std::atomic< T > analogTone_
Definition Chorus.h:1070
T getDepthMs() const noexcept
Definition Chorus.h:394
Model
The engine (setModel()).
Definition Chorus.h:124
@ Digital
Delay lines read by interpolation, voices and feedback (default).
@ Analog
Two bucket-brigade lines on the mono sum (see the file notes).
void setCenterDelay(T ms) noexcept
Sets the base delay time.
Definition Chorus.h:343
void runEngine(Model engine, AudioBufferView< T > buffer, int nCh, int nS) noexcept
Definition Chorus.h:601
std::array< T, kMaxChannels > fbState_
Definition Chorus.h:1057
std::atomic< bool > analogCircuit_
Definition Chorus.h:1071
std::array< std::array< Oscillator< T >, kMaxVoices >, kMaxChannels > lfos_
Definition Chorus.h:1056
double depthFrom_
Definition Chorus.h:1085
Interpolation
Fractional read kernel of the modulated delay lines.
Definition Chorus.h:113
@ Hermite
4-point cubic (default).
static constexpr T kMaxGlideHz
Phase glide: half a cycle per second.
Definition Chorus.h:1029
T targetPhase(int ch, int v, int nv, T spread) const noexcept
Phase offset of a channel/voice LFO from channel 0, voice 0.
Definition Chorus.h:532
Model playing_
Definition Chorus.h:1076
std::atomic< Model > model_
Definition Chorus.h:1066
Model getModel() const noexcept
Definition Chorus.h:389
static constexpr int kMaxVoices
Definition Chorus.h:108
std::atomic< T > stereoSpread_
Definition Chorus.h:1040
std::array< BucketBrigade< T >, 2 > bbd_
Definition Chorus.h:1080
DryWetMixer< T >::MixRule getMixRule() const noexcept
Definition Chorus.h:472
double centreFrom_
Definition Chorus.h:1085
static constexpr double kCircuitOutputHz
The circuit pair: the output filter's corner (tone 0).
Definition Chorus.h:1023
static constexpr double kRise
The sweep's rising share of its period.
Definition Chorus.h:1017
void setAnalogTone(T tone) noexcept
The tone of the analog wet, -1 to 1: the corner of the filter after the lines moves by up to an octav...
Definition Chorus.h:453
DryWetMixer< T > mixer_
Definition Chorus.h:1063
void setMixRule(typename DryWetMixer< T >::MixRule rule) noexcept
The rule of the dry/wet mix (Linear by default; see DryWetMixer::MixRule). Thread-safe.
Definition Chorus.h:470
static constexpr double kAnalogGlideSeconds
Glide of the analog centre, depth and offset.
Definition Chorus.h:1018
static constexpr double kSwitchSettleSeconds
The analog line's filters settle in this after it fills.
Definition Chorus.h:1027
void startSwitch(Model to) noexcept
Starts a change of engine: the incoming one from silence, unheard until its line is full.
Definition Chorus.h:608
void setAnalogCircuitFilters(bool on) noexcept
The analog lines with the filter pair of a chorus circuit (see the file notes) instead of the Butterw...
Definition Chorus.h:465
Model incoming_
Definition Chorus.h:1076
void setFeedback(T amount) noexcept
Sets the feedback gain.
Definition Chorus.h:333
void prepare(const AudioSpec &spec)
Prepares the chorus for processing, allocating delay lines.
Definition Chorus.h:147
T getCenterDelay() const noexcept
Definition Chorus.h:396
double hpY1_
Definition Chorus.h:1083
Interpolation getInterpolation() const noexcept
Returns the fractional read kernel.
Definition Chorus.h:280
AnalogMode getAnalogMode() const noexcept
Definition Chorus.h:419
double analogPhase_
Definition Chorus.h:1083
std::atomic< T > centerDelayMs_
Definition Chorus.h:1039
void processChunk(AudioBufferView< T > buffer) noexcept
One block of at most the prepared size.
Definition Chorus.h:584
double analogCornerFor_
Definition Chorus.h:1082
bool getAnalogCircuitFilters() const noexcept
Definition Chorus.h:467
T readSinc(const RingBuffer< T > &ring, T delay) const noexcept
Sinc read delay samples behind the newest sample of ring (the RingBuffer::read() convention; needs de...
Definition Chorus.h:565
void setDepthMs(T ms) noexcept
Sets the LFO modulation depth in milliseconds.
Definition Chorus.h:301
int decimatePhase_
Definition Chorus.h:1090
static constexpr double kAnalogCornerHz
The analog filters' corner (tone 0).
Definition Chorus.h:1020
std::array< double, 2 > hissHpY_
Definition Chorus.h:1074
std::atomic< bool > lfoPhaseDirty_
Definition Chorus.h:1046
static constexpr int kMaxChannels
Definition Chorus.h:109
uint32_t noiseRng_
Definition Chorus.h:1091
double hpCoeff_
Definition Chorus.h:1082
void setRate(T hz) noexcept
Sets the LFO modulation rate.
Definition Chorus.h:291
std::array< double, 2 > hissHpX_
Definition Chorus.h:1074
const SincInterpolator< T > * sinc_
Set by prepare().
Definition Chorus.h:1061
static constexpr double kHissHighPassHz
The hiss has no lows under this.
Definition Chorus.h:1025
bool analogPrimed_
Definition Chorus.h:1086
std::array< std::array< double, 2 >, 2 > decimateState_
Definition Chorus.h:1088
void updateLfoPhases() noexcept
Sets every LFO phase to its target outright (prepare and reset; while running, the LFOs glide instead...
Definition Chorus.h:546
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition Chorus.h:502
std::atomic< T > analogNoiseDb_
Definition Chorus.h:1068
double hissHpCoeff_
Definition Chorus.h:1073
T getAnalogTone() const noexcept
Definition Chorus.h:458
std::array< double, 2 > noiseLp_
Definition Chorus.h:1089
void setAutoDepth(bool enabled) noexcept
Couples depth to rate automatically to prevent pitch artifacts at high speeds.
Definition Chorus.h:363
double offsetNow_
Definition Chorus.h:1084
static constexpr double kAnalogClockShare
The corner at most this share of the slowest clock.
Definition Chorus.h:1021
T smoothedDepthSamples_
Definition Chorus.h:1051
std::array< double, 2 > engineOut_
Definition Chorus.h:1089
static constexpr double kSwitchFadeSeconds
A change of engine crosses over in this.
Definition Chorus.h:1026
std::atomic< T > feedback_
Definition Chorus.h:1038
AudioBuffer< T > switchBuffer_
Definition Chorus.h:1079
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
Definition DryWetMixer.h:83
MixRule
Defines the mathematical curve used for mixing.
Definition DryWetMixer.h:86
Band-limited oscillator featuring PolyBLEP anti-aliasing and analog-modeled integration.
Definition Oscillator.h:90
Power-of-two circular buffer with compile-time interpolated read access.
Definition RingBuffer.h:64
32-tap Kaiser-windowed sinc reader for transparent fractional reads.
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
Professional-grade pitch vibrato with LFO FM and parameter smoothing.
Definition Vibrato.h:80
Main namespace for the DSPark framework.
T fastTanh(T x) noexcept
Fast tanh approximation using a Pade [5,4] rational function.
Definition DspMath.h:169
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
static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Low-pass filter.
Definition Biquad.h:119