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"
102template <FloatType T>
187 const int lineFactor =
engineRate_ < 88200.0 ? 2 : 1;
199 static constexpr double kQ4[2] = { 0.5411961001461970, 1.3065629648763764 };
200 for (
int k = 0; k < 2; ++k)
227 const int nS = buffer.getNumSamples();
228 for (
int ch = 0; ch < buffer.getNumChannels(); ++ch)
230 T* d = buffer.getChannel(ch);
231 for (
int i = 0; i < nS; ++i)
232 if (!std::isfinite(d[i])) d[i] = T(0);
252 for (
auto& b :
bbd_) b.reset();
266 const int nv =
numVoices_.load(std::memory_order_relaxed);
268 voiceGain_[
static_cast<size_t>(v)] = v < nv ? T(1) : T(0);
276 std::memory_order_relaxed);
293 if (!std::isfinite(hz))
return;
294 rate_.store(std::clamp(hz, T(0.01), T(20)), std::memory_order_relaxed);
303 if (!std::isfinite(ms))
return;
304 depthMs_.store(std::clamp(ms, T(0), T(20)), std::memory_order_relaxed);
314 if (!std::isfinite(dryWet))
return;
315 mix_.store(std::clamp(dryWet, T(0), T(1)), std::memory_order_relaxed);
335 if (!std::isfinite(amount))
return;
336 feedback_.store(std::clamp(amount, T(-0.99), T(0.99)), std::memory_order_relaxed);
345 if (!std::isfinite(ms))
return;
346 centerDelayMs_.store(std::clamp(ms, T(0.1), T(30)), std::memory_order_relaxed);
355 if (!std::isfinite(amount))
return;
356 stereoSpread_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
375 const int w = std::clamp(
static_cast<int>(wf), 0,
378 std::memory_order_relaxed);
392 [[nodiscard]] T
getRate() const noexcept {
return rate_.load(std::memory_order_relaxed); }
408 const int m = std::clamp(
static_cast<int>(mode), 0, 2);
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]));
429 if (std::isfinite(dB))
analogNoiseDb_.store(std::clamp(dB, T(-200), T(-40)), std::memory_order_relaxed);
442 if (std::isfinite(degrees))
analogTapPhase_.store(std::clamp(degrees, T(0), T(180)), std::memory_order_relaxed);
455 if (std::isfinite(tone))
analogTone_.store(std::clamp(tone, T(-1), T(1)), std::memory_order_relaxed);
475 [[nodiscard]] std::vector<uint8_t>
getState()
const
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)));
489 static_cast<int32_t
>(
lfoWaveform_.load(std::memory_order_relaxed)));
515 r.
read(
"waveform", 0)));
519 analogMode_.store(std::clamp(
static_cast<int>(r.
read(
"analogMode", 0)), 0, 2), std::memory_order_relaxed);
532 [[nodiscard]] T
targetPhase(
int ch,
int v,
int nv, T spread)
const noexcept
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);
548 const int nv =
numVoices_.load(std::memory_order_relaxed);
549 const T spreadVal =
stereoSpread_.load(std::memory_order_relaxed);
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);
579 if (interp ==
Interpolation::Linear)
return ring.template readInterpolated<InterpMethod::Linear>(delay);
580 return ring.readInterpolated(delay);
589 const int nS = buffer.getNumSamples();
591 const T mixVal =
mix_.load(std::memory_order_relaxed);
594 const Model wanted =
model_.load(std::memory_order_relaxed);
598 mixer_.mixWet(buffer, mixVal);
612 const double reach =
static_cast<double>(
centerDelayMs_.load(std::memory_order_relaxed) +
depthMs_.load(std::memory_order_relaxed)) * 1e-3;
615 for (
auto& b :
bbd_) b.reset();
640 for (
int ch = 0; ch < nCh; ++ch) std::copy_n(buffer.getChannel(ch), nS, incoming.getChannel(ch));
643 for (
int ch = 0; ch < nCh; ++ch) scratch[ch] = incoming.getChannel(ch);
646 for (
int ch = 0; ch < nCh; ++ch)
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)
653 if (f > 0) { --f;
continue; }
655 const T w = T(1) -
static_cast<T
>(g) /
static_cast<T
>(
switchFade_);
656 out[i] += (in[i] - out[i]) * w;
659 const int filled = std::min(
fillLeft_, nS);
672 T targetRate =
rate_.load(std::memory_order_relaxed);
673 T targetDepth =
depthMs_.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);
687 const auto wf =
lfoWaveform_.load(std::memory_order_relaxed);
690 lfos_[ch][v].setWaveform(wf);
692 const T spreadVal =
stereoSpread_.load(std::memory_order_relaxed);
696 T targetCenterSamples = targetCenter *
static_cast<T
>(
spec_.
sampleRate) / T(1000);
697 T targetDepthSamples = targetDepth *
static_cast<T
>(
spec_.
sampleRate) / T(1000);
699 if (autoD && targetRate > T(0.01))
700 targetDepthSamples /= std::sqrt(targetRate);
704 targetDepthSamples = std::min(targetDepthSamples,
705 std::max(T(0), targetCenterSamples - T(2)));
709 std::array<T, kMaxVoices> gainStart {};
710 std::array<T, kMaxVoices> gainTarget {};
715 const size_t vi =
static_cast<size_t>(v);
716 gainTarget[vi] = v < nVoices ? T(1) : T(0);
718 if (gainStart[vi] == T(0) && gainTarget[vi] > T(0))
721 if (gainStart[vi] > T(0) || gainTarget[vi] > T(0)) nRun = v + 1;
722 fading = fading || gainStart[vi] != gainTarget[vi];
724 const T voiceNorm = T(1) / std::sqrt(
static_cast<T
>(nVoices));
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)
738 if (ch != 0 || v != 0)
741 - (
lfos_[ch][v].getPhase() - refPhase);
742 err -= std::floor(err + T(0.5));
743 if (std::abs(err) > T(1e-5))
746 lfos_[ch][v].setFrequency(freq);
753 T smoothCoeff = std::min(T(1), T(240) /
static_cast<T
>(
spec_.
sampleRate));
757 for (
int ch = 0; ch < nCh; ++ch)
759 auto* channelData = buffer.getChannel(ch);
766 for (
int i = 0; i < nS; ++i)
769 centerSamples += (targetCenterSamples - centerSamples) * smoothCoeff;
770 depthSamples += (targetDepthSamples - depthSamples) * smoothCoeff;
772 T input = channelData[i];
778 ring.push(input + feedbackSig);
785 for (
int v = 0; v < nVoices; ++v)
787 T lfoVal =
lfos_[ch][v].getNextSample();
788 T rawDelay = centerSamples + lfoVal * depthSamples;
791 T delay = std::clamp(rawDelay, minDelay,
static_cast<T
>(
maxDelaySamples_ - 2));
792 wetRaw +=
readTap(ring, delay, interp);
794 fbState_[ch] = wetRaw /
static_cast<T
>(nVoices);
795 channelData[i] = wetRaw * voiceNorm;
803 for (
int v = 0; v < nRun; ++v)
805 const size_t vi =
static_cast<size_t>(v);
806 const T g =
moveTowards(gainStart[vi], gainTarget[vi],
808 T lfoVal =
lfos_[ch][v].getNextSample();
809 T rawDelay = centerSamples + lfoVal * depthSamples;
812 T delay = std::clamp(rawDelay, minDelay,
static_cast<T
>(
maxDelaySamples_ - 2));
814 const T tap =
readTap(ring, delay, interp);
815 wetRaw += g == T(1) ? tap : g * tap;
822 fbState_[ch] = wetRaw / std::max(gainSum, T(1e-6));
823 channelData[i] = wetRaw / std::sqrt(std::max(powerSum, T(1e-12)));
836 const size_t vi =
static_cast<size_t>(v);
842 [[nodiscard]]
static T
moveTowards(T from, T to, T delta)
noexcept
844 return from < to ? std::min(to, from + delta) : std::max(to, from - delta);
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;
883 double slowest = reach > 0.0 ?
static_cast<double>(
kAnalogStages) / (2.0 * reach) : 1e5;
889 const double tone =
static_cast<double>(
analogTone_.load(std::memory_order_relaxed));
893 const bool circuit =
analogCircuit_.load(std::memory_order_relaxed);
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();
912 const double noiseAmp = noiseDb > T(-120)
913 ? std::pow(10.0,
static_cast<double>(noiseDb) / 20.0)
917 const auto triangle = [](
double p)
noexcept {
919 return p < 0.5 ? 4.0 * p - 1.0 : 3.0 - 4.0 * p;
921 const auto glide = [
this](
double& now,
double goal)
noexcept {
923 if (std::abs(goal - now) < 1e-12) now = goal;
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)
930 for (
int ch = 0; ch < nCh; ++ch) mono += static_cast<double>(buffer.getChannel(ch)[i]);
939 for (
size_t k = 0; k < 2; ++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;
953 const double u =
static_cast<double>(i + 1) * perSample;
959 const double depth = std::min(
depthNow_, 0.9 * centre);
960 const double d[2] = { centre + depth * triangle(
analogPhase_),
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)
969 const double n =
static_cast<double>(
noiseRng_ >> 8) / 8388608.0 - 1.0;
975 y[k] += noiseAmp * (d[k] / std::max(centre, 1e-4)) *
noiseLp_[k];
981 for (
int ch = 0; ch < nCh; ++ch)
983 const size_t k =
static_cast<size_t>(ch & 1);
985 buffer.getChannel(ch)[i] =
static_cast<T
>(out);
1001 for (
int edge = 0; edge < 4 && t > 0.0; ++edge)
1004 const double speed = rising ? 0.5 /
kRise : 0.5 / (1.0 -
kRise);
1005 const double need = ((rising ? 0.5 : 1.0) -
analogPhase_) / speed;
1080 std::array<BucketBrigade<T>, 2>
bbd_ {};
Non-owning view over audio channel data.
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.
static constexpr int kAnalogStages
Stages of each analog line.
static const SincInterpolator< T > & sincTable()
The shared sinc table (built on first use: prepare() calls it).
T readTap(const RingBuffer< T > &ring, T delay, Interpolation interp) const noexcept
One modulated read with the selected kernel.
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...
void setModWaveform(typename Oscillator< T >::Waveform wf) noexcept
Sets the oscillator waveform for all voices.
std::atomic< int > analogMode_
static constexpr double kCircuitInputHz
The circuit pair: the input filter's corner.
AnalogMode
Presets of the analog model (setAnalogMode()).
@ Fast
0.85 Hz, the same depth and centre.
@ Slow
0.5 Hz, 1.6 ms of depth about 5 ms, taps in opposition.
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
std::atomic< bool > autoDepth_
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...
void setMix(T dryWet) noexcept
Sets the wet/dry mix ratio.
void setModel(Model m) noexcept
Selects the engine (see Model). Thread-safe; the change fills the incoming engine,...
std::atomic< typename Oscillator< T >::Waveform > lfoWaveform_
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...
static T moveTowards(T from, T to, T delta) noexcept
std::atomic< int > numVoices_
static constexpr double kCircuitClockShare
The circuit pair's input corner at most this share of the slowest clock.
std::array< double, 2 > engineLast_
T getAnalogNoise() const noexcept
std::atomic< T > depthMs_
std::array< BiquadCoeffs, 2 > decimate_
void setAnalogTapPhase(T degrees) noexcept
The offset between the analog model's two taps, 0 to 180 degrees of the sweep (180 in opposition,...
std::atomic< Interpolation > interpolation_
void processDigital(AudioBufferView< T > buffer, int nCh, int nS) noexcept
The digital engine on one block (wet only).
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio block in-place.
std::array< RingBuffer< T >, kMaxChannels > delayLines_
void setStereoSpread(T amount) noexcept
Sets the stereo spread amount.
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.
std::atomic< T > analogTapPhase_
std::atomic< bool > waveformDirty_
T getAnalogTapPhase() const noexcept
void reset() noexcept
Resets delay lines and LFO phases.
void setInterpolation(Interpolation mode) noexcept
Selects the fractional read kernel. Thread-safe; an out-of-range value reads as Hermite.
std::array< T, kMaxVoices > voiceGain_
Voice fades (audio thread).
static constexpr double kCornerOctaveSeconds
The analog filters' corner moves an octave in this time at most.
T getRate() const noexcept
void setVoices(int count) noexcept
Sets the number of active voices per channel.
void setAnalogMode(AnalogMode mode) noexcept
Loads a preset of the analog model: rate, depth and centre (through their setters) and whether the ta...
std::atomic< T > analogTone_
T getDepthMs() const noexcept
Model
The engine (setModel()).
@ 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.
void runEngine(Model engine, AudioBufferView< T > buffer, int nCh, int nS) noexcept
std::array< T, kMaxChannels > fbState_
std::atomic< bool > analogCircuit_
std::array< std::array< Oscillator< T >, kMaxVoices >, kMaxChannels > lfos_
Interpolation
Fractional read kernel of the modulated delay lines.
@ Hermite
4-point cubic (default).
static constexpr T kMaxGlideHz
Phase glide: half a cycle per second.
T targetPhase(int ch, int v, int nv, T spread) const noexcept
Phase offset of a channel/voice LFO from channel 0, voice 0.
std::atomic< Model > model_
Model getModel() const noexcept
static constexpr int kMaxVoices
std::atomic< T > stereoSpread_
std::array< BucketBrigade< T >, 2 > bbd_
DryWetMixer< T >::MixRule getMixRule() const noexcept
static constexpr double kCircuitOutputHz
The circuit pair: the output filter's corner (tone 0).
static constexpr double kRise
The sweep's rising share of its period.
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...
void setMixRule(typename DryWetMixer< T >::MixRule rule) noexcept
The rule of the dry/wet mix (Linear by default; see DryWetMixer::MixRule). Thread-safe.
static constexpr double kAnalogGlideSeconds
Glide of the analog centre, depth and offset.
static constexpr double kSwitchSettleSeconds
The analog line's filters settle in this after it fills.
void startSwitch(Model to) noexcept
Starts a change of engine: the incoming one from silence, unheard until its line is full.
void setAnalogCircuitFilters(bool on) noexcept
The analog lines with the filter pair of a chorus circuit (see the file notes) instead of the Butterw...
void setFeedback(T amount) noexcept
Sets the feedback gain.
void prepare(const AudioSpec &spec)
Prepares the chorus for processing, allocating delay lines.
T getCenterDelay() const noexcept
Interpolation getInterpolation() const noexcept
Returns the fractional read kernel.
AnalogMode getAnalogMode() const noexcept
std::atomic< T > centerDelayMs_
void processChunk(AudioBufferView< T > buffer) noexcept
One block of at most the prepared size.
bool getAnalogCircuitFilters() const noexcept
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...
void setDepthMs(T ms) noexcept
Sets the LFO modulation depth in milliseconds.
static constexpr double kAnalogCornerHz
The analog filters' corner (tone 0).
std::array< double, 2 > hissHpY_
std::atomic< bool > lfoPhaseDirty_
static constexpr int kMaxChannels
void setRate(T hz) noexcept
Sets the LFO modulation rate.
std::array< double, 2 > hissHpX_
const SincInterpolator< T > * sinc_
Set by prepare().
static constexpr double kHissHighPassHz
The hiss has no lows under this.
std::array< std::array< double, 2 >, 2 > decimateState_
void updateLfoPhases() noexcept
Sets every LFO phase to its target outright (prepare and reset; while running, the LFOs glide instead...
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
std::atomic< T > analogNoiseDb_
T getAnalogTone() const noexcept
std::array< double, 2 > noiseLp_
void setAutoDepth(bool enabled) noexcept
Couples depth to rate automatically to prevent pitch artifacts at high speeds.
static constexpr double kAnalogClockShare
The corner at most this share of the slowest clock.
std::array< double, 2 > engineOut_
static constexpr double kSwitchFadeSeconds
A change of engine crosses over in this.
std::atomic< T > feedback_
AudioBuffer< T > switchBuffer_
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
MixRule
Defines the mathematical curve used for mixing.
Band-limited oscillator featuring PolyBLEP anti-aliasing and analog-modeled integration.
Power-of-two circular buffer with compile-time interpolated read access.
32-tap Kaiser-windowed sinc reader for transparent fractional reads.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
bool isValid() const noexcept
uint32_t processorId() const noexcept
Serializes key/value parameters into a versioned blob.
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
void write(const char *key, float value)
Writes a float parameter.
Professional-grade pitch vibrato with LFO FM and parameter smoothing.
Main namespace for the DSPark framework.
T fastTanh(T x) noexcept
Fast tanh approximation using a Pade [5,4] rational function.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Describes the audio environment for a DSP processor.
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
int maxBlockSize
Maximum number of samples per processing block.
double sampleRate
Sample rate in Hz.
static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Low-pass filter.