DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Sampler.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
80#include "DspMath.h"
81#include "AudioBuffer.h"
82#include "AudioSpec.h"
83#include "EnvelopeGenerator.h"
84#include "SampleZone.h"
85#include "detail/SampleReader.h"
86
87#include <algorithm>
88#include <array>
89#include <atomic>
90#include <cmath>
91#include <cstdint>
92#include <memory>
93#include <new>
94#include <span>
95#include <vector>
96
97namespace dspark {
98
114template <FloatType T>
116{
117public:
121 static constexpr int kMaxEvents = 1024;
122
125
129
130 Sampler() = default;
132 {
133 delete pending_.exchange(nullptr, std::memory_order_acq_rel);
134 delete retired_.exchange(nullptr, std::memory_order_acq_rel);
135 delete fading_;
136 delete active_;
137 }
138 Sampler(const Sampler&) = delete;
139 Sampler& operator=(const Sampler&) = delete;
140
141 // -- Lifecycle ---------------------------------------------------------------
142
149 void prepare(const AudioSpec& spec, int maxVoices = 32)
150 {
151 if (!(spec.sampleRate > 0.0) || !std::isfinite(spec.sampleRate) || spec.numChannels < 1)
152 return;
153 sampleRate_ = spec.sampleRate;
154 polyphony_ = std::clamp(maxVoices, 1, 256);
155 voices_.assign(static_cast<size_t>(2 * polyphony_ + 2), Voice {});
156 for (auto& v : voices_)
157 {
158 v.env.prepare(sampleRate_);
159 v.reader.allocate();
160 }
161 weights_.assign(static_cast<size_t>(Reader::kWeightsLength), T(0));
162 (void)Reader::polyphaseTable(); // build the shared tables here, never on the audio thread
163 stealFadeSamples_ = std::max(1, static_cast<int>(std::lround(0.003 * sampleRate_)));
164 gainCoeff_ = 1.0 - std::exp(-1.0 / (0.010 * sampleRate_));
165 reset();
166 prepared_ = true;
167 }
168
170 void reset() noexcept
171 {
172 for (auto& v : voices_) { v.active = false; v.env.reset(); }
173 eventCount_ = 0;
174 sustainPedal_ = false;
175 pitchBend_ = 0.0;
176 currentGain_ = outputGain_.load(std::memory_order_relaxed);
177 activeVoices_.store(0, std::memory_order_relaxed);
178 }
179
180 // -- Zones (control thread) --------------------------------------------------
181
192 bool setZones(std::span<const ZoneSpec> zones)
193 {
194 reclaim();
195 auto set = std::make_unique<ZoneSet>();
196 set->zones.reserve(zones.size());
197 for (const ZoneSpec& z : zones)
198 {
199 ZoneData d;
200 if (!detail::buildSampleZone(z, d)) return false;
201 set->zones.push_back(std::move(d));
202 }
203 publish(set.release());
204 return true;
205 }
206
208 bool loadSample(AudioBufferView<const T> audio, double sampleRate, int rootKey = 60)
209 {
210 ZoneSpec z;
211 z.audio = audio;
212 z.sampleRate = sampleRate;
213 z.rootKey = rootKey;
214 return setZones(std::span<const ZoneSpec>(&z, 1));
215 }
216
218 void clearZones() { reclaim(); publish(new ZoneSet {}); }
219
220 // -- Parameters (any thread) --------------------------------------------------
221
224 void setEnvelope(T attackMs, T decayMs, T sustain, T releaseMs) noexcept
225 {
226 if (!std::isfinite(attackMs) || !std::isfinite(decayMs)
227 || !std::isfinite(sustain) || !std::isfinite(releaseMs)) return;
228 attackMs_.store(std::max(0.01, static_cast<double>(attackMs)), std::memory_order_relaxed);
229 decayMs_.store(std::max(0.01, static_cast<double>(decayMs)), std::memory_order_relaxed);
230 sustain_.store(std::clamp(static_cast<double>(sustain), 0.0, 1.0), std::memory_order_relaxed);
231 releaseMs_.store(std::max(0.01, static_cast<double>(releaseMs)), std::memory_order_relaxed);
232 }
233
236 void setVelocityRange(T rangeDb) noexcept
237 {
238 if (!std::isfinite(rangeDb)) return;
239 velocityRangeDb_.store(std::clamp(static_cast<double>(rangeDb), 0.0, 96.0),
240 std::memory_order_relaxed);
241 }
242
244 void setGain(T dB) noexcept
245 {
246 if (!std::isfinite(dB)) return;
247 outputGain_.store(std::pow(10.0, std::clamp(static_cast<double>(dB), -120.0, 24.0) / 20.0),
248 std::memory_order_relaxed);
249 }
250
251 // -- Events (audio thread) ----------------------------------------------------
252
255 void noteOn(int key, T velocity, int offset = 0) noexcept
256 {
257 noteOnTuned(key, velocity, T(0), offset);
258 }
259
265 void noteOnTuned(int key, T velocity, T tuningCents, int offset = 0) noexcept
266 {
267 if (!std::isfinite(velocity) || !std::isfinite(tuningCents)) return;
268 if (velocity <= T(0)) { noteOff(key, offset); return; }
269 push({ EventType::NoteOn, std::clamp(key, 0, 127),
270 std::clamp(static_cast<double>(velocity), 0.0, 1.0), offset,
271 std::clamp(static_cast<double>(tuningCents), -100.0, 100.0) });
272 }
273
275 void noteOff(int key, int offset = 0) noexcept
276 {
277 push({ EventType::NoteOff, std::clamp(key, 0, 127), 0.0, offset });
278 }
279
281 void setSustainPedal(bool down, int offset = 0) noexcept
282 {
283 push({ EventType::Pedal, 0, down ? 1.0 : 0.0, offset });
284 }
285
287 void setPitchBend(T semitones, int offset = 0) noexcept
288 {
289 if (!std::isfinite(semitones)) return;
290 push({ EventType::Bend, 0, std::clamp(static_cast<double>(semitones), -48.0, 48.0), offset });
291 }
292
294 void allNotesOff(int offset = 0) noexcept
295 {
296 push({ EventType::AllOff, 0, 0.0, offset });
297 }
298
299 // -- Processing (audio thread) -------------------------------------------------
300
311 {
312 const int n = out.getNumSamples();
313 const int nCh = out.getNumChannels();
314 for (int c = 0; c < nCh; ++c)
315 std::fill_n(out.getChannel(c), n, T(0));
316 if (!prepared_) { eventCount_ = 0; return; }
317 if (n <= 0) return; // a host flush: the queued events wait for real samples
318
319 adoptPending();
320
321 int cursor = 0;
322 for (int e = 0; e < eventCount_; ++e)
323 {
324 const int at = std::clamp(events_[static_cast<size_t>(e)].offset, 0, n);
325 if (at > cursor) { render(out, cursor, at); cursor = at; }
326 apply(events_[static_cast<size_t>(e)]);
327 }
328 eventCount_ = 0;
329 if (cursor < n) render(out, cursor, n);
330
331 applyOutputGain(out, n);
332
333 retireFadedSet();
334 int count = 0;
335 for (const auto& v : voices_) count += v.active ? 1 : 0;
336 activeVoices_.store(count, std::memory_order_relaxed);
337 }
338
340 [[nodiscard]] int getActiveVoiceCount() const noexcept
341 {
342 return activeVoices_.load(std::memory_order_relaxed);
343 }
344
346 [[nodiscard]] int getPolyphony() const noexcept { return polyphony_; }
347
348private:
349 using Reader = detail::SampleReader<T>;
350 using ZoneData = detail::SampleZoneData<T>;
351
352 struct ZoneSet { std::vector<ZoneData> zones; };
353
354 // -- Publication -------------------------------------------------------------------
355
357 void reclaim() noexcept
358 {
359 delete retired_.exchange(nullptr, std::memory_order_acq_rel);
360 }
361
363 void publish(ZoneSet* set) noexcept
364 {
365 delete pending_.exchange(set, std::memory_order_acq_rel);
366 }
367
369 void adoptPending() noexcept
370 {
371 if (fading_ != nullptr) return; // one handover at a time
372 ZoneSet* next = pending_.exchange(nullptr, std::memory_order_acq_rel);
373 if (next == nullptr) return;
374 fading_ = active_;
375 active_ = next;
376 }
377
379 void retireFadedSet() noexcept
380 {
381 if (fading_ == nullptr) return;
382 for (const auto& v : voices_)
383 if (v.active && v.set == fading_) return;
384 if (retired_.load(std::memory_order_acquire) != nullptr) return;
385 retired_.store(fading_, std::memory_order_release);
386 fading_ = nullptr;
387 }
388
389 // -- Voices --------------------------------------------------------------------------
390
391 struct Voice
392 {
393 bool active = false;
394 const ZoneSet* set = nullptr;
395 int key = 0;
396 double baseRatio = 1.0;
397 bool held = true;
398 bool sustained = false;
399 double gainL = 1.0, gainR = 1.0, gainMono = 1.0;
400 int stealLeft = -1;
401 uint64_t age = 0;
402 ADSREnvelope<double> env;
403 Reader reader;
404 };
405
406 enum class EventType { NoteOn, NoteOff, Pedal, Bend, AllOff };
407 struct Event { EventType type; int key; double value; int offset; double tuningCents = 0.0; };
408
409 void push(const Event& e) noexcept
410 {
411 if (!prepared_ || eventCount_ >= kMaxEvents) return;
412 // Keep the queue ordered by offset; events with equal offsets keep
413 // their call order.
414 int i = eventCount_++;
415 while (i > 0 && events_[static_cast<size_t>(i - 1)].offset > e.offset)
416 {
417 events_[static_cast<size_t>(i)] = events_[static_cast<size_t>(i - 1)];
418 --i;
419 }
420 events_[static_cast<size_t>(i)] = e;
421 }
422
423 void apply(const Event& e) noexcept
424 {
425 switch (e.type)
426 {
427 case EventType::NoteOn: startNote(e.key, e.value, e.tuningCents); break;
428 case EventType::NoteOff: releaseKey(e.key); break;
429 case EventType::Bend: pitchBend_ = e.value; break;
430 case EventType::Pedal:
431 sustainPedal_ = e.value > 0.5;
432 if (!sustainPedal_)
433 for (auto& v : voices_)
434 if (v.active && v.sustained) release(v);
435 break;
436 case EventType::AllOff:
437 sustainPedal_ = false;
438 for (auto& v : voices_)
439 if (v.active && v.stealLeft < 0) release(v);
440 break;
441 }
442 }
443
444 void release(Voice& v) noexcept
445 {
446 v.held = false;
447 v.sustained = false;
448 v.env.setRelease(static_cast<double>(releaseMs_.load(std::memory_order_relaxed)));
449 v.env.noteOff();
450 v.reader.release();
451 }
452
453 void releaseKey(int key) noexcept
454 {
455 for (auto& v : voices_)
456 if (v.active && v.held && v.key == key && v.stealLeft < 0)
457 {
458 if (sustainPedal_) { v.held = false; v.sustained = true; }
459 else release(v);
460 }
461 }
462
463 void startNote(int key, double velocity, double tuningCents) noexcept
464 {
465 if (active_ == nullptr) return;
466 // A retriggered key releases what it was playing.
467 for (auto& v : voices_)
468 if (v.active && v.key == key && v.stealLeft < 0 && (v.held || v.sustained))
469 release(v);
470
471 const double velGain = std::pow(10.0, velocityRangeDb_.load(std::memory_order_relaxed)
472 * (velocity - 1.0) / 20.0);
473 for (const ZoneData& z : active_->zones)
474 {
475 if (key < z.keyLow || key > z.keyHigh || velocity < z.velLow || velocity > z.velHigh)
476 continue;
477 Voice* v = freeVoice();
478 if (v == nullptr) return;
479 v->active = true;
480 v->set = active_;
481 v->key = key;
482 v->baseRatio = z.sampleRate / sampleRate_
483 * std::pow(2.0, (key - z.rootKey + (z.tuneCents + tuningCents) / 100.0) / 12.0);
484 v->reader.start(z, v->baseRatio * std::pow(2.0, pitchBend_ / 12.0));
485 v->held = true;
486 v->sustained = false;
487 v->stealLeft = -1;
488 v->age = ++clock_;
489 // Constant power for a mono zone (unity at centre), balance otherwise.
490 detail::sampleZonePanGains(z.pan, z.channels, z.gain * velGain,
491 v->gainL, v->gainR, v->gainMono);
492 v->env.setParameters(attackMs_.load(std::memory_order_relaxed),
493 decayMs_.load(std::memory_order_relaxed),
494 sustain_.load(std::memory_order_relaxed),
495 releaseMs_.load(std::memory_order_relaxed));
496 v->env.reset();
497 v->env.noteOn();
498 }
499 }
500
503 Voice* freeVoice() noexcept
504 {
505 int sounding = 0;
506 Voice* idle = nullptr;
507 for (auto& v : voices_)
508 {
509 if (!v.active) { if (idle == nullptr) idle = &v; }
510 else if (v.stealLeft < 0) ++sounding;
511 }
512 if (sounding < polyphony_ && idle != nullptr) return idle;
513
514 // Steal: the oldest released voice, else the quietest, else the oldest.
515 Voice* victim = nullptr;
516 for (auto& v : voices_)
517 {
518 if (!v.active || v.stealLeft >= 0) continue;
519 if (victim == nullptr) { victim = &v; continue; }
520 const bool vr = !v.held && !v.sustained, cr = !victim->held && !victim->sustained;
521 if (vr != cr) { if (vr) victim = &v; continue; }
522 const double va = v.env.getCurrentValue(), ca = victim->env.getCurrentValue();
523 if (va < ca - 1e-9 || (std::abs(va - ca) <= 1e-9 && v.age < victim->age)) victim = &v;
524 }
525 if (victim != nullptr) victim->stealLeft = stealFadeSamples_;
526 if (idle != nullptr) return idle;
527 // No spare slot left: the oldest stealing fade is cut short.
528 Voice* oldest = nullptr;
529 for (auto& v : voices_)
530 if (v.active && v.stealLeft >= 0 && (oldest == nullptr || v.age < oldest->age)) oldest = &v;
531 if (oldest != nullptr) oldest->active = false;
532 return oldest;
533 }
534
535 // -- Rendering --------------------------------------------------------------------------
536
539 void applyOutputGain(AudioBufferView<T> out, int n) noexcept
540 {
541 const double target = outputGain_.load(std::memory_order_relaxed);
542 const int channels = std::min(out.getNumChannels(), 2);
543 int i = 0;
544 for (; i < n && currentGain_ != target; ++i)
545 {
546 currentGain_ += (target - currentGain_) * gainCoeff_;
547 if (std::abs(target - currentGain_) < 1e-9) currentGain_ = target;
548 for (int c = 0; c < channels; ++c)
549 {
550 T* d = out.getChannel(c);
551 d[i] = static_cast<T>(d[i] * currentGain_);
552 }
553 }
554 if (currentGain_ == 1.0) return;
555 for (int c = 0; c < channels; ++c)
556 {
557 T* d = out.getChannel(c);
558 for (int s = i; s < n; ++s) d[s] = static_cast<T>(d[s] * currentGain_);
559 }
560 }
561
564 static bool advanceGain(Voice& v, int stealFade, double& gain) noexcept
565 {
566 gain = v.env.getNextValue();
567 if (v.stealLeft >= 0)
568 {
569 gain *= static_cast<double>(v.stealLeft) / static_cast<double>(stealFade);
570 if (--v.stealLeft < 0) { v.active = false; return false; }
571 }
572 if (!v.env.isActive()) { v.active = false; return false; }
573 return true;
574 }
575
576 void emit(AudioBufferView<T> out, int s, const Voice& v, double a0, double a1, double gain) noexcept
577 {
578 const int nCh = out.getNumChannels();
579 if (nCh < 1) return;
580 if (nCh == 1)
581 out.getChannel(0)[s] += static_cast<T>(a0 * v.gainMono * gain);
582 else
583 {
584 out.getChannel(0)[s] += static_cast<T>(a0 * v.gainL * gain);
585 out.getChannel(1)[s] += static_cast<T>((v.reader.zone()->channels == 1 ? a0 : a1) * v.gainR * gain);
586 }
587 }
588
589 void render(AudioBufferView<T> out, int from, int to) noexcept
590 {
591 const double bendRatio = std::pow(2.0, pitchBend_ / 12.0);
592 const int nCh = out.getNumChannels();
593 for (auto& v : voices_)
594 {
595 if (!v.active) continue;
596 const double ratio = std::clamp(v.baseRatio * bendRatio, v.reader.minRate(), Reader::kMaxRate);
597 for (int s = from; s < to; ++s)
598 {
599 double a0 = 0.0, a1 = 0.0;
600 const auto frame = v.reader.next(ratio, nCh, weights_.data(), a0, a1);
601 if (frame == Reader::Frame::Ended) { v.active = false; break; }
602 double gain = 0.0;
603 if (!advanceGain(v, stealFadeSamples_, gain)) break;
604 emit(out, s, v, a0, a1, gain);
605 if (frame == Reader::Frame::Last) { v.active = false; break; }
606 }
607 }
608 }
609
610 // -- Members ------------------------------------------------------------------------------
611
612
613 double sampleRate_ = 48000.0;
614 int polyphony_ = 0;
615 bool prepared_ = false;
616 int stealFadeSamples_ = 144;
617 uint64_t clock_ = 0;
618 double gainCoeff_ = 0.002;
619 double currentGain_ = 1.0;
620
621 std::vector<Voice> voices_;
622 std::vector<T> weights_;
623 std::array<Event, kMaxEvents> events_ {};
624 int eventCount_ = 0;
625 bool sustainPedal_ = false;
626 double pitchBend_ = 0.0;
627
628 ZoneSet* active_ = nullptr;
629 ZoneSet* fading_ = nullptr;
630 std::atomic<ZoneSet*> pending_ { nullptr };
631 std::atomic<ZoneSet*> retired_ { nullptr };
632
633 std::atomic<double> attackMs_ { 1.0 };
634 std::atomic<double> decayMs_ { 100.0 };
635 std::atomic<double> sustain_ { 1.0 };
636 std::atomic<double> releaseMs_ { 100.0 };
637 std::atomic<double> velocityRangeDb_ { 24.0 };
638 std::atomic<double> outputGain_ { 1.0 };
639 std::atomic<int> activeVoices_ { 0 };
640};
641
642} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Polyphonic multi-zone sample player.
Definition Sampler.h:116
Sampler()=default
void allNotesOff(int offset=0) noexcept
Releases every sounding note (and lifts the pedal).
Definition Sampler.h:294
int getActiveVoiceCount() const noexcept
Voices sounding after the last block, stealing fades included.
Definition Sampler.h:340
int getPolyphony() const noexcept
Polyphony set by prepare().
Definition Sampler.h:346
void clearZones()
Publishes an empty zone set: sounding voices finish, new notes are silent.
Definition Sampler.h:218
void processBlock(AudioBufferView< T > out) noexcept
Renders the block, overwriting out, and applies the queued events at their offsets....
Definition Sampler.h:310
void reset() noexcept
Silences every voice and drops queued events. Audio thread.
Definition Sampler.h:170
void setVelocityRange(T rangeDb) noexcept
Velocity sensitivity: velocity 0 plays rangeDb below velocity 1 (0..96 dB, default 24; 0 ignores velo...
Definition Sampler.h:236
void setSustainPedal(bool down, int offset=0) noexcept
Sustain pedal: while down, released keys keep sounding.
Definition Sampler.h:281
Sampler & operator=(const Sampler &)=delete
Sampler(const Sampler &)=delete
void noteOff(int key, int offset=0) noexcept
Releases a note at offset samples into the next block.
Definition Sampler.h:275
void setGain(T dB) noexcept
Output gain in dB, smoothed over about 10 ms.
Definition Sampler.h:244
void noteOn(int key, T velocity, int offset=0) noexcept
Starts a note at offset samples into the next block. Velocity 0 is a note-off, as in MIDI.
Definition Sampler.h:255
bool loadSample(AudioBufferView< const T > audio, double sampleRate, int rootKey=60)
One zone over the whole keyboard and velocity range.
Definition Sampler.h:208
void setPitchBend(T semitones, int offset=0) noexcept
Pitch bend in semitones (-48..48), applied to every voice.
Definition Sampler.h:287
bool setZones(std::span< const ZoneSpec > zones)
Replaces the zone set.
Definition Sampler.h:192
void prepare(const AudioSpec &spec, int maxVoices=32)
Allocates the voices and the event queue.
Definition Sampler.h:149
void setEnvelope(T attackMs, T decayMs, T sustain, T releaseMs) noexcept
ADSR for notes that start from now on (release: also for notes released from now on)....
Definition Sampler.h:224
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. Tuning adds to the zone tun...
Definition Sampler.h:265
static constexpr int kMaxEvents
Definition Sampler.h:121
One voice's position in a zone and its band-limited read.
static const std::vector< T > & polyphaseTable()
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.
static constexpr double kMaxRate
Highest playback rate; the kernel then spans 8 x 64 taps.
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...
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),...
Main namespace for the DSPark framework.
SampleLoopMode
How a zone loops.
Definition SampleZone.h:30
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
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.