// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later // Port of SampleVoice.kt and AudioEngine.voiceSample(), line for line: Float -> // float, Double -> double, kotlin.math on Float through double (KotlinMath.hpp). #include "SampleVoice.hpp" #include #include #include "KotlinMath.hpp" #if defined(__clang__) #pragma clang fp contract(off) // Java never fuses multiply-adds #endif namespace sizzle::sampler { namespace { constexpr float FADE_STEP = 0.01f; // ~2 ms end fade at 48 kHz constexpr double FADE_SAMPLES = 1.0 / (double)FADE_STEP; // output samples the fade spans constexpr float MIN_ATTACK = 0.0005f; // ~0.5 ms minimum onset ramp /** kotlin minOf / maxOf on Float (Math.min / Math.max: NaN wins). */ inline float minOf(float a, float b) { return a != a ? a : (b != b ? b : (a <= b ? a : b)); } inline float maxOf(float a, float b) { return a != a ? a : (b != b ? b : (a >= b ? a : b)); } /** Double.toInt(): truncation, NaN -> 0, saturating (keeps a wild index defined). */ inline int toInt(double x) { if (x != x) return 0; if (x >= 2147483647.0) return 2147483647; if (x <= -2147483648.0) return (-2147483647 - 1); return (int)x; } } // namespace // ------------------------------------------------------------- voiceSample bool voiceSample(const char *type, const Params &slot, const SampleStore &store, int note, VoiceSample &out) { if (type == nullptr) return false; if (std::strcmp(type, "SAMPLER") == 0) { const int pad = SamplerPads::padFor(note); if (pad < 0 || pad >= SamplerPads::COUNT) return false; const Sample *s = store.get(slot.s(SamplerPads::key(pad).s)); if (!s) return false; out = VoiceSample{}; out.sample = s; out.root = note; out.sliceStart = slot.f(SamplerPads::sliceStartKey(pad).s, 0.f); out.sliceEnd = slot.f(SamplerPads::sliceEndKey(pad).s, 1.f); out.volume = slot.f(SamplerPads::volumeKey(pad).s, SamplerPads::DEFAULT_VOLUME); return true; } if (std::strcmp(type, "SOUNDFONT") == 0) { const Sample *s = store.get(slot.s("sfSample")); if (!s) return false; out = VoiceSample{}; out.sample = s; out.root = kt::toInt(slot.f("sfRoot", 60.f)); out.sliceStart = 0.f; out.sliceEnd = 1.f; out.volume = slot.f("volume", 0.8f); out.attack = slot.f("attack", 0.005f); out.decay = slot.f("decay", 0.10f); out.sustain = slot.f("sustain", 1.f); out.release = slot.f("release", 0.20f); out.loop = std::strcmp(slot.s("loop", "Off"), "On") == 0; out.crossfadeMs = slot.f("loopXfade", 0.f); return true; } return false; } // ------------------------------------------------------------- SampleVoice SampleVoice::SampleVoice(int sr) : engineSampleRate(sr), declickCoeff(kt::expf_(-1.f / ((float)sr * 0.003f))) {} // ~3 ms decay SampleVoice::~SampleVoice() { setSample(nullptr); } void SampleVoice::setSample(const Sample *s) { if (s == sample) return; if (s) SampleStore::pin(s); if (sample) SampleStore::unpin(sample); sample = s; } void SampleVoice::noteOn(const Sample &s, int midi, int velocity, int root, float sliceStart, float sliceEnd, float volume, float attack, float decay, float sustain, float release, bool loop, float crossfadeMs) { const int len = (int)s.data.size(); // An empty sample would make Kotlin's coerceIn(startIndex + 1, 0) throw; play nothing. if (len <= 0) return; // Carry the level we're interrupting so the new note starts continuously. declick += lastY; setSample(&s); pitch = midi; const float a = kt::coerceIn(sliceStart, 0.f, 1.f); const float b = kt::coerceIn(sliceEnd, 0.f, 1.f); startIndex = kt::coerceIn(kt::toInt(minOf(a, b) * (float)len), 0, kt::coerceAtLeast(len - 1, 0)); endIndex = kt::coerceIn(kt::toInt(maxOf(a, b) * (float)len), startIndex + 1, len); position = (double)startIndex; // Loop region: prefer the file's loop points (clamped into the played slice); // otherwise loop the whole slice. Disabled if the resulting span is too short. if (loop) { const int fileLs = s.loopStart; const int fileLe = s.loopEnd; if (fileLe > fileLs && fileLs >= 0 && fileLe <= len) { loopStartIdx = kt::coerceIn(fileLs, startIndex, endIndex - 1); loopEndIdx = kt::coerceIn(fileLe, loopStartIdx + 1, endIndex); } else { loopStartIdx = startIndex; loopEndIdx = endIndex; } loopSpan = (double)(loopEndIdx - loopStartIdx); loopActive = loopSpan >= 2.0; // Crossfade length in samples, kept under half the loop. const double xf = loopActive ? (double)(crossfadeMs / 1000.f * (float)engineSampleRate) : 0.0; xfade = (loopActive && loopSpan >= 4.0) ? kt::coerceIn(xf, 0.0, loopSpan / 2.0 - 1.0) : 0.0; loopBase = loopStartIdx + xfade; loopEff = loopSpan - xfade; } else { loopActive = false; xfade = 0.0; } // Pitch ratio * sample-rate conversion. const double semis = (midi - root) / 12.0; rate = std::pow(2.0, semis) * ((double)s.sampleRate / engineSampleRate); amp = kt::coerceIn((float)velocity / 127.f, 0.f, 1.f) * volume; // Envelope: enforce a tiny minimum attack so the onset never clicks. const float sr = (float)engineSampleRate; sustainLevel = kt::coerceIn(sustain, 0.f, 1.f); attackInc = 1.f / (maxOf(attack, MIN_ATTACK) * sr); decayInc = decay <= 0.f ? 1.f : (1.f - sustainLevel) / (decay * sr); releaseSeconds = release; env = 0.f; phase = Phase::ATTACK; endGain = 1.f; } void SampleVoice::noteOff() { const float sr = (float)engineSampleRate; releaseInc = releaseSeconds <= 0.f ? 1.f : env / (releaseSeconds * sr); if (releaseInc <= 0.f) releaseInc = 1.f; phase = Phase::RELEASE; } void SampleVoice::kill() { setSample(nullptr); pitch = -1; ownerTrack = -1; env = 0.f; endGain = 1.f; lastY = 0.f; declick = 0.f; loopActive = false; } float SampleVoice::declickTail() { if (declick == 0.f) { lastY = 0.f; return 0.f; } const float y = declick; declick *= declickCoeff; if (declick < 1e-5f && declick > -1e-5f) declick = 0.f; lastY = y; return y; } float SampleVoice::render() { const Sample *s = sample; if (!s) return declickTail(); // idle -> 0; ring out any declick tail const float *data = s->data.data(); const int size = (int)s->data.size(); if (loopActive) { // Wrap the (crossfaded) loop; modulo so a very high rate still lands inside. if (position >= loopEndIdx) position = loopBase + std::fmod(position - loopBase, loopEff); // Bounds guard so a malformed loop can never read out of bounds. if (position >= size - 1 || position < loopStartIdx) position = loopBase; } else { const int i = toInt(position); if (i >= endIndex - 1 || i >= size - 1) { setSample(nullptr); pitch = -1; return declickTail(); } // Anti-click fade as the slice end approaches (in OUTPUT samples). if ((endIndex - i) / rate <= FADE_SAMPLES) { endGain = kt::coerceAtLeast(endGain - FADE_STEP, 0.f); if (endGain <= 0.f) { setSample(nullptr); pitch = -1; return declickTail(); } } } // Advance the ADSR envelope one output sample. switch (phase) { case Phase::ATTACK: env += attackInc; if (env >= 1.f) { env = 1.f; phase = Phase::DECAY; } break; case Phase::DECAY: env -= decayInc; if (env <= sustainLevel) { env = sustainLevel; phase = Phase::SUSTAIN; } break; case Phase::SUSTAIN: break; case Phase::RELEASE: env -= releaseInc; if (env <= 0.f) { setSample(nullptr); pitch = -1; return declickTail(); } break; } // Linear interpolation between neighbouring samples (neighbour clamped). const int i = toInt(position); const int i1 = i + 1 < size ? i + 1 : i; const float frac = (float)(position - i); float out = data[i] + (data[i1] - data[i]) * frac; // In the crossfade zone, blend the loop tail into its head (reads only within // [loopStartIdx, loopEndIdx)). if (loopActive && xfade >= 1.0 && position >= loopEndIdx - xfade) { const double into = position - (loopEndIdx - xfade); // 0 ... xfade const float f = (float)(into / xfade); // 0 -> 1 across the zone const double sp = loopStartIdx + into; // matching head position const int si = toInt(sp); const int si1 = si + 1 < size ? si + 1 : si; const float sfrac = (float)(sp - si); const float head = data[si] + (data[si1] - data[si]) * sfrac; out = out * (1.f - f) + head * f; } position += rate; const float y = out * amp * env * endGain + declick; declick *= declickCoeff; lastY = y; return y; } } // namespace sizzle::sampler