DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Oscillator.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
45#include "DspMath.h"
46#include "AudioSpec.h"
47#include "AudioBuffer.h"
48#include "MinBlepTable.h"
49
50#include <cmath>
51#include <algorithm>
52#include <array>
53#include <cassert>
54#include <cstddef>
55#include <type_traits>
56
57namespace dspark {
58
88template <typename T>
90{
91 static_assert(std::is_floating_point_v<T>, "Oscillator requires float or double");
92
97 using Phase = double;
98
99public:
100 enum class Waveform { Sine, Saw, Square, Triangle };
101
103 enum class AntiAliasing
104 {
105 MinBLEP,
106 PolyBLEP
107 };
108
118 void prepare(double sampleRate) noexcept
119 {
120 assert(sampleRate > 0.0);
121 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate)) return;
122 sampleRate_ = sampleRate;
123 // Touch the shared minBLEP table here so its one-time FFT build runs
124 // on the control thread, never inside the audio callback.
125 blepDelay_ = static_cast<Phase>(MinBlepTable<T>::instance().dcDelay());
126 setFrequency(frequency_);
127 if (!syncOn_) primeMinBlep();
128 }
129
134 void prepare(const AudioSpec& spec) noexcept
135 {
136 prepare(spec.sampleRate);
137 }
138
143 void setFrequency(T freq) noexcept
144 {
145 // Reject NaN before clamp: std::clamp(NaN, ...) returns NaN (all
146 // comparisons false), which would poison phaseInc_ and the phase
147 // accumulator forever. Matches Phasor/WavetableOscillator guards.
148 if (freq != freq) return;
149 // Clamp frequency to valid bounds [0, Nyquist] to prevent aliasing breakdown
150 T nyquist = static_cast<T>(sampleRate_ * 0.5);
151 frequency_ = std::clamp(freq, T(0), nyquist);
152 updatePhaseInc();
153 }
154
159 void setWaveform(Waveform w) noexcept
160 {
161 if (w == waveform_) return;
162 waveform_ = w;
163 // The triangle's normalization is only kept current while it plays.
164 if (w == Waveform::Triangle) updateTriNorm();
165 // The pending minBLEP tails belong to the previous waveform's edges.
166 if (!syncOn_) primeMinBlep();
167 }
168
179 void setAntiAliasing(AntiAliasing mode) noexcept
180 {
181 if (mode == antiAliasing_) return;
182 antiAliasing_ = mode;
183 if (!syncOn_) primeMinBlep();
184 }
185
187 [[nodiscard]] AntiAliasing getAntiAliasing() const noexcept { return antiAliasing_; }
188
210 void setSyncRatio(T ratio) noexcept
211 {
212 syncRatio_ = std::max(T(0), ratio);
213 updatePhaseInc();
214 }
215
236 void setPulseWidth(T width) noexcept
237 {
238 if (width != width) return;
239 const T w = std::clamp(width, kMinPulseWidth, T(1) - kMinPulseWidth);
240 if (w == pulseWidth_) return;
241 const T old = pulseWidth_;
242 pulseWidth_ = w;
243 pulseDc_ = T(2) * w - T(1);
244 if (waveform_ != Waveform::Square) return;
245
246 // The falling edge moved across the current phase: the naive value
247 // flips at this very sample. Queue that flip as a minBLEP edge whose
248 // event time is the sample about to be emitted (age 0), so it is
249 // band-limited instead of an instantaneous step.
250 const Phase ph = syncOn_ ? slavePhase_ : phase_;
251 const bool wasHigh = ph < old;
252 const bool isHigh = ph < w;
253 if (wasHigh != isHigh && (syncOn_ || antiAliasing_ == AntiAliasing::MinBLEP))
254 scheduleMinBlep(isHigh ? T(2) : T(-2), T(0));
255 }
256
258 static constexpr T kMinPulseWidth = T(0.01);
259
273 void setPhase(T phase) noexcept
274 {
275 if (!std::isfinite(phase)) return;
276 // Wrap (not clamp): a phase of exactly 1.0 must land on 0.0 so the
277 // first sample is not a one-off discontinuity.
278 phase_ = static_cast<Phase>(phase) - std::floor(static_cast<Phase>(phase));
279 if (phase_ >= 1.0) phase_ -= 1.0;
280
281 if (syncOn_)
282 {
283 reseedSlave();
284 }
285 else
286 {
287 // A forced phase is a new stream: rebuild the pending minBLEP
288 // tails of the edges that stream would already have produced.
289 primeMinBlep();
290 }
291
292 seedTriangle();
293 }
294
301 void reset() noexcept
302 {
303 phase_ = 0.0;
304 slavePhase_ = 0.0;
305 corr_.fill(T(0));
306 corrHead_ = 0;
307 resetAge_ = { kNoReset, kNoReset };
308 if (!syncOn_) primeMinBlep();
309 seedTriangle();
310 }
311
318 [[nodiscard]] inline T getNextSample() noexcept
319 {
320 if (syncOn_)
321 return nextSyncSample();
322 if (antiAliasing_ == AntiAliasing::MinBLEP && waveform_ != Waveform::Sine)
323 return nextMinBlepSample();
324
325 T out = T(0);
326
327 switch (waveform_)
328 {
329 case Waveform::Sine:
330 // fastSin: minimax error ~2e-7 in float / 4e-9 in double
331 // (-135 / -168 dB), 3-6x faster than std::sin.
332 out = static_cast<T>(fastSin(phase_ * twoPi<Phase>));
333 break;
334
335 case Waveform::Saw:
336 out = static_cast<T>(2.0 * phase_ - 1.0 - polyBlep(phase_, phaseInc_));
337 break;
338
339 case Waveform::Square:
340 {
341 Phase raw = (phase_ < pulseWidth_) ? 1.0 : -1.0;
342 raw += polyBlep(phase_, phaseInc_);
343
344 // Phase relative to the falling edge at pulseWidth_ (optimized
345 // shift without std::fmod; 0.5 for the symmetric square).
346 Phase halfPhase = phase_ + (1.0 - static_cast<Phase>(pulseWidth_));
347 if (halfPhase >= 1.0) halfPhase -= 1.0;
348
349 raw -= polyBlep(halfPhase, phaseInc_);
350 out = static_cast<T>(raw - static_cast<Phase>(pulseDc_));
351 break;
352 }
353
355 {
356 Phase raw = (phase_ < 0.5) ? 1.0 : -1.0;
357 raw += polyBlep(phase_, phaseInc_);
358
359 Phase halfPhase = phase_ + 0.5;
360 if (halfPhase >= 1.0) halfPhase -= 1.0;
361 raw -= polyBlep(halfPhase, phaseInc_);
362
363 // Leaky integration for analog-style triangle. The recursion
364 // runs in double (framework rule for recursive state): with a
365 // float accumulator, slow LFO rates quantise near the peaks.
366 const double inc = static_cast<double>(phaseInc_);
367 triState_ = inc * static_cast<double>(raw) + (1.0 - inc) * triState_;
368 out = static_cast<T>(triState_) * triNorm_;
369 break;
370 }
371 }
372
373 // Fast phase wrap assuming positive frequencies only (enforced in setFrequency)
374 phase_ += phaseInc_;
375 if (phase_ >= 1.0) phase_ -= 1.0;
376
377 return out;
378 }
379
390 void processBlock(T* buffer, size_t numSamples) noexcept
391 {
392 for (size_t i = 0; i < numSamples; ++i)
393 {
394 buffer[i] = getNextSample();
395 }
396 }
397
399 [[nodiscard]] inline T getSample() noexcept { return getNextSample(); }
400
406 void generateBlock(AudioBufferView<T> buffer) noexcept
407 {
408 const int nCh = buffer.getNumChannels();
409 const int nS = buffer.getNumSamples();
410 if (nCh <= 0)
411 {
412 for (int i = 0; i < nS; ++i)
413 (void) getNextSample(); // keep the phase advancing
414 return;
415 }
416 T* ch0 = buffer.getChannel(0);
417 for (int i = 0; i < nS; ++i)
418 ch0[i] = getNextSample();
419 for (int ch = 1; ch < nCh; ++ch)
420 std::copy_n(ch0, static_cast<size_t>(nS), buffer.getChannel(ch));
421 }
422
423 [[nodiscard]] T getPhase() const noexcept { return static_cast<T>(phase_); }
424 [[nodiscard]] T getFrequency() const noexcept { return frequency_; }
425 [[nodiscard]] Waveform getWaveform() const noexcept { return waveform_; }
426 [[nodiscard]] T getSyncRatio() const noexcept { return syncRatio_; }
427 [[nodiscard]] T getPulseWidth() const noexcept { return pulseWidth_; }
428
429private:
431 [[nodiscard]] T rawSlaveValue(Phase ph) const noexcept
432 {
433 switch (waveform_)
434 {
435 case Waveform::Sine: return static_cast<T>(fastSin(ph * twoPi<Phase>));
436 case Waveform::Saw: return static_cast<T>(2.0 * ph - 1.0);
437 case Waveform::Square: return (ph < pulseWidth_) ? T(1) : T(-1);
438 case Waveform::Triangle: return (ph < 0.5) ? T(1) : T(-1);
439 }
440 return T(0);
441 }
442
468 void seedTriangle() noexcept
469 {
470 updateTriNorm(); // the seed needs the peak of the current increment
471 Phase ph = syncOn_ ? slavePhase_ : phase_;
472 const Phase peak = static_cast<Phase>(triExpectedPeak_);
473 if (!syncOn_ && antiAliasing_ == AntiAliasing::PolyBLEP && phaseInc_ > 0.0 && phaseInc_ < 1.0)
474 {
475 ph -= 0.5 * phaseInc_;
476 ph -= std::floor(ph);
477 // Offsets from -peak and +peak keep the ends of each arc exact.
478 const Phase decay = std::log1p(-phaseInc_) / phaseInc_; // ln of the leak per unit phase
479 triState_ = (ph < 0.5) ? -peak - (1.0 + peak) * std::expm1(ph * decay)
480 : peak + (1.0 + peak) * std::expm1((ph - 0.5) * decay);
481 return;
482 }
483 if (!syncOn_ && antiAliasing_ == AntiAliasing::MinBLEP)
484 {
485 ph -= phaseInc_ * blepDelay_;
486 ph -= std::floor(ph);
487 }
488 const Phase ideal = (ph < 0.5) ? (4.0 * ph - 1.0) : (3.0 - 4.0 * ph);
489 triState_ = ideal * peak;
490 }
491
504 void primeMinBlep() noexcept
505 {
506 corr_.fill(T(0));
507 corrHead_ = 0;
508 if (antiAliasing_ != AntiAliasing::MinBLEP || waveform_ == Waveform::Sine
509 || !(phaseInc_ > 0.0))
510 return;
511
512 const Phase period = 1.0 / phaseInc_;
513 const auto primeEdge = [&](Phase edgePhase, T jump) noexcept {
514 // Samples elapsed since the most recent edge at edgePhase, taken
515 // relative to the sample about to be emitted.
516 Phase age = (phase_ - edgePhase) * period;
517 if (age < 0.0) age += period;
518 for (; age < static_cast<Phase>(kCorrLen); age += period)
519 scheduleMinBlep(jump, age);
520 };
521 if (waveform_ == Waveform::Saw)
522 {
523 primeEdge(0.0, T(-2));
524 }
525 else
526 {
527 primeEdge(0.0, T(2));
528 primeEdge(fallingEdge(), T(-2));
529 }
530 }
531
534 [[nodiscard]] Phase fallingEdge() const noexcept
535 {
536 return waveform_ == Waveform::Square ? static_cast<Phase>(pulseWidth_) : 0.5;
537 }
538
548 [[nodiscard]] T nextMinBlepSample() noexcept
549 {
550 T raw = rawSlaveValue(phase_) + corr_[static_cast<size_t>(corrHead_)];
551 corr_[static_cast<size_t>(corrHead_)] = T(0);
552 corrHead_ = (corrHead_ + 1) & kCorrMask; // now the NEXT sample's slot
553
554 T out = raw;
555 if (waveform_ == Waveform::Saw)
556 {
557 // Delay the ramp by the minBLEP's own low-frequency delay so the
558 // band-limited jumps and the slope stay time-aligned (see
559 // MinBlepTable::dcDelay): without this the saw carries a DC offset
560 // of 2 * dcDelay * f0 / fs.
561 out -= static_cast<T>(2.0 * phaseInc_ * blepDelay_);
562 }
563 else if (waveform_ == Waveform::Square)
564 {
565 out -= pulseDc_; // AC-coupled pulse (zero at the 0.5 default)
566 }
567 else if (waveform_ == Waveform::Triangle)
568 {
569 // Leaky integration of the band-limited square (double state:
570 // framework rule for recursive state).
571 const double inc = static_cast<double>(phaseInc_);
572 triState_ = inc * static_cast<double>(raw) + (1.0 - inc) * triState_;
573 out = static_cast<T>(triState_) * triNorm_;
574 }
575
576 const Phase old = phase_;
577 phase_ += phaseInc_;
578 if (phaseInc_ > 0.0)
579 {
580 if (waveform_ == Waveform::Saw)
581 {
582 if (phase_ >= 1.0)
583 {
584 // Wrap: the saw falls by 2.
585 const Phase alpha = (1.0 - old) / phaseInc_;
586 scheduleMinBlep(T(-2), 1.0 - alpha);
587 }
588 }
589 else
590 {
591 // The square (or the triangle's drive) rises by 2 at the wrap
592 // and falls by 2 at its falling edge. A narrow or wide pulse
593 // can put both inside one interval -- the falling edge before
594 // the wrap (width near 1) or after it (width near 0) -- so the
595 // candidates are taken in time order. The symmetric square
596 // (increment <= 0.5) never reaches a second one.
597 const Phase edge = fallingEdge();
598 if (old < edge && phase_ >= edge)
599 {
600 const Phase alpha = (edge - old) / phaseInc_;
601 scheduleMinBlep(T(-2), 1.0 - alpha);
602 }
603 if (phase_ >= 1.0)
604 {
605 const Phase alpha = (1.0 - old) / phaseInc_;
606 scheduleMinBlep(T(2), 1.0 - alpha);
607 if (phase_ >= 1.0 + edge)
608 {
609 const Phase alphaFall = (1.0 + edge - old) / phaseInc_;
610 scheduleMinBlep(T(-2), 1.0 - alphaFall);
611 }
612 }
613 }
614 }
615 if (phase_ >= 1.0) phase_ -= 1.0;
616 return out;
617 }
618
631 [[nodiscard]] T nextSyncSample() noexcept
632 {
633 const bool squareLike =
634 waveform_ == Waveform::Square || waveform_ == Waveform::Triangle;
635
636 // --- emit: raw value plus the pending band-limiting correction ------
637 // The sine is evaluated dcDelay() samples late (see delayedSinePhase).
638 const T naive = (waveform_ == Waveform::Sine)
639 ? static_cast<T>(fastSin(delayedSinePhase() * twoPi<Phase>))
640 : rawSlaveValue(slavePhase_);
641 T raw = naive + corr_[static_cast<size_t>(corrHead_)];
642 corr_[static_cast<size_t>(corrHead_)] = T(0);
643 corrHead_ = (corrHead_ + 1) & kCorrMask; // now the NEXT sample's slot
644 resetAge_[0] += 1.0;
645 resetAge_[1] += 1.0;
646
647 T out = raw;
648 if (waveform_ == Waveform::Saw)
649 {
650 // Ramp aligned with the minBLEP delay (see nextMinBlepSample()).
651 out -= static_cast<T>(2.0 * slaveInc_ * blepDelay_);
652 }
653 else if (waveform_ == Waveform::Square)
654 {
655 out -= pulseDc_; // the free-running pulse's DC (see setPulseWidth())
656 }
657 else if (waveform_ == Waveform::Triangle)
658 {
659 // Feed the integrator with the duty-compensated square: the synced
660 // square has inherent DC (see updatePhaseInc) and the integrator's
661 // unity DC gain times triNorm_ would turn it into a large offset
662 // (+0.45 measured at ratio 2.7 without compensation).
663 const double inc = static_cast<double>(slaveInc_);
664 triState_ = inc * (static_cast<double>(raw) - static_cast<double>(syncSquareDc_))
665 + (1.0 - inc) * triState_;
666 out = static_cast<T>(triState_) * triNorm_;
667 }
668
669 // --- advance both phases; schedule corrections in time order --------
670 const Phase masterOld = phase_;
671 const Phase slaveOld = slavePhase_;
672 phase_ += phaseInc_;
673 slavePhase_ += slaveInc_;
674
675 const bool masterWrap = phase_ >= 1.0;
676 const Phase alphaSync = masterWrap ? (1.0 - masterOld) / phaseInc_ : 2.0;
677
678 // Natural slave edge inside this interval (at most one: slaveInc_ is
679 // clamped to 0.5). It only happens if the reset does not pre-empt it;
680 // on an exact tie the edge wins and the reset jump measures zero.
681 if (waveform_ != Waveform::Sine)
682 {
683 const auto naturalEdge = [&](Phase at, T jump) noexcept {
684 const Phase alphaEdge = (at - slaveOld) / slaveInc_;
685 if (alphaEdge <= alphaSync && alphaEdge <= 1.0)
686 scheduleMinBlep(jump, 1.0 - alphaEdge);
687 };
688 if (squareLike)
689 {
690 // Falling edge, wrap, and (narrow pulse) the next falling edge,
691 // in time order; the symmetric square crosses at most one.
692 const Phase edge = fallingEdge();
693 if (slaveOld < edge && slavePhase_ >= edge)
694 naturalEdge(edge, T(-2));
695 if (slavePhase_ >= 1.0)
696 {
697 naturalEdge(1.0, T(2));
698 if (slavePhase_ >= 1.0 + edge)
699 naturalEdge(1.0 + edge, T(-2));
700 }
701 }
702 else if (slavePhase_ >= 1.0)
703 {
704 naturalEdge(1.0, T(-2)); // the saw falls by 2 at its wrap
705 }
706 }
707 if (slavePhase_ >= 1.0) slavePhase_ -= 1.0;
708
709 if (masterWrap)
710 {
711 // Slave value the instant before the reset (wrap folded in); the
712 // jump lands on the freshly seeded phase-0 value.
713 Phase atJump = slaveOld + alphaSync * slaveInc_;
714 atJump -= std::floor(atJump);
715 const T jump = rawSlaveValue(0.0) - rawSlaveValue(atJump);
716 if (waveform_ == Waveform::Sine)
717 {
718 // Jump and kink, against the delayed naive sine: the slope
719 // per sample goes from 2 pi inc cos(2 pi atJump) to 2 pi inc.
720 const auto& table = MinBlepTable<T>::instance();
721 const Phase age = 1.0 - alphaSync;
722 const auto slopeJump = static_cast<T>(
723 twoPi<Phase> * slaveInc_ * (1.0 - std::cos(twoPi<Phase> * atJump)));
724 table.addDelayedStep(corr_.data(), corrHead_, jump, static_cast<T>(age));
725 table.addDelayedRamp(corr_.data(), corrHead_, slopeJump, static_cast<T>(age));
726 resetAge_[1] = resetAge_[0];
727 prePhase_[1] = prePhase_[0];
728 resetAge_[0] = age;
729 prePhase_[0] = atJump;
730 }
731 else if (jump != T(0))
732 {
733 scheduleMinBlep(jump, 1.0 - alphaSync);
734 }
735
736 phase_ -= 1.0;
737 slavePhase_ = (phase_ / std::max(phaseInc_, 1e-12)) * slaveInc_;
738 slavePhase_ -= std::floor(slavePhase_);
739 }
740 return out;
741 }
742
750 void scheduleMinBlep(T jump, Phase frac) noexcept
751 {
752 MinBlepTable<T>::instance().addStep(corr_.data(), corrHead_, jump, static_cast<T>(frac));
753 }
754
764 void reseedSlave() noexcept
765 {
766 const Phase r = slaveInc_ / std::max(phaseInc_, 1e-12);
767 slavePhase_ = phase_ * r;
768 slavePhase_ -= std::floor(slavePhase_);
769 corr_.fill(T(0));
770 corrHead_ = 0;
771 resetAge_ = { kNoReset, kNoReset };
772 }
773
783 [[nodiscard]] Phase delayedSinePhase() const noexcept
784 {
785 const Phase d = blepDelay_;
786 Phase ph;
787 if (resetAge_[0] >= d) ph = slavePhase_ - slaveInc_ * d;
788 else if (resetAge_[1] >= d) ph = prePhase_[0] - slaveInc_ * (d - resetAge_[0]);
789 else ph = prePhase_[1] - slaveInc_ * (d - resetAge_[1]);
790 return ph - std::floor(ph);
791 }
792
800 static inline Phase polyBlep(Phase phase, Phase inc) noexcept
801 {
802 if (inc < 1e-10) return 0.0;
803
804 if (phase < inc)
805 {
806 Phase t = phase / inc;
807 return t + t - t * t - 1.0;
808 }
809 else if (phase > 1.0 - inc)
810 {
811 Phase t = (phase - 1.0) / inc;
812 return t * t + t + t + 1.0;
813 }
814 return 0.0;
815 }
816
818 void updatePhaseInc() noexcept
819 {
820 // Defensive Nyquist clamp. setFrequency() already clamps, but prepare()
821 // can lower the sample rate afterwards (it re-clamps too), and the
822 // T-cast Nyquist bound may round up by an ulp; polyBlep() and the
823 // sync event logic both assume inc <= 0.5.
824 phaseInc_ = std::min(static_cast<Phase>(frequency_) / sampleRate_, 0.5);
825 const bool wasOn = syncOn_;
826 syncOn_ = syncRatio_ > T(1.001) && phaseInc_ > 0.0;
827 // Clamp the slave below Nyquist like any oscillator frequency.
828 slaveInc_ = std::min(phaseInc_ * static_cast<Phase>(syncRatio_), 0.5);
829
830 // DC of the hard-synced square (feeds the triangle integrator). The
831 // slave always restarts in its +1 half, so its duty cycle is
832 // asymmetric by construction: for an effective ratio r with
833 // fractional part f, the +1 time per master cycle exceeds the -1
834 // time by min(f, 0.5) - max(f - 0.5, 0) slave cycles.
835 syncSquareDc_ = 0.0;
836 if (syncOn_ && phaseInc_ > 0.0)
837 {
838 const Phase r = slaveInc_ / phaseInc_; // effective (clamped) ratio
839 const Phase f = r - std::floor(r);
840 syncSquareDc_ = (std::min(f, 0.5) - std::max(f - 0.5, 0.0)) / r;
841 }
842
843 // Sync just (re-)engaged: the ring may hold corrections from a
844 // previous sync run and the slave phase is stale -- re-seed both.
845 if (syncOn_ && !wasOn)
846 reseedSlave();
847
848 // Only the Triangle reads the normalization, and its std::pow would
849 // otherwise run on every frequency change of every waveform: a voice
850 // modulating its pitch per sample calls setFrequency() per sample.
851 // setWaveform() and seedTriangle() refresh it when it is next needed,
852 // from the same pure function of the increment.
853 if (waveform_ == Waveform::Triangle) updateTriNorm();
854 }
855
859 void updateTriNorm() noexcept
860 {
861 // Under hard sync the integrator runs at the slave rate.
862 const Phase inc = syncOn_ ? slaveInc_ : phaseInc_;
863 if (inc == triNormInc_)
864 return; // unchanged increment
865 triNormInc_ = inc;
866 if (inc > 0.0 && inc < 1.0)
867 {
868 // Steady-state peak of the leaky integrator driven by a +-1 square:
869 // over a half period of n samples starting at -p, the state reaches
870 // p = q*(-p) + (1 - q) with q = leak^n, so p = (1 - q) / (1 + q).
871 // (Using just 1 - q under-normalised the triangle by ~4 dB.)
872 //
873 // A pitch modulated every sample (vibrato, glide, a synthesizer
874 // voice) moves the increment every sample, and the exact form
875 // costs a std::pow each time. Within 0.1% of the increment the
876 // peak was last solved at, the first-order expansion around that
877 // anchor is used instead: its error is about 1e-7 of the peak.
878 Phase expectedPeak;
879 if (std::abs(inc - triAnchorInc_) <= 1e-3 * triAnchorInc_)
880 {
881 expectedPeak = triAnchorPeak_ + triAnchorSlope_ * (inc - triAnchorInc_);
882 }
883 else
884 {
885 const Phase lnQ = 0.5 * std::log1p(-inc) / inc;
886 const Phase q = std::exp(lnQ);
887 expectedPeak = (1.0 - q) / (1.0 + q);
888 // dp/dinc = dp/dq * q * dlnQ/dinc
889 const Phase dLnQ = 0.5 * (-inc / (1.0 - inc) - std::log1p(-inc)) / (inc * inc);
890 triAnchorInc_ = inc;
891 triAnchorPeak_ = expectedPeak;
892 triAnchorSlope_ = -2.0 / ((1.0 + q) * (1.0 + q)) * q * dLnQ;
893 }
894 triExpectedPeak_ = static_cast<T>(expectedPeak);
895 triNorm_ = (expectedPeak > 0.001) ? static_cast<T>(1.0 / expectedPeak) : T(4);
896 }
897 else
898 {
899 triExpectedPeak_ = T(0.25);
900 triNorm_ = T(4);
901 }
902 }
903
904 double sampleRate_ = 48000.0;
905 T frequency_ = T(440);
906 Phase phase_ = 0.0;
907 Phase phaseInc_ = 0.0;
908 double triState_ = 0.0;
909 T triNorm_ = T(4);
910 T triExpectedPeak_ = T(0.25);
911 Phase triNormInc_ = -1.0;
912 Phase triAnchorInc_ = -1.0;
913 Phase triAnchorPeak_ = 0.25;
914 Phase triAnchorSlope_ = 0.0;
915 Waveform waveform_ = Waveform::Sine;
916 AntiAliasing antiAliasing_ = AntiAliasing::MinBLEP;
917 Phase blepDelay_ = 0.0;
918
919 // Hard sync (slave) and minBLEP correction state.
920 static constexpr int kCorrLen = MinBlepTable<T>::kTaps;
921 static constexpr int kCorrMask = kCorrLen - 1;
922 static_assert((kCorrLen & kCorrMask) == 0, "minBLEP ring needs a power-of-two span");
923
924 bool syncOn_ = false;
925 T syncRatio_ = T(0);
926 Phase slavePhase_ = 0.0;
927 Phase slaveInc_ = 0.0;
928 Phase syncSquareDc_ = 0.0;
929 static constexpr Phase kNoReset = 1e9;
930 std::array<Phase, 2> resetAge_{ kNoReset, kNoReset };
931 std::array<Phase, 2> prePhase_{};
932 T pulseWidth_ = T(0.5);
933 T pulseDc_ = T(0);
934 std::array<T, kCorrLen> corr_{};
935 int corrHead_ = 0;
936};
937
938} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
T dcDelay() const noexcept
Low-frequency delay of the minimum-phase step, in samples.
static const MinBlepTable & instance() noexcept
Returns the process-wide shared table, building it on first call.
void addStep(T *ring, int head, T jump, T frac) const noexcept
Adds jump * residual(j + frac) to ring[(head + j) & (kTaps - 1)] for every tap j.
static constexpr int kTaps
Correction span in base-rate samples (power of two, ring-buffer friendly).
Band-limited oscillator featuring PolyBLEP anti-aliasing and analog-modeled integration.
Definition Oscillator.h:90
AntiAliasing
Discontinuity correction used when hard sync is off.
Definition Oscillator.h:104
@ MinBLEP
Minimum-phase band-limited step table (default; audio duty).
@ PolyBLEP
2-point polynomial step (no overshoot; LFO duty).
void setSyncRatio(T ratio) noexcept
Enables band-limited hard sync.
Definition Oscillator.h:210
Waveform getWaveform() const noexcept
Definition Oscillator.h:425
T getSyncRatio() const noexcept
Definition Oscillator.h:426
void generateBlock(AudioBufferView< T > buffer) noexcept
Fills every channel of the view with the generated waveform. Satisfies the GeneratorProcessor concept...
Definition Oscillator.h:406
T getPulseWidth() const noexcept
Definition Oscillator.h:427
static constexpr T kMinPulseWidth
Narrowest pulse width setPulseWidth() accepts (and 1 minus it the widest).
Definition Oscillator.h:258
void processBlock(T *buffer, size_t numSamples) noexcept
Fills a buffer with generated samples.
Definition Oscillator.h:390
void reset() noexcept
Hard-resets the oscillator phase and integrator state.
Definition Oscillator.h:301
void setFrequency(T freq) noexcept
Sets the oscillator's fundamental frequency.
Definition Oscillator.h:143
void setPulseWidth(T width) noexcept
Sets the Square's pulse width (duty cycle).
Definition Oscillator.h:236
void prepare(double sampleRate) noexcept
Prepares the oscillator with the system sample rate.
Definition Oscillator.h:118
T getPhase() const noexcept
Definition Oscillator.h:423
void setPhase(T phase) noexcept
Forces the oscillator phase to a specific value.
Definition Oscillator.h:273
AntiAliasing getAntiAliasing() const noexcept
Returns the discontinuity correction in use (see setAntiAliasing()).
Definition Oscillator.h:187
void prepare(const AudioSpec &spec) noexcept
Prepares the oscillator from an AudioSpec configuration.
Definition Oscillator.h:134
void setAntiAliasing(AntiAliasing mode) noexcept
Selects the discontinuity correction for the non-synced waveforms.
Definition Oscillator.h:179
T getNextSample() noexcept
Computes and returns the next single audio sample.
Definition Oscillator.h:318
T getSample() noexcept
Generator contract alias for getNextSample() (GeneratorProcessor).
Definition Oscillator.h:399
void setWaveform(Waveform w) noexcept
Changes the active waveform.
Definition Oscillator.h:159
T getFrequency() const noexcept
Definition Oscillator.h:424
Main namespace for the DSPark framework.
T fastSin(T x) noexcept
Fast sine approximation (degree-9 odd minimax polynomial).
Definition DspMath.h:340
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37