DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
WavetableOscillator.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
46#include "DspMath.h"
47#include "AudioSpec.h"
48#include "AudioBuffer.h"
49#include "Phasor.h"
50#include "WavetableBank.h"
51
52#include <algorithm>
53#include <cassert>
54#include <cmath>
55
56namespace dspark {
57
64template <FloatType T>
66{
67public:
69 static constexpr int kTableSize = 2048;
70 static constexpr int kTableMask = kTableSize - 1;
73
75
85 void prepare(double sampleRate)
86 {
87 assert(sampleRate > 0.0);
88 if (!(sampleRate > 0.0)) return;
89
90 sampleRate_ = sampleRate;
91 phasor_.prepare(sampleRate);
92 updateMipSelection();
93 }
94
99 void prepare(const AudioSpec& spec)
100 {
101 prepare(spec.sampleRate);
102 }
103
104 // -- Built-in waveform generators (OFFLINE ONLY) ----------------------------
105
110 void buildSaw()
111 {
112 buildFromHarmonics([](int harmonic) -> T {
113 return (harmonic % 2 == 0) ? T(-1.0 / harmonic) : T(1.0 / harmonic);
114 });
115 }
116
122 {
123 buildFromHarmonics([](int harmonic) -> T {
124 return (harmonic % 2 == 0) ? T(0) : T(1.0 / harmonic);
125 });
126 }
127
133 {
134 buildFromHarmonics([](int harmonic) -> T {
135 if (harmonic % 2 == 0) return T(0);
136 T sign = ((harmonic / 2) % 2 == 0) ? T(1) : T(-1);
137 return sign / static_cast<T>(harmonic * harmonic);
138 });
139 }
140
146 {
147 own_.buildFromHarmonics(1, 1, [](int, int) {
148 return WavetableBank::Harmonic { 0.0, 1.0 };
149 });
150 updateMipSelection();
151 }
152
161 template <typename HarmonicFunc>
162 void buildFromHarmonics(HarmonicFunc harmonicFunc)
163 {
164 own_.buildFromHarmonics(1, WavetableBank::kMaxHarmonics, [&](int, int h) {
165 return WavetableBank::Harmonic { 0.0, static_cast<double>(harmonicFunc(h)) };
166 });
167 updateMipSelection();
168 }
169
181 void loadWavetable(const T* data, int size)
182 {
183 if (!data || size < 3) return;
185 updateMipSelection();
186 }
187
195 void setBank(const WavetableBank* bank) noexcept
196 {
197 external_ = bank;
198 updateMipSelection();
199 }
200
205 void setPosition(T position) noexcept
206 {
207 if (position != position) return;
208 position_ = position;
209 }
210
211 [[nodiscard]] T getPosition() const noexcept { return position_; }
212
213 // -- Playback (REAL-TIME SAFE) ----------------------------------------------
214
220 void setFrequency(T frequencyHz) noexcept
221 {
222 // NaN is ignored, mirroring the internal Phasor: otherwise the pitch
223 // would keep the old value while the mip selection went to the
224 // dullest level (inconsistent timbre).
225 if (frequencyHz != frequencyHz) return;
226 const bool changed = frequencyHz != frequency_;
227 frequency_ = frequencyHz;
228 phasor_.setFrequency(frequencyHz);
229 if (changed) updateMipSelection();
230 }
231
236 [[nodiscard]] T getFrequency() const noexcept { return frequency_; }
237
243 [[nodiscard]] inline T getSample() noexcept
244 {
245 const T phase = phasor_.advance();
246 return bank().template read<T>(static_cast<double>(phase),
247 static_cast<double>(position_), mip_);
248 }
249
255 void processBlock(T* output, int numSamples) noexcept
256 {
257 for (int i = 0; i < numSamples; ++i)
258 output[i] = getSample();
259 }
260
265 void generateBlock(AudioBufferView<T> buffer) noexcept
266 {
267 const int nCh = buffer.getNumChannels();
268 const int nS = buffer.getNumSamples();
269 for (int i = 0; i < nS; ++i)
270 {
271 const T s = getSample();
272 for (int ch = 0; ch < nCh; ++ch)
273 buffer.getChannel(ch)[i] = s;
274 }
275 }
276
281 void reset(T phase = T(0)) noexcept
282 {
283 phasor_.reset(phase);
284 }
285
286private:
287 [[nodiscard]] const WavetableBank& bank() const noexcept
288 {
289 return external_ != nullptr ? *external_ : own_;
290 }
291
293 void updateMipSelection() noexcept
294 {
295 mip_ = bank().selectMip(static_cast<double>(frequency_), sampleRate_);
296 }
297
298 double sampleRate_ = 48000.0;
299 T frequency_ = T(440);
300 T position_ = T(0);
301
302 Phasor<T> phasor_;
303
304 WavetableBank own_;
305 const WavetableBank* external_ = nullptr;
306 WavetableBank::Mip mip_;
307};
308
309} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Mipmapped multi-frame wavetable storage and its morphing reader.
static constexpr int kMaxHarmonics
Harmonics of the richest level.
@ PerFrame
Every frame peaks at 1 (equal peak level across a morph).
static constexpr int kMipLevels
Mip levels, half an octave apart.
bool loadFrames(const S *data, int frameSize, int numFrames, Normalization normalization=Normalization::Bank)
Builds the bank from consecutive single-cycle frames.
Mip selectMip(double frequencyHz, double sampleRate) const noexcept
Chooses the level pair and crossfade weight for a pitch.
bool buildFromHarmonics(int numFrames, int numHarmonics, Coefficients &&coefficients, Normalization normalization=Normalization::PerFrame)
Builds the bank from per-frame harmonic amplitudes.
Professional mipmapped wavetable oscillator for bandlimited synthesis.
void prepare(double sampleRate)
Prepares the oscillator for a given sample rate.
void setBank(const WavetableBank *bank) noexcept
Plays an external bank instead of the oscillator's own table.
void buildTriangle()
Builds a bandlimited triangle wavetable with mipmaps.
static constexpr int kTableSize
Samples of the shortest level table (brighter levels hold more; see WavetableBank).
void prepare(const AudioSpec &spec)
Prepares from AudioSpec (unified API).
T getFrequency() const noexcept
Returns the current internal frequency.
void buildFromHarmonics(HarmonicFunc harmonicFunc)
Builds contiguous mipmapped tables from a harmonic amplitude function.
static constexpr int kMaxMipLevels
Mip levels, half an octave apart.
void buildSquare()
Builds a bandlimited square wavetable with mipmaps.
void buildSine()
Builds a pure sine wavetable.
void generateBlock(AudioBufferView< T > buffer) noexcept
Fills every channel of the view with the generated waveform. Satisfies the GeneratorProcessor concept...
void loadWavetable(const T *data, int size)
Loads and analyzes a custom single-cycle wavetable.
T getSample() noexcept
Generates the next sample.
void buildSaw()
Builds a bandlimited sawtooth wavetable with mipmaps.
void reset(T phase=T(0)) noexcept
Hard resets the oscillator phase.
void processBlock(T *output, int numSamples) noexcept
Generates a block of samples.
static constexpr int kTableMask
void setFrequency(T frequencyHz) noexcept
Sets the fundamental oscillation frequency.
void setPosition(T position) noexcept
Morph position across the bank's frames, 0 .. frames - 1 (fractional positions blend adjacent frames;...
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
One harmonic's cosine and sine amplitudes.