DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Lfo.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
50#include "DspMath.h"
51
52#include <algorithm>
53#include <array>
54#include <cmath>
55#include <cstddef>
56#include <cstdint>
57
58namespace dspark {
59
78template <FloatType T>
79class Lfo
80{
81public:
82 enum class Shape
83 {
84 Sine,
86 SawUp,
87 SawDown,
88 Square,
91 Steps
92 };
93 static constexpr int kNumShapes = 8;
94
96 static constexpr int kMaxSteps = 16;
97
108 static constexpr int kNumDivisions = 19;
109
111 [[nodiscard]] static constexpr double beatsPerCycle(Division d) noexcept
112 {
113 switch (d)
114 {
115 case Division::EightBars: return 32.0;
116 case Division::FourBars: return 16.0;
117 case Division::TwoBars: return 8.0;
118 case Division::Whole: return 4.0;
119 case Division::HalfDotted: return 3.0;
120 case Division::Half: return 2.0;
121 case Division::HalfTriplet: return 4.0 / 3.0;
122 case Division::QuarterDotted: return 1.5;
123 case Division::Quarter: return 1.0;
124 case Division::QuarterTriplet: return 2.0 / 3.0;
125 case Division::EighthDotted: return 0.75;
126 case Division::Eighth: return 0.5;
127 case Division::EighthTriplet: return 1.0 / 3.0;
128 case Division::SixteenthDotted: return 0.375;
129 case Division::Sixteenth: return 0.25;
130 case Division::SixteenthTriplet: return 1.0 / 6.0;
131 case Division::ThirtySecond: return 0.125;
132 case Division::ThirtySecondTriplet: return 1.0 / 12.0;
133 case Division::SixtyFourth: return 0.0625;
134 }
135 return 1.0;
136 }
137
139 static constexpr double kMaxRateHz = 1000.0;
140
142 void prepare(double sampleRate) noexcept
143 {
144 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate)) return;
145 sampleRate_ = sampleRate;
146 updateIncrement();
147 updateEnvelope();
148 }
149
154 void reset() noexcept
155 {
156 // The glide of a retrigger starts from where the output is now.
157 retrigFrom_ = static_cast<double>(value());
158 retrigLeft_ = retrigSamples_;
159 cycles_ = startPhase_;
160 age_ = 0;
161 }
162
163 // -- Parameters (owning thread) -------------------------------------------
164
165 void setShape(Shape s) noexcept { shape_ = s; }
166 [[nodiscard]] Shape getShape() const noexcept { return shape_; }
167
169 void setRateHz(double hz) noexcept
170 {
171 if (hz != hz) return;
172 rateHz_ = std::clamp(hz, 0.0, kMaxRateHz);
173 updateIncrement();
174 }
175
177 void setTempoSync(bool on) noexcept { sync_ = on; updateIncrement(); }
178 void setDivision(Division d) noexcept { division_ = d; updateIncrement(); }
179
181 void setTempo(double bpm) noexcept
182 {
183 if (!(bpm >= 1.0) || !(bpm <= 999.0)) return;
184 bpm_ = bpm;
185 updateIncrement();
186 }
187
189 void setStartPhase(double phase) noexcept
190 {
191 if (!std::isfinite(phase)) return;
192 startPhase_ = phase - std::floor(phase);
193 }
194
196 void setDelayMs(double ms) noexcept
197 {
198 if (!(ms >= 0.0) || !std::isfinite(ms)) return;
199 delayMs_ = ms;
200 updateEnvelope();
201 }
202
204 void setFadeInMs(double ms) noexcept
205 {
206 if (!(ms >= 0.0) || !std::isfinite(ms)) return;
207 fadeMs_ = ms;
208 updateEnvelope();
209 }
210
212 void setSeed(uint64_t seed) noexcept { seed_ = seed; stepCacheCycle_ = kNoCycle; }
213
218 void setRetriggerGlideMs(double ms) noexcept
219 {
220 if (!(ms >= 0.0) || !std::isfinite(ms)) return;
221 retrigMs_ = ms;
222 updateEnvelope();
223 }
224
225 // -- The Steps shape (owning thread) ---------------------------------------
226
228 void setNumSteps(int count) noexcept
229 {
230 numSteps_ = std::clamp(count, 1, kMaxSteps);
231 stepCacheCycle_ = kNoCycle;
232 }
233 [[nodiscard]] int getNumSteps() const noexcept { return numSteps_; }
234
245 void setStep(int index, double value, double glide = 0.0, double curve = 0.0) noexcept
246 {
247 if (index < 0 || index >= kMaxSteps || !std::isfinite(value) || !std::isfinite(glide) || !std::isfinite(curve)) return;
248 const auto i = static_cast<size_t>(index);
249 stepValue_[i] = std::clamp(value, -1.0, 1.0);
250 stepGlide_[i] = std::clamp(glide, 0.0, 1.0);
251 stepCurve_[i] = std::clamp(curve, -1.0, 1.0);
252 stepCacheCycle_ = kNoCycle;
253 }
254
256 void setStepRandom(int index, bool random) noexcept
257 {
258 if (index < 0 || index >= kMaxSteps) return;
259 stepRandom_[static_cast<size_t>(index)] = random;
260 stepCacheCycle_ = kNoCycle;
261 }
262
263 [[nodiscard]] double getStepValue(int index) const noexcept { return stepValue_[stepIndex(index)]; }
264 [[nodiscard]] double getStepGlide(int index) const noexcept { return stepGlide_[stepIndex(index)]; }
265 [[nodiscard]] double getStepCurve(int index) const noexcept { return stepCurve_[stepIndex(index)]; }
266 [[nodiscard]] bool isStepRandom(int index) const noexcept { return stepRandom_[stepIndex(index)]; }
267
273 void setStepSwing(double swing) noexcept
274 {
275 if (std::isfinite(swing)) swing_ = std::clamp(swing, -1.0, 1.0);
276 }
277 [[nodiscard]] double getStepSwing() const noexcept { return swing_; }
278
285 void setStepQuantize(int divisions) noexcept
286 {
287 stepQuantize_ = std::clamp(divisions, 0, 1200);
288 stepCacheCycle_ = kNoCycle;
289 }
290 [[nodiscard]] int getStepQuantize() const noexcept { return stepQuantize_; }
291
296 [[nodiscard]] double stepsAt(double cycles) const noexcept
297 {
298 if (!std::isfinite(cycles)) cycles = 0.0;
299 const double index = std::floor(cycles);
300 const double ph = cycles - index;
301 const auto cycle = static_cast<int64_t>(index);
302 if (cycle != stepCacheCycle_) fillStepCache(cycle);
303 // Where the phase is in the steps, with the swing inside each pair.
304 const double pos = ph * static_cast<double>(numSteps_);
305 int step = static_cast<int>(pos);
306 double within = pos - static_cast<double>(step);
307 if (swing_ != 0.0 && numSteps_ >= 2)
308 {
309 const int pair = step / 2;
310 if (2 * pair + 1 < numSteps_)
311 {
312 const double inPair = pos - 2.0 * static_cast<double>(pair); // 0..2
313 const double edge = 1.0 + 0.5 * swing_;
314 if (inPair < edge) { step = 2 * pair; within = inPair / edge; }
315 else { step = 2 * pair + 1; within = (inPair - edge) / (2.0 - edge); }
316 }
317 }
318 step = std::clamp(step, 0, numSteps_ - 1);
319 // Indexed through stepIndex(), whose bounds are constants: the same
320 // index, one a compiler can prove inside the arrays.
321 const size_t at = stepIndex(step);
322 const double to = stepCache_[at];
323 const double from = step > 0 ? stepCache_[stepIndex(step - 1)] : stepCacheBefore_;
324 const double glide = stepGlide_[at];
325 if (!(within < glide)) return to;
326 const double x = within / glide;
327 const double c = stepCurve_[at];
328 const double bent = c > 0.0 ? 1.0 - std::pow(1.0 - x, 1.0 + 4.0 * c)
329 : c < 0.0 ? std::pow(x, 1.0 - 4.0 * c) : x;
330 return from + (to - from) * bent;
331 }
332
334 [[nodiscard]] double getRateHz() const noexcept { return increment_ * sampleRate_; }
335
337 [[nodiscard]] double getCycles() const noexcept { return cycles_; }
338
339 // -- Generation (owning thread) --------------------------------------------
340
342 [[nodiscard]] T value() const noexcept
343 {
344 const double shaped = (shape_ == Shape::Steps) ? stepsAt(cycles_) : valueAt(shape_, cycles_, seed_);
345 const double v = shaped * depthAt(age_);
346 if (retrigLeft_ <= 0) return static_cast<T>(v);
347 const double share = static_cast<double>(retrigLeft_) / static_cast<double>(retrigSamples_);
348 return static_cast<T>(v + (retrigFrom_ - v) * share);
349 }
350
355 T advance(int samples = 1) noexcept
356 {
357 const T v = value();
358 const auto n = static_cast<int64_t>(std::max(samples, 0));
359 cycles_ += increment_ * static_cast<double>(n);
360 age_ += n;
361 retrigLeft_ = std::max<int64_t>(0, retrigLeft_ - n);
362 return v;
363 }
364
369 T advanceScaled(int samples, double rateScale) noexcept
370 {
371 const T v = value();
372 const auto n = static_cast<int64_t>(std::max(samples, 0));
373 const double scale = (rateScale >= 0.0) ? std::min(rateScale, 64.0) : 0.0;
374 cycles_ += increment_ * scale * static_cast<double>(n);
375 age_ += n;
376 retrigLeft_ = std::max<int64_t>(0, retrigLeft_ - n);
377 return v;
378 }
379
384 [[nodiscard]] double depthAt(int64_t samples) const noexcept
385 {
386 if (samples < delaySamples_) return 0.0;
387 if (fadeSamples_ <= 0) return 1.0;
388 const double x = static_cast<double>(samples - delaySamples_) / static_cast<double>(fadeSamples_);
389 return std::min(x, 1.0);
390 }
391
399 [[nodiscard]] static double valueAt(Shape shape, double cycles, uint64_t seed) noexcept
400 {
401 if (!std::isfinite(cycles)) cycles = 0.0;
402 const double index = std::floor(cycles);
403 const double ph = cycles - index;
404 switch (shape)
405 {
406 case Shape::Sine: return std::sin(twoPi<double> * ph);
407 case Shape::Triangle: return (ph < 0.25) ? 4.0 * ph
408 : (ph < 0.75) ? 2.0 - 4.0 * ph
409 : 4.0 * ph - 4.0;
410 case Shape::SawUp: return 2.0 * ph - 1.0;
411 case Shape::SawDown: return 1.0 - 2.0 * ph;
412 case Shape::Square: return (ph < 0.5) ? 1.0 : -1.0;
414 return random(seed, static_cast<int64_t>(index));
416 {
417 const double a = random(seed, static_cast<int64_t>(index));
418 const double b = random(seed, static_cast<int64_t>(index) + 1);
419 return a + (b - a) * 0.5 * (1.0 - std::cos(pi<double> * ph));
420 }
421 case Shape::Steps: return 0.0;
422 }
423 return 0.0;
424 }
425
427 [[nodiscard]] static double random(uint64_t seed, int64_t index) noexcept
428 {
429 uint64_t x = seed + 0x9E3779B97F4A7C15ull * (static_cast<uint64_t>(index) + 1ull);
430 x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
431 x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
432 x ^= x >> 31;
433 return static_cast<double>(x >> 11) * (2.0 / 9007199254740992.0) - 1.0;
434 }
435
436private:
437 void updateIncrement() noexcept
438 {
439 const double hz = sync_ ? (bpm_ / 60.0) / beatsPerCycle(division_) : rateHz_;
440 increment_ = hz / sampleRate_;
441 }
442
443 void updateEnvelope() noexcept
444 {
445 delaySamples_ = static_cast<int64_t>(std::llround(delayMs_ * 0.001 * sampleRate_));
446 fadeSamples_ = static_cast<int64_t>(std::llround(fadeMs_ * 0.001 * sampleRate_));
447 retrigSamples_ = static_cast<int64_t>(std::llround(retrigMs_ * 0.001 * sampleRate_));
448 retrigLeft_ = std::min(retrigLeft_, retrigSamples_);
449 }
450
451 [[nodiscard]] static size_t stepIndex(int index) noexcept { return static_cast<size_t>(std::clamp(index, 0, kMaxSteps - 1)); }
452
456 [[nodiscard]] double stepValueIn(int64_t cycle, int step, double before) const noexcept
457 {
458 double v = stepValue_[stepIndex(step)];
459 if (stepRandom_[stepIndex(step)])
460 {
461 const double u = 0.5 * (random(seed_ ^ 0x5DEECE66Dull, cycle * kMaxSteps + step) + 1.0); // 0..1
462 const bool up = before < 0.0;
463 const double room = up ? 1.0 - before : before + 1.0; // 1..2
464 const double away = room * (0.25 + 0.75 * u);
465 v = std::clamp(up ? before + away : before - away, -1.0, 1.0);
466 }
467 return quantized(v);
468 }
469
471 [[nodiscard]] double quantized(double v) const noexcept
472 {
473 if (stepQuantize_ <= 0) return v;
474 const double q = static_cast<double>(stepQuantize_);
475 return std::clamp(std::round(v * q) / q, -1.0, 1.0);
476 }
477
483 void fillStepCache(int64_t cycle) const noexcept
484 {
485 auto walk = [&](int64_t c, std::array<double, kMaxSteps>& out) {
486 const int last = numSteps_ - 1;
487 double before = quantized(stepValue_[stepIndex(last)]);
488 for (int s = 0; s < numSteps_; ++s)
489 {
490 out[stepIndex(s)] = stepValueIn(c, s, before);
491 before = out[stepIndex(s)];
492 }
493 };
494 std::array<double, kMaxSteps> previous {};
495 walk(cycle - 1, previous);
496 stepCacheBefore_ = previous[stepIndex(numSteps_ - 1)];
497 walk(cycle, stepCache_);
498 stepCacheCycle_ = cycle;
499 }
500
501 double sampleRate_ = 48000.0;
502 Shape shape_ = Shape::Sine;
503 double rateHz_ = 1.0;
504 bool sync_ = false;
505 Division division_ = Division::Quarter;
506 double bpm_ = 120.0;
507 double startPhase_ = 0.0;
508 double delayMs_ = 0.0;
509 double fadeMs_ = 0.0;
510 uint64_t seed_ = 0;
511
512 // The Steps shape.
513 static constexpr int64_t kNoCycle = INT64_MIN;
514 int numSteps_ = kMaxSteps;
515 std::array<double, kMaxSteps> stepValue_ {};
516 std::array<double, kMaxSteps> stepGlide_ {};
517 std::array<double, kMaxSteps> stepCurve_ {};
518 std::array<bool, kMaxSteps> stepRandom_ {};
519 double swing_ = 0.0;
520 int stepQuantize_ = 0;
521 mutable std::array<double, kMaxSteps> stepCache_ {};
522 mutable double stepCacheBefore_ = 0.0;
523 mutable int64_t stepCacheCycle_ = kNoCycle;
524 // The glide of a retrigger.
525 double retrigMs_ = 0.0;
526 int64_t retrigSamples_ = 0;
527 int64_t retrigLeft_ = 0;
528 double retrigFrom_ = 0.0;
529
530 double increment_ = 1.0 / 48000.0;
531 double cycles_ = 0.0;
532 int64_t age_ = 0;
533 int64_t delaySamples_ = 0;
534 int64_t fadeSamples_ = 0;
535};
536
537} // namespace dspark
Modulation oscillator with tempo sync, delay, fade-in and seeded random shapes.
Definition Lfo.h:80
int getStepQuantize() const noexcept
Definition Lfo.h:290
void setTempo(double bpm) noexcept
Tempo in BPM for tempo sync, 1..999 (invalid values ignored).
Definition Lfo.h:181
void prepare(double sampleRate) noexcept
Prepares for a sample rate (invalid rates are ignored).
Definition Lfo.h:142
double getRateHz() const noexcept
Effective rate in Hz (the synced one when tempo sync is on).
Definition Lfo.h:334
static constexpr int kNumDivisions
Definition Lfo.h:108
double getStepSwing() const noexcept
Definition Lfo.h:277
static double valueAt(Shape shape, double cycles, uint64_t seed) noexcept
The shape's value at an absolute cycle position.
Definition Lfo.h:399
void setDivision(Division d) noexcept
Definition Lfo.h:178
void setStepQuantize(int divisions) noexcept
Quantizes the step values to a grid of 1/divisions (0, the default, leaves them free; 12 puts them on...
Definition Lfo.h:285
static constexpr double beatsPerCycle(Division d) noexcept
Beats (quarter notes) per cycle of a division.
Definition Lfo.h:111
static double random(uint64_t seed, int64_t index) noexcept
Uniform value in [-1, 1) for a cycle index (splitmix64 hash).
Definition Lfo.h:427
double getStepCurve(int index) const noexcept
Definition Lfo.h:265
static constexpr int kNumShapes
Definition Lfo.h:93
void setShape(Shape s) noexcept
Definition Lfo.h:165
double getCycles() const noexcept
Cycles run since reset(), start phase included.
Definition Lfo.h:337
T value() const noexcept
The output now (shape times delay/fade depth), without advancing.
Definition Lfo.h:342
void reset() noexcept
Restarts the cycle at the start phase, the cycle count at zero and the delay and fade-in from the beg...
Definition Lfo.h:154
void setRateHz(double hz) noexcept
Free rate in Hz, 0..kMaxRateHz (NaN ignored). Used while sync is off.
Definition Lfo.h:169
void setNumSteps(int count) noexcept
Steps in a cycle, 1..kMaxSteps (16, the default).
Definition Lfo.h:228
T advance(int samples=1) noexcept
Returns the output now, then advances by samples at the current rate (a control-rate owner advances i...
Definition Lfo.h:355
void setStepRandom(int index, bool random) noexcept
Makes a step draw its value from the seed every cycle (see the file notes).
Definition Lfo.h:256
static constexpr int kMaxSteps
Most steps of the Steps shape.
Definition Lfo.h:96
void setSeed(uint64_t seed) noexcept
Seed of the random shapes (the same seed repeats the same sequence).
Definition Lfo.h:212
void setStartPhase(double phase) noexcept
Cycle position reset() starts at, 0..1 (wrapped).
Definition Lfo.h:189
void setFadeInMs(double ms) noexcept
Linear rise to full depth after the delay, in ms (>= 0).
Definition Lfo.h:204
double stepsAt(double cycles) const noexcept
The Steps shape's value at an absolute cycle position (the integer part is the cycle whose random ste...
Definition Lfo.h:296
void setStep(int index, double value, double glide=0.0, double curve=0.0) noexcept
One step: its value, how much of its length it glides to it from the step before, and the curve of th...
Definition Lfo.h:245
int getNumSteps() const noexcept
Definition Lfo.h:233
bool isStepRandom(int index) const noexcept
Definition Lfo.h:266
T advanceScaled(int samples, double rateScale) noexcept
Advances by samples at rateScale times the current rate (rate modulation; the scale is clamped to 0....
Definition Lfo.h:369
double getStepValue(int index) const noexcept
Definition Lfo.h:263
static constexpr double kMaxRateHz
Highest free rate (Hz).
Definition Lfo.h:139
void setStepSwing(double swing) noexcept
Moves the boundary inside each pair of steps, -1..1: at 0.5 the first step of a pair lasts 1....
Definition Lfo.h:273
void setRetriggerGlideMs(double ms) noexcept
How long reset() glides from the output it was at to the new start, in ms (0, the default,...
Definition Lfo.h:218
void setDelayMs(double ms) noexcept
Silence before the depth starts rising, in ms (>= 0).
Definition Lfo.h:196
double depthAt(int64_t samples) const noexcept
Depth of the delay and fade-in samples after reset(): 0 during the delay, then a linear rise to 1.
Definition Lfo.h:384
Division
Note values for tempo sync (four beats to the whole note).
Definition Lfo.h:100
double getStepGlide(int index) const noexcept
Definition Lfo.h:264
Shape getShape() const noexcept
Definition Lfo.h:166
void setTempoSync(bool on) noexcept
Tempo sync on or off; when on, the rate is the division of the tempo.
Definition Lfo.h:177
Main namespace for the DSPark framework.