DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Synthesizer.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
93#include "DspMath.h"
94#include "AudioSpec.h"
95#include "AudioBuffer.h"
96#include "DenormalGuard.h"
97#include "Oscillator.h"
98#include "EnvelopeGenerator.h"
99#include "Lfo.h"
100#include "WavetableBank.h"
101#include "SampleZone.h"
102#include "AnalogRandom.h"
103#include "Oversampling.h"
104#include "StateBlob.h"
105#include "detail/LadderZdf.h"
106#include "detail/TptSvf.h"
107#include "detail/SampleReader.h"
108
109#include <algorithm>
110#include <array>
111#include <atomic>
112#include <cmath>
113#include <cstdint>
114#include <limits>
115#include <memory>
116#include <numbers>
117#include <span>
118#include <string_view>
119#include <vector>
120
121namespace dspark {
122
128namespace synthesizer {
129
130enum class Engine { Analog, Fm, Wavetable };
131enum class VoiceMode { Poly, Mono, Legato };
132enum class GlideMode { Always, Legato };
133enum class PhaseMode { Reset, Random };
134enum class OscWave { Sine, Triangle, Saw, Pulse };
135enum class SubWave { Square, Triangle, Sine };
137enum class LfoMode { Free, Retrigger };
138
147inline constexpr int kNumModSources = 15;
148
160inline constexpr int kNumModDests = 26;
161
163enum class Param : int
164{
199 Count
200};
201inline constexpr int kNumParams = static_cast<int>(Param::Count);
202
212{
214 const char* id;
215 const char* name;
216 float minValue;
217 float maxValue;
218 float defValue;
219 const char* unit;
220 int steps;
221 const char* const* labels;
222};
223
224inline constexpr int kMaxUnison = 8;
225inline constexpr int kModSlots = 8;
226inline constexpr int kMaxPolyphony = 64;
227
228inline constexpr const char* kEngineLabels[] = { "Analog", "FM", "Wavetable" };
229inline constexpr const char* kVoiceModeLabels[] = { "Poly", "Mono", "Legato" };
230inline constexpr const char* kGlideModeLabels[] = { "Always", "Legato" };
231inline constexpr const char* kPhaseLabels[] = { "Reset", "Random" };
232inline constexpr const char* kOversamplingLabels[] = { "1x", "2x", "4x" };
233inline constexpr const char* kOscWaveLabels[] = { "Sine", "Triangle", "Saw", "Pulse" };
234inline constexpr const char* kSubOctaveLabels[] = { "-1", "-2" };
235inline constexpr const char* kSubWaveLabels[] = { "Square", "Triangle", "Sine" };
236inline constexpr const char* kAlgorithmLabels[] = {
237 "1: 4>3>2>1", "2: (3+4)>2>1", "3: (4 + 3>2)>1", "4: (4>3 + 2)>1",
238 "5: 4>3, 2>1", "6: 4>(1, 2, 3)", "7: 4>3, 2, 1", "8: 1, 2, 3, 4" };
239inline constexpr const char* kBankLabels[] = { "Basic", "Harmonic", "Formant", "FM", "User" };
240inline constexpr const char* kFilterLabels[] = {
241 "Off", "Ladder LP24", "Ladder LP12", "Ladder BP12", "Ladder HP24",
242 "SVF LP", "SVF HP", "SVF BP", "SVF Notch" };
243inline constexpr const char* kLfoShapeLabels[] = {
244 "Sine", "Triangle", "Saw Up", "Saw Down", "Square", "Sample and Hold", "Smooth Random" };
245inline constexpr const char* kDivisionLabels[] = {
246 "8 bars", "4 bars", "2 bars", "1/1", "1/2.", "1/2", "1/2T", "1/4.", "1/4", "1/4T",
247 "1/8.", "1/8", "1/8T", "1/16.", "1/16", "1/16T", "1/32", "1/32T", "1/64" };
248inline constexpr const char* kLfoModeLabels[] = { "Free", "Retrigger" };
249inline constexpr const char* kModSourceLabels[] = {
250 "None", "Velocity", "Release Velocity", "Key", "Mod Wheel", "Pressure", "Pitch Bend",
251 "Expression", "Breath", "LFO 1", "LFO 2", "Env 1", "Env 2", "Env 3", "Random" };
252inline constexpr const char* kModDestLabels[] = {
253 "None", "Pitch", "Osc 1 Pitch", "Osc 2 Pitch", "Osc 3 Pitch", "Osc 1 Level",
254 "Osc 2 Level", "Osc 3 Level", "Sub Level", "Noise Level", "Sample Level",
255 "Pulse Width", "WT Position", "WT 1 Position", "WT 2 Position", "Op 1 Level",
256 "Op 2 Level", "Op 3 Level", "Op 4 Level", "FM Feedback", "Cutoff", "Resonance",
257 "Amp", "Pan", "LFO 1 Rate", "LFO 2 Rate" };
258
259namespace table {
260constexpr ParamInfo cont(Param p, const char* id, const char* name, float lo, float hi,
261 float def, const char* unit) noexcept
262{
263 return { p, id, name, lo, hi, def, unit, 0, nullptr };
264}
265constexpr ParamInfo integer(Param p, const char* id, const char* name, int lo, int hi,
266 int def, const char* unit) noexcept
267{
268 return { p, id, name, static_cast<float>(lo), static_cast<float>(hi),
269 static_cast<float>(def), unit, hi - lo, nullptr };
270}
271constexpr ParamInfo toggle(Param p, const char* id, const char* name, bool def) noexcept
272{
273 return { p, id, name, 0.0f, 1.0f, def ? 1.0f : 0.0f, "", 1, nullptr };
274}
275template <size_t N>
276constexpr ParamInfo choice(Param p, const char* id, const char* name,
277 const char* const (&labels)[N], int def) noexcept
278{
279 return { p, id, name, 0.0f, static_cast<float>(N - 1), static_cast<float>(def), "",
280 static_cast<int>(N - 1), labels };
281}
282} // namespace table
283
285inline constexpr std::array<ParamInfo, kNumParams> kParams = {{
286 table::choice(Param::Engine, "engine", "Engine", kEngineLabels, 0),
287 table::choice(Param::VoiceMode, "voice.mode", "Voice Mode", kVoiceModeLabels, 0),
288 table::integer(Param::Polyphony, "voice.polyphony", "Polyphony", 1, kMaxPolyphony, 16, "voices"),
289 table::cont(Param::Glide, "voice.glide", "Glide", 0.0f, 10000.0f, 0.0f, "ms"),
290 table::choice(Param::GlideMode, "voice.glideMode", "Glide Mode", kGlideModeLabels, 0),
291 table::integer(Param::BendRange, "voice.bendRange", "Bend Range", 0, 48, 2, "st"),
292 table::integer(Param::Unison, "voice.unison", "Unison", 1, kMaxUnison, 1, ""),
293 table::cont(Param::UnisonDetune, "voice.unisonDetune", "Unison Detune", 0.0f, 100.0f, 20.0f, "cents"),
294 table::cont(Param::UnisonSpread, "voice.unisonSpread", "Unison Spread", 0.0f, 1.0f, 0.5f, ""),
295 table::cont(Param::Drift, "voice.drift", "Analog Drift", 0.0f, 1.0f, 0.0f, ""),
296 table::integer(Param::Seed, "voice.seed", "Seed", 0, 65535, 0, ""),
297 table::choice(Param::PhaseMode, "voice.phase", "Oscillator Phase", kPhaseLabels, 0),
298 table::cont(Param::MasterVolume, "master.volume", "Volume", -60.0f, 12.0f, -6.0f, "dB"),
299 table::cont(Param::MasterTune, "master.tune", "Tune", -100.0f, 100.0f, 0.0f, "cents"),
300 table::choice(Param::Oversampling, "quality.oversampling", "Oversampling", kOversamplingLabels, 0),
301
302 table::choice(Param::Osc1Wave, "osc1.wave", "Osc 1 Wave", kOscWaveLabels, 2),
303 table::cont(Param::Osc1Level, "osc1.level", "Osc 1 Level", 0.0f, 1.0f, 1.0f, ""),
304 table::integer(Param::Osc1Octave, "osc1.octave", "Osc 1 Octave", -3, 3, 0, ""),
305 table::integer(Param::Osc1Semitone, "osc1.semitone", "Osc 1 Semitone", -12, 12, 0, "st"),
306 table::cont(Param::Osc1Fine, "osc1.fine", "Osc 1 Fine", -100.0f, 100.0f, 0.0f, "cents"),
307 table::cont(Param::Osc1PulseWidth, "osc1.pulseWidth", "Osc 1 Pulse Width", 0.01f, 0.99f, 0.5f, ""),
308 table::toggle(Param::Osc1Sync, "osc1.sync", "Osc 1 Sync", false),
309 table::choice(Param::Osc2Wave, "osc2.wave", "Osc 2 Wave", kOscWaveLabels, 2),
310 table::cont(Param::Osc2Level, "osc2.level", "Osc 2 Level", 0.0f, 1.0f, 0.0f, ""),
311 table::integer(Param::Osc2Octave, "osc2.octave", "Osc 2 Octave", -3, 3, 0, ""),
312 table::integer(Param::Osc2Semitone, "osc2.semitone", "Osc 2 Semitone", -12, 12, 0, "st"),
313 table::cont(Param::Osc2Fine, "osc2.fine", "Osc 2 Fine", -100.0f, 100.0f, 0.0f, "cents"),
314 table::cont(Param::Osc2PulseWidth, "osc2.pulseWidth", "Osc 2 Pulse Width", 0.01f, 0.99f, 0.5f, ""),
315 table::toggle(Param::Osc2Sync, "osc2.sync", "Osc 2 Sync", false),
316 table::choice(Param::Osc3Wave, "osc3.wave", "Osc 3 Wave", kOscWaveLabels, 2),
317 table::cont(Param::Osc3Level, "osc3.level", "Osc 3 Level", 0.0f, 1.0f, 0.0f, ""),
318 table::integer(Param::Osc3Octave, "osc3.octave", "Osc 3 Octave", -3, 3, 0, ""),
319 table::integer(Param::Osc3Semitone, "osc3.semitone", "Osc 3 Semitone", -12, 12, 0, "st"),
320 table::cont(Param::Osc3Fine, "osc3.fine", "Osc 3 Fine", -100.0f, 100.0f, 0.0f, "cents"),
321 table::cont(Param::Osc3PulseWidth, "osc3.pulseWidth", "Osc 3 Pulse Width", 0.01f, 0.99f, 0.5f, ""),
322 table::toggle(Param::Osc3Sync, "osc3.sync", "Osc 3 Sync", false),
323
324 table::cont(Param::SubLevel, "sub.level", "Sub Level", 0.0f, 1.0f, 0.0f, ""),
325 table::choice(Param::SubOctave, "sub.octave", "Sub Octave", kSubOctaveLabels, 0),
326 table::choice(Param::SubWave, "sub.wave", "Sub Wave", kSubWaveLabels, 0),
327 table::cont(Param::NoiseLevel, "noise.level", "Noise Level", 0.0f, 1.0f, 0.0f, ""),
328 table::cont(Param::SampleLevel, "sample.level", "Sample Level", 0.0f, 1.0f, 0.0f, ""),
329 table::integer(Param::SampleOctave, "sample.octave", "Sample Octave", -3, 3, 0, ""),
330 table::integer(Param::SampleSemitone, "sample.semitone", "Sample Semitone", -12, 12, 0, "st"),
331 table::cont(Param::SampleFine, "sample.fine", "Sample Fine", -100.0f, 100.0f, 0.0f, "cents"),
332 table::toggle(Param::SampleKeyTrack, "sample.keyTrack", "Sample Key Track", true),
333
334 table::choice(Param::FmAlgorithm, "fm.algorithm", "FM Algorithm", kAlgorithmLabels, 0),
335 table::cont(Param::FmFeedback, "fm.feedback", "FM Feedback", 0.0f, 1.0f, 0.0f, ""),
336 table::cont(Param::Op1Ratio, "op1.ratio", "Op 1 Ratio", 0.25f, 32.0f, 1.0f, ""),
337 table::cont(Param::Op1Detune, "op1.detune", "Op 1 Detune", -100.0f, 100.0f, 0.0f, "cents"),
338 table::toggle(Param::Op1Fixed, "op1.fixed", "Op 1 Fixed", false),
339 table::cont(Param::Op1Frequency, "op1.frequency", "Op 1 Frequency", 1.0f, 20000.0f, 440.0f, "Hz"),
340 table::cont(Param::Op1Level, "op1.level", "Op 1 Level", 0.0f, 1.0f, 1.0f, ""),
341 table::cont(Param::Op1Velocity, "op1.velocity", "Op 1 Velocity", 0.0f, 1.0f, 0.0f, ""),
342 table::cont(Param::Op1KeyScale, "op1.keyScale", "Op 1 Key Scale", -1.0f, 1.0f, 0.0f, ""),
343 table::cont(Param::Op1Attack, "op1.attack", "Op 1 Attack", 0.0f, 20000.0f, 1.0f, "ms"),
344 table::cont(Param::Op1Decay, "op1.decay", "Op 1 Decay", 0.0f, 20000.0f, 500.0f, "ms"),
345 table::cont(Param::Op1Sustain, "op1.sustain", "Op 1 Sustain", 0.0f, 1.0f, 1.0f, ""),
346 table::cont(Param::Op1Release, "op1.release", "Op 1 Release", 0.0f, 20000.0f, 300.0f, "ms"),
347 table::cont(Param::Op2Ratio, "op2.ratio", "Op 2 Ratio", 0.25f, 32.0f, 1.0f, ""),
348 table::cont(Param::Op2Detune, "op2.detune", "Op 2 Detune", -100.0f, 100.0f, 0.0f, "cents"),
349 table::toggle(Param::Op2Fixed, "op2.fixed", "Op 2 Fixed", false),
350 table::cont(Param::Op2Frequency, "op2.frequency", "Op 2 Frequency", 1.0f, 20000.0f, 440.0f, "Hz"),
351 table::cont(Param::Op2Level, "op2.level", "Op 2 Level", 0.0f, 1.0f, 0.0f, ""),
352 table::cont(Param::Op2Velocity, "op2.velocity", "Op 2 Velocity", 0.0f, 1.0f, 0.0f, ""),
353 table::cont(Param::Op2KeyScale, "op2.keyScale", "Op 2 Key Scale", -1.0f, 1.0f, 0.0f, ""),
354 table::cont(Param::Op2Attack, "op2.attack", "Op 2 Attack", 0.0f, 20000.0f, 1.0f, "ms"),
355 table::cont(Param::Op2Decay, "op2.decay", "Op 2 Decay", 0.0f, 20000.0f, 500.0f, "ms"),
356 table::cont(Param::Op2Sustain, "op2.sustain", "Op 2 Sustain", 0.0f, 1.0f, 1.0f, ""),
357 table::cont(Param::Op2Release, "op2.release", "Op 2 Release", 0.0f, 20000.0f, 300.0f, "ms"),
358 table::cont(Param::Op3Ratio, "op3.ratio", "Op 3 Ratio", 0.25f, 32.0f, 1.0f, ""),
359 table::cont(Param::Op3Detune, "op3.detune", "Op 3 Detune", -100.0f, 100.0f, 0.0f, "cents"),
360 table::toggle(Param::Op3Fixed, "op3.fixed", "Op 3 Fixed", false),
361 table::cont(Param::Op3Frequency, "op3.frequency", "Op 3 Frequency", 1.0f, 20000.0f, 440.0f, "Hz"),
362 table::cont(Param::Op3Level, "op3.level", "Op 3 Level", 0.0f, 1.0f, 0.0f, ""),
363 table::cont(Param::Op3Velocity, "op3.velocity", "Op 3 Velocity", 0.0f, 1.0f, 0.0f, ""),
364 table::cont(Param::Op3KeyScale, "op3.keyScale", "Op 3 Key Scale", -1.0f, 1.0f, 0.0f, ""),
365 table::cont(Param::Op3Attack, "op3.attack", "Op 3 Attack", 0.0f, 20000.0f, 1.0f, "ms"),
366 table::cont(Param::Op3Decay, "op3.decay", "Op 3 Decay", 0.0f, 20000.0f, 500.0f, "ms"),
367 table::cont(Param::Op3Sustain, "op3.sustain", "Op 3 Sustain", 0.0f, 1.0f, 1.0f, ""),
368 table::cont(Param::Op3Release, "op3.release", "Op 3 Release", 0.0f, 20000.0f, 300.0f, "ms"),
369 table::cont(Param::Op4Ratio, "op4.ratio", "Op 4 Ratio", 0.25f, 32.0f, 1.0f, ""),
370 table::cont(Param::Op4Detune, "op4.detune", "Op 4 Detune", -100.0f, 100.0f, 0.0f, "cents"),
371 table::toggle(Param::Op4Fixed, "op4.fixed", "Op 4 Fixed", false),
372 table::cont(Param::Op4Frequency, "op4.frequency", "Op 4 Frequency", 1.0f, 20000.0f, 440.0f, "Hz"),
373 table::cont(Param::Op4Level, "op4.level", "Op 4 Level", 0.0f, 1.0f, 0.0f, ""),
374 table::cont(Param::Op4Velocity, "op4.velocity", "Op 4 Velocity", 0.0f, 1.0f, 0.0f, ""),
375 table::cont(Param::Op4KeyScale, "op4.keyScale", "Op 4 Key Scale", -1.0f, 1.0f, 0.0f, ""),
376 table::cont(Param::Op4Attack, "op4.attack", "Op 4 Attack", 0.0f, 20000.0f, 1.0f, "ms"),
377 table::cont(Param::Op4Decay, "op4.decay", "Op 4 Decay", 0.0f, 20000.0f, 500.0f, "ms"),
378 table::cont(Param::Op4Sustain, "op4.sustain", "Op 4 Sustain", 0.0f, 1.0f, 1.0f, ""),
379 table::cont(Param::Op4Release, "op4.release", "Op 4 Release", 0.0f, 20000.0f, 300.0f, "ms"),
380
381 table::choice(Param::Wt1Bank, "wt1.bank", "WT 1 Bank", kBankLabels, 0),
382 table::cont(Param::Wt1Position, "wt1.position", "WT 1 Position", 0.0f, 1.0f, 0.0f, ""),
383 table::cont(Param::Wt1Level, "wt1.level", "WT 1 Level", 0.0f, 1.0f, 1.0f, ""),
384 table::integer(Param::Wt1Octave, "wt1.octave", "WT 1 Octave", -3, 3, 0, ""),
385 table::integer(Param::Wt1Semitone, "wt1.semitone", "WT 1 Semitone", -12, 12, 0, "st"),
386 table::cont(Param::Wt1Fine, "wt1.fine", "WT 1 Fine", -100.0f, 100.0f, 0.0f, "cents"),
387 table::choice(Param::Wt2Bank, "wt2.bank", "WT 2 Bank", kBankLabels, 0),
388 table::cont(Param::Wt2Position, "wt2.position", "WT 2 Position", 0.0f, 1.0f, 0.0f, ""),
389 table::cont(Param::Wt2Level, "wt2.level", "WT 2 Level", 0.0f, 1.0f, 0.0f, ""),
390 table::integer(Param::Wt2Octave, "wt2.octave", "WT 2 Octave", -3, 3, 0, ""),
391 table::integer(Param::Wt2Semitone, "wt2.semitone", "WT 2 Semitone", -12, 12, 0, "st"),
392 table::cont(Param::Wt2Fine, "wt2.fine", "WT 2 Fine", -100.0f, 100.0f, 0.0f, "cents"),
393
394 table::choice(Param::FilterType, "filter.type", "Filter Type", kFilterLabels, 1),
395 table::cont(Param::FilterCutoff, "filter.cutoff", "Cutoff", 20.0f, 20000.0f, 20000.0f, "Hz"),
396 table::cont(Param::FilterResonance, "filter.resonance", "Resonance", 0.0f, 1.0f, 0.0f, ""),
397 table::cont(Param::FilterDrive, "filter.drive", "Drive", 1.0f, 10.0f, 1.0f, ""),
398 table::cont(Param::FilterKeyTrack, "filter.keyTrack", "Key Track", 0.0f, 1.0f, 0.0f, ""),
399 table::cont(Param::FilterEnvAmount, "filter.envAmount", "Env Amount", -10.0f, 10.0f, 0.0f, "oct"),
400 table::cont(Param::FilterVelocity, "filter.velocity", "Velocity to Env", 0.0f, 1.0f, 0.0f, ""),
401 table::cont(Param::AmpVelocity, "amp.velocity", "Velocity Range", 0.0f, 60.0f, 24.0f, "dB"),
402 table::cont(Param::AmpPan, "amp.pan", "Pan", -1.0f, 1.0f, 0.0f, ""),
403
404 table::cont(Param::Env1Attack, "env1.attack", "Env 1 Attack", 0.0f, 20000.0f, 2.0f, "ms"),
405 table::cont(Param::Env1Decay, "env1.decay", "Env 1 Decay", 0.0f, 20000.0f, 300.0f, "ms"),
406 table::cont(Param::Env1Sustain, "env1.sustain", "Env 1 Sustain", 0.0f, 1.0f, 1.0f, ""),
407 table::cont(Param::Env1Release, "env1.release", "Env 1 Release", 0.0f, 20000.0f, 300.0f, "ms"),
408 table::cont(Param::Env1Curve, "env1.curve", "Env 1 Curve", 0.1f, 10.0f, 3.0f, ""),
409 table::cont(Param::Env2Attack, "env2.attack", "Env 2 Attack", 0.0f, 20000.0f, 2.0f, "ms"),
410 table::cont(Param::Env2Decay, "env2.decay", "Env 2 Decay", 0.0f, 20000.0f, 400.0f, "ms"),
411 table::cont(Param::Env2Sustain, "env2.sustain", "Env 2 Sustain", 0.0f, 1.0f, 0.0f, ""),
412 table::cont(Param::Env2Release, "env2.release", "Env 2 Release", 0.0f, 20000.0f, 300.0f, "ms"),
413 table::cont(Param::Env2Curve, "env2.curve", "Env 2 Curve", 0.1f, 10.0f, 3.0f, ""),
414 table::cont(Param::Env3Attack, "env3.attack", "Env 3 Attack", 0.0f, 20000.0f, 2.0f, "ms"),
415 table::cont(Param::Env3Decay, "env3.decay", "Env 3 Decay", 0.0f, 20000.0f, 300.0f, "ms"),
416 table::cont(Param::Env3Sustain, "env3.sustain", "Env 3 Sustain", 0.0f, 1.0f, 0.0f, ""),
417 table::cont(Param::Env3Release, "env3.release", "Env 3 Release", 0.0f, 20000.0f, 300.0f, "ms"),
418 table::cont(Param::Env3Curve, "env3.curve", "Env 3 Curve", 0.1f, 10.0f, 3.0f, ""),
419
420 table::choice(Param::Lfo1Shape, "lfo1.shape", "LFO 1 Shape", kLfoShapeLabels, 0),
421 table::cont(Param::Lfo1Rate, "lfo1.rate", "LFO 1 Rate", 0.01f, 100.0f, 5.0f, "Hz"),
422 table::toggle(Param::Lfo1Sync, "lfo1.sync", "LFO 1 Tempo Sync", false),
423 table::choice(Param::Lfo1Division, "lfo1.division", "LFO 1 Division", kDivisionLabels, 8),
424 table::cont(Param::Lfo1Delay, "lfo1.delay", "LFO 1 Delay", 0.0f, 10000.0f, 0.0f, "ms"),
425 table::cont(Param::Lfo1FadeIn, "lfo1.fadeIn", "LFO 1 Fade In", 0.0f, 10000.0f, 0.0f, "ms"),
426 table::cont(Param::Lfo1Phase, "lfo1.phase", "LFO 1 Phase", 0.0f, 1.0f, 0.0f, ""),
427 table::choice(Param::Lfo1Mode, "lfo1.mode", "LFO 1 Mode", kLfoModeLabels, 1),
428 table::choice(Param::Lfo2Shape, "lfo2.shape", "LFO 2 Shape", kLfoShapeLabels, 0),
429 table::cont(Param::Lfo2Rate, "lfo2.rate", "LFO 2 Rate", 0.01f, 100.0f, 5.0f, "Hz"),
430 table::toggle(Param::Lfo2Sync, "lfo2.sync", "LFO 2 Tempo Sync", false),
431 table::choice(Param::Lfo2Division, "lfo2.division", "LFO 2 Division", kDivisionLabels, 8),
432 table::cont(Param::Lfo2Delay, "lfo2.delay", "LFO 2 Delay", 0.0f, 10000.0f, 0.0f, "ms"),
433 table::cont(Param::Lfo2FadeIn, "lfo2.fadeIn", "LFO 2 Fade In", 0.0f, 10000.0f, 0.0f, "ms"),
434 table::cont(Param::Lfo2Phase, "lfo2.phase", "LFO 2 Phase", 0.0f, 1.0f, 0.0f, ""),
435 table::choice(Param::Lfo2Mode, "lfo2.mode", "LFO 2 Mode", kLfoModeLabels, 1),
436
437 table::choice(Param::Mod1Source, "mod1.source", "Mod 1 Source", kModSourceLabels, 0),
438 table::choice(Param::Mod1Via, "mod1.via", "Mod 1 Via", kModSourceLabels, 0),
439 table::choice(Param::Mod1Destination, "mod1.destination", "Mod 1 Destination", kModDestLabels, 0),
440 table::cont(Param::Mod1Amount, "mod1.amount", "Mod 1 Amount", -48.0f, 48.0f, 0.0f, ""),
441 table::choice(Param::Mod2Source, "mod2.source", "Mod 2 Source", kModSourceLabels, 0),
442 table::choice(Param::Mod2Via, "mod2.via", "Mod 2 Via", kModSourceLabels, 0),
443 table::choice(Param::Mod2Destination, "mod2.destination", "Mod 2 Destination", kModDestLabels, 0),
444 table::cont(Param::Mod2Amount, "mod2.amount", "Mod 2 Amount", -48.0f, 48.0f, 0.0f, ""),
445 table::choice(Param::Mod3Source, "mod3.source", "Mod 3 Source", kModSourceLabels, 0),
446 table::choice(Param::Mod3Via, "mod3.via", "Mod 3 Via", kModSourceLabels, 0),
447 table::choice(Param::Mod3Destination, "mod3.destination", "Mod 3 Destination", kModDestLabels, 0),
448 table::cont(Param::Mod3Amount, "mod3.amount", "Mod 3 Amount", -48.0f, 48.0f, 0.0f, ""),
449 table::choice(Param::Mod4Source, "mod4.source", "Mod 4 Source", kModSourceLabels, 0),
450 table::choice(Param::Mod4Via, "mod4.via", "Mod 4 Via", kModSourceLabels, 0),
451 table::choice(Param::Mod4Destination, "mod4.destination", "Mod 4 Destination", kModDestLabels, 0),
452 table::cont(Param::Mod4Amount, "mod4.amount", "Mod 4 Amount", -48.0f, 48.0f, 0.0f, ""),
453 table::choice(Param::Mod5Source, "mod5.source", "Mod 5 Source", kModSourceLabels, 0),
454 table::choice(Param::Mod5Via, "mod5.via", "Mod 5 Via", kModSourceLabels, 0),
455 table::choice(Param::Mod5Destination, "mod5.destination", "Mod 5 Destination", kModDestLabels, 0),
456 table::cont(Param::Mod5Amount, "mod5.amount", "Mod 5 Amount", -48.0f, 48.0f, 0.0f, ""),
457 table::choice(Param::Mod6Source, "mod6.source", "Mod 6 Source", kModSourceLabels, 0),
458 table::choice(Param::Mod6Via, "mod6.via", "Mod 6 Via", kModSourceLabels, 0),
459 table::choice(Param::Mod6Destination, "mod6.destination", "Mod 6 Destination", kModDestLabels, 0),
460 table::cont(Param::Mod6Amount, "mod6.amount", "Mod 6 Amount", -48.0f, 48.0f, 0.0f, ""),
461 table::choice(Param::Mod7Source, "mod7.source", "Mod 7 Source", kModSourceLabels, 0),
462 table::choice(Param::Mod7Via, "mod7.via", "Mod 7 Via", kModSourceLabels, 0),
463 table::choice(Param::Mod7Destination, "mod7.destination", "Mod 7 Destination", kModDestLabels, 0),
464 table::cont(Param::Mod7Amount, "mod7.amount", "Mod 7 Amount", -48.0f, 48.0f, 0.0f, ""),
465 table::choice(Param::Mod8Source, "mod8.source", "Mod 8 Source", kModSourceLabels, 0),
466 table::choice(Param::Mod8Via, "mod8.via", "Mod 8 Via", kModSourceLabels, 0),
467 table::choice(Param::Mod8Destination, "mod8.destination", "Mod 8 Destination", kModDestLabels, 0),
468 table::cont(Param::Mod8Amount, "mod8.amount", "Mod 8 Amount", -48.0f, 48.0f, 0.0f, ""),
469}};
470
473constexpr bool tableIsConsistent() noexcept
474{
475 std::array<std::string_view, kNumParams> ids {};
476 for (int i = 0; i < kNumParams; ++i)
477 {
478 const ParamInfo& a = kParams[static_cast<size_t>(i)];
479 if (static_cast<int>(a.param) != i) return false;
480 if (!(a.minValue <= a.defValue && a.defValue <= a.maxValue)) return false;
481 ids[static_cast<size_t>(i)] = a.id;
482 }
483 // Sorted, so duplicates are neighbours: within every compiler's
484 // constant-evaluation budget, unlike comparing all pairs.
485 std::sort(ids.begin(), ids.end());
486 return std::adjacent_find(ids.begin(), ids.end()) == ids.end();
487}
488static_assert(tableIsConsistent(), "Synthesizer parameter table out of order, duplicated or out of range");
489
491[[nodiscard]] inline int findParam(std::string_view id) noexcept
492{
493 for (int i = 0; i < kNumParams; ++i)
494 if (id == kParams[static_cast<size_t>(i)].id) return i;
495 return -1;
496}
497
498} // namespace synthesizer
499
519template <FloatType T>
521{
522public:
526 static constexpr int kMaxEvents = 1024;
527
540
541 static constexpr int kNumParams = synthesizer::kNumParams;
542 static constexpr int kMaxUnison = synthesizer::kMaxUnison;
543 static constexpr int kModSlots = synthesizer::kModSlots;
546 static constexpr int kControlPeriod = 16;
547
549 [[nodiscard]] static constexpr const ParamInfo& getParamInfo(Param p) noexcept
550 {
551 return synthesizer::kParams[static_cast<size_t>(std::clamp(static_cast<int>(p), 0, kNumParams - 1))];
552 }
553
555 [[nodiscard]] static int findParam(std::string_view id) noexcept { return synthesizer::findParam(id); }
556
557 // -- Construction ---------------------------------------------------------------
558
559 Synthesizer() noexcept
560 {
561 for (int i = 0; i < kNumParams; ++i)
562 {
563 values_[static_cast<size_t>(i)].store(info(i).defValue, std::memory_order_relaxed);
564 params_[static_cast<size_t>(i)] = info(i).defValue;
565 }
566 }
567
569 {
570 delete pending_.exchange(nullptr, std::memory_order_acq_rel);
571 delete retired_.exchange(nullptr, std::memory_order_acq_rel);
572 delete fading_;
573 delete active_;
574 }
575
576 Synthesizer(const Synthesizer&) = delete;
578
579 // -- Lifecycle ------------------------------------------------------------------
580
589 void prepare(const AudioSpec& spec, int maxVoices = 16)
590 {
591 if (!(spec.sampleRate > 0.0) || !std::isfinite(spec.sampleRate) || spec.maxBlockSize < 1)
592 return;
593 prepared_ = false;
594 baseRate_ = spec.sampleRate;
595 maxBlock_ = spec.maxBlockSize;
596 maxVoices_ = std::clamp(maxVoices, 1, kMaxPolyphony);
597 voices_ = std::vector<Voice>(static_cast<size_t>(2 * maxVoices_ + 2));
598 for (auto& v : voices_)
599 for (auto& u : v.uni) u.reader.allocate();
600 weights_.assign(static_cast<size_t>(Reader::kWeightsLength), T(0));
601 for (auto& b : mix_) b.assign(static_cast<size_t>(maxBlock_), T(0));
602 const AudioSpec osSpec { baseRate_, maxBlock_, 2 };
603 os2_.prepare(osSpec);
604 os4_.prepare(osSpec);
605 // Shared tables, built here and never on the audio thread.
607 for (int b = 0; b < WavetableBank::kNumBuiltins; ++b)
608 (void)WavetableBank::builtin(static_cast<WavetableBank::Builtin>(b));
610
611 snapshotParameters(true);
612 configureRate(oversamplingFactor());
613 reset();
614 prepared_ = true;
615 }
616
619 void reset() noexcept
620 {
621 for (auto& v : voices_) v.active = false;
622 eventCount_ = 0;
623 sustainPedal_ = false;
624 bend_ = 0.0;
625 modWheel_ = 0.0;
626 pressure_ = 0.0;
627 expression_ = 1.0;
628 breath_ = 0.0;
629 noteCounter_ = 0;
630 clock_ = 0;
631 timeHi_ = 0;
632 heldCount_ = 0;
633 lastPitch_ = -1.0;
634 haveLastPitch_ = false;
635 for (int k = 0; k < 2; ++k)
636 {
637 freeLfo_[static_cast<size_t>(k)].anchorCycles = p(lfoParam(k, 6));
638 freeLfo_[static_cast<size_t>(k)].anchorTime = 0;
639 }
640 masterGain_ = decibelsToGain(static_cast<double>(p(Param::MasterVolume)), -200.0);
641 os2_.reset();
642 os4_.reset();
643 activeVoices_.store(0, std::memory_order_relaxed);
644 }
645
647 [[nodiscard]] int getLatency() const noexcept { return latency_.load(std::memory_order_relaxed); }
648
650 [[nodiscard]] int getActiveVoiceCount() const noexcept
651 {
652 return activeVoices_.load(std::memory_order_relaxed);
653 }
654
656 [[nodiscard]] int getMaxVoices() const noexcept { return maxVoices_; }
657
658 // -- Parameters (any thread) ------------------------------------------------------
659
662 void setParameter(Param param, float value) noexcept
663 {
664 const int i = static_cast<int>(param);
665 if (i < 0 || i >= kNumParams || value != value) return;
666 const ParamInfo& pinfo = info(i);
667 float v = std::clamp(value, pinfo.minValue, pinfo.maxValue);
668 if (pinfo.steps > 0) v = std::round(v);
669 values_[static_cast<size_t>(i)].store(v, std::memory_order_relaxed);
670 }
671
673 bool setParameter(std::string_view id, float value) noexcept
674 {
675 const int i = findParam(id);
676 if (i < 0) return false;
677 setParameter(static_cast<Param>(i), value);
678 return true;
679 }
680
682 [[nodiscard]] float getParameter(Param param) const noexcept
683 {
684 const int i = std::clamp(static_cast<int>(param), 0, kNumParams - 1);
685 return values_[static_cast<size_t>(i)].load(std::memory_order_relaxed);
686 }
687
689 void setTempo(double bpm) noexcept
690 {
691 if (!(bpm >= 1.0) || !(bpm <= 999.0)) return;
692 tempo_.store(static_cast<float>(bpm), std::memory_order_relaxed);
693 }
694
695 // -- Samples and wavetables (control thread) ------------------------------------------
696
707 bool setSampleZones(std::span<const SampleZoneSpec<T>> zones)
708 {
709 auto built = std::make_shared<std::vector<ZoneData>>();
710 built->reserve(zones.size());
711 for (const auto& z : zones)
712 {
713 ZoneData d;
714 if (!detail::buildSampleZone(z, d)) return false;
715 built->push_back(std::move(d));
716 }
717 controlZones_ = std::move(built);
718 publishContent();
719 return true;
720 }
721
723 bool loadSample(AudioBufferView<const T> audio, double sampleRate, int rootKey = 60)
724 {
726 z.audio = audio;
727 z.sampleRate = sampleRate;
728 z.rootKey = rootKey;
729 return setSampleZones(std::span<const SampleZoneSpec<T>>(&z, 1));
730 }
731
734 {
735 controlZones_.reset();
736 publishContent();
737 }
738
744 bool loadUserWavetable(const T* frames, int frameSize, int numFrames)
745 {
746 auto bank = std::make_shared<WavetableBank>();
747 if (!bank->loadFrames(frames, frameSize, numFrames)) return false;
748 controlWavetable_ = std::move(bank);
749 publishContent();
750 return true;
751 }
752
753 // -- Events (audio thread) -------------------------------------------------------------
754
757 void noteOn(int key, T velocity, int offset = 0) noexcept
758 {
759 noteOnTuned(key, velocity, T(0), offset);
760 }
761
770 void noteOnTuned(int key, T velocity, T tuningCents, int offset = 0) noexcept
771 {
772 if (!std::isfinite(velocity) || !std::isfinite(tuningCents)) return;
773 if (velocity <= T(0)) { noteOff(key, T(0), offset); return; }
774 push({ EventType::NoteOn, std::clamp(key, 0, 127),
775 std::clamp(static_cast<double>(velocity), 0.0, 1.0), offset,
776 std::clamp(static_cast<double>(tuningCents), -100.0, 100.0) });
777 }
778
780 void noteOff(int key, T releaseVelocity = T(0), int offset = 0) noexcept
781 {
782 const double rv = std::isfinite(releaseVelocity) ? static_cast<double>(releaseVelocity) : 0.0;
783 push({ EventType::NoteOff, std::clamp(key, 0, 127), std::clamp(rv, 0.0, 1.0), offset });
784 }
785
787 void setPitchBend(T bend, int offset = 0) noexcept
788 {
789 if (!std::isfinite(bend)) return;
790 push({ EventType::Bend, 0, std::clamp(static_cast<double>(bend), -1.0, 1.0), offset });
791 }
792
794 void setModWheel(T value, int offset = 0) noexcept { pushController(EventType::ModWheel, 0, value, offset); }
795
797 void setChannelPressure(T value, int offset = 0) noexcept { pushController(EventType::Pressure, 0, value, offset); }
798
800 void setPolyPressure(int key, T value, int offset = 0) noexcept
801 {
802 pushController(EventType::PolyPressure, std::clamp(key, 0, 127), value, offset);
803 }
804
806 void setSustainPedal(bool down, int offset = 0) noexcept
807 {
808 push({ EventType::Pedal, 0, down ? 1.0 : 0.0, offset });
809 }
810
817 void setController(int controller, T value, int offset = 0) noexcept
818 {
819 switch (controller)
820 {
821 case 1: setModWheel(value, offset); break;
822 case 2: pushController(EventType::Breath, 0, value, offset); break;
823 case 11: pushController(EventType::Expression, 0, value, offset); break;
824 case 64: if (std::isfinite(value)) setSustainPedal(value >= T(0.5), offset); break;
825 case 120:
826 case 123: allNotesOff(offset); break;
827 default: break;
828 }
829 }
830
832 void allNotesOff(int offset = 0) noexcept { push({ EventType::AllOff, 0, 0.0, offset }); }
833
834 // -- Processing (audio thread) ------------------------------------------------------
835
842 {
843 DenormalGuard guard;
844 const int n = out.getNumSamples();
845 const int nCh = out.getNumChannels();
846 for (int c = 0; c < nCh; ++c)
847 std::fill_n(out.getChannel(c), n, T(0));
848 if (!prepared_) { eventCount_ = 0; return; }
849 if (n <= 0) return; // a host flush: the queued events wait for real samples
850
851 adoptPending();
852 snapshotParameters(false);
853
854 int e = 0;
855 for (int start = 0; start < n; start += maxBlock_)
856 {
857 const int len = std::min(maxBlock_, n - start);
858 renderPiece(out, start, len, e, start + len >= n);
859 }
860 eventCount_ = 0;
861
862 retireFadedContent();
863 int count = 0;
864 for (const auto& v : voices_) count += v.active ? 1 : 0;
865 activeVoices_.store(count, std::memory_order_relaxed);
866 }
867
868 // -- State (setup/UI thread) ----------------------------------------------------------
869
872 [[nodiscard]] std::vector<uint8_t> getState() const
873 {
874 StateWriter w(stateId("SYNT"), 1);
875 for (int i = 0; i < kNumParams; ++i)
876 w.write(info(i).id, values_[static_cast<size_t>(i)].load(std::memory_order_relaxed));
877 return w.blob();
878 }
879
882 bool setState(const uint8_t* data, size_t size)
883 {
884 StateReader r(data, size);
885 if (!r.isValid() || r.processorId() != stateId("SYNT")) return false;
886 for (int i = 0; i < kNumParams; ++i)
887 setParameter(static_cast<Param>(i), r.read(info(i).id, info(i).defValue));
888 return true;
889 }
890
891private:
892 // ===================================================================================
893 // Types
894 // ===================================================================================
895
896 using Reader = detail::SampleReader<T>;
897 using ZoneData = detail::SampleZoneData<T>;
898
899 [[nodiscard]] static constexpr const ParamInfo& info(int i) noexcept
900 {
901 return synthesizer::kParams[static_cast<size_t>(i)];
902 }
903
905 struct Content
906 {
907 std::shared_ptr<const std::vector<ZoneData>> zones;
908 std::shared_ptr<const WavetableBank> wavetable;
909 };
910
914 struct Ramp
915 {
916 double start = 0.0, step = 0.0, target = 0.0;
917 [[nodiscard]] double at(int pos) const noexcept { return start + step * static_cast<double>(pos); }
918 void to(double next, double invPeriod) noexcept
919 {
920 start = target;
921 target = next;
922 step = (next - start) * invPeriod;
923 }
924 void snap(double value) noexcept { start = target = value; step = 0.0; }
925 [[nodiscard]] bool live() const noexcept { return start > 0.0 || target > 0.0; }
926 };
927
928 struct UnisonVoice
929 {
930 std::array<Oscillator<T>, 3> osc;
931 std::array<bool, 3> oscOn {};
932 std::array<Ramp, 3> freq;
933 std::array<Ramp, 3> master;
934 std::array<double, 2> wtPhase {};
935 std::array<WavetableBank::Mip, 2> mip {};
936 std::array<double, 4> opPhase {};
937 std::array<Ramp, 4> opFreq;
938 double fb1 = 0.0, fb2 = 0.0;
939 Reader reader;
940 bool readerOn = false;
941 Ramp sampleRatio;
942 double gainL = 1.0, gainR = 1.0;
943 double detune = 1.0;
944 std::array<double, 3> spread {};
945 double driftCents = 0.0;
946 AnalogRandom::Generator<double> drift { 1 };
947 };
948
949 // Indices of the smoothed values in Voice::smooth.
950 enum Smoothed : int
951 {
952 kOsc1Level, kOsc2Level, kOsc3Level, kSubLevel, kNoiseLevel, kSampleLevel,
953 kPw1, kPw2, kPw3, kWt1Pos, kWt2Pos, kWt1Level, kWt2Level,
954 kOp1Level, kOp2Level, kOp3Level, kOp4Level, kFeedback,
955 kCutoff, kResonance, kDrive, kPan, kNumSmoothed
956 };
957
958 struct Voice
959 {
960 bool active = false;
961 bool held = false;
962 bool sustained = false;
963 bool firstTick = true;
964 bool stereo = false;
965 int key = 60;
966 int unison = 1;
967 int stealLeft = -1;
968 int tickLeft = 0;
969 int tickPos = 0;
970 Engine engine = Engine::Analog;
971 uint64_t age = 0;
972 uint64_t seed = 0;
973 int64_t ageHi = 0;
974 double velocity = 1.0;
975 double tuningCents = 0.0;
976 double releaseVelocity = 0.0;
977 double polyPressure = 0.0;
978 double random = 0.0;
979 double velGain = 1.0;
980 // Pitch in semitones: a glide from glideFrom to key over glideTotal samples.
981 double glideFrom = 60.0;
982 double glideLeft = 0.0;
983 double glideTotal = 0.0;
984 double pitch = 60.0;
985 const Content* content = nullptr;
986 const ZoneData* zone = nullptr;
987 double zoneGainL = 1.0, zoneGainR = 1.0;
988 uint32_t noise = 1;
989 ADSREnvelope<double> amp;
990 ADSREnvelope<double> env2, env3;
991 std::array<ADSREnvelope<double>, 4> opEnv;
992 std::array<Lfo<double>, 2> lfo;
993 std::array<double, 2> lfoValue {};
994 std::array<double, kNumSmoothed> smooth {};
995 std::array<Ramp, 3> oscLevel;
996 Ramp subLevel, noiseLevel, sampleLevel;
997 std::array<Ramp, 3> pulseWidth;
998 std::array<Ramp, 2> wtPosition, wtLevel;
999 std::array<Ramp, 4> opLevel;
1000 Ramp feedback, g, resonance, svfK, drive, ampGain, panL, panR, subFreq;
1001 std::array<std::array<T, 4>, 2> ladder {};
1002 std::array<detail::TptSvfState<T>, 2> svf {};
1003 Oscillator<T> sub;
1004 AnalogRandom::Generator<double> cutoffDrift { 1 };
1005 std::array<UnisonVoice, kMaxUnison> uni;
1006 };
1007
1009 static constexpr int kChunk = 128;
1010 struct Lane
1011 {
1012 Voice* voice = nullptr;
1013 int start = 0;
1014 int count = 0;
1015 std::array<double, kChunk> l {}, r {}, gain {}, panL {}, panR {};
1016 std::array<T, kChunk> g {}, q {}, drive {};
1017 };
1018
1019 enum class EventType { NoteOn, NoteOff, Pedal, Bend, ModWheel, Pressure, PolyPressure, Expression, Breath, AllOff };
1020 struct Event { EventType type; int key; double value; int offset; double tuningCents = 0.0; };
1021
1022 struct FreeLfo
1023 {
1024 double anchorCycles = 0.0;
1025 int64_t anchorTime = 0;
1026 double increment = 0.0;
1027 };
1028
1029 // ===================================================================================
1030 // Parameter access
1031 // ===================================================================================
1032
1033 [[nodiscard]] float p(Param param) const noexcept { return params_[static_cast<size_t>(param)]; }
1034 [[nodiscard]] int ip(Param param) const noexcept { return static_cast<int>(params_[static_cast<size_t>(param)]); }
1035 [[nodiscard]] static Param at(Param first, int offset) noexcept
1036 {
1037 return static_cast<Param>(static_cast<int>(first) + offset);
1038 }
1039 // Field offsets inside each repeated group of the table.
1040 [[nodiscard]] static Param oscParam(int k, int field) noexcept { return at(Param::Osc1Wave, 7 * k + field); }
1041 [[nodiscard]] static Param opParam(int k, int field) noexcept { return at(Param::Op1Ratio, 11 * k + field); }
1042 [[nodiscard]] static Param wtParam(int k, int field) noexcept { return at(Param::Wt1Bank, 6 * k + field); }
1043 [[nodiscard]] static Param envParam(int k, int field) noexcept { return at(Param::Env1Attack, 5 * k + field); }
1044 [[nodiscard]] static Param lfoParam(int k, int field) noexcept { return at(Param::Lfo1Shape, 8 * k + field); }
1045 [[nodiscard]] static Param modParam(int k, int field) noexcept { return at(Param::Mod1Source, 4 * k + field); }
1046 [[nodiscard]] static ModDest dest(ModDest first, int k) noexcept
1047 {
1048 return static_cast<ModDest>(static_cast<int>(first) + k);
1049 }
1050
1051 [[nodiscard]] int oversamplingFactor() const noexcept
1052 {
1053 const int choice = ip(Param::Oversampling);
1054 return choice == 2 ? 4 : (choice == 1 ? 2 : 1);
1055 }
1056
1058 void snapshotParameters(bool force) noexcept
1059 {
1060 std::array<float, kNumParams> next {};
1061 for (int i = 0; i < kNumParams; ++i)
1062 next[static_cast<size_t>(i)] = values_[static_cast<size_t>(i)].load(std::memory_order_relaxed);
1063 const float tempo = tempo_.load(std::memory_order_relaxed);
1064 const bool tempoChanged = tempo != tempoApplied_;
1065
1066 auto changed = [&](Param a, Param b) noexcept {
1067 if (force) return true;
1068 for (int i = static_cast<int>(a); i <= static_cast<int>(b); ++i)
1069 if (next[static_cast<size_t>(i)] != params_[static_cast<size_t>(i)]) return true;
1070 return false;
1071 };
1072 const bool envs = changed(Param::Env1Attack, Param::Env3Curve);
1073 const bool ops = changed(Param::Op1Ratio, Param::Op4Release);
1074 const bool lfos = changed(Param::Lfo1Shape, Param::Lfo2Mode) || tempoChanged;
1075 const bool rate = !force && next[static_cast<size_t>(Param::Oversampling)]
1076 != params_[static_cast<size_t>(Param::Oversampling)];
1077
1078 // Free LFOs re-anchor where they are now, so a rate change keeps the
1079 // phase continuous.
1080 std::array<double, 2> cyclesNow {};
1081 for (int k = 0; k < 2; ++k) cyclesNow[static_cast<size_t>(k)] = freeCycles(k, timeHi_);
1082 params_ = next;
1083 tempoApplied_ = tempo;
1084
1085 if (rate && prepared_) configureRate(oversamplingFactor());
1086 if (envs)
1087 for (auto& v : voices_) applyEnvelopes(v);
1088 if (ops)
1089 for (auto& v : voices_) applyOperatorEnvelopes(v);
1090 if (lfos)
1091 {
1092 for (int k = 0; k < 2; ++k)
1093 {
1094 auto& f = freeLfo_[static_cast<size_t>(k)];
1095 f.anchorCycles = cyclesNow[static_cast<size_t>(k)];
1096 f.anchorTime = timeHi_;
1097 f.increment = lfoRateHz(k) / internalRate_;
1098 }
1099 for (auto& v : voices_)
1100 for (int k = 0; k < 2; ++k) applyLfo(v, k);
1101 }
1102 }
1103
1104 // ===================================================================================
1105 // Rate configuration
1106 // ===================================================================================
1107
1108 void configureRate(int factor) noexcept
1109 {
1110 factor_ = factor;
1111 internalRate_ = baseRate_ * factor_;
1112 periodHi_ = kControlPeriod * factor_;
1113 invPeriod_ = 1.0 / static_cast<double>(periodHi_);
1114 const int delay = (factor_ == 2) ? os2_.getDecimationDelay()
1115 : (factor_ == 4 ? os4_.getDecimationDelay() : 0);
1116 // The latency is the delay rounded up to whole base samples, and the
1117 // content starts later by what the rounding added. Written with the
1118 // remainder on purpose. The other way round (latency = (delay +
1119 // factor - 1) / factor, then latency * factor - delay) is the same
1120 // number, and one optimizer in use evaluates its second line short
1121 // by about the latency (MSVC 19.52.37029 for x64, at /O1 and /O2:
1122 // -63 where 1 is right at 2x, -65 for 3 at 4x), which put every
1123 // event 64 or 68 high-rate samples early.
1124 const int over = delay % factor_;
1125 const int latency = delay / factor_ + (over != 0 ? 1 : 0);
1126 shift_ = (over != 0) ? factor_ - over : 0;
1127 latency_.store(latency, std::memory_order_relaxed);
1128 smoothAlpha_ = 1.0 - std::exp(-static_cast<double>(kControlPeriod) / (0.010 * baseRate_));
1129 stealFade_ = std::max(1, static_cast<int>(std::lround(0.003 * internalRate_)));
1130 noiseScale_ = std::sqrt(static_cast<double>(factor_)); // decimation keeps 1 / factor of its power
1131 const double controlRate = baseRate_ / kControlPeriod;
1132 for (auto& v : voices_)
1133 {
1134 v.active = false;
1135 v.amp.prepare(internalRate_);
1136 v.env2.prepare(controlRate);
1137 v.env3.prepare(controlRate);
1138 for (auto& e : v.opEnv) e.prepare(internalRate_);
1139 for (auto& l : v.lfo) l.prepare(internalRate_);
1140 v.sub.prepare(internalRate_);
1141 v.cutoffDrift.setNoiseType(AnalogRandom::NoiseType::Pink);
1142 v.cutoffDrift.setRange(-1.0, 1.0);
1143 v.cutoffDrift.setRateHz(1.5);
1144 v.cutoffDrift.setSmoothing(true, 150.0);
1145 v.cutoffDrift.prepare(controlRate);
1146 for (auto& u : v.uni)
1147 {
1148 for (auto& o : u.osc) o.prepare(internalRate_);
1149 u.drift.setNoiseType(AnalogRandom::NoiseType::Pink);
1150 u.drift.setRange(-1.0, 1.0);
1151 u.drift.setRateHz(2.0);
1152 u.drift.setSmoothing(true, 150.0);
1153 u.drift.prepare(controlRate);
1154 }
1155 applyEnvelopes(v);
1156 applyOperatorEnvelopes(v);
1157 for (int k = 0; k < 2; ++k) applyLfo(v, k);
1158 }
1159 os2_.reset();
1160 os4_.reset();
1161 for (int k = 0; k < 2; ++k)
1162 freeLfo_[static_cast<size_t>(k)].increment = lfoRateHz(k) / internalRate_;
1163 }
1164
1165 // ===================================================================================
1166 // Content publication (as Sampler's zone sets)
1167 // ===================================================================================
1168
1170 void publishContent()
1171 {
1172 delete retired_.exchange(nullptr, std::memory_order_acq_rel);
1173 auto* content = new Content { controlZones_, controlWavetable_ };
1174 delete pending_.exchange(content, std::memory_order_acq_rel);
1175 }
1176
1177 void adoptPending() noexcept
1178 {
1179 if (fading_ != nullptr) return; // one handover at a time
1180 Content* next = pending_.exchange(nullptr, std::memory_order_acq_rel);
1181 if (next == nullptr) return;
1182 fading_ = active_;
1183 active_ = next;
1184 }
1185
1186 void retireFadedContent() noexcept
1187 {
1188 if (fading_ == nullptr) return;
1189 for (const auto& v : voices_)
1190 if (v.active && v.content == fading_) return;
1191 if (retired_.load(std::memory_order_acquire) != nullptr) return;
1192 retired_.store(fading_, std::memory_order_release);
1193 fading_ = nullptr;
1194 }
1195
1196 // ===================================================================================
1197 // Events
1198 // ===================================================================================
1199
1200 void push(const Event& e) noexcept
1201 {
1202 if (!prepared_ || eventCount_ >= kMaxEvents) return;
1203 // Ordered by offset; equal offsets keep their call order.
1204 int i = eventCount_++;
1205 while (i > 0 && events_[static_cast<size_t>(i - 1)].offset > e.offset)
1206 {
1207 events_[static_cast<size_t>(i)] = events_[static_cast<size_t>(i - 1)];
1208 --i;
1209 }
1210 events_[static_cast<size_t>(i)] = e;
1211 }
1212
1213 void pushController(EventType type, int key, T value, int offset) noexcept
1214 {
1215 if (!std::isfinite(value)) return;
1216 push({ type, key, std::clamp(static_cast<double>(value), 0.0, 1.0), offset });
1217 }
1218
1219 void apply(const Event& e) noexcept
1220 {
1221 switch (e.type)
1222 {
1223 case EventType::NoteOn: noteOnNow(e.key, e.value, e.tuningCents); break;
1224 case EventType::NoteOff: noteOffNow(e.key, e.value); break;
1225 case EventType::Bend: bend_ = e.value; break;
1226 case EventType::ModWheel: modWheel_ = e.value; break;
1227 case EventType::Pressure: pressure_ = e.value; break;
1228 case EventType::Expression: expression_ = e.value; break;
1229 case EventType::Breath: breath_ = e.value; break;
1230 case EventType::PolyPressure:
1231 for (auto& v : voices_)
1232 if (v.active && v.key == e.key && v.stealLeft < 0) v.polyPressure = e.value;
1233 break;
1234 case EventType::Pedal:
1235 sustainPedal_ = e.value > 0.5;
1236 if (!sustainPedal_)
1237 for (auto& v : voices_)
1238 if (v.active && v.sustained && !v.held) release(v);
1239 break;
1240 case EventType::AllOff:
1241 sustainPedal_ = false;
1242 heldCount_ = 0;
1243 for (auto& v : voices_)
1244 if (v.active && v.stealLeft < 0) release(v);
1245 break;
1246 }
1247 }
1248
1249 [[nodiscard]] bool monophonic() const noexcept
1250 {
1251 return static_cast<VoiceMode>(ip(Param::VoiceMode)) != VoiceMode::Poly;
1252 }
1253
1254 void noteOnNow(int key, double velocity, double tuningCents) noexcept
1255 {
1256 const bool anyHeldBefore = heldCount_ > 0;
1257 pushHeld(key);
1258 heldTuning_[static_cast<size_t>(key)] = tuningCents;
1259 if (monophonic())
1260 {
1261 for (auto& v : voices_)
1262 if (v.active && v.stealLeft < 0)
1263 {
1264 const bool legato = anyHeldBefore && v.held;
1265 const bool retrigger = !(legato && static_cast<VoiceMode>(ip(Param::VoiceMode)) == VoiceMode::Legato);
1266 if (moveRestartsSample(v, key, velocity, retrigger))
1267 {
1268 v.stealLeft = stealFade_;
1269 break;
1270 }
1271 moveMonoVoice(v, key, velocity, tuningCents, retrigger, legato);
1272 return;
1273 }
1274 }
1275 else
1276 {
1277 // A retriggered key releases what it was playing.
1278 for (auto& v : voices_)
1279 if (v.active && v.key == key && v.stealLeft < 0 && (v.held || v.sustained))
1280 release(v);
1281 }
1282 if (Voice* v = freeVoice()) startVoice(*v, key, velocity, tuningCents, anyHeldBefore);
1283 }
1284
1285 void noteOffNow(int key, double releaseVelocity) noexcept
1286 {
1287 removeHeld(key);
1288 for (auto& v : voices_)
1289 {
1290 if (!v.active || !v.held || v.key != key || v.stealLeft >= 0) continue;
1291 if (monophonic() && heldCount_ > 0)
1292 {
1293 // Back to the most recent key still held: no retrigger.
1294 const int nextKey = held_[static_cast<size_t>(heldCount_ - 1)];
1295 const double nextTuning = heldTuning_[static_cast<size_t>(nextKey)];
1296 if (moveRestartsSample(v, nextKey, v.velocity, false))
1297 {
1298 v.stealLeft = stealFade_;
1299 if (Voice* next = freeVoice()) startVoice(*next, nextKey, v.velocity, nextTuning, true);
1300 continue;
1301 }
1302 moveMonoVoice(v, nextKey, v.velocity, nextTuning, false, true);
1303 continue;
1304 }
1305 v.releaseVelocity = releaseVelocity;
1306 if (sustainPedal_) { v.held = false; v.sustained = true; }
1307 else release(v);
1308 }
1309 }
1310
1312 [[nodiscard]] const ZoneData* zoneFor(int key, double velocity) const noexcept
1313 {
1314 if (active_ != nullptr && active_->zones != nullptr)
1315 for (const auto& z : *active_->zones)
1316 if (key >= z.keyLow && key <= z.keyHigh && velocity >= z.velLow && velocity <= z.velHigh)
1317 return &z;
1318 return nullptr;
1319 }
1320
1322 [[nodiscard]] bool sampleSourceInUse() const noexcept
1323 {
1324 if (p(Param::SampleLevel) > 0.0f) return true;
1325 for (int s = 0; s < kModSlots; ++s)
1326 if (static_cast<ModDest>(ip(modParam(s, 2))) == ModDest::SampleLevel) return true;
1327 return false;
1328 }
1329
1333 [[nodiscard]] bool moveRestartsSample(const Voice& v, int key, double velocity, bool retrigger) const noexcept
1334 {
1335 if (!sampleSourceInUse()) return false;
1336 const ZoneData* next = zoneFor(key, velocity);
1337 return next != v.zone || (retrigger && next != nullptr);
1338 }
1339
1340 void pushHeld(int key) noexcept
1341 {
1342 removeHeld(key);
1343 if (heldCount_ < 128) held_[static_cast<size_t>(heldCount_++)] = key;
1344 }
1345
1346 void removeHeld(int key) noexcept
1347 {
1348 int w = 0;
1349 for (int i = 0; i < heldCount_; ++i)
1350 if (held_[static_cast<size_t>(i)] != key) held_[static_cast<size_t>(w++)] = held_[static_cast<size_t>(i)];
1351 heldCount_ = w;
1352 }
1353
1354 void release(Voice& v) noexcept
1355 {
1356 v.held = false;
1357 v.sustained = false;
1358 v.amp.noteOff();
1359 v.env2.noteOff();
1360 v.env3.noteOff();
1361 for (auto& e : v.opEnv) e.noteOff();
1362 for (int u = 0; u < v.unison; ++u) v.uni[static_cast<size_t>(u)].reader.release();
1363 }
1364
1366 void moveMonoVoice(Voice& v, int key, double velocity, double tuningCents, bool retrigger, bool legato) noexcept
1367 {
1368 const double glideMs = static_cast<double>(p(Param::Glide));
1369 const bool glide = glideMs > 0.0
1370 && (static_cast<GlideMode>(ip(Param::GlideMode)) == GlideMode::Always || legato);
1371 const double tunedPitch = static_cast<double>(key) + tuningCents / 100.0;
1372 v.glideFrom = glide ? v.pitch : tunedPitch;
1373 v.glideTotal = glide ? glideMs * 0.001 * internalRate_ : 0.0;
1374 v.glideLeft = v.glideTotal;
1375 v.key = key;
1376 v.tuningCents = tuningCents;
1377 v.held = true;
1378 v.sustained = false;
1379 lastPitch_ = tunedPitch;
1380 haveLastPitch_ = true;
1381 if (!retrigger) return;
1382 v.velocity = velocity;
1383 v.releaseVelocity = 0.0;
1384 v.velGain = velocityGain(velocity);
1385 v.amp.noteOn();
1386 v.env2.noteOn();
1387 v.env3.noteOn();
1388 for (auto& e : v.opEnv) e.noteOn();
1389 for (int k = 0; k < 2; ++k)
1390 if (static_cast<LfoMode>(ip(lfoParam(k, 7))) == LfoMode::Retrigger)
1391 v.lfo[static_cast<size_t>(k)].reset();
1392 }
1393
1394 [[nodiscard]] double velocityGain(double velocity) const noexcept
1395 {
1396 return std::pow(10.0, static_cast<double>(p(Param::AmpVelocity)) * (velocity - 1.0) / 20.0);
1397 }
1398
1401 Voice* freeVoice() noexcept
1402 {
1403 const int polyphony = monophonic() ? 1 : std::min(ip(Param::Polyphony), maxVoices_);
1404 int sounding = 0;
1405 Voice* idle = nullptr;
1406 for (auto& v : voices_)
1407 {
1408 if (!v.active) { if (idle == nullptr) idle = &v; }
1409 else if (v.stealLeft < 0) ++sounding;
1410 }
1411 if (sounding < polyphony && idle != nullptr) return idle;
1412
1413 // Steal: the oldest released voice, else the quietest, else the oldest.
1414 Voice* victim = nullptr;
1415 for (auto& v : voices_)
1416 {
1417 if (!v.active || v.stealLeft >= 0) continue;
1418 if (victim == nullptr) { victim = &v; continue; }
1419 const bool vr = !v.held && !v.sustained, cr = !victim->held && !victim->sustained;
1420 if (vr != cr) { if (vr) victim = &v; continue; }
1421 const double va = v.amp.getCurrentValue(), ca = victim->amp.getCurrentValue();
1422 if (va < ca - 1e-9 || (std::abs(va - ca) <= 1e-9 && v.age < victim->age)) victim = &v;
1423 }
1424 if (victim != nullptr) victim->stealLeft = stealFade_;
1425 if (idle != nullptr) return idle;
1426 // No spare slot left: the oldest stealing fade is cut short.
1427 Voice* oldest = nullptr;
1428 for (auto& v : voices_)
1429 if (v.active && v.stealLeft >= 0 && (oldest == nullptr || v.age < oldest->age)) oldest = &v;
1430 if (oldest != nullptr) oldest->active = false;
1431 return oldest;
1432 }
1433
1434 // ===================================================================================
1435 // Voice start
1436 // ===================================================================================
1437
1438 [[nodiscard]] static uint64_t mix64(uint64_t x) noexcept
1439 {
1440 x += 0x9E3779B97F4A7C15ull;
1441 x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
1442 x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
1443 return x ^ (x >> 31);
1444 }
1445
1447 [[nodiscard]] static double voiceRandom(uint64_t seed, int stream) noexcept
1448 {
1449 return Lfo<double>::random(seed, stream);
1450 }
1451
1452 void startVoice(Voice& v, int key, double velocity, double tuningCents, bool anyHeldBefore) noexcept
1453 {
1454 v.active = true;
1455 v.held = true;
1456 v.sustained = false;
1457 v.firstTick = true;
1458 v.stealLeft = -1;
1459 v.key = key;
1460 v.tuningCents = tuningCents;
1461 v.velocity = velocity;
1462 v.releaseVelocity = 0.0;
1463 v.polyPressure = 0.0;
1464 v.velGain = velocityGain(velocity);
1465 v.age = ++clock_;
1466 v.seed = mix64(static_cast<uint64_t>(ip(Param::Seed)) * 0x100000001B3ull + noteCounter_++);
1467 v.random = voiceRandom(v.seed, 0);
1468 v.engine = static_cast<Engine>(ip(Param::Engine));
1469 v.unison = std::clamp(ip(Param::Unison), 1, kMaxUnison);
1470 v.content = active_;
1471 v.ageHi = 0;
1472 v.noise = static_cast<uint32_t>(mix64(v.seed ^ 0x6E6F697365ull)) | 1u;
1473
1474 // Glide from the previous note.
1475 const double glideMs = static_cast<double>(p(Param::Glide));
1476 const bool glide = glideMs > 0.0 && haveLastPitch_
1477 && (static_cast<GlideMode>(ip(Param::GlideMode)) == GlideMode::Always || anyHeldBefore);
1478 const double tunedPitch = static_cast<double>(key) + tuningCents / 100.0;
1479 v.glideFrom = glide ? lastPitch_ : tunedPitch;
1480 v.glideTotal = glide ? glideMs * 0.001 * internalRate_ : 0.0;
1481 v.glideLeft = v.glideTotal;
1482 v.pitch = v.glideFrom;
1483 lastPitch_ = tunedPitch;
1484 haveLastPitch_ = true;
1485
1486 // Sample zone: the first one answering the key and velocity.
1487 v.zone = zoneFor(key, velocity);
1488 if (v.zone != nullptr)
1489 {
1490 double mono = 1.0;
1491 detail::sampleZonePanGains(v.zone->pan, v.zone->channels, v.zone->gain,
1492 v.zoneGainL, v.zoneGainR, mono);
1493 }
1494
1495 // Unison layout: symmetric detune, spread across the stereo field,
1496 // power normalised.
1497 const int U = v.unison;
1498 const double spread = static_cast<double>(p(Param::UnisonSpread));
1499 const double detuneCents = static_cast<double>(p(Param::UnisonDetune));
1500 const double drift = static_cast<double>(p(Param::Drift));
1501 const double norm = 1.0 / std::sqrt(static_cast<double>(U));
1502 // A multichannel or panned zone is stereo whatever its level is now:
1503 // the level can arrive later, or from the matrix.
1504 v.stereo = (U > 1 && spread > 0.0)
1505 || (v.zone != nullptr && (v.zone->channels > 1 || v.zone->pan != 0.0));
1506 for (int u = 0; u < U; ++u)
1507 {
1508 auto& uv = v.uni[static_cast<size_t>(u)];
1509 const double x = (U > 1) ? 2.0 * static_cast<double>(u) / static_cast<double>(U - 1) - 1.0 : 0.0;
1510 uv.detune = std::exp2(0.5 * x * detuneCents / 1200.0);
1511 // cos on both sides (sin(a) = cos(pi/2 - a)): mirrored positions
1512 // get exactly mirrored gains, and the centre is exactly mono.
1513 uv.gainL = norm * std::cos(0.25 * pi<double> * (1.0 + x * spread)) * sqrt2<double>;
1514 uv.gainR = norm * std::cos(0.25 * pi<double> * (1.0 - x * spread)) * sqrt2<double>;
1515 for (int k = 0; k < 3; ++k)
1516 uv.spread[static_cast<size_t>(k)] =
1517 std::exp2(drift * 3.0 * voiceRandom(v.seed, 10 + 3 * u + k) / 1200.0);
1518 uv.driftCents = 0.0;
1519 uv.drift.reseed(mix64(v.seed + 101u + static_cast<uint64_t>(u)) | 1u);
1520 uv.fb1 = uv.fb2 = 0.0;
1521 uv.readerOn = false;
1522 uv.oscOn = {};
1523 }
1524 v.cutoffDrift.reseed(mix64(v.seed + 77u) | 1u);
1525
1526 // Envelopes and LFOs.
1527 applyEnvelopes(v);
1528 applyOperatorEnvelopes(v);
1529 v.amp.reset();
1530 v.amp.noteOn();
1531 v.env2.reset();
1532 v.env2.noteOn();
1533 v.env3.reset();
1534 v.env3.noteOn();
1535 for (auto& e : v.opEnv) { e.reset(); e.noteOn(); }
1536 for (int k = 0; k < 2; ++k)
1537 {
1538 applyLfo(v, k);
1539 auto& l = v.lfo[static_cast<size_t>(k)];
1540 l.setSeed(mix64(v.seed + 200u + static_cast<uint64_t>(k)));
1541 l.reset();
1542 v.lfoValue[static_cast<size_t>(k)] = 0.0;
1543 }
1544 v.ladder = {};
1545 v.svf = {};
1546
1547 // The first control tick sets every frequency and snaps every ramp;
1548 // the oscillators are phased after it, at their real frequencies.
1549 controlTick(v);
1550 const bool randomPhase = static_cast<PhaseMode>(ip(Param::PhaseMode)) == PhaseMode::Random;
1551 for (int u = 0; u < U; ++u)
1552 {
1553 auto& uv = v.uni[static_cast<size_t>(u)];
1554 for (int k = 0; k < 3; ++k)
1555 {
1556 const double ph = randomPhase ? 0.5 + 0.5 * voiceRandom(v.seed, 40 + 3 * u + k) : 0.0;
1557 uv.osc[static_cast<size_t>(k)].setPhase(static_cast<T>(ph));
1558 }
1559 for (int k = 0; k < 2; ++k)
1560 uv.wtPhase[static_cast<size_t>(k)] = randomPhase ? 0.5 + 0.5 * voiceRandom(v.seed, 70 + 2 * u + k) : 0.0;
1561 for (int k = 0; k < 4; ++k)
1562 uv.opPhase[static_cast<size_t>(k)] = randomPhase ? 0.5 + 0.5 * voiceRandom(v.seed, 90 + 4 * u + k) : 0.0;
1563 if (v.zone != nullptr)
1564 {
1565 uv.reader.start(*v.zone, uv.sampleRatio.target);
1566 uv.readerOn = true;
1567 }
1568 }
1569 v.sub.reset();
1570 v.tickLeft = periodHi_;
1571 v.tickPos = 0;
1572 }
1573
1574 void applyEnvelopes(Voice& v) noexcept
1575 {
1576 auto set = [&](ADSREnvelope<double>& e, int k) noexcept {
1577 e.setParameters(p(envParam(k, 0)), p(envParam(k, 1)), p(envParam(k, 2)), p(envParam(k, 3)));
1578 e.setCurvature(p(envParam(k, 4)));
1579 };
1580 set(v.amp, 0);
1581 set(v.env2, 1);
1582 set(v.env3, 2);
1583 }
1584
1585 void applyOperatorEnvelopes(Voice& v) noexcept
1586 {
1587 for (int k = 0; k < 4; ++k)
1588 v.opEnv[static_cast<size_t>(k)].setParameters(p(opParam(k, 7)), p(opParam(k, 8)),
1589 p(opParam(k, 9)), p(opParam(k, 10)));
1590 }
1591
1592 [[nodiscard]] double lfoRateHz(int k) const noexcept
1593 {
1594 if (ip(lfoParam(k, 2)) != 0)
1595 {
1596 const auto d = static_cast<typename Lfo<double>::Division>(ip(lfoParam(k, 3)));
1597 return (static_cast<double>(tempoApplied_) / 60.0) / Lfo<double>::beatsPerCycle(d);
1598 }
1599 return static_cast<double>(p(lfoParam(k, 1)));
1600 }
1601
1602 void applyLfo(Voice& v, int k) noexcept
1603 {
1604 auto& l = v.lfo[static_cast<size_t>(k)];
1605 l.setShape(static_cast<typename Lfo<double>::Shape>(ip(lfoParam(k, 0))));
1606 l.setRateHz(static_cast<double>(p(lfoParam(k, 1))));
1607 l.setTempo(static_cast<double>(tempoApplied_));
1608 l.setDivision(static_cast<typename Lfo<double>::Division>(ip(lfoParam(k, 3))));
1609 l.setTempoSync(ip(lfoParam(k, 2)) != 0);
1610 l.setDelayMs(static_cast<double>(p(lfoParam(k, 4))));
1611 l.setFadeInMs(static_cast<double>(p(lfoParam(k, 5))));
1612 l.setStartPhase(static_cast<double>(p(lfoParam(k, 6))));
1613 }
1614
1615 [[nodiscard]] double freeCycles(int k, int64_t t) const noexcept
1616 {
1617 const auto& f = freeLfo_[static_cast<size_t>(k)];
1618 return f.anchorCycles + f.increment * static_cast<double>(t - f.anchorTime);
1619 }
1620
1621 // ===================================================================================
1622 // Control tick: modulation and the next period's targets
1623 // ===================================================================================
1624
1625 [[nodiscard]] static double noteHz(double semitones) noexcept
1626 {
1627 return 440.0 * std::exp2((semitones - 69.0) / 12.0);
1628 }
1629
1630 void controlTick(Voice& v) noexcept
1631 {
1632 const bool first = v.firstTick;
1633 v.firstTick = false;
1634 v.tickPos = 0;
1635 const int64_t now = timeHi_ + offsetHi_;
1636
1637 // -- Glide: constant time, linear in semitones.
1638 const double keyPitch = static_cast<double>(v.key);
1639 const double tunedPitch = keyPitch + v.tuningCents / 100.0;
1640 if (v.glideLeft > 0.0)
1641 {
1642 v.pitch = tunedPitch + (v.glideFrom - tunedPitch) * (v.glideLeft / std::max(v.glideTotal, 1.0));
1643 v.glideLeft = std::max(0.0, v.glideLeft - static_cast<double>(periodHi_));
1644 }
1645 else
1646 {
1647 v.pitch = tunedPitch;
1648 }
1649
1650 // -- Sources.
1651 std::array<double, synthesizer::kNumModSources> src {};
1652 auto source = [&](ModSource s) noexcept -> double& { return src[static_cast<size_t>(s)]; };
1653 source(ModSource::Velocity) = v.velocity;
1654 source(ModSource::ReleaseVelocity) = v.releaseVelocity;
1655 source(ModSource::Key) = (keyPitch - 60.0) / 60.0;
1656 source(ModSource::ModWheel) = modWheel_;
1657 source(ModSource::Pressure) = std::max(pressure_, v.polyPressure);
1658 source(ModSource::PitchBend) = bend_;
1659 source(ModSource::Expression) = expression_;
1660 source(ModSource::Breath) = breath_;
1661 source(ModSource::Env1) = v.amp.getCurrentValue();
1662 source(ModSource::Env2) = v.env2.getNextValue();
1663 source(ModSource::Env3) = v.env3.getNextValue();
1664 source(ModSource::Random) = v.random;
1665 source(ModSource::Lfo1) = v.lfoValue[0];
1666 source(ModSource::Lfo2) = v.lfoValue[1];
1667
1668 // -- Matrix: the LFO rate destinations first, since they shape the
1669 // LFOs' advance (an LFO source is last tick's value there), then
1670 // everything else with this tick's LFOs as sources.
1671 std::array<double, synthesizer::kNumModDests> dst {};
1672 auto runMatrix = [&](bool rateOnly) noexcept {
1673 for (int s = 0; s < kModSlots; ++s)
1674 {
1675 const auto d = static_cast<ModDest>(ip(modParam(s, 2)));
1676 const auto a = static_cast<ModSource>(ip(modParam(s, 0)));
1677 const double amount = static_cast<double>(p(modParam(s, 3)));
1678 if (d == ModDest::None || a == ModSource::None || amount == 0.0) continue;
1679 const bool isRate = d == ModDest::Lfo1Rate || d == ModDest::Lfo2Rate;
1680 if (isRate != rateOnly) continue;
1681 const auto via = static_cast<ModSource>(ip(modParam(s, 1)));
1682 const double scale = (via == ModSource::None) ? 1.0 : src[static_cast<size_t>(via)];
1683 dst[static_cast<size_t>(d)] += src[static_cast<size_t>(a)] * scale * amount;
1684 }
1685 };
1686 auto mod = [&](ModDest d) noexcept { return dst[static_cast<size_t>(d)]; };
1687 runMatrix(true);
1688 for (int k = 0; k < 2; ++k)
1689 {
1690 auto& l = v.lfo[static_cast<size_t>(k)];
1691 double value;
1692 if (static_cast<LfoMode>(ip(lfoParam(k, 7))) == LfoMode::Retrigger)
1693 {
1694 value = l.advanceScaled(periodHi_, std::exp2(mod(k == 0 ? ModDest::Lfo1Rate : ModDest::Lfo2Rate)));
1695 }
1696 else
1697 {
1698 const auto shape = static_cast<typename Lfo<double>::Shape>(ip(lfoParam(k, 0)));
1699 const uint64_t seed = mix64(static_cast<uint64_t>(ip(Param::Seed)) + 300u + static_cast<uint64_t>(k));
1700 value = Lfo<double>::valueAt(shape, freeCycles(k, now), seed) * l.depthAt(v.ageHi);
1701 }
1702 source(k == 0 ? ModSource::Lfo1 : ModSource::Lfo2) = value;
1703 v.lfoValue[static_cast<size_t>(k)] = value;
1704 }
1705 runMatrix(false);
1706
1707 // -- Smoothed base values (10 ms one-pole per control period).
1708 std::array<double, kNumSmoothed> base {};
1709 for (int k = 0; k < 3; ++k)
1710 {
1711 base[static_cast<size_t>(kOsc1Level + k)] = p(oscParam(k, 1));
1712 base[static_cast<size_t>(kPw1 + k)] = p(oscParam(k, 5));
1713 }
1714 base[kSubLevel] = p(Param::SubLevel);
1715 base[kNoiseLevel] = p(Param::NoiseLevel);
1716 base[kSampleLevel] = p(Param::SampleLevel);
1717 base[kWt1Pos] = p(wtParam(0, 1));
1718 base[kWt2Pos] = p(wtParam(1, 1));
1719 base[kWt1Level] = p(wtParam(0, 2));
1720 base[kWt2Level] = p(wtParam(1, 2));
1721 for (int k = 0; k < 4; ++k) base[static_cast<size_t>(kOp1Level + k)] = p(opParam(k, 4));
1722 base[kFeedback] = p(Param::FmFeedback);
1723 base[kCutoff] = std::log2(static_cast<double>(p(Param::FilterCutoff)));
1724 base[kResonance] = p(Param::FilterResonance);
1725 base[kDrive] = p(Param::FilterDrive);
1726 base[kPan] = p(Param::AmpPan);
1727 for (int i = 0; i < kNumSmoothed; ++i)
1728 {
1729 double& s = v.smooth[static_cast<size_t>(i)];
1730 s = first ? base[static_cast<size_t>(i)] : s + (base[static_cast<size_t>(i)] - s) * smoothAlpha_;
1731 }
1732 auto sm = [&](int i) noexcept { return v.smooth[static_cast<size_t>(i)]; };
1733 auto setRamp = [&](Ramp& r, double value) noexcept {
1734 if (first) r.snap(value);
1735 else r.to(value, invPeriod_);
1736 };
1737 auto unit = [](double x) noexcept { return std::clamp(x, 0.0, 1.0); };
1738
1739 // -- Pitches.
1740 const double bendSt = bend_ * static_cast<double>(p(Param::BendRange));
1741 const double notePitch = v.pitch + bendSt + static_cast<double>(p(Param::MasterTune)) / 100.0
1742 + mod(ModDest::Pitch);
1743 const double baseHz = noteHz(notePitch);
1744 const double limitHz = 0.499 * internalRate_;
1745 auto clampHz = [&](double hz) noexcept { return std::clamp(hz, 0.0, limitHz); };
1746
1747 // Only the latched engine reads its pitches.
1748 std::array<double, 3> oscRatio {};
1749 if (v.engine == Engine::Analog)
1750 for (int k = 0; k < 3; ++k)
1751 oscRatio[static_cast<size_t>(k)] = std::exp2((12.0 * p(oscParam(k, 2)) + p(oscParam(k, 3))
1752 + p(oscParam(k, 4)) / 100.0 + mod(dest(ModDest::Osc1Pitch, k))) / 12.0);
1753 std::array<double, 2> wtRatio {};
1754 if (v.engine == Engine::Wavetable)
1755 for (int k = 0; k < 2; ++k)
1756 wtRatio[static_cast<size_t>(k)] = std::exp2((12.0 * p(wtParam(k, 3)) + p(wtParam(k, 4))
1757 + p(wtParam(k, 5)) / 100.0 + mod(dest(ModDest::Osc1Pitch, k))) / 12.0);
1758 std::array<double, 4> opHz {};
1759 std::array<bool, 4> opFixed {};
1760 if (v.engine == Engine::Fm)
1761 for (int k = 0; k < 4; ++k)
1762 {
1763 opFixed[static_cast<size_t>(k)] = ip(opParam(k, 2)) != 0;
1764 opHz[static_cast<size_t>(k)] = opFixed[static_cast<size_t>(k)]
1765 ? static_cast<double>(p(opParam(k, 3)))
1766 : static_cast<double>(p(opParam(k, 0))) * std::exp2(static_cast<double>(p(opParam(k, 1))) / 1200.0);
1767 }
1768
1769 const double driftAmount = static_cast<double>(p(Param::Drift));
1770 constexpr double centRatio = std::numbers::ln2 / 1200.0; // 2^(c/1200) ~ 1 + c ln2 / 1200
1771 for (int u = 0; u < v.unison; ++u)
1772 {
1773 auto& uv = v.uni[static_cast<size_t>(u)];
1774 uv.driftCents = driftAmount > 0.0 ? 6.0 * driftAmount * uv.drift.getNextSample() : 0.0;
1775 const double unisonHz = baseHz * uv.detune * (1.0 + uv.driftCents * centRatio);
1776 switch (v.engine)
1777 {
1778 case Engine::Analog:
1779 for (int k = 0; k < 3; ++k)
1780 {
1781 const double masterHz = unisonHz * uv.spread[static_cast<size_t>(k)];
1782 setRamp(uv.freq[static_cast<size_t>(k)], clampHz(masterHz * oscRatio[static_cast<size_t>(k)]));
1783 setRamp(uv.master[static_cast<size_t>(k)], clampHz(masterHz));
1784 }
1785 break;
1786 case Engine::Wavetable:
1787 for (int k = 0; k < 2; ++k)
1788 setRamp(uv.freq[static_cast<size_t>(k)],
1789 clampHz(unisonHz * uv.spread[static_cast<size_t>(k)] * wtRatio[static_cast<size_t>(k)]));
1790 break;
1791 case Engine::Fm:
1792 for (int k = 0; k < 4; ++k)
1793 setRamp(uv.opFreq[static_cast<size_t>(k)],
1794 clampHz(opFixed[static_cast<size_t>(k)] ? opHz[static_cast<size_t>(k)]
1795 : unisonHz * opHz[static_cast<size_t>(k)]));
1796 break;
1797 }
1798 if (v.zone != nullptr)
1799 {
1800 const auto& z = *v.zone;
1801 const double offset = 12.0 * p(Param::SampleOctave) + p(Param::SampleSemitone)
1802 + p(Param::SampleFine) / 100.0;
1803 const double played = (ip(Param::SampleKeyTrack) != 0)
1804 ? notePitch : static_cast<double>(z.rootKey) + bendSt + mod(ModDest::Pitch);
1805 const double st = played + offset - static_cast<double>(z.rootKey) + z.tuneCents / 100.0;
1806 const double ratio = z.sampleRate / internalRate_ * std::exp2(st / 12.0) * uv.detune
1807 * (1.0 + uv.driftCents * centRatio);
1808 const bool scatters = first ? ratio > 1.0 : uv.reader.scatters();
1809 setRamp(uv.sampleRatio, std::clamp(ratio, scatters ? Reader::kMinScatterRate : Reader::kMinGatherRate,
1810 Reader::kMaxRate));
1811 }
1812 }
1813 setRamp(v.subFreq, clampHz(baseHz * (ip(Param::SubOctave) == 1 ? 0.25 : 0.5)));
1814
1815 // -- Levels and timbre.
1816 for (int k = 0; k < 3; ++k)
1817 {
1818 setRamp(v.oscLevel[static_cast<size_t>(k)], unit(sm(kOsc1Level + k) + mod(dest(ModDest::Osc1Level, k))));
1819 setRamp(v.pulseWidth[static_cast<size_t>(k)], std::clamp(sm(kPw1 + k) + mod(ModDest::PulseWidth), 0.01, 0.99));
1820 }
1821 setRamp(v.subLevel, unit(sm(kSubLevel) + mod(ModDest::SubLevel)));
1822 setRamp(v.noiseLevel, unit(sm(kNoiseLevel) + mod(ModDest::NoiseLevel)));
1823 setRamp(v.sampleLevel, unit(sm(kSampleLevel) + mod(ModDest::SampleLevel)));
1824 for (int k = 0; k < 2; ++k)
1825 {
1826 setRamp(v.wtPosition[static_cast<size_t>(k)],
1827 unit(sm(kWt1Pos + k) + mod(ModDest::WtPosition) + mod(dest(ModDest::Wt1Position, k))));
1828 setRamp(v.wtLevel[static_cast<size_t>(k)], unit(sm(kWt1Level + k) + mod(dest(ModDest::Osc1Level, k))));
1829 }
1830 const double keyOctaves = (keyPitch - 60.0) / 12.0;
1831 if (v.engine == Engine::Fm)
1832 for (int k = 0; k < 4; ++k)
1833 {
1834 const double velSens = static_cast<double>(p(opParam(k, 5)));
1835 const double keyDb = 6.0 * static_cast<double>(p(opParam(k, 6))) * keyOctaves;
1836 const double level = unit(sm(kOp1Level + k) + mod(dest(ModDest::Op1Level, k)))
1837 * (1.0 - velSens * (1.0 - v.velocity)) * std::pow(10.0, keyDb / 20.0);
1838 setRamp(v.opLevel[static_cast<size_t>(k)], level);
1839 }
1840 setRamp(v.feedback, unit(sm(kFeedback) + mod(ModDest::FmFeedback)));
1841
1842 // -- Wavetable mip levels for this period's highest frequency.
1843 if (v.engine == Engine::Wavetable)
1844 for (int u = 0; u < v.unison; ++u)
1845 for (int k = 0; k < 2; ++k)
1846 {
1847 auto& uv = v.uni[static_cast<size_t>(u)];
1848 const auto& r = uv.freq[static_cast<size_t>(k)];
1849 uv.mip[static_cast<size_t>(k)] = bankFor(v, k).selectMip(std::max(r.start, r.target), internalRate_);
1850 }
1851
1852 // -- Filter.
1853 const double cutDrift = driftAmount > 0.0 ? 0.15 * driftAmount * v.cutoffDrift.getNextSample() : 0.0;
1854 const double envScale = 1.0 - static_cast<double>(p(Param::FilterVelocity)) * (1.0 - v.velocity);
1855 const double octaves = sm(kCutoff)
1856 + static_cast<double>(p(Param::FilterKeyTrack)) * keyOctaves
1857 + static_cast<double>(p(Param::FilterEnvAmount)) * envScale * source(ModSource::Env2)
1858 + mod(ModDest::Cutoff) + cutDrift;
1859 const auto filterType = static_cast<FilterType>(ip(Param::FilterType));
1860 if (filterType != FilterType::Off || first)
1861 {
1862 const double cutoff = std::clamp(std::exp2(octaves), 10.0, std::min(0.49 * internalRate_, 40000.0));
1863 setRamp(v.g, std::tan(pi<double> * cutoff / internalRate_));
1864 }
1865 const double resonance = unit(sm(kResonance) + mod(ModDest::Resonance));
1866 setRamp(v.resonance, resonance);
1867 if (filterType >= FilterType::SvfLp || first)
1868 setRamp(v.svfK, 2.0 / std::pow(100.0, resonance)); // Q from 0.5 to 50
1869 setRamp(v.drive, std::max(sm(kDrive), 1.01));
1870
1871 // -- Amplifier and pan (MIDI expression scales the level).
1872 setRamp(v.ampGain, v.velGain * std::max(0.0, 1.0 + mod(ModDest::Amp)) * expression_);
1873 const double pan = std::clamp(sm(kPan) + mod(ModDest::Pan), -1.0, 1.0);
1874 if (v.stereo)
1875 {
1876 setRamp(v.panL, std::min(1.0, 1.0 - pan));
1877 setRamp(v.panR, std::min(1.0, 1.0 + pan));
1878 }
1879 else
1880 {
1881 // Constant power, symmetric as the unison spread: centred is mono.
1882 setRamp(v.panL, std::cos(0.25 * pi<double> * (1.0 + pan)) * sqrt2<double>);
1883 setRamp(v.panR, std::cos(0.25 * pi<double> * (1.0 - pan)) * sqrt2<double>);
1884 }
1885
1886 // -- Oscillators at the period start (analog engine) and the sub.
1887 if (v.engine == Engine::Analog)
1888 for (int u = 0; u < v.unison; ++u)
1889 for (int k = 0; k < 3; ++k)
1890 {
1891 auto& uv = v.uni[static_cast<size_t>(u)];
1892 auto& o = uv.osc[static_cast<size_t>(k)];
1893 const bool on = v.oscLevel[static_cast<size_t>(k)].live();
1894 o.setWaveform(waveOf(static_cast<OscWave>(ip(oscParam(k, 0)))));
1895 o.setPulseWidth(static_cast<T>(v.pulseWidth[static_cast<size_t>(k)].start));
1896 if (ip(oscParam(k, 6)) != 0)
1897 {
1898 const double m = uv.master[static_cast<size_t>(k)].start;
1899 o.setFrequency(static_cast<T>(m));
1900 o.setSyncRatio(static_cast<T>(m > 0.0 ? uv.freq[static_cast<size_t>(k)].start / m : 0.0));
1901 }
1902 else
1903 {
1904 o.setSyncRatio(T(0));
1905 o.setFrequency(static_cast<T>(uv.freq[static_cast<size_t>(k)].start));
1906 }
1907 if (on && !uv.oscOn[static_cast<size_t>(k)] && !first)
1908 o.setPhase(o.getPhase()); // restart cleanly after a silent stretch
1909 uv.oscOn[static_cast<size_t>(k)] = on;
1910 }
1911 v.sub.setWaveform(subWaveOf(static_cast<SubWave>(ip(Param::SubWave))));
1912 v.sub.setFrequency(static_cast<T>(v.subFreq.start));
1913 }
1914
1915 [[nodiscard]] static typename Oscillator<T>::Waveform waveOf(OscWave w) noexcept
1916 {
1917 using W = typename Oscillator<T>::Waveform;
1918 switch (w)
1919 {
1920 case OscWave::Sine: return W::Sine;
1921 case OscWave::Triangle: return W::Triangle;
1922 case OscWave::Saw: return W::Saw;
1923 case OscWave::Pulse: return W::Square;
1924 }
1925 return W::Saw;
1926 }
1927
1928 [[nodiscard]] static typename Oscillator<T>::Waveform subWaveOf(SubWave w) noexcept
1929 {
1930 using W = typename Oscillator<T>::Waveform;
1931 switch (w)
1932 {
1933 case SubWave::Square: return W::Square;
1934 case SubWave::Triangle: return W::Triangle;
1935 case SubWave::Sine: return W::Sine;
1936 }
1937 return W::Square;
1938 }
1939
1940 [[nodiscard]] const WavetableBank& bankFor(const Voice& v, int k) const noexcept
1941 {
1942 const int b = ip(wtParam(k, 0));
1944 {
1945 if (v.content != nullptr && v.content->wavetable != nullptr) return *v.content->wavetable;
1947 }
1948 return WavetableBank::builtin(static_cast<WavetableBank::Builtin>(b));
1949 }
1950
1951 // ===================================================================================
1952 // Rendering
1953 // ===================================================================================
1954
1955 void renderPiece(AudioBufferView<T> out, int start, int len, int& e, bool lastPiece) noexcept
1956 {
1957 const int lenHi = len * factor_;
1958 T* hiL = mix_[0].data();
1959 T* hiR = mix_[1].data();
1960 if (factor_ > 1)
1961 {
1962 const AudioBufferView<T> hi = (factor_ == 2) ? os2_.getHighRateBlock(len) : os4_.getHighRateBlock(len);
1963 hiL = hi.getChannel(0);
1964 hiR = hi.getChannel(1);
1965 }
1966 std::fill_n(hiL, lenHi, T(0));
1967 std::fill_n(hiR, lenHi, T(0));
1968
1969 int cursor = 0;
1970 while (e < eventCount_)
1971 {
1972 const Event& ev = events_[static_cast<size_t>(e)];
1973 const int offset = std::max(ev.offset, 0);
1974 if (!lastPiece && offset >= start + len) break;
1975 const int local = std::clamp(offset - start, 0, len);
1976 const int atHi = (local >= len) ? lenHi : local * factor_ + shift_;
1977 if (atHi > cursor) { renderVoices(hiL, hiR, cursor, atHi); cursor = atHi; }
1978 offsetHi_ = cursor;
1979 apply(ev);
1980 ++e;
1981 }
1982 if (cursor < lenHi) renderVoices(hiL, hiR, cursor, lenHi);
1983 timeHi_ += lenHi;
1984 offsetHi_ = 0;
1985
1986 T* baseL = mix_[0].data();
1987 T* baseR = mix_[1].data();
1988 if (factor_ > 1)
1989 {
1990 T* ch[2] = { baseL, baseR };
1991 const AudioBufferView<T> base(ch, 2, len);
1992 if (factor_ == 2) os2_.downsample(base); else os4_.downsample(base);
1993 }
1994
1995 // Master volume, smoothed (10 ms) per output sample.
1996 const double targetGain = decibelsToGain(static_cast<double>(p(Param::MasterVolume)), -200.0);
1997 const double a = 1.0 - std::exp(-1.0 / (0.010 * baseRate_));
1998 const int nCh = out.getNumChannels();
1999 T* outL = nCh > 0 ? out.getChannel(0) : nullptr;
2000 T* outR = nCh > 1 ? out.getChannel(1) : nullptr;
2001 for (int i = 0; i < len; ++i)
2002 {
2003 masterGain_ += (targetGain - masterGain_) * a;
2004 const auto g = static_cast<T>(masterGain_);
2005 if (outR != nullptr)
2006 {
2007 outL[start + i] = baseL[i] * g;
2008 outR[start + i] = baseR[i] * g;
2009 }
2010 else if (outL != nullptr)
2011 {
2012 outL[start + i] = T(0.5) * (baseL[i] + baseR[i]) * g;
2013 }
2014 }
2015 }
2016
2017 // Voices render in chunks, two at a time. Each lane first gathers its
2018 // voice's sources and the per-sample values of its filter and amplifier;
2019 // then both filter recursions run in one loop. A ZDF ladder or SVF sample
2020 // is a chain of dependent operations, so a second independent chain in
2021 // flight nearly halves the filter's cost. The arithmetic per voice is
2022 // unchanged and every output sample still sums the voices in index order,
2023 // so the output is identical to rendering the voices one after another.
2024 // Without a filter there is no recursion to interleave: each voice
2025 // renders its whole stretch and adds itself to the output as it goes.
2026
2027 void renderVoices(T* hiL, T* hiR, int from, int to) noexcept
2028 {
2029 const auto type = static_cast<FilterType>(ip(Param::FilterType));
2030 if (type == FilterType::Off)
2031 {
2032 for (auto& v : voices_)
2033 if (v.active) gather(v, lanes_[0], from, to, type, hiL, hiR);
2034 return;
2035 }
2036 for (int c0 = from; c0 < to; c0 += kChunk)
2037 {
2038 const int c1 = std::min(to, c0 + kChunk);
2039 bool pending = false;
2040 for (auto& v : voices_)
2041 {
2042 if (!v.active) continue;
2043 gather(v, lanes_[pending ? 1 : 0], c0, c1, type, hiL, hiR);
2044 if (pending) mixLanes(type, hiL, hiR, true);
2045 pending = !pending;
2046 }
2047 if (pending) mixLanes(type, hiL, hiR, false);
2048 }
2049 }
2050
2054 void gather(Voice& v, Lane& lane, int from, int to, FilterType type, T* outL, T* outR) noexcept
2055 {
2056 const bool filtered = type != FilterType::Off;
2057 const bool ladder = type == FilterType::LadderLp24 || type == FilterType::LadderLp12
2058 || type == FilterType::LadderBp12 || type == FilterType::LadderHp24;
2059 lane.voice = &v;
2060 lane.start = from;
2061 int i = from;
2062 while (i < to)
2063 {
2064 if (v.tickLeft == 0)
2065 {
2066 offsetHi_ = i;
2067 controlTick(v);
2068 v.tickLeft = periodHi_;
2069 }
2070 const int m = std::min(to - i, v.tickLeft);
2071 const int at = filtered ? i - from : 0; // unfiltered: scratch per segment
2072 double* L = lane.l.data() + at;
2073 double* R = lane.r.data() + at;
2074 std::fill_n(L, m, 0.0);
2075 std::fill_n(R, m, 0.0);
2076 renderSources(v, L, R, m);
2077
2078 const int pos0 = v.tickPos;
2079 for (int j = 0; j < m; ++j)
2080 {
2081 const int pos = pos0 + j;
2082 const auto s = static_cast<size_t>(at + j);
2083 if (filtered)
2084 {
2085 lane.g[s] = static_cast<T>(v.g.at(pos));
2086 lane.q[s] = static_cast<T>(ladder ? v.resonance.at(pos) : v.svfK.at(pos));
2087 if (ladder) lane.drive[s] = static_cast<T>(v.drive.at(pos));
2088 }
2089 double gain = v.amp.getNextValue() * v.ampGain.at(pos);
2090 if (v.stealLeft >= 0)
2091 {
2092 gain *= static_cast<double>(v.stealLeft) / static_cast<double>(stealFade_);
2093 if (--v.stealLeft < 0)
2094 {
2095 lane.count = at + j;
2096 v.active = false;
2097 return;
2098 }
2099 }
2100 if (filtered)
2101 {
2102 lane.gain[s] = gain;
2103 lane.panL[s] = v.panL.at(pos);
2104 lane.panR[s] = v.panR.at(pos);
2105 }
2106 else
2107 {
2108 const double l = L[j];
2109 const double r = v.stereo ? R[j] : l;
2110 outL[i + j] += static_cast<T>(l * gain * v.panL.at(pos));
2111 outR[i + j] += static_cast<T>(r * gain * v.panR.at(pos));
2112 }
2113 if (!v.amp.isActive())
2114 {
2115 lane.count = at + j + 1;
2116 v.active = false;
2117 return;
2118 }
2119 }
2120 v.tickLeft -= m;
2121 v.tickPos += m;
2122 v.ageHi += m;
2123 i += m;
2124 }
2125 lane.count = to - from;
2126 }
2127
2128 void mixLanes(FilterType type, T* outL, T* outR, bool pair) noexcept
2129 {
2130 using detail::LadderTap;
2131 switch (type)
2132 {
2133 case FilterType::LadderLp24: mixWith<LadderKernel<LadderTap::LP24>>(outL, outR, pair); break;
2134 case FilterType::LadderLp12: mixWith<LadderKernel<LadderTap::LP12>>(outL, outR, pair); break;
2135 case FilterType::LadderBp12: mixWith<LadderKernel<LadderTap::BP12>>(outL, outR, pair); break;
2136 case FilterType::LadderHp24: mixWith<LadderKernel<LadderTap::HP24>>(outL, outR, pair); break;
2137 case FilterType::SvfHp: mixWith<SvfKernel<FilterType::SvfHp>>(outL, outR, pair); break;
2138 case FilterType::SvfBp: mixWith<SvfKernel<FilterType::SvfBp>>(outL, outR, pair); break;
2139 case FilterType::SvfNotch: mixWith<SvfKernel<FilterType::SvfNotch>>(outL, outR, pair); break;
2140 default: mixWith<SvfKernel<FilterType::SvfLp>>(outL, outR, pair); break;
2141 }
2142 }
2143
2146 template <class Kernel>
2147 void mixWith(T* outL, T* outR, bool pair) noexcept
2148 {
2149 Lane& a = lanes_[0];
2150 Lane& b = lanes_[1];
2151 const int both = pair ? std::min(a.count, b.count) : 0;
2152 for (int j = 0; j < both; ++j)
2153 {
2154 mixSample<Kernel>(a, j, outL, outR);
2155 mixSample<Kernel>(b, j, outL, outR);
2156 }
2157 for (int j = both; j < a.count; ++j) mixSample<Kernel>(a, j, outL, outR);
2158 if (pair)
2159 for (int j = both; j < b.count; ++j) mixSample<Kernel>(b, j, outL, outR);
2160 }
2161
2162 template <class Kernel>
2163 static void mixSample(Lane& lane, int j, T* outL, T* outR) noexcept
2164 {
2165 const auto s = static_cast<size_t>(j);
2166 Voice& v = *lane.voice;
2167 double l = lane.l[s];
2168 double r = v.stereo ? lane.r[s] : l;
2169 Kernel::run(v, lane, s, l, r);
2170 outL[lane.start + j] += static_cast<T>(l * lane.gain[s] * lane.panL[s]);
2171 outR[lane.start + j] += static_cast<T>(r * lane.gain[s] * lane.panR[s]);
2172 }
2173
2174 template <detail::LadderTap Tap> struct LadderKernel
2175 {
2176 static void run(Voice& v, const Lane& lane, size_t s, double& l, double& r) noexcept
2177 {
2178 const auto c = detail::makeLadderCoeffs(lane.g[s], lane.q[s]);
2179 const T drive = lane.drive[s];
2180 l = static_cast<double>(detail::ladderStep<Tap>(static_cast<T>(l), v.ladder[0], c, drive));
2181 r = v.stereo ? static_cast<double>(detail::ladderStep<Tap>(static_cast<T>(r), v.ladder[1], c, drive)) : l;
2182 }
2183 };
2184
2185 template <FilterType Type> struct SvfKernel
2186 {
2187 static T highpass(T x, T k, T bandpass, T lowpass) noexcept { return x - k * bandpass - lowpass; }
2188
2189 static double step(T x, detail::TptSvfState<T>& state, T a1, T a2, T a3, T k) noexcept
2190 {
2191 const auto o = detail::tptSvfStep(x, state, a1, a2, a3);
2192 if constexpr (Type == FilterType::SvfHp)
2193 return static_cast<double>(highpass(x, k, o.bandpass, o.lowpass));
2194 else if constexpr (Type == FilterType::SvfBp)
2195 return static_cast<double>(k * o.bandpass); // unit peak gain
2196 else if constexpr (Type == FilterType::SvfNotch)
2197 return static_cast<double>(o.lowpass + highpass(x, k, o.bandpass, o.lowpass));
2198 else
2199 return static_cast<double>(o.lowpass);
2200 }
2201
2202 static void run(Voice& v, const Lane& lane, size_t s, double& l, double& r) noexcept
2203 {
2204 const T g = lane.g[s];
2205 const T k = lane.q[s];
2206 const T a1 = T(1) / (T(1) + g * (g + k));
2207 const T a2 = g * a1;
2208 const T a3 = g * a2;
2209 l = step(static_cast<T>(l), v.svf[0], a1, a2, a3, k);
2210 r = v.stereo ? step(static_cast<T>(r), v.svf[1], a1, a2, a3, k) : l;
2211 }
2212 };
2213
2214 void renderSources(Voice& v, double* L, double* R, int m) noexcept
2215 {
2216 const int pos0 = v.tickPos;
2217 switch (v.engine)
2218 {
2219 case Engine::Analog: renderAnalog(v, L, R, m, pos0); break;
2220 case Engine::Wavetable: renderWavetable(v, L, R, m, pos0); break;
2221 case Engine::Fm: renderFm(v, L, R, m, pos0); break;
2222 }
2223
2224 // Sample source (every engine). Its readers keep moving while the
2225 // level is zero, so the sample stays in time if it comes back.
2226 if (v.zone != nullptr)
2227 {
2228 const bool audible = v.sampleLevel.live();
2229 const bool zoneStereo = v.zone->channels > 1;
2230 for (int u = 0; u < v.unison; ++u)
2231 {
2232 auto& uv = v.uni[static_cast<size_t>(u)];
2233 for (int j = 0; j < m && uv.readerOn; ++j)
2234 {
2235 double a0 = 0.0, a1 = 0.0;
2236 const auto frame = uv.reader.next(uv.sampleRatio.at(pos0 + j), 2, weights_.data(), a0, a1);
2237 if (frame == Reader::Frame::Ended) { uv.readerOn = false; break; }
2238 if (audible)
2239 {
2240 const double level = v.sampleLevel.at(pos0 + j);
2241 L[j] += a0 * v.zoneGainL * level * uv.gainL;
2242 R[j] += (zoneStereo ? a1 : a0) * v.zoneGainR * level * uv.gainR;
2243 }
2244 if (frame == Reader::Frame::Last) uv.readerOn = false;
2245 }
2246 }
2247 }
2248
2249 // Sub-oscillator and noise, centred.
2250 if (v.subLevel.live())
2251 for (int j = 0; j < m; ++j)
2252 {
2253 if (v.subFreq.step != 0.0) v.sub.setFrequency(static_cast<T>(v.subFreq.at(pos0 + j)));
2254 const double s = static_cast<double>(v.sub.getNextSample()) * v.subLevel.at(pos0 + j);
2255 L[j] += s;
2256 R[j] += s;
2257 }
2258 if (v.noiseLevel.live())
2259 for (int j = 0; j < m; ++j)
2260 {
2261 uint32_t x = v.noise;
2262 x ^= x << 13;
2263 x ^= x >> 17;
2264 x ^= x << 5;
2265 v.noise = x;
2266 const double s = (static_cast<double>(x) * (2.0 / 4294967296.0) - 1.0)
2267 * noiseScale_ * v.noiseLevel.at(pos0 + j);
2268 L[j] += s;
2269 R[j] += s;
2270 }
2271 }
2272
2273 void renderAnalog(Voice& v, double* L, double* R, int m, int pos0) noexcept
2274 {
2275 for (int k = 0; k < 3; ++k)
2276 {
2277 const auto& lv = v.oscLevel[static_cast<size_t>(k)];
2278 if (!lv.live()) continue;
2279 const auto& pw = v.pulseWidth[static_cast<size_t>(k)];
2280 const bool sync = ip(oscParam(k, 6)) != 0;
2281 const bool pulse = static_cast<OscWave>(ip(oscParam(k, 0))) == OscWave::Pulse;
2282 for (int u = 0; u < v.unison; ++u)
2283 {
2284 auto& uv = v.uni[static_cast<size_t>(u)];
2285 auto& o = uv.osc[static_cast<size_t>(k)];
2286 const auto& fr = uv.freq[static_cast<size_t>(k)];
2287 const auto& ms = uv.master[static_cast<size_t>(k)];
2288 const bool moving = fr.step != 0.0 || ms.step != 0.0;
2289 for (int j = 0; j < m; ++j)
2290 {
2291 const int pos = pos0 + j;
2292 if (moving)
2293 {
2294 if (sync)
2295 {
2296 const double mh = ms.at(pos);
2297 o.setFrequency(static_cast<T>(mh));
2298 o.setSyncRatio(static_cast<T>(mh > 0.0 ? fr.at(pos) / mh : 0.0));
2299 }
2300 else
2301 {
2302 o.setFrequency(static_cast<T>(fr.at(pos)));
2303 }
2304 }
2305 if (pulse && pw.step != 0.0) o.setPulseWidth(static_cast<T>(pw.at(pos)));
2306 const double s = static_cast<double>(o.getNextSample()) * lv.at(pos);
2307 L[j] += s * uv.gainL;
2308 R[j] += s * uv.gainR;
2309 }
2310 }
2311 }
2312 }
2313
2314 void renderWavetable(Voice& v, double* L, double* R, int m, int pos0) noexcept
2315 {
2316 for (int k = 0; k < 2; ++k)
2317 {
2318 const auto& lv = v.wtLevel[static_cast<size_t>(k)];
2319 if (!lv.live()) continue;
2320 const WavetableBank& bank = bankFor(v, k);
2321 const double frames = static_cast<double>(std::max(bank.getNumFrames() - 1, 0));
2322 const auto& wp = v.wtPosition[static_cast<size_t>(k)];
2323 // The bank reads a block per unison copy: the phases are
2324 // accumulated first (the same recursion as a per-sample loop),
2325 // then interpolated together, which the bank vectorises.
2326 constexpr int kWaveChunk = kControlPeriod * 4;
2327 for (int c0 = 0; c0 < m; c0 += kWaveChunk)
2328 {
2329 const int mc = std::min(kWaveChunk, m - c0);
2330 const bool morphing = wp.step != 0.0;
2331 std::array<double, kWaveChunk> positions; // written below when morphing
2332 if (morphing)
2333 for (int j = 0; j < mc; ++j)
2334 positions[static_cast<size_t>(j)] = wp.at(pos0 + c0 + j) * frames;
2335 const double still = wp.at(pos0 + c0) * frames;
2336 for (int u = 0; u < v.unison; ++u)
2337 {
2338 auto& uv = v.uni[static_cast<size_t>(u)];
2339 const auto& fr = uv.freq[static_cast<size_t>(k)];
2340 double& phase = uv.wtPhase[static_cast<size_t>(k)];
2341 const auto mip = uv.mip[static_cast<size_t>(k)];
2342 std::array<double, kWaveChunk> phases; // the first mc entries are written
2343 std::array<T, kWaveChunk> wave;
2344 for (int j = 0; j < mc; ++j)
2345 {
2346 phases[static_cast<size_t>(j)] = phase;
2347 phase += fr.at(pos0 + c0 + j) / internalRate_;
2348 if (phase >= 1.0) phase -= 1.0;
2349 }
2350 if (morphing)
2351 bank.readBlock<T>(phases.data(), positions.data(), mip, wave.data(), mc);
2352 else
2353 bank.readBlock<T>(phases.data(), still, mip, wave.data(), mc);
2354 for (int j = 0; j < mc; ++j)
2355 {
2356 const double s = static_cast<double>(wave[static_cast<size_t>(j)]) * lv.at(pos0 + c0 + j);
2357 L[c0 + j] += s * uv.gainL;
2358 R[c0 + j] += s * uv.gainR;
2359 }
2360 }
2361 }
2362 }
2363 }
2364
2365 void renderFm(Voice& v, double* L, double* R, int m, int pos0) noexcept
2366 {
2367 // Modulation index: an operator at full level and envelope deviates
2368 // its target's phase by up to 4 pi radians.
2369 constexpr double kIndex = 4.0 * pi<double>;
2370 constexpr int kMax = kControlPeriod * 4;
2371 const int algorithm = std::clamp(ip(Param::FmAlgorithm), 0, 7);
2372
2373 // Operator amplitudes (level times envelope), shared by the unison
2374 // copies. A silent operator costs no sine; its phase keeps running.
2375 std::array<std::array<double, kMax>, 4> amp; // every used entry is written below
2376 std::array<bool, 4> live {};
2377 for (int k = 0; k < 4; ++k) live[static_cast<size_t>(k)] = v.opLevel[static_cast<size_t>(k)].live();
2378 for (int j = 0; j < m; ++j)
2379 for (int k = 0; k < 4; ++k)
2380 amp[static_cast<size_t>(k)][static_cast<size_t>(j)] =
2381 v.opLevel[static_cast<size_t>(k)].at(pos0 + j) * v.opEnv[static_cast<size_t>(k)].getNextValue();
2382
2383 for (int u = 0; u < v.unison; ++u)
2384 {
2385 auto& uv = v.uni[static_cast<size_t>(u)];
2386 for (int j = 0; j < m; ++j)
2387 {
2388 const int pos = pos0 + j;
2389 auto op = [&](int k, double pm) noexcept {
2390 return live[static_cast<size_t>(k)]
2391 ? amp[static_cast<size_t>(k)][static_cast<size_t>(j)]
2392 * fastSin(twoPi<double> * uv.opPhase[static_cast<size_t>(k)] + pm)
2393 : 0.0;
2394 };
2395 // Operator 4 feeds back the mean of its last two outputs.
2396 const double o4 = op(3, v.feedback.at(pos) * pi<double> * 0.5 * (uv.fb1 + uv.fb2));
2397 uv.fb2 = uv.fb1;
2398 uv.fb1 = o4;
2399 double out = 0.0;
2400 switch (algorithm)
2401 {
2402 case 0: { const double o3 = op(2, kIndex * o4); const double o2 = op(1, kIndex * o3);
2403 out = op(0, kIndex * o2); break; }
2404 case 1: { const double o3 = op(2, 0.0); const double o2 = op(1, kIndex * (o3 + o4));
2405 out = op(0, kIndex * o2); break; }
2406 case 2: { const double o3 = op(2, 0.0); const double o2 = op(1, kIndex * o3);
2407 out = op(0, kIndex * (o2 + o4)); break; }
2408 case 3: { const double o3 = op(2, kIndex * o4); const double o2 = op(1, 0.0);
2409 out = op(0, kIndex * (o2 + o3)); break; }
2410 case 4: { const double o3 = op(2, kIndex * o4); const double o2 = op(1, 0.0);
2411 out = 0.5 * (op(0, kIndex * o2) + o3); break; }
2412 case 5: out = (op(0, kIndex * o4) + op(1, kIndex * o4) + op(2, kIndex * o4)) / 3.0; break;
2413 case 6: out = (op(0, 0.0) + op(1, 0.0) + op(2, kIndex * o4)) / 3.0; break;
2414 default: out = 0.25 * (op(0, 0.0) + op(1, 0.0) + op(2, 0.0) + o4); break;
2415 }
2416 for (int k = 0; k < 4; ++k)
2417 {
2418 double& ph = uv.opPhase[static_cast<size_t>(k)];
2419 ph += uv.opFreq[static_cast<size_t>(k)].at(pos) / internalRate_;
2420 if (ph >= 1.0) ph -= 1.0;
2421 }
2422 L[j] += out * uv.gainL;
2423 R[j] += out * uv.gainR;
2424 }
2425 }
2426 }
2427
2428 // ===================================================================================
2429 // Members
2430 // ===================================================================================
2431
2432
2433 std::array<std::atomic<float>, kNumParams> values_ {};
2434 std::array<float, kNumParams> params_ {};
2435 std::atomic<float> tempo_ { 120.0f };
2436 float tempoApplied_ = 120.0f;
2437
2438 double baseRate_ = 48000.0;
2439 double internalRate_ = 48000.0;
2440 int maxBlock_ = 512;
2441 int maxVoices_ = 16;
2442 int factor_ = 1;
2443 int periodHi_ = kControlPeriod;
2444 double invPeriod_ = 1.0 / kControlPeriod;
2445 int shift_ = 0;
2446 int stealFade_ = 144;
2447 double noiseScale_ = 1.0;
2448 double smoothAlpha_ = 0.03;
2449 bool prepared_ = false;
2450
2451 std::vector<Voice> voices_;
2452 std::vector<T> weights_;
2453 std::array<std::vector<T>, 2> mix_;
2454 std::array<Lane, 2> lanes_ {};
2455 Oversampling<T, 2> os2_ { 2, Oversampling<T, 2>::Quality::Maximum };
2456 Oversampling<T, 2> os4_ { 4, Oversampling<T, 2>::Quality::Maximum };
2457
2458 std::array<Event, kMaxEvents> events_ {};
2459 int eventCount_ = 0;
2460 std::array<int, 128> held_ {};
2461 std::array<double, 128> heldTuning_ {};
2462 int heldCount_ = 0;
2463 bool sustainPedal_ = false;
2464 double bend_ = 0.0;
2465 double modWheel_ = 0.0;
2466 double pressure_ = 0.0;
2467 double expression_ = 1.0;
2468 double breath_ = 0.0;
2469 double lastPitch_ = -1.0;
2470 bool haveLastPitch_ = false;
2471 double masterGain_ = 0.5;
2472 uint64_t noteCounter_ = 0;
2473 uint64_t clock_ = 0;
2474 int64_t timeHi_ = 0;
2475 int offsetHi_ = 0;
2476 std::array<FreeLfo, 2> freeLfo_ {};
2477
2478 // Control thread's current content, shared with what it publishes.
2479 std::shared_ptr<const std::vector<ZoneData>> controlZones_;
2480 std::shared_ptr<const WavetableBank> controlWavetable_;
2481
2482 Content* active_ = nullptr;
2483 Content* fading_ = nullptr;
2484 std::atomic<Content*> pending_ { nullptr };
2485 std::atomic<Content*> retired_ { nullptr };
2486
2487 std::atomic<int> latency_ { 0 };
2488 std::atomic<int> activeVoices_ { 0 };
2489};
2490
2491} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
static double valueAt(Shape shape, double cycles, uint64_t seed) noexcept
The shape's value at an absolute cycle position.
Definition Lfo.h:399
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
Division
Note values for tempo sync (four beats to the whole note).
Definition Lfo.h:100
Shared minimum-phase band-limited step (minBLEP) residual table.
AudioBufferView< T > getHighRateBlock(int numSamples) noexcept
Writable high-rate block for a source that renders directly at the oversampled rate (a synthesizer,...
void downsample(AudioBufferView< T > output) noexcept
Downsamples the internal high-rate buffer back to base-rate.
void reset() noexcept
Flushes all internal delay lines and history buffers. Call this when resetting the transport or to cl...
int getDecimationDelay() const noexcept
Group delay of the decimation path alone, in HIGH-RATE samples.
void prepare(const AudioSpec &spec)
Pre-allocates buffers and computes FIR filter coefficients.
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
Polyphonic synthesizer with analog, FM and wavetable engines and a sample source.
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant: missing ids keep their defaults, unknown ids are ignored; ...
synthesizer::FilterType FilterType
void noteOn(int key, T velocity, int offset=0) noexcept
Starts a note offset samples into the next block; velocity 0..1 (0 is a note-off, as in MIDI).
int getMaxVoices() const noexcept
Polyphony prepared (the upper bound of voice.polyphony).
void setTempo(double bpm) noexcept
Tempo for tempo-synced LFOs, 1..999 BPM (default 120).
void setModWheel(T value, int offset=0) noexcept
Mod wheel (CC 1), 0..1.
bool loadUserWavetable(const T *frames, int frameSize, int numFrames)
Loads the user wavetable (bank "User"): consecutive single-cycle frames, analysed as WavetableBank::l...
Synthesizer(const Synthesizer &)=delete
std::vector< uint8_t > getState() const
Serializes every parameter by id (allocates). Samples and the user wavetable are data,...
synthesizer::ModDest ModDest
synthesizer::Param Param
synthesizer::ParamInfo ParamInfo
synthesizer::PhaseMode PhaseMode
int getLatency() const noexcept
Output delay in base-rate samples (0 at 1x; 64 at 2x, 68 at 4x).
void setSustainPedal(bool down, int offset=0) noexcept
Sustain pedal: while down, released keys keep sounding.
synthesizer::LfoMode LfoMode
static constexpr const ParamInfo & getParamInfo(Param p) noexcept
The description of a parameter.
bool loadSample(AudioBufferView< const T > audio, double sampleRate, int rootKey=60)
One zone over the whole keyboard and velocity range.
synthesizer::OscWave OscWave
void clearSampleZones()
Removes the sample zones (the user wavetable is kept).
static constexpr int kMaxEvents
int getActiveVoiceCount() const noexcept
Voices sounding after the last block, stealing fades included.
bool setSampleZones(std::span< const SampleZoneSpec< T > > zones)
Replaces the zones the sample source plays (sample.level).
static int findParam(std::string_view id) noexcept
Index of the parameter with this id, or -1.
Synthesizer() noexcept
void setParameter(Param param, float value) noexcept
Sets a parameter, clamped to its range and rounded to its steps; NaN is ignored. Takes effect at the ...
void allNotesOff(int offset=0) noexcept
Releases every sounding note (and lifts the pedal).
static constexpr int kNumParams
void setPitchBend(T bend, int offset=0) noexcept
Pitch bend, -1..+1 (scaled by voice.bendRange semitones).
void setChannelPressure(T value, int offset=0) noexcept
Channel pressure, 0..1.
void prepare(const AudioSpec &spec, int maxVoices=16)
Allocates the voices, buffers and oversamplers and builds the shared tables (minBLEP,...
void noteOff(int key, T releaseVelocity=T(0), int offset=0) noexcept
Releases a note; releaseVelocity 0..1 is a modulation source.
static constexpr int kMaxPolyphony
synthesizer::Engine Engine
void noteOnTuned(int key, T velocity, T tuningCents, int offset=0) noexcept
Starts a note with individual fine tuning in cents, clamped to -100..100. The tuned pitch is the glid...
static constexpr int kControlPeriod
Base-rate samples between modulation evaluations (interpolated between).
Synthesizer & operator=(const Synthesizer &)=delete
synthesizer::GlideMode GlideMode
static constexpr int kModSlots
static constexpr int kMaxUnison
void reset() noexcept
Silences every voice, drops queued events and restarts the note count, the controllers and the free L...
bool setParameter(std::string_view id, float value) noexcept
Sets a parameter by id; false for an unknown id.
synthesizer::VoiceMode VoiceMode
void setController(int controller, T value, int offset=0) noexcept
A MIDI control change, value 0..1: 1 mod wheel, 2 breath, 11 expression (it also scales the amplifier...
void processBlock(AudioBufferView< T > out) noexcept
Renders the block, overwriting out, and applies the queued events at their offsets....
synthesizer::SubWave SubWave
synthesizer::ModSource ModSource
float getParameter(Param param) const noexcept
The value last set (any thread).
void setPolyPressure(int key, T value, int offset=0) noexcept
Polyphonic pressure of one key, 0..1.
static constexpr int kNumBuiltins
static const WavetableBank & builtin(Builtin which)
A built-in bank, built on the first call and shared by the process.
Builtin
Built-in banks (see builtin()).
@ Basic
6 frames: sine, triangle, saw, square, 25% and 12.5% pulse.
Mip selectMip(double frequencyHz, double sampleRate) const noexcept
Chooses the level pair and crossfade weight for a pitch.
One voice's position in a zone and its band-limited read.
static const std::vector< T > & polyphaseTable()
static constexpr double kMinScatterRate
Lowest rate of the scatter form, whose kernel widens as the rate falls.
static constexpr int kWeightsLength
Scratch weights a caller provides to next().
@ Ended
The zone ended before this sample: nothing produced.
@ Last
A frame was produced and it was the last one.
@ Pink
1/f noise for organic drift.
constexpr int delay
Delay of the projected output behind the newest input, in samples.
bool buildSampleZone(const SampleZoneSpec< T > &z, SampleZoneData< T > &d)
Validates and copies a zone, clamping its loop and baking the loop crossfade. False (and d unspecifie...
TptSvfOutput< T > tptSvfStep(T input, TptSvfState< T > &state, T a1, T a2, T a3) noexcept
Advances the expanded Simper TPT recurrence by one sample.
Definition TptSvf.h:43
void sampleZonePanGains(double pan, int channels, double gain, double &left, double &right, double &mono) noexcept
Output gains of a zone at gain: a mono zone pans with constant power (unity at centre),...
LadderCoeffs< T > makeLadderCoeffs(T g, T res) noexcept
Derives the ladder coefficients.
Definition LadderZdf.h:48
LadderTap
Output tap mix of the four-stage cascade.
Definition LadderZdf.h:28
constexpr Param param(const char *id, const char *name, float minValue, float maxValue, float defValue, const char *unit) noexcept
Continuous parameter helper.
constexpr ParamInfo choice(Param p, const char *id, const char *name, const char *const (&labels)[N], int def) noexcept
constexpr ParamInfo toggle(Param p, const char *id, const char *name, bool def) noexcept
constexpr ParamInfo cont(Param p, const char *id, const char *name, float lo, float hi, float def, const char *unit) noexcept
constexpr ParamInfo integer(Param p, const char *id, const char *name, int lo, int hi, int def, const char *unit) noexcept
constexpr const char * kDivisionLabels[]
constexpr const char * kOscWaveLabels[]
ModSource
Modulation sources (values: velocity, pressure, wheel, expression and breath 0..1; key (key - 60) / 6...
constexpr const char * kGlideModeLabels[]
constexpr int kModSlots
constexpr int kNumParams
constexpr int kMaxUnison
constexpr const char * kAlgorithmLabels[]
constexpr const char * kEngineLabels[]
constexpr const char * kSubWaveLabels[]
constexpr const char * kSubOctaveLabels[]
constexpr const char * kLfoShapeLabels[]
constexpr bool tableIsConsistent() noexcept
True when the table is in Param order, ids are unique and every default lies in its range.
constexpr int kNumModDests
constexpr const char * kPhaseLabels[]
constexpr std::array< ParamInfo, kNumParams > kParams
The parameter table, indexed by Param.
ModDest
Modulation destinations. OscN Pitch and OscN Level reach analog oscillator N and wavetable oscillator...
constexpr const char * kVoiceModeLabels[]
Param
Every parameter, in the order of the parameter table.
constexpr const char * kModDestLabels[]
constexpr const char * kLfoModeLabels[]
constexpr const char * kModSourceLabels[]
constexpr int kMaxPolyphony
constexpr const char * kFilterLabels[]
constexpr const char * kOversamplingLabels[]
constexpr int kNumModSources
int findParam(std::string_view id) noexcept
Index of the parameter with this id, or -1.
constexpr const char * kBankLabels[]
Main namespace for the DSPark framework.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
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
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
One zone, as the caller describes it.
Definition SampleZone.h:39
int rootKey
MIDI key that plays it untransposed.
Definition SampleZone.h:42
AudioBufferView< const T > audio
The recording (1 or more channels).
Definition SampleZone.h:40
double sampleRate
Its sample rate.
Definition SampleZone.h:41
One validated zone, its audio copied and its loop crossfade baked.
Description of one parameter (the shape of the plugin layer's parameter declarations,...
const char *const * labels
const char * id
Stable text id (state keys, automation identity).
const char * unit
"ms", "Hz", "dB", "cents", "st", "oct", "voices" or "".
const char * name
Display name.