DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Vibrato.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
45#include "../Core/AudioBuffer.h"
46#include "../Core/AudioSpec.h"
47#include "../Core/BucketBrigade.h"
48#include "../Core/DspMath.h"
49#include "../Core/Interpolation.h"
50#include "../Core/Phasor.h"
51#include "../Core/RingBuffer.h"
52#include "../Core/StateBlob.h"
53
54#include <algorithm>
55#include <atomic>
56#include <cmath>
57#include <cstddef>
58#include <cstdint>
59#include <numbers>
60#include <vector>
61
62namespace dspark {
63
78template <FloatType T>
80{
81public:
83 enum class Interpolation
84 {
85 Hermite,
86 Sinc
89 };
90
92 enum class Model
93 {
94 Digital,
95 Analog
96 };
97
113 void prepare(const AudioSpec& spec)
114 {
115 if (!spec.isValid()) return; // release-safe: keep previous state
116
117 sampleRate_ = spec.sampleRate;
118 numChannels_ = spec.numChannels;
119
120 // Worst-case LFO deviation in samples: depth * ln2 / 12 converts
121 // semitones to a log-frequency ratio, and the peak pitch excursion of
122 // a sinusoidal delay d(n) = centre + D * sin(2*pi*f*n/fs) is
123 // D * 2*pi*f/fs, so D = depth * ln2 * fs / (2*pi * 12 * f). Computed
124 // in double and capped before the int cast (an absurd-but-finite
125 // sample rate must not overflow the conversion; the ring clamps
126 // further), with 128 samples of padding for safety.
127 constexpr double kMinAllowedHz = 0.1;
128 constexpr double kMaxAllowedSemitones = 4.0;
129 const double maxDeviation =
130 (kMaxAllowedSemitones * std::numbers::ln2 * sampleRate_)
131 / (2.0 * std::numbers::pi * kMinAllowedHz * 12.0);
132 const double required =
133 2.0 * maxDeviation + static_cast<double>(kCentreOffset) + 128.0;
134 const int maxDelaySamples =
135 static_cast<int>(std::min(required, static_cast<double>(1 << 28)));
136
137 delays_.resize(numChannels_);
138 phasors_.resize(numChannels_);
139 modPhasors_.resize(numChannels_);
140 readPos_.assign(static_cast<size_t>(numChannels_), -1.0);
141 sinc_ = &sincTable(); // built on this setup thread, once per process
142
143 bbd_.resize(static_cast<size_t>(numChannels_));
144 noiseLp_.assign(static_cast<size_t>(numChannels_), 0.0);
145 noiseRng_.resize(static_cast<size_t>(numChannels_));
146 for (int ch = 0; ch < numChannels_; ++ch)
147 {
148 delays_[ch].prepare(maxDelaySamples);
149 phasors_[ch].prepare(sampleRate_);
150 modPhasors_[ch].prepare(sampleRate_);
151 bbd_[static_cast<size_t>(ch)].prepare(sampleRate_, kAnalogStages, 0.45 * sampleRate_);
152 noiseRng_[static_cast<size_t>(ch)] = 0x5A17C3u + 0x9E3779B9u * static_cast<uint32_t>(ch);
153 }
154 analogCornerFor_ = -1.0;
155
156 // Initialize smoothing state to prevent startup ramps
157 currentRate_ = rate_.load(std::memory_order_relaxed);
158 currentDepth_ = depthSemitones_.load(std::memory_order_relaxed);
159 currentModDepth_ = modDepth_.load(std::memory_order_relaxed);
160 }
161
166 void processBlock(AudioBufferView<T> buffer) noexcept
167 {
168 const int numCh = std::min(buffer.getNumChannels(), numChannels_);
169 const int numSamples = buffer.getNumSamples();
170 if (numSamples == 0 || numCh == 0) return;
171
172 // Fetch targets
173 const T targetRate = rate_.load(std::memory_order_relaxed);
174 const T targetDepth = depthSemitones_.load(std::memory_order_relaxed);
175 const T modRate = modRate_.load(std::memory_order_relaxed);
176 const T targetModDepth = modDepth_.load(std::memory_order_relaxed);
177
178 // Parameter smoothing increments (linear ramp over the block). Rate
179 // and depth set the width and centre of the delay sweep; the read
180 // position slew limit below turns even a large change into a brief
181 // glide. The FM depth is ramped too, so the LFO speed changes
182 // smoothly. The FM rate needs no smoothing: it only changes the speed
183 // of a continuous phase, which cannot produce a discontinuity.
184 const T rateInc = (targetRate - currentRate_) / static_cast<T>(numSamples);
185 const T depthInc = (targetDepth - currentDepth_) / static_cast<T>(numSamples);
186 const T modDepthInc = (targetModDepth - currentModDepth_) / static_cast<T>(numSamples);
187
188 // Keep the FM oscillator running while any part of the depth ramp is
189 // live, so a fade-out drains along the moving LFO instead of freezing
190 // mid-ramp. With FM fully off the oscillator holds its phase.
191 const bool fmActive = (targetModDepth > T(0)) || (currentModDepth_ > T(0));
192
193 constexpr double kTwoPi = 2.0 * std::numbers::pi;
194 const double deviationScaler = (std::numbers::ln2 * sampleRate_) / (kTwoPi * 12.0);
195 const bool analog = model_.load(std::memory_order_relaxed) == Model::Analog;
196 const bool sinc = !analog && sinc_ && interpolation_.load(std::memory_order_relaxed) == Interpolation::Sinc;
197 // Trough headroom and read window: Hermite reads 1 sample later and 2
198 // earlier; the sinc reader needs 16 later and 16 earlier; the analog
199 // line's trough is the fastest clock it runs.
200 const double centreOffset = analog ? kAnalogTrough
201 : sinc ? static_cast<double>(SincInterpolator<T>::kAfter)
202 : static_cast<double>(kCentreOffset);
203 const double maxRead = static_cast<double>(delays_[0].getCapacity()
204 - (sinc ? SincInterpolator<T>::kAfter + 1 : 4));
205
206 double noiseAmp = 0.0;
207 if (analog)
208 {
209 // The filters sit at a fifth of the slowest clock of this block's
210 // sweep (its peak delay, 2 * deviation + trough).
211 const auto deviationOf = [&](T depth, T rate) {
212 return static_cast<double>(depth) * deviationScaler / std::max(static_cast<double>(rate), 0.1);
213 };
214 const double peak = 2.0 * std::max(deviationOf(currentDepth_, currentRate_), deviationOf(targetDepth, targetRate))
215 + centreOffset;
216 const double slowest = static_cast<double>(kAnalogStages) * sampleRate_ / (2.0 * peak);
217 if (std::abs(slowest - analogCornerFor_) > 1e-3 * slowest)
218 {
219 const double corner = std::min(0.2 * slowest, 0.45 * sampleRate_);
220 for (auto& b : bbd_) b.setCorner(corner);
221 noiseCoeff_ = 1.0 - std::exp(-2.0 * std::numbers::pi * corner / sampleRate_);
222 analogCornerFor_ = slowest;
223 }
224 const T noiseDb = analogNoiseDb_.load(std::memory_order_relaxed);
225 // White noise through a one-pole at the corner, scaled by that
226 // filter's own gain (the same level at any rate), and by the
227 // delay against the sweep's centre (a slower clock, more hiss).
228 if (noiseDb > T(-120))
229 noiseAmp = std::pow(10.0, static_cast<double>(noiseDb) / 20.0) * 1.7320508075688772
230 / std::sqrt(std::max(1e-9, noiseCoeff_ / (2.0 - noiseCoeff_)));
231 }
232
233 for (int ch = 0; ch < numCh; ++ch)
234 {
235 T* data = buffer.getChannel(ch);
236 auto& delay = delays_[ch];
237 auto& phasor = phasors_[ch];
238 auto& modPhasor = modPhasors_[ch];
239
240 modPhasor.setFrequency(modRate);
241
242 // Local state for smoothing (identical ramps on every channel)
243 T smoothRate = currentRate_;
244 T smoothDepth = currentDepth_;
245 T smoothModDepth = currentModDepth_;
246
247 for (int i = 0; i < numSamples; ++i)
248 {
249 smoothRate += rateInc;
250 smoothDepth += depthInc;
251 smoothModDepth += modDepthInc;
252
253 delay.push(data[i]);
254
255 // Sweep geometry from the smoothed base rate only: a sinusoidal
256 // delay centre + D * sin(phase) peaks at a pitch excursion of
257 // D * 2*pi*f/fs, so D = depth * deviationScaler / rate gives
258 // the set depth at the base rate, and the centre sits one
259 // deviation above the offset so the trough never dips below
260 // it. FM used to feed its instantaneous rate into D and the
261 // centre (D ~ rate^-1.5): at deep or fast FM the rate neared
262 // the floor and the read point leapt by hundreds of samples
263 // per sample (noise, not vibrato).
264 const double baseRate = std::max(static_cast<double>(smoothRate), 0.1);
265 const double deviation = (static_cast<double>(smoothDepth) * deviationScaler) / baseRate;
266 const double centre = deviation + centreOffset;
267
268 // FM varies only the speed of the LFO, between (1 - modDepth)
269 // and (1 + modDepth) times the rate, so the pitch excursion
270 // follows the instantaneous speed: up to twice the depth at
271 // full FM, and never a jump.
272 double speed = 1.0;
273 if (fmActive)
274 speed += fastSin(modPhasor.advance() * kTwoPi) * static_cast<double>(smoothModDepth);
275 phasor.setFrequency(baseRate * std::max(speed, 0.0));
276 const double lfo = fastSin(phasor.advance() * kTwoPi);
277
278 // Safety clamp to the interpolator's read window.
279 const double delaySamples = std::clamp(centre + lfo * deviation,
280 (sinc || analog) ? centreOffset : 1.0, maxRead);
281
282 // Read-position slew limit. Depth and rate scale the deviation
283 // and centre, so a parameter change moves the read point;
284 // ramped per block, a small block moved it by hundreds of
285 // samples at once (a click, or a backwards read). Limiting the
286 // motion to 0.5 samples per sample bounds any parameter jump
287 // to a brief pitch glide, and never touches the vibrato itself
288 // (its steepest motion, 4 semitones at full FM, is
289 // 2 * 4 * ln2 / 12 = 0.46 samples per sample).
290 double& pos = readPos_[static_cast<size_t>(ch)];
291 pos = (pos < 0.0) ? delaySamples
292 : pos + std::clamp(delaySamples - pos, -kMaxReadSlope, kMaxReadSlope);
293
294 if (analog)
295 {
296 const auto c = static_cast<size_t>(ch);
297 double y = static_cast<double>(bbd_[c].processSample(data[i], pos / sampleRate_));
298 if (noiseAmp > 0.0)
299 {
300 noiseRng_[c] = noiseRng_[c] * 1664525u + 1013904223u;
301 const double n = static_cast<double>(noiseRng_[c] >> 8) / 8388608.0 - 1.0;
302 noiseLp_[c] += noiseCoeff_ * (n - noiseLp_[c]);
303 y += noiseAmp * (pos / centre) * noiseLp_[c];
304 }
305 data[i] = static_cast<T>(y);
306 }
307 else
308 {
309 data[i] = sinc ? readSinc(delay, pos) : readHermite(delay, pos);
310 }
311 }
312 }
313
314 // Update current state for the next block
315 currentRate_ = targetRate;
316 currentDepth_ = targetDepth;
317 currentModDepth_ = targetModDepth;
318 }
319
325 void reset() noexcept
326 {
327 for (int ch = 0; ch < numChannels_; ++ch)
328 {
329 delays_[ch].reset();
330 phasors_[ch].reset();
331 modPhasors_[ch].reset();
332 }
333 for (auto& b : bbd_) b.reset();
334 std::fill(noiseLp_.begin(), noiseLp_.end(), 0.0);
335 std::fill(readPos_.begin(), readPos_.end(), -1.0); // re-seed on the next sample
336 }
337
345 void setRate(T hz) noexcept
346 {
347 if (!std::isfinite(hz)) return; // NaN/Inf would poison the delay sweep
348 rate_.store(std::max(hz, T(0.1)), std::memory_order_relaxed);
349 }
350
357 void setDepth(T semitones) noexcept
358 {
359 if (!std::isfinite(semitones)) return;
360 depthSemitones_.store(std::clamp(semitones, T(0), T(4)), std::memory_order_relaxed);
361 }
362
372 void setModRate(T hz) noexcept
373 {
374 if (!std::isfinite(hz)) return;
375 modRate_.store(std::max(hz, T(0)), std::memory_order_relaxed);
376 }
377
390 void setModDepth(T amount) noexcept
391 {
392 if (!std::isfinite(amount)) return;
393 modDepth_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
394 }
395
396 [[nodiscard]] T getRate() const noexcept { return rate_.load(std::memory_order_relaxed); }
397 [[nodiscard]] T getDepth() const noexcept { return depthSemitones_.load(std::memory_order_relaxed); }
398 [[nodiscard]] T getModRate() const noexcept { return modRate_.load(std::memory_order_relaxed); }
399 [[nodiscard]] T getModDepth() const noexcept { return modDepth_.load(std::memory_order_relaxed); }
400
404 void setInterpolation(Interpolation mode) noexcept
405 {
406 interpolation_.store(mode == Interpolation::Sinc ? Interpolation::Sinc : Interpolation::Hermite,
407 std::memory_order_relaxed);
408 }
409
411 [[nodiscard]] Interpolation getInterpolation() const noexcept
412 {
413 return interpolation_.load(std::memory_order_relaxed);
414 }
415
418 void setModel(Model m) noexcept
419 {
420 model_.store(static_cast<Model>(std::clamp(static_cast<int>(m), 0, 1)), std::memory_order_relaxed);
421 }
423 [[nodiscard]] Model getModel() const noexcept { return model_.load(std::memory_order_relaxed); }
424
430 void setAnalogNoise(T dbfs) noexcept
431 {
432 if (!std::isfinite(dbfs)) return;
433 analogNoiseDb_.store(std::clamp(dbfs, T(-140), T(-40)), std::memory_order_relaxed);
434 }
436 [[nodiscard]] T getAnalogNoise() const noexcept { return analogNoiseDb_.load(std::memory_order_relaxed); }
437
439 [[nodiscard]] std::vector<uint8_t> getState() const
440 {
441 // The blob stores float (setState reads float back); the explicit
442 // casts also keep this overload resolvable when T is double.
443 StateWriter w(stateId("VIBR"), 1);
444 w.write("rate", static_cast<float>(rate_.load(std::memory_order_relaxed)));
445 w.write("depth", static_cast<float>(depthSemitones_.load(std::memory_order_relaxed)));
446 w.write("modRate", static_cast<float>(modRate_.load(std::memory_order_relaxed)));
447 w.write("modDepth", static_cast<float>(modDepth_.load(std::memory_order_relaxed)));
448 w.write("interp", static_cast<int32_t>(interpolation_.load(std::memory_order_relaxed)));
449 w.write("model", static_cast<int32_t>(model_.load(std::memory_order_relaxed)));
450 w.write("analogNoise", static_cast<float>(analogNoiseDb_.load(std::memory_order_relaxed)));
451 return w.blob();
452 }
453
455 bool setState(const uint8_t* data, size_t size)
456 {
457 StateReader r(data, size);
458 if (!r.isValid() || r.processorId() != stateId("VIBR")) return false;
459 setRate(static_cast<T>(r.read("rate", 5.0f)));
460 setDepth(static_cast<T>(r.read("depth", 0.5f)));
461 setModRate(static_cast<T>(r.read("modRate", 0.0f)));
462 setModDepth(static_cast<T>(r.read("modDepth", 0.0f)));
464 setModel(r.read("model", 0) == 1 ? Model::Analog : Model::Digital);
465 setAnalogNoise(static_cast<T>(r.read("analogNoise", -84.0f)));
466 return true;
467 }
468
469private:
472 static constexpr T kCentreOffset = T(4);
474 static constexpr double kMaxReadSlope = 0.5;
477 static constexpr int kAnalogStages = 1024;
478 static constexpr double kAnalogTrough = 12.0;
479
481 static const SincInterpolator<T>& sincTable()
482 {
483 static const SincInterpolator<T> table;
484 return table;
485 }
486
489 [[nodiscard]] static T readHermite(const RingBuffer<T>& ring, double delay) noexcept
490 {
491 const int d = static_cast<int>(delay);
492 const T frac = static_cast<T>(delay - static_cast<double>(d));
493 return interpolateHermite(ring.read(d - 1), ring.read(d), ring.read(d + 1), ring.read(d + 2), frac);
494 }
495
498 [[nodiscard]] T readSinc(const RingBuffer<T>& ring, double delay) const noexcept
499 {
500 const int d = static_cast<int>(delay);
501 const double frac = delay - static_cast<double>(d);
502 const int64_t newest = static_cast<int64_t>(ring.getWritePosition()) - 1;
503 const int64_t intPos = newest - d - (frac > 0.0 ? 1 : 0);
504 return sinc_->readRing(ring.data(), static_cast<int64_t>(ring.getCapacity() - 1), intPos,
505 frac > 0.0 ? 1.0 - frac : 0.0);
506 }
507
508 double sampleRate_ = 44100.0;
509 int numChannels_ = 0;
510
511 // Atomic targets for UI thread publication
512 std::atomic<T> rate_ { T(5) };
513 std::atomic<T> depthSemitones_ { T(0.5) };
514 std::atomic<T> modRate_ { T(0) };
515 std::atomic<T> modDepth_ { T(0) };
516
517 // Smoothed state for the audio thread
518 T currentRate_ { T(5) };
519 T currentDepth_ { T(0.5) };
520 T currentModDepth_ { T(0) };
521
522 // Dynamic allocation via STL, safe because it only happens in prepare()
523 std::vector<RingBuffer<T>> delays_;
524 std::vector<Phasor<double>> phasors_;
525 std::vector<Phasor<double>> modPhasors_;
526 std::vector<double> readPos_;
527 std::atomic<Interpolation> interpolation_ { Interpolation::Hermite };
528 const SincInterpolator<T>* sinc_ = nullptr;
529
530 std::atomic<Model> model_ { Model::Digital };
531 std::atomic<T> analogNoiseDb_ { T(-84) };
532 std::vector<BucketBrigade<T>> bbd_;
533 std::vector<double> noiseLp_;
534 std::vector<uint32_t> noiseRng_;
535 double noiseCoeff_ = 0.0, analogCornerFor_ = -1.0;
536};
537
538} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
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
Model getModel() const noexcept
Definition Vibrato.h:423
T getModDepth() const noexcept
Definition Vibrato.h:399
Model
The engine.
Definition Vibrato.h:93
@ Digital
Interpolated reads of a delay line (default).
@ Analog
A bucket-brigade line per channel (see the file comment).
Interpolation
Fractional read kernel of the modulated delay line.
Definition Vibrato.h:84
@ Hermite
4-point cubic (default).
void setAnalogNoise(T dbfs) noexcept
Hiss of the analog line at the sweep's centre.
Definition Vibrato.h:430
void processBlock(AudioBufferView< T > buffer) noexcept
Processes audio in-place, applying vibrato per channel.
Definition Vibrato.h:166
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition Vibrato.h:439
void setModel(Model m) noexcept
Selects the engine (see Model). Thread-safe; the engines do not crossfade; out-of-range values are cl...
Definition Vibrato.h:418
void setDepth(T semitones) noexcept
Sets the vibrato pitch depth. Parameter is smoothed internally.
Definition Vibrato.h:357
void setModRate(T hz) noexcept
Sets the rate of the secondary FM oscillator.
Definition Vibrato.h:372
void reset() noexcept
Clears delay line memory and resets LFO phases.
Definition Vibrato.h:325
T getDepth() const noexcept
Definition Vibrato.h:397
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition Vibrato.h:455
void setModDepth(T amount) noexcept
Sets the intensity of the FM modulation on the primary LFO.
Definition Vibrato.h:390
T getRate() const noexcept
Definition Vibrato.h:396
T getAnalogNoise() const noexcept
Definition Vibrato.h:436
T getModRate() const noexcept
Definition Vibrato.h:398
void setRate(T hz) noexcept
Sets the primary LFO rate. Parameter is smoothed internally.
Definition Vibrato.h:345
Interpolation getInterpolation() const noexcept
Returns the fractional read kernel.
Definition Vibrato.h:411
void prepare(const AudioSpec &spec)
Allocates delay lines and settles the parameter smoothing state.
Definition Vibrato.h:113
void setInterpolation(Interpolation mode) noexcept
Selects the fractional read kernel. Thread-safe; a switch moves the sweep trough (see Interpolation),...
Definition Vibrato.h:404
constexpr int delay
Delay of the projected output behind the newest input, in samples.
Main namespace for the DSPark framework.
T interpolateHermite(T y0, T y1, T y2, T y3, T frac) noexcept
4-point, 3rd-order Hermite interpolation (optimized x-form).
T fastSin(T x) noexcept
Fast sine approximation (degree-9 odd minimax polynomial).
Definition DspMath.h:340
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
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45