DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Phaser.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
39#include "../Core/Oscillator.h"
40#include "../Core/DryWetMixer.h"
41#include "../Core/AudioSpec.h"
42#include "../Core/AudioBuffer.h"
43#include "../Core/DenormalGuard.h"
44#include "../Core/DspMath.h" // fastExp, fastTan, fastTanh
45#include "../Core/StateBlob.h"
46
47#include <algorithm>
48#include <array>
49#include <atomic>
50#include <cmath>
51#include <cstddef>
52#include <cstdint>
53#include <numbers>
54#include <vector>
55
56namespace dspark {
57
67template <FloatType T>
68class Phaser
69{
70public:
71 ~Phaser() = default; // non-virtual: leaf class (no virtual dispatch)
72
73 static constexpr int kMaxStages = 12;
74
76 static constexpr double kSpreadGlideSeconds = 0.1;
77
78 // -- Lifecycle --------------------------------------------------------------
79
88 void prepare(const AudioSpec& spec)
89 {
90 if (!spec.isValid()) return; // release-safe: keep previous state
91
92 spec_ = spec;
93 mixer_.prepare(spec);
94
95 lfo_.prepare(spec.sampleRate);
96 // LFO duty: keep the waveforms inside [-1, 1] (no minBLEP overshoot).
98 lfo_.setFrequency(rate_.load(std::memory_order_relaxed));
99 lfo_.setWaveform(lfoWaveform_.load(std::memory_order_relaxed));
100
101 lfoR_.prepare(spec.sampleRate);
103 lfoR_.setFrequency(rate_.load(std::memory_order_relaxed));
104 lfoR_.setWaveform(lfoWaveform_.load(std::memory_order_relaxed));
105
106 // One-pole parameter smoothing at a 20 Hz corner (~8 ms time constant)
107 smoothCoef_ = T(1) - std::exp(static_cast<T>(-2.0 * std::numbers::pi * 20.0) / static_cast<T>(spec_.sampleRate));
108
109 prepared_ = true;
110 reset();
111 }
112
121 void processBlock(AudioBufferView<T> buffer) noexcept
122 {
123 if (!prepared_) return; // without prepare(), fsInv below would be 1/0 -> NaN chain
124 // The allpass chain's decaying tails reach denormals within seconds
125 // of silence: flush them in hardware for the whole callback.
126 DenormalGuard denormalGuard;
127 const int total = buffer.getNumSamples();
128 const int slice = std::max(1, spec_.maxBlockSize);
129 for (int offset = 0; offset < total; offset += slice)
130 processChunk(buffer.getSubView(offset, std::min(slice, total - offset)));
131 }
132
133protected:
135 void processChunk(AudioBufferView<T> buffer) noexcept
136 {
137
138 const int nCh = std::min(buffer.getNumChannels(), kMaxChannels);
139 const int nS = buffer.getNumSamples();
140
141 // Front-door non-finite guard: the allpass recursion (yPrev/xPrev)
142 // latches a NaN/Inf input permanently -- even with feedback
143 // off -- so a single glitch would silence the effect forever. Replace
144 // non-finite input with 0 before it reaches the dry snapshot or any
145 // allpass/feedback state. No-op on finite input (metrics byte-identical).
146 for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
147 {
148 T* d = buffer.getChannel(ch);
149 for (int i = 0; i < nS; ++i)
150 if (!std::isfinite(d[i])) d[i] = T(0);
151 }
152
153 // Target parameters loaded once per block
154 const T targetDepth = depth_.load(std::memory_order_relaxed);
155 const T targetMix = mix_.load(std::memory_order_relaxed);
156 const T targetFb = feedback_.load(std::memory_order_relaxed);
157 const int stagesVal = numStages_.load(std::memory_order_relaxed);
158 const T minF = minFreq_.load(std::memory_order_relaxed);
159 const T maxF = maxFreq_.load(std::memory_order_relaxed);
160 const T spreadVal = stereoSpread_.load(std::memory_order_relaxed);
161
162 // Apply LFO rate/waveform on the AUDIO thread (the setters only publish
163 // atomics) so the non-atomic Oscillator state is never written concurrently.
164 lfo_.setFrequency(rate_.load(std::memory_order_relaxed));
165 lfo_.setWaveform(lfoWaveform_.load(std::memory_order_relaxed));
166 lfoR_.setFrequency(rate_.load(std::memory_order_relaxed));
167 lfoR_.setWaveform(lfoWaveform_.load(std::memory_order_relaxed));
168
169 // A spread change moves the right-channel LFO's phase offset on the
170 // audio thread (Oscillator state is not thread-safe). The first block
171 // after prepare()/reset() starts on the spread; later changes glide
172 // the offset linearly over kSpreadGlideSeconds, sample by sample, so
173 // the right channel's allpass coefficients never step. (Re-phasing in
174 // one go stepped them: a second difference up to 455 times the
175 // effect's own on a 60 Hz tone.)
176 if (std::abs(spreadVal - lastSpread_) > T(0.0001))
177 {
178 spreadTarget_ = 0.5 * static_cast<double>(spreadVal);
179 if (lastSpread_ < T(0))
180 {
183 T ph = lfo_.getPhase() + static_cast<T>(spreadOffset_);
184 ph -= std::floor(ph);
185 lfoR_.setPhase(ph);
186 }
187 else
188 {
189 spreadGlideLeft_ = std::max(1, static_cast<int>(kSpreadGlideSeconds * spec_.sampleRate + 0.5));
191 }
192 lastSpread_ = spreadVal;
193 }
194 const bool useSpread = (spreadVal > T(0.0001) || spreadGlideLeft_ > 0 || spreadOffset_ > 0.0)
195 && (nCh >= 2);
196
197 // Stages activated by a live increase start from cleared state: their
198 // history is from whenever they were last active (arbitrarily old),
199 // and replaying it injects an unrelated step into the chain.
200 if (stagesVal > lastStages_)
201 for (int s = lastStages_; s < stagesVal; ++s)
202 {
203 stages_[s].xPrev.fill(T(0));
204 stages_[s].yPrev.fill(T(0));
205 }
206 lastStages_ = stagesVal;
207
208 mixer_.pushDry(buffer);
209
210 const T logMin = std::log(minF);
211 const T logMax = std::log(maxF);
212 const T fsInv = T(1) / static_cast<T>(spec_.sampleRate);
213 const T nyquist = static_cast<T>(spec_.sampleRate) * T(0.499);
214 constexpr T kPi = static_cast<T>(std::numbers::pi);
215
216 auto coeffFromLfo = [&](T lfoVal) noexcept -> T
217 {
218 T modAmount = (lfoVal + T(1)) * T(0.5) * currentDepth_;
219 T logFreq = logMin + modAmount * (logMax - logMin);
220 // Convert log-frequency back to linear Hz (fastExp, ~2x std::exp)
221 T cutoff = std::min(fastExp(logFreq), nyquist);
222 // Bilinear-transform coefficient: tan(pi * f / Fs). fastTan is safe:
223 // `cutoff` stays below Nyquist thanks to the clamp above.
224 T tanVal = fastTan(kPi * cutoff * fsInv);
225 return (tanVal - T(1)) / (tanVal + T(1));
226 };
227
228 for (int i = 0; i < nS; ++i)
229 {
230 // Parameter smoothing (1-pole lowpass) to prevent zipper noise
231 currentDepth_ += smoothCoef_ * (targetDepth - currentDepth_);
232 currentFb_ += smoothCoef_ * (targetFb - currentFb_);
233
234 if (spreadGlideLeft_ > 0)
235 {
236 // Lands exactly on the target on the glide's last sample.
238 double ph = static_cast<double>(lfo_.getPhase()) + spreadOffset_;
239 ph -= std::floor(ph);
240 lfoR_.setPhase(static_cast<T>(ph));
241 }
242
243 const T cL = coeffFromLfo(lfo_.getNextSample());
244 const T lfoRVal = lfoR_.getNextSample(); // keep phase advancing always
245 const T cR = useSpread ? coeffFromLfo(lfoRVal) : cL;
246
247 // Process active channels (odd channels follow the spread LFO)
248 for (int ch = 0; ch < nCh; ++ch)
249 {
250 const T c = (ch & 1) ? cR : cL;
251 T sample = buffer.getChannel(ch)[i];
252
253 // Analog-modeled feedback with soft clipping to prevent digital
254 // blowups. fastTanh is internally clamped; at typical levels
255 // the argument stays below 1, where its error is < 0.05%.
256 T fbSignal = fastTanh(fbState_[ch] * currentFb_);
257 sample += fbSignal;
258
259 // Series first-order allpass chain
260 for (int s = 0; s < stagesVal; ++s)
261 {
262 auto& st = stages_[s];
263 T y = c * sample + st.xPrev[ch] - c * st.yPrev[ch];
264 st.xPrev[ch] = sample;
265 st.yPrev[ch] = y;
266 sample = y;
267 }
268
269 fbState_[ch] = sample; // 1-sample delay for next iteration
270 buffer.getChannel(ch)[i] = sample;
271 }
272 }
273
274 // DryWetMixer smooths the mix parameter internally.
275 mixer_.mixWet(buffer, targetMix);
276 }
277
278public:
279
284 void reset() noexcept
285 {
286 for (auto& stage : stages_)
287 {
288 stage.xPrev.fill(T(0));
289 stage.yPrev.fill(T(0));
290 }
291 for (auto& fb : fbState_) fb = T(0);
292
293 currentDepth_ = depth_.load(std::memory_order_relaxed);
294 currentFb_ = feedback_.load(std::memory_order_relaxed);
295
296 lfo_.reset();
297 lfoR_.reset();
298 lastSpread_ = T(-1); // the next block starts on the spread (no glide)
299 spreadOffset_ = 0.0;
301 mixer_.reset();
302 }
303
304 // -- Level 1: Simple API ----------------------------------------------------
305
311 void setRate(T hz) noexcept
312 {
313 if (!std::isfinite(hz)) return;
314 rate_.store(std::clamp(hz, T(0.01), T(20)), std::memory_order_relaxed); // applied on the audio thread
315 }
316
322 void setDepth(T amount) noexcept
323 {
324 if (!std::isfinite(amount)) return;
325 depth_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
326 }
327
333 void setMix(T dryWet) noexcept
334 {
335 if (!std::isfinite(dryWet)) return;
336 mix_.store(std::clamp(dryWet, T(0), T(1)), std::memory_order_relaxed);
337 }
338
339 // -- Level 2: Intermediate API ----------------------------------------------
340
345 void setStages(int count) noexcept
346 {
347 numStages_.store(std::clamp(count, 1, kMaxStages), std::memory_order_relaxed);
348 }
349
355 void setFeedback(T amount) noexcept
356 {
357 if (!std::isfinite(amount)) return;
358 feedback_.store(std::clamp(amount, T(-0.99), T(0.99)), std::memory_order_relaxed);
359 }
360
374 void setStereoSpread(T amount) noexcept
375 {
376 if (!std::isfinite(amount)) return;
377 stereoSpread_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
378 }
379
390 void setCenterFrequency(T hz) noexcept
391 {
392 if (!std::isfinite(hz) || !(hz > T(0))) return;
393 T curMin = minFreq_.load(std::memory_order_relaxed);
394 T curMax = maxFreq_.load(std::memory_order_relaxed);
395 T halfRange = std::sqrt(curMax / (curMin > T(0) ? curMin : T(1)));
396
397 const T ceiling = (spec_.sampleRate > 0)
398 ? static_cast<T>(spec_.sampleRate) * T(0.499) : T(20000);
399 const T mn = std::clamp(hz / halfRange, T(20), ceiling - T(1));
400 minFreq_.store(mn, std::memory_order_relaxed);
401 maxFreq_.store(std::clamp(hz * halfRange, mn + T(1), ceiling),
402 std::memory_order_relaxed);
403 }
404
411 void setFrequencyRange(T minHz, T maxHz) noexcept
412 {
413 if (!std::isfinite(minHz) || !std::isfinite(maxHz)) return;
414 T mn = std::max(minHz, T(20));
415 minFreq_.store(mn, std::memory_order_relaxed);
416 maxFreq_.store(std::max(maxHz, mn + T(1)), std::memory_order_relaxed);
417 }
418
419 // -- Level 3: Expert API ----------------------------------------------------
420
425 void setLfoWaveform(typename Oscillator<T>::Waveform wf) noexcept
426 {
427 const int w = std::clamp(static_cast<int>(wf), 0,
428 static_cast<int>(Oscillator<T>::Waveform::Triangle));
429 lfoWaveform_.store(static_cast<typename Oscillator<T>::Waveform>(w),
430 std::memory_order_relaxed); // applied on the audio thread
431 }
432
434 [[nodiscard]] int getStages() const noexcept { return numStages_.load(std::memory_order_relaxed); }
435
437 [[nodiscard]] T getRate() const noexcept { return rate_.load(std::memory_order_relaxed); }
438
439
441 [[nodiscard]] std::vector<uint8_t> getState() const
442 {
443 // The blob stores float: the casts keep the double instantiation
444 // compiling (a double matches no StateWriter overload unambiguously).
445 StateWriter w(stateId("PHSR"), 1);
446 w.write("rate", static_cast<float>(rate_.load(std::memory_order_relaxed)));
447 w.write("depth", static_cast<float>(depth_.load(std::memory_order_relaxed)));
448 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
449 w.write("feedback", static_cast<float>(feedback_.load(std::memory_order_relaxed)));
450 w.write("minFreq", static_cast<float>(minFreq_.load(std::memory_order_relaxed)));
451 w.write("maxFreq", static_cast<float>(maxFreq_.load(std::memory_order_relaxed)));
452 w.write("stages", numStages_.load(std::memory_order_relaxed));
453 w.write("spread", static_cast<float>(stereoSpread_.load(std::memory_order_relaxed)));
454 w.write("waveform",
455 static_cast<int32_t>(lfoWaveform_.load(std::memory_order_relaxed)));
456 return w.blob();
457 }
458
460 bool setState(const uint8_t* data, size_t size)
461 {
462 StateReader r(data, size);
463 if (!r.isValid() || r.processorId() != stateId("PHSR")) return false;
464 setRate(static_cast<T>(r.read("rate", 0.5f)));
465 setDepth(static_cast<T>(r.read("depth", 0.8f)));
466 setMix(static_cast<T>(r.read("mix", 0.5f)));
467 setFeedback(static_cast<T>(r.read("feedback", 0.0f)));
468 setFrequencyRange(static_cast<T>(r.read("minFreq", 200.0f)),
469 static_cast<T>(r.read("maxFreq", 6000.0f)));
470 setStages(r.read("stages", 4));
471 setStereoSpread(static_cast<T>(r.read("spread", 0.0f)));
472 setLfoWaveform(static_cast<typename Oscillator<T>::Waveform>(
473 r.read("waveform", 0)));
474 return true;
475 }
476
477protected:
478 static constexpr int kMaxChannels = 16;
479
481
482 // Parameters
483 std::atomic<T> rate_ { T(0.5) };
484 std::atomic<T> depth_ { T(0.8) };
485 std::atomic<T> mix_ { T(0.5) };
486 std::atomic<T> feedback_ { T(0) };
487 std::atomic<T> minFreq_ { T(200) };
488 std::atomic<T> maxFreq_ { T(6000) };
489 std::atomic<int> numStages_ { 4 };
490 std::atomic<typename Oscillator<T>::Waveform> lfoWaveform_ { Oscillator<T>::Waveform::Sine };
491 std::atomic<T> stereoSpread_ { T(0) };
492
493 // Smoothed state parameters
494 bool prepared_ { false };
495 T currentDepth_ { T(0.8) };
496 T currentFb_ { T(0) };
497 T smoothCoef_ { T(0.01) };
498 T lastSpread_ { T(-1) };
499 double spreadOffset_ { 0.0 };
500 double spreadTarget_ { 0.0 };
501 double spreadStep_ { 0.0 };
503 int lastStages_ { kMaxStages }; // audio-thread: clears newly activated stages
504
506 {
507 std::array<T, kMaxChannels> xPrev {};
508 std::array<T, kMaxChannels> yPrev {};
509 };
510
511 // Processing state
512 std::array<FirstOrderAllpass, kMaxStages> stages_ {};
513 std::array<T, kMaxChannels> fbState_ {};
515 Oscillator<T> lfoR_; // right-channel LFO for stereo spread
517};
518
519} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
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
Band-limited oscillator featuring PolyBLEP anti-aliasing and analog-modeled integration.
Definition Oscillator.h:90
Zero-latency, highly optimized allpass-based phaser.
Definition Phaser.h:69
std::atomic< T > rate_
Definition Phaser.h:483
void setFeedback(T amount) noexcept
Injects phase-shifted signal back into the input for resonance.
Definition Phaser.h:355
std::atomic< int > numStages_
Definition Phaser.h:489
std::atomic< T > feedback_
Definition Phaser.h:486
std::atomic< T > mix_
Definition Phaser.h:485
void setMix(T dryWet) noexcept
Balances the unprocessed and processed signal.
Definition Phaser.h:333
int spreadGlideLeft_
Samples left in the glide (0 = settled).
Definition Phaser.h:502
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition Phaser.h:460
double spreadOffset_
Current right-LFO phase offset (cycles).
Definition Phaser.h:499
int lastStages_
Definition Phaser.h:503
~Phaser()=default
void processChunk(AudioBufferView< T > buffer) noexcept
One block of at most the prepared size.
Definition Phaser.h:135
int getStages() const noexcept
Retrieves the active stage count.
Definition Phaser.h:434
static constexpr int kMaxStages
Definition Phaser.h:73
void setDepth(T amount) noexcept
Sets how wide the frequency sweep is.
Definition Phaser.h:322
static constexpr double kSpreadGlideSeconds
Duration of the right-LFO phase glide after a spread change.
Definition Phaser.h:76
void setFrequencyRange(T minHz, T maxHz) noexcept
Explicitly defines the sweep boundaries.
Definition Phaser.h:411
void setCenterFrequency(T hz) noexcept
Defines the midpoint of the logarithmic frequency sweep.
Definition Phaser.h:390
void setStages(int count) noexcept
Configures the intensity/color of the phaser via filter stages.
Definition Phaser.h:345
void reset() noexcept
Clears internal DSP state and history buffers. Call this when transport stops or playback jumps.
Definition Phaser.h:284
void setStereoSpread(T amount) noexcept
Sets the stereo phase spread of the sweep LFO.
Definition Phaser.h:374
T getRate() const noexcept
Retrieves the current sweep rate.
Definition Phaser.h:437
std::atomic< T > stereoSpread_
Definition Phaser.h:491
std::array< FirstOrderAllpass, kMaxStages > stages_
Definition Phaser.h:512
std::atomic< T > maxFreq_
Definition Phaser.h:488
std::array< T, kMaxChannels > fbState_
Definition Phaser.h:513
std::atomic< typename Oscillator< T >::Waveform > lfoWaveform_
Definition Phaser.h:490
std::atomic< T > depth_
Definition Phaser.h:484
void prepare(const AudioSpec &spec)
Prepares the phaser and allocates internal state blocks.
Definition Phaser.h:88
Oscillator< T > lfoR_
Definition Phaser.h:515
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition Phaser.h:441
double spreadTarget_
Offset the glide lands on (cycles).
Definition Phaser.h:500
bool prepared_
Definition Phaser.h:494
Oscillator< T > lfo_
Definition Phaser.h:514
DryWetMixer< T > mixer_
Definition Phaser.h:516
std::atomic< T > minFreq_
Definition Phaser.h:487
void setRate(T hz) noexcept
Sets the speed of the phaser sweep.
Definition Phaser.h:311
void setLfoWaveform(typename Oscillator< T >::Waveform wf) noexcept
Changes the geometric shape of the LFO modulation.
Definition Phaser.h:425
double spreadStep_
Per-sample offset increment of the glide.
Definition Phaser.h:501
AudioSpec spec_
Definition Phaser.h:480
static constexpr int kMaxChannels
Definition Phaser.h:478
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio block in-place.
Definition Phaser.h:121
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 fastTan(T x) noexcept
Fast approximation of tan(x) using a Pade [5,4] rational approximant.
Definition DspMath.h:310
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
T fastExp(T x) noexcept
e^x via std::exp2, using the identity e^x = 2^(x * log2(e)).
Definition DspMath.h:220
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 maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
std::array< T, kMaxChannels > xPrev
Definition Phaser.h:507
std::array< T, kMaxChannels > yPrev
Definition Phaser.h:508