0.37.0 (71): one engine, one version for Android and iOS
- Three source trees: core/ (shared C++ engine, moved from ios/core), app/ (Android UI), ios/app/ (iOS UI) - Android plays through core/ via JNI (EngineHost, jni_engine.cpp): the Oboe callback renders natively; the Kotlin model is mirrored as project text and applied as a diff, so playback continues through edits - The Kotlin engine moves to the unit tests as ReferenceEngine (golden reference) - Shared MasterRecorder in core/src/host, used by both apps; host_test - versions.properties: one versionName/versionCode for both platforms, continuing Android's numbering (iOS 0.6.0/11 -> 0.37.0/71) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
64e21e0bcc
commit
2bc5cb1cbb
@@ -0,0 +1,245 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Port of SampleStore.kt (see SampleStore.hpp for the thread-safety design).
|
||||
// decodeWav / encodeWav are line for line; Kotlin's ByteBuffer exceptions (a read
|
||||
// past the end, position() past the limit) become explicit checks that return
|
||||
// nothing, which is what the Kotlin's catch-all does.
|
||||
|
||||
#include "SampleStore.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include "KotlinMath.hpp"
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang fp contract(off) // Java never fuses multiply-adds
|
||||
#endif
|
||||
|
||||
namespace sizzle::sampler {
|
||||
|
||||
namespace {
|
||||
|
||||
bool idLess(const std::string &a, const std::string &b) { return std::strcmp(a.c_str(), b.c_str()) < 0; }
|
||||
|
||||
// Little-endian reads; callers check bounds first.
|
||||
inline uint32_t u32le(const uint8_t *p) {
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
inline int32_t i32le(const uint8_t *p) { return (int32_t)u32le(p); }
|
||||
inline int u16le(const uint8_t *p) { return (int)p[0] | ((int)p[1] << 8); }
|
||||
inline int16_t i16le(const uint8_t *p) { return (int16_t)(uint16_t)u16le(p); }
|
||||
inline bool tagIs(const uint8_t *p, const char *t) { return std::memcmp(p, t, 4) == 0; }
|
||||
|
||||
inline void putTag(std::vector<uint8_t> &b, const char *t) { b.insert(b.end(), t, t + 4); }
|
||||
inline void put32(std::vector<uint8_t> &b, uint32_t v) {
|
||||
b.push_back((uint8_t)v); b.push_back((uint8_t)(v >> 8)); b.push_back((uint8_t)(v >> 16)); b.push_back((uint8_t)(v >> 24));
|
||||
}
|
||||
inline void put16(std::vector<uint8_t> &b, uint16_t v) { b.push_back((uint8_t)v); b.push_back((uint8_t)(v >> 8)); }
|
||||
|
||||
} // namespace
|
||||
|
||||
// ------------------------------------------------------------------ the store
|
||||
|
||||
SampleStore::SampleStore() : current(std::make_unique<Snapshot>()) {
|
||||
snap.store(current.get(), std::memory_order_release);
|
||||
}
|
||||
|
||||
SampleStore::~SampleStore() = default;
|
||||
|
||||
const Sample *SampleStore::put(const std::string &id, Sample sample) {
|
||||
auto owned = std::make_unique<Sample>(std::move(sample));
|
||||
const Sample *p = owned.get();
|
||||
std::lock_guard<std::mutex> g(writeLock);
|
||||
std::unique_ptr<Sample> old;
|
||||
auto it = std::lower_bound(live.begin(), live.end(), id,
|
||||
[](const auto &e, const std::string &k) { return idLess(e.first, k); });
|
||||
if (it != live.end() && it->first == id) {
|
||||
old = std::move(it->second);
|
||||
it->second = std::move(owned);
|
||||
} else {
|
||||
live.insert(it, {id, std::move(owned)});
|
||||
}
|
||||
publishLocked();
|
||||
if (old) retiredSamples.push_back({std::move(old), epoch.load(std::memory_order_relaxed)});
|
||||
collectLocked();
|
||||
return p;
|
||||
}
|
||||
|
||||
void SampleStore::remove(const std::string &id) {
|
||||
if (id.empty()) return;
|
||||
std::lock_guard<std::mutex> g(writeLock);
|
||||
auto it = std::find_if(live.begin(), live.end(), [&](const auto &e) { return e.first == id; });
|
||||
if (it == live.end()) return;
|
||||
std::unique_ptr<Sample> old = std::move(it->second);
|
||||
live.erase(it);
|
||||
publishLocked();
|
||||
retiredSamples.push_back({std::move(old), epoch.load(std::memory_order_relaxed)});
|
||||
collectLocked();
|
||||
}
|
||||
|
||||
void SampleStore::publishLocked() {
|
||||
auto next = std::make_unique<Snapshot>();
|
||||
next->entries.reserve(live.size());
|
||||
for (const auto &e : live) next->entries.emplace_back(e.first, e.second.get());
|
||||
snap.store(next.get(), std::memory_order_release);
|
||||
std::unique_ptr<Snapshot> old = std::move(current);
|
||||
current = std::move(next);
|
||||
// The epoch moves after the new snapshot is visible: a reader that has seen this
|
||||
// epoch at quiescent() can only find the new snapshot from then on.
|
||||
uint64_t e = epoch.fetch_add(1, std::memory_order_acq_rel) + 1;
|
||||
retiredSnaps.push_back({std::move(old), e});
|
||||
}
|
||||
|
||||
void SampleStore::collect() {
|
||||
std::lock_guard<std::mutex> g(writeLock);
|
||||
collectLocked();
|
||||
}
|
||||
|
||||
void SampleStore::collectLocked() {
|
||||
uint64_t s = seen.load(std::memory_order_acquire);
|
||||
retiredSnaps.erase(std::remove_if(retiredSnaps.begin(), retiredSnaps.end(),
|
||||
[s](const RetiredSnapshot &r) { return r.epoch <= s; }), retiredSnaps.end());
|
||||
retiredSamples.erase(std::remove_if(retiredSamples.begin(), retiredSamples.end(),
|
||||
[s](const RetiredSample &r) {
|
||||
return r.epoch <= s && r.sample->users.load(std::memory_order_acquire) == 0;
|
||||
}), retiredSamples.end());
|
||||
}
|
||||
|
||||
size_t SampleStore::retiredCount() const {
|
||||
std::lock_guard<std::mutex> g(writeLock);
|
||||
return retiredSnaps.size() + retiredSamples.size();
|
||||
}
|
||||
|
||||
const Sample *SampleStore::get(const char *id) const {
|
||||
if (id == nullptr || id[0] == '\0') return nullptr;
|
||||
const Snapshot *s = snap.load(std::memory_order_acquire);
|
||||
size_t lo = 0, hi = s->entries.size();
|
||||
while (lo < hi) {
|
||||
size_t mid = lo + (hi - lo) / 2;
|
||||
int c = std::strcmp(s->entries[mid].first.c_str(), id);
|
||||
if (c == 0) return s->entries[mid].second;
|
||||
if (c < 0) lo = mid + 1; else hi = mid;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void SampleStore::quiescent() {
|
||||
seen.store(epoch.load(std::memory_order_acquire), std::memory_order_release);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- decodeWav
|
||||
|
||||
std::optional<Sample> SampleStore::decodeWav(const uint8_t *bytes, size_t size) {
|
||||
if (bytes == nullptr || size > 0x7FFFFFFF) return std::nullopt; // a Kotlin ByteArray's limit
|
||||
const int32_t limit = (int32_t)size;
|
||||
if (limit < 44) return std::nullopt;
|
||||
if (bytes[0] != 'R' || bytes[1] != 'I') return std::nullopt; // "RIFF"
|
||||
int32_t pos = 8;
|
||||
if (!tagIs(bytes + pos, "WAVE")) return std::nullopt;
|
||||
pos += 4;
|
||||
|
||||
int audioFormat = 1;
|
||||
int channels = 1;
|
||||
int32_t sampleRate = 44100;
|
||||
int bitsPerSample = 16;
|
||||
int32_t dataOffset = -1;
|
||||
int32_t dataLength = 0;
|
||||
|
||||
// Walk the chunks looking for "fmt " and "data".
|
||||
while (limit - pos >= 8) {
|
||||
const uint8_t *tag = bytes + pos;
|
||||
int32_t size32 = i32le(bytes + pos + 4);
|
||||
pos += 8;
|
||||
if (size32 < 0) break; // corrupt chunk size — stop scanning, use what we have
|
||||
int32_t next = (int32_t)((uint32_t)pos + (uint32_t)size32); // Kotlin Int wraps
|
||||
if (tagIs(tag, "fmt ")) {
|
||||
if (limit - pos < 16) return std::nullopt; // BufferUnderflowException
|
||||
audioFormat = u16le(bytes + pos);
|
||||
channels = std::max(u16le(bytes + pos + 2), 1);
|
||||
sampleRate = i32le(bytes + pos + 4);
|
||||
// byteRate (4), blockAlign (2)
|
||||
bitsPerSample = u16le(bytes + pos + 14);
|
||||
pos += 16;
|
||||
} else if (tagIs(tag, "data")) {
|
||||
dataOffset = pos; dataLength = size32;
|
||||
}
|
||||
if (next >= 0 && next <= limit) {
|
||||
int32_t np = (int32_t)((uint32_t)next + (uint32_t)(size32 & 1)); // word-aligned
|
||||
if (np < 0 || np > limit) return std::nullopt; // position() past the limit throws
|
||||
pos = np;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (dataOffset < 0) return std::nullopt;
|
||||
// A header can over-report the data length; never read past the actual bytes.
|
||||
dataLength = kt::coerceIn(dataLength, (int32_t)0, limit - dataOffset);
|
||||
|
||||
const int bytesPerSample = bitsPerSample / 8;
|
||||
if (bytesPerSample == 0) return std::nullopt;
|
||||
const int32_t frameCount = dataLength / (bytesPerSample * channels);
|
||||
if (frameCount <= 0) return std::nullopt;
|
||||
// The Kotlin's `else -> return null` runs on the first sample: decide up front.
|
||||
const bool isFloat = audioFormat == 3 && bitsPerSample == 32;
|
||||
if (!isFloat && bitsPerSample != 16 && bitsPerSample != 8 && bitsPerSample != 24 && bitsPerSample != 32)
|
||||
return std::nullopt;
|
||||
std::vector<float> out((size_t)frameCount);
|
||||
const uint8_t *data = bytes + dataOffset;
|
||||
size_t at = 0;
|
||||
|
||||
for (int32_t f = 0; f < frameCount; ++f) {
|
||||
float acc = 0.f;
|
||||
for (int c = 0; c < channels; ++c) {
|
||||
float v;
|
||||
if (isFloat) {
|
||||
uint32_t u = u32le(data + at); at += 4;
|
||||
std::memcpy(&v, &u, 4);
|
||||
} else if (bitsPerSample == 16) {
|
||||
v = (float)i16le(data + at) / 32768.f; at += 2;
|
||||
} else if (bitsPerSample == 8) {
|
||||
v = (float)((int)data[at] - 128) / 128.f; at += 1;
|
||||
} else if (bitsPerSample == 24) {
|
||||
int b0 = data[at], b1 = data[at + 1];
|
||||
int b2 = (int)(int8_t)data[at + 2]; // signed high byte
|
||||
at += 3;
|
||||
v = (float)(int32_t)(((uint32_t)b2 << 16) | ((uint32_t)b1 << 8) | (uint32_t)b0) / 8388608.f;
|
||||
} else { // 32-bit integer PCM
|
||||
v = (float)i32le(data + at) / 2147483648.f; at += 4;
|
||||
}
|
||||
acc += v;
|
||||
}
|
||||
out[(size_t)f] = acc / (float)channels; // down-mix to mono
|
||||
}
|
||||
return Sample(std::move(out), sampleRate);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- encodeWav
|
||||
|
||||
std::vector<uint8_t> SampleStore::encodeWav(const Sample &sample) {
|
||||
const int32_t frames = (int32_t)sample.data.size();
|
||||
const int32_t bytesPerSample = 2;
|
||||
const int32_t channels = 1;
|
||||
const uint32_t dataSize = (uint32_t)frames * bytesPerSample * channels;
|
||||
std::vector<uint8_t> bb;
|
||||
bb.reserve(44 + (size_t)dataSize);
|
||||
putTag(bb, "RIFF");
|
||||
put32(bb, 36u + dataSize);
|
||||
putTag(bb, "WAVE");
|
||||
putTag(bb, "fmt ");
|
||||
put32(bb, 16); // PCM fmt chunk size
|
||||
put16(bb, 1); // audioFormat = PCM
|
||||
put16(bb, (uint16_t)channels);
|
||||
put32(bb, (uint32_t)sample.sampleRate);
|
||||
put32(bb, (uint32_t)sample.sampleRate * channels * bytesPerSample); // byteRate (wraps like Int)
|
||||
put16(bb, (uint16_t)(channels * bytesPerSample)); // blockAlign
|
||||
put16(bb, 16); // bitsPerSample
|
||||
putTag(bb, "data");
|
||||
put32(bb, dataSize);
|
||||
for (float v : sample.data) {
|
||||
put16(bb, (uint16_t)(int16_t)kt::toInt(kt::coerceIn(v, -1.f, 1.f) * 32767.f));
|
||||
}
|
||||
return bb;
|
||||
}
|
||||
|
||||
} // namespace sizzle::sampler
|
||||
@@ -0,0 +1,100 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
|
||||
// Port of SampleStore.kt: the cache of decoded samples (id -> Sample) the Sampler,
|
||||
// SoundFont and Grain Cloud play from, plus decodeWav / encodeWav.
|
||||
//
|
||||
// Thread safety (the Kotlin uses a ConcurrentHashMap; this is the real-time-safe
|
||||
// equivalent):
|
||||
//
|
||||
// - Writers (put / remove / collect, any non-audio thread) are serialised by a
|
||||
// mutex. Each change builds a new immutable Snapshot (a sorted id -> Sample*
|
||||
// array) and publishes it with one atomic pointer store, then bumps an epoch.
|
||||
// - The audio thread reads with get(): one atomic load and a binary search with
|
||||
// strcmp. No lock, no allocation, no reference counting.
|
||||
// - Nothing a reader can still see is freed early. A replaced snapshot and a
|
||||
// removed (or replaced) sample are retired with the epoch of the change and freed
|
||||
// by a later writer call (collect(), also run by put/remove) only once
|
||||
// * the audio thread has called quiescent() after that epoch: it holds no
|
||||
// pointer from an older snapshot (contract: a pointer from get() that is not
|
||||
// pinned is used only until the reader's next quiescent(), i.e. within one
|
||||
// audio block), and
|
||||
// * the sample's `users` count is 0: no voice still plays it (SampleVoice pins
|
||||
// from noteOn until it lets go). That is the Kotlin guarantee "any voice
|
||||
// already playing it keeps its own reference".
|
||||
// - quiescent() is called by the single reader thread (the engine's render
|
||||
// callback, at each block start). When no audio thread runs, the owner may call
|
||||
// it from its own thread to let retired memory go.
|
||||
// - The store must outlive every reader; the destructor frees everything.
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include "sizzle/Sample.hpp"
|
||||
|
||||
namespace sizzle::sampler {
|
||||
|
||||
class SampleStore {
|
||||
public:
|
||||
SampleStore();
|
||||
~SampleStore();
|
||||
SampleStore(const SampleStore &) = delete;
|
||||
SampleStore &operator=(const SampleStore &) = delete;
|
||||
|
||||
// ---- writer side (any thread except the audio thread; may allocate)
|
||||
/** Store [sample] under [id] (replacing any previous one); returns it. */
|
||||
const Sample *put(const std::string &id, Sample sample);
|
||||
/** Drop a cached sample. A voice already playing it keeps it alive. */
|
||||
void remove(const std::string &id);
|
||||
/** Free retired snapshots/samples no reader can reach any more. */
|
||||
void collect();
|
||||
/** Retired objects not freed yet (for tests and diagnostics). */
|
||||
size_t retiredCount() const;
|
||||
|
||||
// ---- reader side (the audio thread; lock- and allocation-free)
|
||||
/** The sample stored under [id], or null (also for an empty id). */
|
||||
const Sample *get(const char *id) const;
|
||||
/** The reader holds no unpinned pointer from get() past this point. */
|
||||
void quiescent();
|
||||
|
||||
/** Pin / unpin a sample a player holds across blocks (Sample::users). */
|
||||
static void pin(const Sample *s) { if (s) s->users.fetch_add(1, std::memory_order_acq_rel); }
|
||||
static void unpin(const Sample *s) { if (s) s->users.fetch_sub(1, std::memory_order_acq_rel); }
|
||||
|
||||
/**
|
||||
* Decode a WAV file (the common uncompressed formats) into a mono Sample.
|
||||
* Supports 8/16/24-bit PCM and 32-bit float, mono or stereo (stereo is
|
||||
* down-mixed). Returns nothing if the bytes are not a WAV we understand.
|
||||
*/
|
||||
static std::optional<Sample> decodeWav(const uint8_t *bytes, size_t size);
|
||||
/** A 16-bit mono PCM WAV file of [sample] (the inverse of decodeWav). */
|
||||
static std::vector<uint8_t> encodeWav(const Sample &sample);
|
||||
|
||||
private:
|
||||
struct Snapshot {
|
||||
std::vector<std::pair<std::string, const Sample *>> entries; // sorted by strcmp
|
||||
};
|
||||
struct RetiredSnapshot { std::unique_ptr<Snapshot> snap; uint64_t epoch; };
|
||||
struct RetiredSample { std::unique_ptr<Sample> sample; uint64_t epoch; };
|
||||
|
||||
void publishLocked();
|
||||
void collectLocked();
|
||||
|
||||
mutable std::mutex writeLock;
|
||||
std::vector<std::pair<std::string, std::unique_ptr<Sample>>> live; // writer-owned, sorted
|
||||
std::unique_ptr<Snapshot> current; // owner of `snap`
|
||||
std::atomic<const Snapshot *> snap{nullptr};
|
||||
std::atomic<uint64_t> epoch{0};
|
||||
std::atomic<uint64_t> seen{0}; // last epoch the reader passed quiescent() at
|
||||
std::vector<RetiredSnapshot> retiredSnaps;
|
||||
std::vector<RetiredSample> retiredSamples;
|
||||
};
|
||||
|
||||
} // namespace sizzle::sampler
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The reference-test maker for kind "SAMPLE" (see TestVoice.hpp and
|
||||
// IosGoldenInstruments.kt): one SampleVoice playing the script with the engine's
|
||||
// voiceSample() settings; the test sample is put in a store under every id the
|
||||
// slot names (Sampler pads, SoundFont sfSample).
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include "SampleStore.hpp"
|
||||
#include "SampleVoice.hpp"
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
|
||||
namespace sizzle {
|
||||
namespace {
|
||||
|
||||
class SampleTestVoice final : public TestVoice {
|
||||
sampler::SampleStore store;
|
||||
sampler::SampleVoice voice;
|
||||
const char *type;
|
||||
const Params *params;
|
||||
public:
|
||||
explicit SampleTestVoice(const TestVoiceSetup &s) : voice(s.sampleRate), type(s.type), params(s.params) {
|
||||
if (s.sample && s.sampleLength > 0) {
|
||||
Sample smp(std::vector<float>(s.sample, s.sample + s.sampleLength), s.sampleRate2, s.loopStart, s.loopEnd);
|
||||
auto putId = [&](const char *id) { if (id && id[0]) store.put(id, smp); };
|
||||
for (int pad = 0; pad < sampler::SamplerPads::COUNT; ++pad)
|
||||
putId(params->s(sampler::SamplerPads::key(pad).s));
|
||||
putId(params->s("sfSample"));
|
||||
}
|
||||
}
|
||||
void blockStart(int) override { store.quiescent(); }
|
||||
void noteOn(int midi, int velocity) override {
|
||||
sampler::VoiceSample vs;
|
||||
if (sampler::voiceSample(type, *params, store, midi, vs)) voice.noteOn(vs, midi, velocity);
|
||||
}
|
||||
void noteOff(int) override { voice.noteOff(); }
|
||||
float render() override { return voice.render(); }
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<TestVoice> makeSampleTestVoice(const TestVoiceSetup &setup) {
|
||||
return std::make_unique<SampleTestVoice>(setup);
|
||||
}
|
||||
|
||||
} // namespace sizzle
|
||||
@@ -0,0 +1,221 @@
|
||||
// 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 <cmath>
|
||||
#include <cstring>
|
||||
#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
|
||||
@@ -0,0 +1,146 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
|
||||
// Port of SampleVoice.kt (the pitched one-shot / looping sample voice of the
|
||||
// Sampler and SoundFont instruments), AudioEngine.voiceSample() (which sample a
|
||||
// note plays and how) and SamplerPads (model/Toolbox.kt).
|
||||
|
||||
#include "SampleStore.hpp"
|
||||
#include "sizzle/Params.hpp"
|
||||
#include "sizzle/Sample.hpp"
|
||||
|
||||
namespace sizzle::sampler {
|
||||
|
||||
/** SamplerPads: pad n plays MIDI note BASE_NOTE + n; its settings live under
|
||||
* "pad<n>" (sample id), "pad<n>S"/"pad<n>E" (slice start/end), "pad<n>V" (volume). */
|
||||
namespace SamplerPads {
|
||||
inline constexpr int COUNT = 16;
|
||||
inline constexpr int BASE_NOTE = 36; // C2 (this app uses MIDI 60 == C4)
|
||||
inline constexpr float DEFAULT_VOLUME = 0.8f;
|
||||
|
||||
/** A key built on the stack (no allocation): use `.s`. */
|
||||
struct Key { char s[16]; };
|
||||
inline Key make(int pad, char suffix) { // "pad" + decimal pad + suffix, hand-built (no printf on the audio thread)
|
||||
Key k{};
|
||||
int n = 0;
|
||||
k.s[n++] = 'p'; k.s[n++] = 'a'; k.s[n++] = 'd';
|
||||
unsigned u = pad < 0 ? 0u - (unsigned)pad : (unsigned)pad;
|
||||
if (pad < 0) k.s[n++] = '-';
|
||||
char digits[10];
|
||||
int d = 0;
|
||||
do { digits[d++] = (char)('0' + u % 10); u /= 10; } while (u != 0);
|
||||
while (d > 0) k.s[n++] = digits[--d];
|
||||
if (suffix) k.s[n++] = suffix;
|
||||
k.s[n] = '\0';
|
||||
return k;
|
||||
}
|
||||
inline Key key(int pad) { return make(pad, 0); }
|
||||
inline Key sliceStartKey(int pad) { return make(pad, 'S'); }
|
||||
inline Key sliceEndKey(int pad) { return make(pad, 'E'); }
|
||||
inline Key volumeKey(int pad) { return make(pad, 'V'); }
|
||||
|
||||
/** The MIDI note a pad triggers, and the inverse. */
|
||||
inline int noteFor(int pad) { return BASE_NOTE + pad; }
|
||||
inline int padFor(int note) { return note - BASE_NOTE; }
|
||||
} // namespace SamplerPads
|
||||
|
||||
/** AudioEngine.VoiceSample: what SampleVoice::noteOn plays for a note. */
|
||||
struct VoiceSample {
|
||||
const Sample *sample = nullptr;
|
||||
int root = 60;
|
||||
float sliceStart = 0.f, sliceEnd = 1.f, volume = 0.8f;
|
||||
float attack = 0.002f, decay = 0.f;
|
||||
float sustain = 1.f, release = 0.02f;
|
||||
bool loop = false;
|
||||
float crossfadeMs = 0.f;
|
||||
};
|
||||
|
||||
/**
|
||||
* AudioEngine.voiceSample(): the sample [note] plays on a slot of [type] ("SAMPLER":
|
||||
* the pad the note maps to, root == note so it plays unpitched, one-shot envelope;
|
||||
* "SOUNDFONT": sfSample at sfRoot with the slot's envelope and loop). False when the
|
||||
* slot isn't a loaded sample instrument (the engine then uses the synth).
|
||||
* Audio-thread safe: no allocation, no locks.
|
||||
*/
|
||||
bool voiceSample(const char *type, const Params &slot, const SampleStore &store, int note, VoiceSample &out);
|
||||
|
||||
/**
|
||||
* Plays a Sample as a pitched voice: the note's distance from the root sets the
|
||||
* playback rate, the slice bounds the region, a linear ADSR shapes it, a SoundFont
|
||||
* can sustain-loop with a crossfaded seam. render() / noteOn() don't allocate.
|
||||
*
|
||||
* The voice pins the sample it plays (Sample::users) from noteOn until it lets go,
|
||||
* so SampleStore never frees a sample still playing.
|
||||
*/
|
||||
class SampleVoice {
|
||||
public:
|
||||
explicit SampleVoice(int engineSampleRate);
|
||||
~SampleVoice();
|
||||
SampleVoice(const SampleVoice &) = delete;
|
||||
SampleVoice &operator=(const SampleVoice &) = delete;
|
||||
|
||||
int pitch = -1;
|
||||
/** Which tracker (lane,track) started this voice, or -1 if unowned. */
|
||||
int ownerTrack = -1;
|
||||
|
||||
bool isActive() const { return sample != nullptr; }
|
||||
/** Note is still held (not in its release stage). */
|
||||
bool isGated() const { return sample != nullptr && phase != Phase::RELEASE; }
|
||||
|
||||
/**
|
||||
* [root]: MIDI note at which the sample plays at its natural pitch;
|
||||
* [sliceStart]/[sliceEnd]: 0..1 fractions of the sample to play; [volume] 0..1;
|
||||
* [attack]/[decay]/[release] in seconds; [sustain] level 0..1.
|
||||
*/
|
||||
void noteOn(const Sample &s, int midi, int velocity, int root,
|
||||
float sliceStart, float sliceEnd, float volume,
|
||||
float attack = 0.002f, float decay = 0.f, float sustain = 1.f, float release = 0.02f,
|
||||
bool loop = false, float crossfadeMs = 0.f);
|
||||
void noteOn(const VoiceSample &v, int midi, int velocity) {
|
||||
if (v.sample) noteOn(*v.sample, midi, velocity, v.root, v.sliceStart, v.sliceEnd, v.volume,
|
||||
v.attack, v.decay, v.sustain, v.release, v.loop, v.crossfadeMs);
|
||||
}
|
||||
/** Enter the release stage: fade from the current level to 0 over the release time. */
|
||||
void noteOff();
|
||||
void kill();
|
||||
float render();
|
||||
|
||||
private:
|
||||
enum class Phase { ATTACK, DECAY, SUSTAIN, RELEASE };
|
||||
|
||||
void setSample(const Sample *s); // sample = s, moving the pin
|
||||
float declickTail();
|
||||
|
||||
const int engineSampleRate;
|
||||
const Sample *sample = nullptr;
|
||||
double position = 0.0; // fractional read index into sample->data
|
||||
double rate = 1.0; // samples advanced per output sample
|
||||
int startIndex = 0;
|
||||
int endIndex = 0;
|
||||
float amp = 0.f;
|
||||
|
||||
bool loopActive = false;
|
||||
int loopStartIdx = 0;
|
||||
int loopEndIdx = 0;
|
||||
double loopSpan = 0.0;
|
||||
double xfade = 0.0;
|
||||
double loopBase = 0.0;
|
||||
double loopEff = 0.0;
|
||||
|
||||
Phase phase = Phase::ATTACK;
|
||||
float env = 0.f;
|
||||
float attackInc = 1.f;
|
||||
float decayInc = 1.f;
|
||||
float sustainLevel = 1.f;
|
||||
float releaseSeconds = 0.02f;
|
||||
float releaseInc = 1.f;
|
||||
|
||||
float endGain = 1.f;
|
||||
|
||||
float lastY = 0.f;
|
||||
float declick = 0.f;
|
||||
const float declickCoeff;
|
||||
};
|
||||
|
||||
} // namespace sizzle::sampler
|
||||
@@ -0,0 +1,188 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Port of SoundFontLoader.kt, line for line. Kotlin's runCatching turns any
|
||||
// ByteBuffer exception into null; here each read that could throw is checked first
|
||||
// and returns nothing instead. Positions are int64 where the Kotlin resolves in Long.
|
||||
|
||||
#include "SoundFontLoader.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include "SampleStore.hpp"
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang fp contract(off) // Java never fuses multiply-adds
|
||||
#endif
|
||||
|
||||
namespace sizzle::sampler::SoundFontLoader {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int SHDR_REC = 46;
|
||||
|
||||
inline bool tagAt(const uint8_t *b, int64_t size, int64_t off, const char *t) {
|
||||
return off >= 0 && off + 4 <= size && std::memcmp(b + off, t, 4) == 0;
|
||||
}
|
||||
inline int32_t i32(const uint8_t *p) {
|
||||
return (int32_t)((uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24));
|
||||
}
|
||||
inline int u16(const uint8_t *b, int64_t off) { return (int)b[off] | ((int)b[off + 1] << 8); }
|
||||
inline int64_t u32(const uint8_t *b, int64_t off) { return (int64_t)(uint32_t)i32(b + off); }
|
||||
|
||||
// ------------------------------------------------------------------- SF2
|
||||
|
||||
bool looksLikeSf2(const uint8_t *b, int64_t n) {
|
||||
return n > 12 && tagAt(b, n, 0, "RIFF") && tagAt(b, n, 8, "sfbk");
|
||||
}
|
||||
|
||||
std::optional<Loaded> loadSf2(const uint8_t *bytes, int64_t limit) {
|
||||
int64_t pos = 0;
|
||||
if (!tagAt(bytes, limit, pos, "RIFF")) return std::nullopt;
|
||||
pos += 4;
|
||||
pos += 4; // riff size
|
||||
if (!tagAt(bytes, limit, pos, "sfbk")) return std::nullopt;
|
||||
pos += 4;
|
||||
|
||||
int64_t smplOff = -1, shdrOff = -1;
|
||||
int32_t shdrBytes = 0;
|
||||
// RIFF chunk walk over attacker-controlled sizes; every seek is forced FORWARD
|
||||
// (a negative or small size would otherwise loop forever).
|
||||
while (limit - pos >= 8) {
|
||||
const int64_t chunkStart = pos;
|
||||
const uint8_t *id = bytes + pos;
|
||||
const int32_t size = i32(bytes + pos + 4);
|
||||
pos += 8;
|
||||
if (size < 0) break; // a size that cannot be honoured ends the walk
|
||||
const int64_t chunkEnd = std::min(pos + (int64_t)size, limit);
|
||||
if (std::memcmp(id, "LIST", 4) == 0 && limit - pos >= 4) {
|
||||
const uint8_t *listType = bytes + pos;
|
||||
pos += 4;
|
||||
while (pos + 8 <= chunkEnd) {
|
||||
const int64_t subStart = pos;
|
||||
const uint8_t *sid = bytes + pos;
|
||||
const int32_t ssize = i32(bytes + pos + 4);
|
||||
pos += 8;
|
||||
if (ssize < 0) break;
|
||||
const int64_t dataPos = pos;
|
||||
if (std::memcmp(listType, "sdta", 4) == 0 && std::memcmp(sid, "smpl", 4) == 0) smplOff = dataPos;
|
||||
if (std::memcmp(listType, "pdta", 4) == 0 && std::memcmp(sid, "shdr", 4) == 0) { shdrOff = dataPos; shdrBytes = ssize; }
|
||||
const int64_t next = std::clamp(dataPos + ssize + (ssize & 1), (int64_t)0, limit);
|
||||
if (next <= subStart) break; // no forward progress
|
||||
pos = next;
|
||||
}
|
||||
}
|
||||
const int64_t next = std::clamp(chunkEnd + (size & 1), (int64_t)0, limit);
|
||||
if (next <= chunkStart) break; // no forward progress
|
||||
pos = next;
|
||||
}
|
||||
if (smplOff < 0 || shdrOff < 0 || shdrBytes < SHDR_REC) return std::nullopt;
|
||||
|
||||
// First sample header record (46 bytes): 20-byte name, then the fields. The
|
||||
// chunk may claim more bytes than the file has: the Kotlin's reads would throw.
|
||||
const int64_t h = shdrOff + 20;
|
||||
if (h + 21 > limit) return std::nullopt;
|
||||
const int64_t start = u32(bytes, h);
|
||||
const int64_t end = u32(bytes, h + 4);
|
||||
const int64_t startLoop = u32(bytes, h + 8);
|
||||
const int64_t endLoop = u32(bytes, h + 12);
|
||||
const int32_t sampleRate = i32(bytes + h + 16);
|
||||
const int originalKey = bytes[h + 20];
|
||||
if (end <= start) return std::nullopt;
|
||||
|
||||
// Coerce the span as a Long before narrowing (a huge header can't overflow).
|
||||
const int frames = (int)std::clamp(end - start, (int64_t)0, (int64_t)MAX_FRAMES);
|
||||
if (frames <= 0) return std::nullopt;
|
||||
std::vector<float> out((size_t)frames);
|
||||
// start is a 32-bit unsigned frame index: resolve the offset in 64 bits.
|
||||
const int64_t readAt = std::clamp(smplOff + start * 2, (int64_t)0, limit);
|
||||
int64_t db = readAt;
|
||||
int i = 0;
|
||||
while (i < frames && limit - db >= 2) {
|
||||
out[(size_t)i] = (float)(int16_t)(uint16_t)u16(bytes, db) / 32768.f;
|
||||
db += 2;
|
||||
i++;
|
||||
}
|
||||
|
||||
const int root = (originalKey >= 1 && originalKey <= 127) ? originalKey : 60;
|
||||
const int rate = (sampleRate >= 8000 && sampleRate <= 192000) ? sampleRate : 44100;
|
||||
// Loop points are absolute (same base as start/end): make them relative to the
|
||||
// extracted region and keep only if they fall inside it.
|
||||
const int64_t lsRel = startLoop - start;
|
||||
const int64_t leRel = endLoop - start;
|
||||
const int loopS = (leRel > lsRel && lsRel >= 0 && leRel <= frames) ? (int)lsRel : -1;
|
||||
const int loopE = loopS >= 0 ? (int)leRel : -1;
|
||||
return Loaded{Sample(std::move(out), rate, loopS, loopE), root};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- XI
|
||||
|
||||
bool looksLikeXi(const uint8_t *b, int64_t n) {
|
||||
return n > 300 && std::memcmp(b, "Extended Instru", 15) == 0;
|
||||
}
|
||||
|
||||
std::optional<Loaded> loadXi(const uint8_t *bytes, int64_t size) {
|
||||
// Fixed XI header layout: number-of-samples word at 296, first 40-byte sample
|
||||
// header at 298, then delta-encoded sample data after all headers.
|
||||
const int numSamples = u16(bytes, 296);
|
||||
if (numSamples < 1) return std::nullopt;
|
||||
const int hp = 298;
|
||||
if (hp + 40 > size) return std::nullopt;
|
||||
const int32_t length = (int32_t)u32(bytes, hp); // sample length in bytes (toInt wraps)
|
||||
const int type = bytes[hp + 14];
|
||||
const int relativeNote = (int8_t)bytes[hp + 16]; // signed
|
||||
const bool is16 = (type & 0x10) != 0;
|
||||
|
||||
const int dataStart = hp + numSamples * 40;
|
||||
if (length <= 0 || dataStart >= size) return std::nullopt;
|
||||
const int32_t byteLen = (int32_t)std::min((int64_t)length, size - dataStart);
|
||||
|
||||
const int div = is16 ? 2 : 1;
|
||||
const int32_t n = std::min(byteLen / div, (int32_t)MAX_FRAMES);
|
||||
if (n <= 0) return std::nullopt;
|
||||
std::vector<float> out((size_t)n);
|
||||
if (is16) {
|
||||
int old = 0;
|
||||
for (int32_t k = 0; k < n; ++k) {
|
||||
const int16_t d = (int16_t)(uint16_t)u16(bytes, (int64_t)dataStart + 2 * (int64_t)k);
|
||||
old = (old + d) & 0xFFFF;
|
||||
out[(size_t)k] = (float)(int16_t)(uint16_t)old / 32768.f;
|
||||
}
|
||||
} else {
|
||||
int old = 0;
|
||||
for (int32_t k = 0; k < n; ++k) {
|
||||
old = (old + (int8_t)bytes[dataStart + k]) & 0xFF;
|
||||
out[(size_t)k] = (float)(int8_t)(uint8_t)old / 128.f;
|
||||
}
|
||||
}
|
||||
// Loop info: type bits 0-1 (0 none, 1 forward, 2 ping-pong); loopStart/loopLen
|
||||
// are byte offsets (halved for 16-bit). Ping-pong is treated as forward.
|
||||
const int loopType = type & 0x03;
|
||||
const int32_t loopStartB = (int32_t)u32(bytes, hp + 4);
|
||||
const int32_t loopLenB = (int32_t)u32(bytes, hp + 8);
|
||||
int loopS = -1;
|
||||
int loopE = -1;
|
||||
if (loopType != 0 && loopLenB > 0 && loopStartB >= 0) {
|
||||
const int32_t ls = loopStartB / div;
|
||||
const int32_t le = (int32_t)((uint32_t)loopStartB + (uint32_t)loopLenB) / div; // Int wraps
|
||||
if (ls >= 0 && ls < n && le >= ls + 1 && le <= n) { loopS = ls; loopE = le; }
|
||||
}
|
||||
// XI/XM samples have no stored rate; C-4 plays at 8363 Hz by convention.
|
||||
// root = 60 - relativeNote, so that note plays the sample's natural pitch.
|
||||
const int root = std::clamp(60 - relativeNote, 0, 127);
|
||||
return Loaded{Sample(std::move(out), 8363, loopS, loopE), root};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<Loaded> load(const uint8_t *bytes, size_t size) {
|
||||
if (bytes == nullptr || size > 0x7FFFFFFF) return std::nullopt; // a Kotlin ByteArray's limit
|
||||
const int64_t n = (int64_t)size;
|
||||
if (looksLikeSf2(bytes, n)) return loadSf2(bytes, n);
|
||||
if (looksLikeXi(bytes, n)) return loadXi(bytes, n);
|
||||
if (auto s = SampleStore::decodeWav(bytes, size)) return Loaded{std::move(*s), 60};
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
} // namespace sizzle::sampler::SoundFontLoader
|
||||
@@ -0,0 +1,28 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
|
||||
// Port of SoundFontLoader.kt: a SoundFont (.sf2) or FastTracker II instrument (.xi)
|
||||
// file -> its first sample, root note and loop points. A plain WAV is accepted too
|
||||
// (root 60). The bytes are untrusted: every read is bounds-checked and sizes are
|
||||
// capped (MAX_FRAMES) as in the Kotlin. Runs on a loader thread (allocates).
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include "sizzle/Sample.hpp"
|
||||
|
||||
namespace sizzle::sampler::SoundFontLoader {
|
||||
|
||||
struct Loaded {
|
||||
Sample sample;
|
||||
int rootNote = 60;
|
||||
};
|
||||
|
||||
/** Frames cap so a pathologically large sample region can't exhaust memory. */
|
||||
inline constexpr int MAX_FRAMES = 48000 * 30;
|
||||
|
||||
/** The file's sample, or nothing if the bytes are not a format we understand. */
|
||||
std::optional<Loaded> load(const uint8_t *bytes, size_t size);
|
||||
|
||||
} // namespace sizzle::sampler::SoundFontLoader
|
||||
Reference in New Issue
Block a user