133 delete pending_.exchange(
nullptr, std::memory_order_acq_rel);
134 delete retired_.exchange(
nullptr, std::memory_order_acq_rel);
154 polyphony_ = std::clamp(maxVoices, 1, 256);
155 voices_.assign(
static_cast<size_t>(2 * polyphony_ + 2), Voice {});
156 for (
auto& v : voices_)
158 v.env.prepare(sampleRate_);
163 stealFadeSamples_ = std::max(1,
static_cast<int>(std::lround(0.003 * sampleRate_)));
164 gainCoeff_ = 1.0 - std::exp(-1.0 / (0.010 * sampleRate_));
172 for (
auto& v : voices_) { v.active =
false; v.env.reset(); }
174 sustainPedal_ =
false;
176 currentGain_ = outputGain_.load(std::memory_order_relaxed);
177 activeVoices_.store(0, std::memory_order_relaxed);
195 auto set = std::make_unique<ZoneSet>();
196 set->zones.reserve(zones.size());
201 set->zones.push_back(std::move(d));
203 publish(set.release());
214 return setZones(std::span<const ZoneSpec>(&z, 1));
224 void setEnvelope(T attackMs, T decayMs, T sustain, T releaseMs)
noexcept
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);
238 if (!std::isfinite(rangeDb))
return;
239 velocityRangeDb_.store(std::clamp(
static_cast<double>(rangeDb), 0.0, 96.0),
240 std::memory_order_relaxed);
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);
255 void noteOn(
int key, T velocity,
int offset = 0) noexcept
265 void noteOnTuned(
int key, T velocity, T tuningCents,
int offset = 0) noexcept
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) });
275 void noteOff(
int key,
int offset = 0) noexcept
277 push({ EventType::NoteOff, std::clamp(key, 0, 127), 0.0, offset });
283 push({ EventType::Pedal, 0, down ? 1.0 : 0.0, offset });
289 if (!std::isfinite(semitones))
return;
290 push({ EventType::Bend, 0, std::clamp(
static_cast<double>(semitones), -48.0, 48.0), offset });
296 push({ EventType::AllOff, 0, 0.0, offset });
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; }
322 for (
int e = 0; e < eventCount_; ++e)
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)]);
329 if (cursor < n) render(out, cursor, n);
331 applyOutputGain(out, n);
335 for (
const auto& v : voices_) count += v.active ? 1 : 0;
336 activeVoices_.store(count, std::memory_order_relaxed);
342 return activeVoices_.load(std::memory_order_relaxed);
352 struct ZoneSet { std::vector<ZoneData> zones; };
357 void reclaim() noexcept
359 delete retired_.exchange(
nullptr, std::memory_order_acq_rel);
363 void publish(ZoneSet* set)
noexcept
365 delete pending_.exchange(set, std::memory_order_acq_rel);
369 void adoptPending() noexcept
371 if (fading_ !=
nullptr)
return;
372 ZoneSet* next = pending_.exchange(
nullptr, std::memory_order_acq_rel);
373 if (next ==
nullptr)
return;
379 void retireFadedSet() noexcept
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);
394 const ZoneSet* set =
nullptr;
396 double baseRatio = 1.0;
398 bool sustained =
false;
399 double gainL = 1.0, gainR = 1.0, gainMono = 1.0;
402 ADSREnvelope<double> env;
406 enum class EventType { NoteOn, NoteOff, Pedal, Bend, AllOff };
407 struct Event { EventType type;
int key;
double value;
int offset;
double tuningCents = 0.0; };
409 void push(
const Event& e)
noexcept
411 if (!prepared_ || eventCount_ >=
kMaxEvents)
return;
414 int i = eventCount_++;
415 while (i > 0 && events_[
static_cast<size_t>(i - 1)].offset > e.offset)
417 events_[
static_cast<size_t>(i)] = events_[
static_cast<size_t>(i - 1)];
420 events_[
static_cast<size_t>(i)] = e;
423 void apply(
const Event& e)
noexcept
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;
433 for (
auto& v : voices_)
434 if (v.active && v.sustained) release(v);
436 case EventType::AllOff:
437 sustainPedal_ =
false;
438 for (
auto& v : voices_)
439 if (v.active && v.stealLeft < 0) release(v);
444 void release(Voice& v)
noexcept
448 v.env.setRelease(
static_cast<double>(releaseMs_.load(std::memory_order_relaxed)));
453 void releaseKey(
int key)
noexcept
455 for (
auto& v : voices_)
456 if (v.active && v.held && v.key == key && v.stealLeft < 0)
458 if (sustainPedal_) { v.held =
false; v.sustained =
true; }
463 void startNote(
int key,
double velocity,
double tuningCents)
noexcept
465 if (active_ ==
nullptr)
return;
467 for (
auto& v : voices_)
468 if (v.active && v.key == key && v.stealLeft < 0 && (v.held || v.sustained))
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)
475 if (key < z.keyLow || key > z.keyHigh || velocity < z.velLow || velocity > z.velHigh)
477 Voice* v = freeVoice();
478 if (v ==
nullptr)
return;
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));
486 v->sustained =
false;
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));
503 Voice* freeVoice() noexcept
506 Voice* idle =
nullptr;
507 for (
auto& v : voices_)
509 if (!v.active) {
if (idle ==
nullptr) idle = &v; }
510 else if (v.stealLeft < 0) ++sounding;
512 if (sounding < polyphony_ && idle !=
nullptr)
return idle;
515 Voice* victim =
nullptr;
516 for (
auto& v : voices_)
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;
525 if (victim !=
nullptr) victim->stealLeft = stealFadeSamples_;
526 if (idle !=
nullptr)
return idle;
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;
539 void applyOutputGain(AudioBufferView<T> out,
int n)
noexcept
541 const double target = outputGain_.load(std::memory_order_relaxed);
542 const int channels = std::min(out.getNumChannels(), 2);
544 for (; i < n && currentGain_ != target; ++i)
546 currentGain_ += (target - currentGain_) * gainCoeff_;
547 if (std::abs(target - currentGain_) < 1e-9) currentGain_ = target;
548 for (
int c = 0; c < channels; ++c)
550 T* d = out.getChannel(c);
551 d[i] =
static_cast<T
>(d[i] * currentGain_);
554 if (currentGain_ == 1.0)
return;
555 for (
int c = 0; c < channels; ++c)
557 T* d = out.getChannel(c);
558 for (
int s = i; s < n; ++s) d[s] = static_cast<T>(d[s] * currentGain_);
564 static bool advanceGain(Voice& v,
int stealFade,
double& gain)
noexcept
566 gain = v.env.getNextValue();
567 if (v.stealLeft >= 0)
569 gain *=
static_cast<double>(v.stealLeft) /
static_cast<double>(stealFade);
570 if (--v.stealLeft < 0) { v.active =
false;
return false; }
572 if (!v.env.isActive()) { v.active =
false;
return false; }
576 void emit(AudioBufferView<T> out,
int s,
const Voice& v,
double a0,
double a1,
double gain)
noexcept
578 const int nCh = out.getNumChannels();
581 out.getChannel(0)[s] +=
static_cast<T
>(a0 * v.gainMono * gain);
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);
589 void render(AudioBufferView<T> out,
int from,
int to)
noexcept
591 const double bendRatio = std::pow(2.0, pitchBend_ / 12.0);
592 const int nCh = out.getNumChannels();
593 for (
auto& v : voices_)
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)
599 double a0 = 0.0, a1 = 0.0;
600 const auto frame = v.reader.next(ratio, nCh, weights_.data(), a0, a1);
603 if (!advanceGain(v, stealFadeSamples_, gain))
break;
604 emit(out, s, v, a0, a1, gain);
613 double sampleRate_ = 48000.0;
615 bool prepared_ =
false;
616 int stealFadeSamples_ = 144;
618 double gainCoeff_ = 0.002;
619 double currentGain_ = 1.0;
621 std::vector<Voice> voices_;
622 std::vector<T> weights_;
623 std::array<Event, kMaxEvents> events_ {};
625 bool sustainPedal_ =
false;
626 double pitchBend_ = 0.0;
628 ZoneSet* active_ =
nullptr;
629 ZoneSet* fading_ =
nullptr;
630 std::atomic<ZoneSet*> pending_ {
nullptr };
631 std::atomic<ZoneSet*> retired_ {
nullptr };
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 };