iOS core: Synth voice, Sampler, sample store and SF2/XI loader ported, bit-exact with Kotlin
All six instruments now run in C++ (61 reference scenarios, 16 sampler tests). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
8d85b14a67
commit
a5b2f4c873
+6
-1
@@ -66,9 +66,14 @@ build/core/golden_test: $(CORE_SRC) $(CORE_HDR) core/tests/golden_test.cpp
|
|||||||
mkdir -p build/core
|
mkdir -p build/core
|
||||||
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) core/tests/golden_test.cpp
|
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) core/tests/golden_test.cpp
|
||||||
|
|
||||||
core-test: build/core/golden_test
|
build/core/sampler_test: $(CORE_SRC) $(CORE_HDR) core/tests/sampler_test.cpp
|
||||||
|
mkdir -p build/core
|
||||||
|
$(CXX) $(CXXFLAGS) -Icore/src/sampler -o $@ $(CORE_SRC) core/tests/sampler_test.cpp
|
||||||
|
|
||||||
|
core-test: build/core/golden_test build/core/sampler_test
|
||||||
@test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden
|
@test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden
|
||||||
build/core/golden_test $(GOLDEN) $(TYPES)
|
build/core/golden_test $(GOLDEN) $(TYPES)
|
||||||
|
build/core/sampler_test
|
||||||
|
|
||||||
# ------------------------------------------------------------------ app
|
# ------------------------------------------------------------------ app
|
||||||
build/core/au_test: app/FX/SizzleEffectAU.mm app/FX/SizzleEffectAU.h app/FX/Components.gen.h app/tests/au_test.mm $(CORE_SRC) $(CORE_HDR)
|
build/core/au_test: app/FX/SizzleEffectAU.mm app/FX/SizzleEffectAU.h app/FX/Components.gen.h app/tests/au_test.mm $(CORE_SRC) $(CORE_HDR)
|
||||||
|
|||||||
@@ -52,6 +52,24 @@ Each milestone ends with a build that runs on the iPad.
|
|||||||
5. **Everything else.** MIDI in/out and clock sync, gamepad and key bindings,
|
5. **Everything else.** MIDI in/out and clock sync, gamepad and key bindings,
|
||||||
recording, sample recorder, sharing/import, backups, themes, settings.
|
recording, sample recorder, sharing/import, backups, themes, settings.
|
||||||
|
|
||||||
|
## Progress
|
||||||
|
|
||||||
|
- 2026-11-15: all six instruments' sound is in C++ and matches Kotlin bit for bit
|
||||||
|
(Synth, Morph Pad, Wavetable, Grain Cloud, Sampler, SF2/XI), plus the 12 factory
|
||||||
|
wavetables, the sample store and the WAV/SF2/XI readers (`core/tests/sampler_test`).
|
||||||
|
`make -C ios core-test`: 61 reference scenarios + 16 sampler tests.
|
||||||
|
|
||||||
|
Notes for the engine port (from the voice ports):
|
||||||
|
- Kotlin seeds every new FrasilVoice and GrainCloud from global counters, and every
|
||||||
|
SynthVoice builds a FrasilVoice. The C++ engine owns one `frasil::FrasilSeeds`,
|
||||||
|
one `echofield::GrainSeeds` and one `frasil::FrasilClock`, and builds its voice
|
||||||
|
pools in AudioEngine's order, or full-song renders won't match.
|
||||||
|
- `synth::SynthPatch` has an id standing in for Kotlin's object identity
|
||||||
|
(`setPatch` skips retuning for the same patch): reuse the patch built per block,
|
||||||
|
don't rebuild it.
|
||||||
|
- `sampler::SampleStore`: the audio thread calls `quiescent()` once per block;
|
||||||
|
voices pin samples. The Grain Cloud's custom-sample pointer isn't pinned yet.
|
||||||
|
|
||||||
## Rules for ports
|
## Rules for ports
|
||||||
|
|
||||||
- Translate line for line and keep Kotlin's types (`Float` → `float`, `Double` →
|
- Translate line for line and keep Kotlin's types (`Float` → `float`, `Double` →
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
// SampleStore.Sample (SampleStore.kt): decoded mono PCM at its own rate, shared by
|
||||||
|
// the Sampler / SoundFont voice (core/src/sampler) and the Grain Cloud's custom
|
||||||
|
// source (core/src/echofield).
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace sizzle {
|
||||||
|
|
||||||
|
struct Sample {
|
||||||
|
std::vector<float> data;
|
||||||
|
int sampleRate = 0;
|
||||||
|
/** Sample-loop points in frames (from an SF2/XI file), or -1 when the source has
|
||||||
|
* none; the SoundFont voice uses them for sustain looping. */
|
||||||
|
int loopStart = -1;
|
||||||
|
int loopEnd = -1;
|
||||||
|
/** Players currently holding this sample across audio blocks (SampleVoice pins
|
||||||
|
* it from noteOn until it lets go). sampler::SampleStore frees a removed sample
|
||||||
|
* only once this is 0, which is what "a voice keeps its own reference" means in
|
||||||
|
* the Kotlin. Not copied: a copy is a new, unpinned sample. */
|
||||||
|
mutable std::atomic<int> users{0};
|
||||||
|
|
||||||
|
Sample() = default;
|
||||||
|
Sample(std::vector<float> d, int rate, int ls = -1, int le = -1)
|
||||||
|
: data(std::move(d)), sampleRate(rate), loopStart(ls), loopEnd(le) {}
|
||||||
|
Sample(const Sample &o)
|
||||||
|
: data(o.data), sampleRate(o.sampleRate), loopStart(o.loopStart), loopEnd(o.loopEnd) {}
|
||||||
|
Sample(Sample &&o) noexcept
|
||||||
|
: data(std::move(o.data)), sampleRate(o.sampleRate), loopStart(o.loopStart), loopEnd(o.loopEnd) {}
|
||||||
|
Sample &operator=(const Sample &o) {
|
||||||
|
data = o.data; sampleRate = o.sampleRate; loopStart = o.loopStart; loopEnd = o.loopEnd;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
Sample &operator=(Sample &&o) noexcept {
|
||||||
|
data = std::move(o.data); sampleRate = o.sampleRate; loopStart = o.loopStart; loopEnd = o.loopEnd;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace sizzle
|
||||||
@@ -2,19 +2,10 @@
|
|||||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
// The part of SampleStore.kt the Grain Cloud needs: SampleStore.Sample, mono float
|
// The Grain Cloud's name for the shared sample type (sizzle/Sample.hpp).
|
||||||
// PCM at its own rate. Minimal on purpose; the sampler port (core/src/sampler) can
|
|
||||||
// adopt or replace it.
|
|
||||||
|
|
||||||
#include <vector>
|
#include "sizzle/Sample.hpp"
|
||||||
|
|
||||||
namespace sizzle::echofield {
|
namespace sizzle::echofield {
|
||||||
|
using Sample = sizzle::Sample;
|
||||||
struct Sample {
|
|
||||||
std::vector<float> data;
|
|
||||||
int sampleRate = 0;
|
|
||||||
int loopStart = -1;
|
|
||||||
int loopEnd = -1;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace sizzle::echofield
|
} // namespace sizzle::echofield
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Port of TimeDivision (model/Toolbox.kt): tempo-synced note lengths.
|
||||||
|
|
||||||
|
namespace sizzle::model {
|
||||||
|
|
||||||
|
enum class TimeDivision : int {
|
||||||
|
WHOLE, HALF, QUARTER, EIGHTH, SIXTEENTH, THIRTYSECOND, DOTTED_EIGHTH
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr int TIME_DIVISION_COUNT = 7;
|
||||||
|
|
||||||
|
/** TimeDivision.entries' labels. */
|
||||||
|
constexpr const char *TIME_DIVISION_LABELS[TIME_DIVISION_COUNT] = {
|
||||||
|
"1/1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/8."};
|
||||||
|
|
||||||
|
/** TimeDivision.entries' beatFraction (length in beats). */
|
||||||
|
constexpr double TIME_DIVISION_BEATS[TIME_DIVISION_COUNT] = {4.0, 2.0, 1.0, 0.5, 0.25, 0.125, 0.75};
|
||||||
|
|
||||||
|
/** TimeDivision.fromIndex(i): clamps to 0..lastIndex. */
|
||||||
|
constexpr TimeDivision fromIndex(int i) {
|
||||||
|
return (TimeDivision)(i < 0 ? 0 : (i > TIME_DIVISION_COUNT - 1 ? TIME_DIVISION_COUNT - 1 : i));
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr double beatFraction(TimeDivision d) { return TIME_DIVISION_BEATS[(int)d]; }
|
||||||
|
constexpr const char *label(TimeDivision d) { return TIME_DIVISION_LABELS[(int)d]; }
|
||||||
|
|
||||||
|
} // namespace sizzle::model
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Port of model/SynthDefs.kt: the option lists the subtractive synth's slot
|
||||||
|
// values are written with, and its shape constants.
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
namespace sizzle::synth::defs {
|
||||||
|
|
||||||
|
/** Oscillator waveforms. */
|
||||||
|
constexpr const char *WAVES[] = {"Tri", "Saw", "Square", "Pulse25", "Pulse12"};
|
||||||
|
constexpr int WAVES_COUNT = 5;
|
||||||
|
/** LFO waveforms. */
|
||||||
|
constexpr const char *LFO_WAVES[] = {"Tri", "Saw", "Square", "Sine", "S&H"};
|
||||||
|
constexpr int LFO_WAVES_COUNT = 5;
|
||||||
|
/** LFO start-phase offsets, eight 45-degree steps. */
|
||||||
|
constexpr const char *LFO_PHASES[] = {"0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"};
|
||||||
|
constexpr int LFO_PHASES_COUNT = 8;
|
||||||
|
/** Modulation-matrix sources; index 0 ("Off") disables the slot. */
|
||||||
|
constexpr const char *MOD_SRC[] = {"Off", "LFO", "FiltEnv", "AmpEnv", "Vel", "KeyTrk"};
|
||||||
|
constexpr int MOD_SRC_COUNT = 6;
|
||||||
|
/** Modulation-matrix destinations. */
|
||||||
|
constexpr const char *MOD_DST[] = {"Pitch", "Osc2", "Osc3", "Cutoff", "PWM", "Amp"};
|
||||||
|
constexpr int MOD_DST_COUNT = 6;
|
||||||
|
|
||||||
|
constexpr int OSC_COUNT = 3;
|
||||||
|
constexpr int MOD_SLOTS = 4;
|
||||||
|
|
||||||
|
/** Init-patch oscillator waveforms (per oscillator). */
|
||||||
|
constexpr const char *DEF_OSC_WAVE[OSC_COUNT] = {"Saw", "Square", "Tri"};
|
||||||
|
/** Init-patch oscillator mixer levels (only oscillator 1 audible by default). */
|
||||||
|
constexpr float DEF_OSC_LEVEL[OSC_COUNT] = {0.9f, 0.f, 0.f};
|
||||||
|
|
||||||
|
/** List.indexOf: -1 when absent. */
|
||||||
|
inline int indexOf(const char *const *list, int n, const char *v) {
|
||||||
|
for (int i = 0; i < n; ++i) if (std::strcmp(list[i], v) == 0) return i;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A LFO_PHASES label as a fraction of one LFO cycle (0..1). */
|
||||||
|
inline float lfoPhaseFraction(const char *label) {
|
||||||
|
int i = indexOf(LFO_PHASES, LFO_PHASES_COUNT, label);
|
||||||
|
return i < 0 ? 0.f : (float)i / (float)LFO_PHASES_COUNT;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace sizzle::synth::defs
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
// Port of SynthPatch.kt, line for line.
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdio>
|
||||||
|
#include "synth/SynthPatch.hpp"
|
||||||
|
#include "KotlinMath.hpp"
|
||||||
|
#include "model/TimeDivision.hpp"
|
||||||
|
#include "sizzle/Params.hpp"
|
||||||
|
|
||||||
|
#if defined(__clang__)
|
||||||
|
#pragma clang fp contract(off) // Java never fuses multiply-adds
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace sizzle::synth {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
std::atomic<uint32_t> nextId{1};
|
||||||
|
|
||||||
|
int idx(int i) { return i < 0 ? 0 : i; }
|
||||||
|
int waveIndex(const char *s) { return idx(defs::indexOf(defs::WAVES, defs::WAVES_COUNT, s)); }
|
||||||
|
int lfoWaveIndex(const char *s) { return idx(defs::indexOf(defs::LFO_WAVES, defs::LFO_WAVES_COUNT, s)); }
|
||||||
|
int srcIndex(const char *s) { return idx(defs::indexOf(defs::MOD_SRC, defs::MOD_SRC_COUNT, s)); }
|
||||||
|
int dstIndex(const char *s) { return idx(defs::indexOf(defs::MOD_DST, defs::MOD_DST_COUNT, s)); }
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
SynthPatch SynthPatch::from(const Params *slot, float tempoBpm) {
|
||||||
|
auto f = [&](const char *k, float d) { return slot ? slot->f(k, d) : d; };
|
||||||
|
auto s = [&](const char *k, const char *d) { return slot ? slot->s(k, d) : d; };
|
||||||
|
char key[16];
|
||||||
|
SynthPatch p;
|
||||||
|
for (int i = 0; i < OSC_COUNT; ++i) {
|
||||||
|
std::snprintf(key, sizeof key, "osc%dwave", i);
|
||||||
|
p.oscWave[i] = waveIndex(s(key, defs::DEF_OSC_WAVE[i]));
|
||||||
|
std::snprintf(key, sizeof key, "osc%doct", i);
|
||||||
|
p.oscOct[i] = kt::coerceIn(kt::toInt(f(key, 0.f)), -2, 2);
|
||||||
|
std::snprintf(key, sizeof key, "osc%dsemi", i);
|
||||||
|
p.oscSemi[i] = kt::coerceIn(kt::toInt(f(key, 0.f)), -12, 12);
|
||||||
|
std::snprintf(key, sizeof key, "osc%dfine", i);
|
||||||
|
p.oscFine[i] = kt::coerceIn(f(key, 0.f), -50.f, 50.f);
|
||||||
|
std::snprintf(key, sizeof key, "osc%dlevel", i);
|
||||||
|
p.oscLevel[i] = kt::coerceIn(f(key, defs::DEF_OSC_LEVEL[i]), 0.f, 1.f);
|
||||||
|
}
|
||||||
|
|
||||||
|
int divIdx = kt::toInt(f("lfodiv", 3.f));
|
||||||
|
float beatFraction = (float)model::beatFraction(model::fromIndex(divIdx));
|
||||||
|
p.lfoHz = beatFraction > 0.f ? (tempoBpm / 60.f) / beatFraction : 2.f;
|
||||||
|
|
||||||
|
for (int n = 0; n < MOD_SLOTS; ++n) {
|
||||||
|
std::snprintf(key, sizeof key, "m%dsrc", n);
|
||||||
|
p.modSrc[n] = srcIndex(s(key, "Off"));
|
||||||
|
std::snprintf(key, sizeof key, "m%ddst", n);
|
||||||
|
p.modDst[n] = dstIndex(s(key, "Cutoff"));
|
||||||
|
std::snprintf(key, sizeof key, "m%damt", n);
|
||||||
|
p.modAmt[n] = kt::coerceIn(f(key, 0.f), -1.f, 1.f);
|
||||||
|
}
|
||||||
|
|
||||||
|
p.noiseLevel = kt::coerceIn(f("noise", 0.f), 0.f, 1.f);
|
||||||
|
p.cutoff = kt::coerceIn(f("cutoff", 0.55f), 0.f, 1.f);
|
||||||
|
p.resonance = kt::coerceIn(f("reso", 0.15f), 0.f, 1.f);
|
||||||
|
p.keytrack = kt::coerceIn(f("keytrack", 0.3f), 0.f, 1.f);
|
||||||
|
p.filterEnvAmt = kt::coerceIn(f("fenvamt", 0.4f), -1.f, 1.f);
|
||||||
|
p.fA = f("fatk", 0.005f); p.fD = f("fdec", 0.25f);
|
||||||
|
p.fS = f("fsus", 0.4f); p.fR = f("frel", 0.2f);
|
||||||
|
p.aA = f("attack", 0.005f); p.aD = f("decay", 0.2f);
|
||||||
|
p.aS = f("sustain", 0.7f); p.aR = f("release", 0.2f);
|
||||||
|
p.lfoWave = lfoWaveIndex(s("lfowave", "Tri"));
|
||||||
|
// Absent in presets saved before the phase control existed: the default label, 0.
|
||||||
|
p.lfoPhase = defs::lfoPhaseFraction(s("lfophase", defs::LFO_PHASES[0]));
|
||||||
|
p.kind = Kind::SYNTH;
|
||||||
|
p.id = nextId.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SynthPatch &SynthPatch::defaults() {
|
||||||
|
static const SynthPatch d = from(nullptr, 120.f);
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
SynthPatch SynthPatch::forPad(const frasil::FrasilPatch &pad) {
|
||||||
|
SynthPatch p = defaults();
|
||||||
|
p.kind = Kind::PAD;
|
||||||
|
p.pad = pad;
|
||||||
|
p.id = nextId.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
SynthPatch SynthPatch::forWave(const wavetable::WavePatch &wave) {
|
||||||
|
SynthPatch p = defaults();
|
||||||
|
p.kind = Kind::WAVE;
|
||||||
|
p.wave = wave;
|
||||||
|
p.id = nextId.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace sizzle::synth
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Port of audio/SynthPatch.kt: every parameter of the subtractive synth voice,
|
||||||
|
// parsed once from a slot. A fixed-size copyable value (no heap). Kotlin's nullable
|
||||||
|
// `pad` / `wave` fields become [kind] plus the patch value.
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include "frasil/FrasilVoice.hpp"
|
||||||
|
#include "synth/SynthDefs.hpp"
|
||||||
|
#include "wavetable/WaveVoice.hpp"
|
||||||
|
|
||||||
|
namespace sizzle {
|
||||||
|
class Params;
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace sizzle::synth {
|
||||||
|
|
||||||
|
struct SynthPatch {
|
||||||
|
static constexpr int OSC_COUNT = defs::OSC_COUNT;
|
||||||
|
static constexpr int MOD_SLOTS = defs::MOD_SLOTS;
|
||||||
|
|
||||||
|
/** Which engine plays the note: Kotlin's pad != null / wave != null. */
|
||||||
|
enum class Kind : uint8_t { SYNTH, PAD, WAVE };
|
||||||
|
|
||||||
|
// ---- oscillators (index 0..2) ----
|
||||||
|
int oscWave[OSC_COUNT] = {}; // index into WAVES
|
||||||
|
int oscOct[OSC_COUNT] = {}; // octave transpose, -2..+2
|
||||||
|
int oscSemi[OSC_COUNT] = {}; // semitone detune, -12..+12
|
||||||
|
float oscFine[OSC_COUNT] = {}; // fine detune in cents, -50..+50
|
||||||
|
float oscLevel[OSC_COUNT] = {}; // mixer level, 0..1
|
||||||
|
float noiseLevel = 0.f;
|
||||||
|
// ---- filter ----
|
||||||
|
float cutoff = 0.f, resonance = 0.f, keytrack = 0.f, filterEnvAmt = 0.f;
|
||||||
|
float fA = 0.f, fD = 0.f, fS = 0.f, fR = 0.f;
|
||||||
|
// ---- amplifier ----
|
||||||
|
float aA = 0.f, aD = 0.f, aS = 0.f, aR = 0.f;
|
||||||
|
// ---- LFO ----
|
||||||
|
int lfoWave = 0;
|
||||||
|
float lfoHz = 0.f; // tempo-synced rate
|
||||||
|
float lfoPhase = 0.f; // start-phase offset, 0..1
|
||||||
|
// ---- modulation matrix ----
|
||||||
|
int modSrc[MOD_SLOTS] = {}; // index into MOD_SRC (0 == Off)
|
||||||
|
int modDst[MOD_SLOTS] = {}; // index into MOD_DST
|
||||||
|
float modAmt[MOD_SLOTS] = {}; // -1..1
|
||||||
|
|
||||||
|
Kind kind = Kind::SYNTH;
|
||||||
|
/** Valid when kind == PAD (the subtractive fields above are then unused). */
|
||||||
|
frasil::FrasilPatch pad{};
|
||||||
|
/** Valid when kind == WAVE. */
|
||||||
|
wavetable::WavePatch wave{};
|
||||||
|
|
||||||
|
/** Stands in for Kotlin's object identity (SynthVoice.setPatch's `p === patch`):
|
||||||
|
* stamped by each factory below, kept by copies. */
|
||||||
|
uint32_t id = 0;
|
||||||
|
|
||||||
|
/** SynthPatch.from(slot, tempoBpm); [slot] may be null (init patch). */
|
||||||
|
static SynthPatch from(const Params *slot, float tempoBpm);
|
||||||
|
/** SynthPatch.DEFAULT: from(null, 120). */
|
||||||
|
static const SynthPatch &defaults();
|
||||||
|
/** A Morph Pad patch: the default synth fields, carrying [pad]. */
|
||||||
|
static SynthPatch forPad(const frasil::FrasilPatch &pad);
|
||||||
|
/** A Wavetable patch: the default synth fields, carrying [wave]. */
|
||||||
|
static SynthPatch forWave(const wavetable::WavePatch &wave);
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace sizzle::synth
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
// The reference tests' SYNTH maker (see TestVoice.hpp, IosGoldenInstruments.kt):
|
||||||
|
// a SynthVoice with the patch the engine builds for the slot's type.
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include "frasil/FrasilVoice.hpp"
|
||||||
|
#include "sizzle/TestVoice.hpp"
|
||||||
|
#include "synth/SynthVoice.hpp"
|
||||||
|
#include "wavetable/WaveTables.hpp"
|
||||||
|
|
||||||
|
namespace sizzle {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using frasil::FrasilClock;
|
||||||
|
using frasil::FrasilSeeds;
|
||||||
|
using synth::SynthPatch;
|
||||||
|
using synth::SynthVoice;
|
||||||
|
|
||||||
|
SynthPatch enginePatch(const TestVoiceSetup &s) {
|
||||||
|
if (std::strcmp(s.type, "NES_SYNTH") == 0) return SynthPatch::from(s.params, s.tempoBpm);
|
||||||
|
if (std::strcmp(s.type, "MORPH_PAD") == 0) return SynthPatch::forPad(frasil::FrasilPatch::from(s.params));
|
||||||
|
if (std::strcmp(s.type, "WAVETABLE") == 0)
|
||||||
|
return SynthPatch::forWave(wavetable::WavePatch::from(s.params, s.tempoBpm));
|
||||||
|
return SynthPatch::defaults();
|
||||||
|
}
|
||||||
|
|
||||||
|
FrasilSeeds seedsAt(uint32_t counter) {
|
||||||
|
FrasilSeeds seeds;
|
||||||
|
seeds.seeds = counter;
|
||||||
|
return seeds;
|
||||||
|
}
|
||||||
|
|
||||||
|
class SynthTestVoice final : public TestVoice {
|
||||||
|
FrasilClock clock;
|
||||||
|
FrasilSeeds seeds;
|
||||||
|
SynthPatch patch;
|
||||||
|
SynthVoice voice;
|
||||||
|
int sampleRate;
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit SynthTestVoice(const TestVoiceSetup &s)
|
||||||
|
: clock{s.clock0}, seeds(seedsAt(s.frasilSeeds)), patch(enginePatch(s)),
|
||||||
|
voice(s.sampleRate, clock, seeds.next()), sampleRate(s.sampleRate) {}
|
||||||
|
|
||||||
|
void blockStart(int frames) override { clock.advance(frames, sampleRate); }
|
||||||
|
void noteOn(int midi, int velocity) override { voice.noteOn(midi, velocity, patch); }
|
||||||
|
void noteOff(int) override { voice.noteOff(); }
|
||||||
|
float render() override { return voice.render(); }
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::unique_ptr<TestVoice> makeSynthTestVoice(const TestVoiceSetup &setup) {
|
||||||
|
wavetable::WaveTables::prewarmBlocking();
|
||||||
|
return std::make_unique<SynthTestVoice>(setup);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace sizzle
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
// Port of SynthVoice.kt, line for line. See the Kotlin for the commentary on the
|
||||||
|
// sound; comments here are about the port.
|
||||||
|
|
||||||
|
#include <cmath>
|
||||||
|
#include "synth/SynthVoice.hpp"
|
||||||
|
#include "KotlinMath.hpp"
|
||||||
|
|
||||||
|
#if defined(__clang__)
|
||||||
|
#pragma clang fp contract(off) // Java never fuses multiply-adds
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace sizzle::synth {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr double PI = 3.141592653589793; // Math.PI
|
||||||
|
constexpr float OUT_GAIN = 0.5f;
|
||||||
|
constexpr int CTRL_INTERVAL = 16;
|
||||||
|
constexpr double AMP_MOD_SMOOTH_SEC = 0.002;
|
||||||
|
|
||||||
|
double fastPow2(double x) { return std::pow(2.0, x); }
|
||||||
|
double fastPow(double base, double x) { return std::pow(base, x); }
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------- Adsr ---
|
||||||
|
|
||||||
|
void SynthVoice::Adsr::gateOn(float aa, float dd, float ss, float rr) {
|
||||||
|
a = kt::coerceAtLeast(aa, 0.0005f); d = dd; s = kt::coerceIn(ss, 0.f, 1.f); r = rr;
|
||||||
|
stage = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
float SynthVoice::Adsr::advance(float dt) {
|
||||||
|
switch (stage) {
|
||||||
|
case 1: level += dt / a; if (level >= 1.f) { level = 1.f; stage = 2; } break;
|
||||||
|
case 2: level -= dt / kt::coerceAtLeast(d, 0.001f) * (1.f - s); if (level <= s) { level = s; stage = 3; } break;
|
||||||
|
case 3: break;
|
||||||
|
case 4: level -= dt / kt::coerceAtLeast(r, 0.001f); if (level <= 0.f) { level = 0.f; stage = 0; } break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
return level;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- SynthVoice ---
|
||||||
|
|
||||||
|
SynthVoice::SynthVoice(int sampleRate, const frasil::FrasilClock &clock, int32_t padSeed)
|
||||||
|
: sampleRate(sampleRate), patch(SynthPatch::defaults()),
|
||||||
|
ampModCoeff((float)(1.0 - std::exp(-1.0 / (sampleRate * AMP_MOD_SMOOTH_SEC)))),
|
||||||
|
pad(sampleRate, clock, padSeed), wave(sampleRate) {}
|
||||||
|
|
||||||
|
double SynthVoice::midiToHz(int midi) { return 440.0 * std::pow(2.0, (midi - 69) / 12.0); }
|
||||||
|
|
||||||
|
bool SynthVoice::isActive() const {
|
||||||
|
switch (mode) {
|
||||||
|
case MODE_PAD: return pad.isActive();
|
||||||
|
case MODE_WAVE: return wave.isActive();
|
||||||
|
default: return ampEnv.active();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SynthVoice::isGated() const {
|
||||||
|
switch (mode) {
|
||||||
|
case MODE_PAD: return pad.isGated();
|
||||||
|
case MODE_WAVE: return wave.isGated();
|
||||||
|
default: return ampEnv.gateOpen();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void SynthVoice::noteOn(int midi, int velocity, const SynthPatch &p) {
|
||||||
|
const bool hasPad = p.kind == SynthPatch::Kind::PAD;
|
||||||
|
const bool hasWave = p.kind == SynthPatch::Kind::WAVE;
|
||||||
|
const int want = hasPad ? MODE_PAD : hasWave ? MODE_WAVE : MODE_SYNTH;
|
||||||
|
if (want != mode) { // a slot switched kinds: the old engine stops
|
||||||
|
ampEnv.kill(); filtEnv.kill(); pad.kill(); wave.kill();
|
||||||
|
mode = want;
|
||||||
|
}
|
||||||
|
if (hasPad) {
|
||||||
|
patch = p;
|
||||||
|
pitch_ = midi;
|
||||||
|
pad.noteOn(midi, (float)velocity / 127.f, p.pad);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (hasWave) {
|
||||||
|
patch = p;
|
||||||
|
pitch_ = midi;
|
||||||
|
wave.noteOn(midi, (float)velocity / 127.f, p.wave);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
patch = p;
|
||||||
|
pitch_ = midi;
|
||||||
|
this->velocity = kt::coerceIn((float)velocity / 127.f, 0.f, 1.f);
|
||||||
|
baseFreq = midiToHz(midi);
|
||||||
|
keyNorm = kt::coerceIn((float)(midi - 60) / 60.f, -1.f, 1.f);
|
||||||
|
ampEnv.gateOn(patch.aA, patch.aD, patch.aS, patch.aR);
|
||||||
|
filtEnv.gateOn(patch.fA, patch.fD, patch.fS, patch.fR);
|
||||||
|
lfoInc = (double)patch.lfoHz / sampleRate;
|
||||||
|
lfoPhase = 0.0;
|
||||||
|
ctrl = 0;
|
||||||
|
ampModPrimed = false;
|
||||||
|
computeTuning();
|
||||||
|
}
|
||||||
|
|
||||||
|
void SynthVoice::noteOff() {
|
||||||
|
switch (mode) {
|
||||||
|
case MODE_PAD: pad.noteOff(); break;
|
||||||
|
case MODE_WAVE: wave.noteOff(); break;
|
||||||
|
default: ampEnv.gateOff(); filtEnv.gateOff(); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void SynthVoice::kill() {
|
||||||
|
ampEnv.kill(); filtEnv.kill();
|
||||||
|
pad.kill();
|
||||||
|
wave.kill();
|
||||||
|
pitch_ = -1;
|
||||||
|
ownerTrack = -1;
|
||||||
|
icB = 0.f; icL = 0.f;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SynthVoice::setPatch(const SynthPatch &p) {
|
||||||
|
if (p.id == patch.id) return;
|
||||||
|
const bool hasPad = p.kind == SynthPatch::Kind::PAD;
|
||||||
|
const bool hasWave = p.kind == SynthPatch::Kind::WAVE;
|
||||||
|
if (mode != MODE_SYNTH || hasPad || hasWave) {
|
||||||
|
// Only within the same kind; a slot switched kinds takes effect on the next note.
|
||||||
|
if (mode == MODE_PAD && hasPad) { patch = p; pad.setPatch(p.pad); }
|
||||||
|
if (mode == MODE_WAVE && hasWave) { patch = p; wave.setPatch(p.wave); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
patch = p;
|
||||||
|
lfoInc = (double)p.lfoHz / sampleRate;
|
||||||
|
computeTuning();
|
||||||
|
}
|
||||||
|
|
||||||
|
void SynthVoice::computeTuning() {
|
||||||
|
for (int i = 0; i < OSC_COUNT; ++i) {
|
||||||
|
float semis = (float)patch.oscOct[i] * 12.f + (float)patch.oscSemi[i] + patch.oscFine[i] / 100.f;
|
||||||
|
staticSemis[i] = semis;
|
||||||
|
staticInc[i] = kt::coerceIn(baseFreq * fastPow2(semis / 12.0) / sampleRate, 0.0, 0.49);
|
||||||
|
modInc[i] = staticInc[i];
|
||||||
|
}
|
||||||
|
pitchModActive = false;
|
||||||
|
for (int n = 0; n < MOD_SLOTS; ++n)
|
||||||
|
if (patch.modSrc[n] != 0 && patch.modDst[n] >= 0 && patch.modDst[n] <= 2) { pitchModActive = true; break; }
|
||||||
|
}
|
||||||
|
|
||||||
|
float SynthVoice::render() {
|
||||||
|
if (mode == MODE_PAD) return pad.render();
|
||||||
|
if (mode == MODE_WAVE) return wave.render();
|
||||||
|
if (!ampEnv.active()) return 0.f;
|
||||||
|
const float dt = 1.f / (float)sampleRate;
|
||||||
|
const float ampE = ampEnv.advance(dt);
|
||||||
|
const float filtE = filtEnv.advance(dt);
|
||||||
|
|
||||||
|
// ---- LFO ----
|
||||||
|
lfoPhase += lfoInc;
|
||||||
|
if (lfoPhase >= 1.0) { lfoPhase -= 1.0; shValue = nextRand(); }
|
||||||
|
const float lfo = lfoValue();
|
||||||
|
|
||||||
|
// ---- modulation matrix ----
|
||||||
|
float mPitch = 0.f, mOsc2 = 0.f, mOsc3 = 0.f;
|
||||||
|
float mCut = 0.f, mPwm = 0.f, mAmp = 0.f;
|
||||||
|
for (int n = 0; n < MOD_SLOTS; ++n) {
|
||||||
|
float s;
|
||||||
|
switch (patch.modSrc[n]) {
|
||||||
|
case 1: s = lfo; break;
|
||||||
|
case 2: s = filtE; break;
|
||||||
|
case 3: s = ampE; break;
|
||||||
|
case 4: s = velocity; break;
|
||||||
|
case 5: s = keyNorm; break;
|
||||||
|
default: continue;
|
||||||
|
}
|
||||||
|
const float v = patch.modAmt[n] * s;
|
||||||
|
switch (patch.modDst[n]) {
|
||||||
|
case 0: mPitch += v; break;
|
||||||
|
case 1: mOsc2 += v; break;
|
||||||
|
case 2: mOsc3 += v; break;
|
||||||
|
case 3: mCut += v; break;
|
||||||
|
case 4: mPwm += v; break;
|
||||||
|
case 5: mAmp += v; break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- control-rate update ----
|
||||||
|
if (ctrl <= 0) {
|
||||||
|
ctrl = CTRL_INTERVAL;
|
||||||
|
const float e = kt::coerceIn(patch.cutoff + patch.filterEnvAmt * filtE + patch.keytrack * keyNorm + mCut,
|
||||||
|
0.f, 1.3f);
|
||||||
|
const double hz = kt::coerceIn(20.0 * fastPow(1000.0, (double)e), 20.0, sampleRate * 0.45);
|
||||||
|
const float g = (float)std::tan(PI * hz / sampleRate);
|
||||||
|
const float k = kt::coerceIn(2.f - 1.96f * patch.resonance, 0.05f, 2.f);
|
||||||
|
ca1 = 1.f / (1.f + g * (g + k)); ca2 = g * ca1; ca3 = g * ca2;
|
||||||
|
if (pitchModActive) {
|
||||||
|
for (int i = 0; i < OSC_COUNT; ++i) {
|
||||||
|
float semis = staticSemis[i] + mPitch * 12.f;
|
||||||
|
if (i == 1) semis += mOsc2 * 12.f;
|
||||||
|
if (i == 2) semis += mOsc3 * 12.f;
|
||||||
|
modInc[i] = kt::coerceIn(baseFreq * fastPow2(semis / 12.0) / sampleRate, 0.0, 0.49);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctrl--;
|
||||||
|
|
||||||
|
// ---- oscillators + noise ----
|
||||||
|
float mix = 0.f;
|
||||||
|
for (int i = 0; i < OSC_COUNT; ++i) {
|
||||||
|
const float level = patch.oscLevel[i];
|
||||||
|
if (level <= 0.0001f) continue;
|
||||||
|
const double inc = pitchModActive ? modInc[i] : staticInc[i];
|
||||||
|
double ph = phase[i] + inc;
|
||||||
|
if (ph >= 1.0) ph -= 1.0;
|
||||||
|
phase[i] = ph;
|
||||||
|
mix += waveform(patch.oscWave[i], ph, inc, mPwm) * level;
|
||||||
|
}
|
||||||
|
if (patch.noiseLevel > 0.0001f) mix += nextRand() * patch.noiseLevel;
|
||||||
|
|
||||||
|
// ---- filter ----
|
||||||
|
const float filtered = svf(mix);
|
||||||
|
|
||||||
|
// ---- amplifier ----
|
||||||
|
if (ampModPrimed) ampMod += (mAmp - ampMod) * ampModCoeff;
|
||||||
|
else { ampMod = mAmp; ampModPrimed = true; }
|
||||||
|
float a = ampE * velocity * (1.f + ampMod);
|
||||||
|
if (a < 0.f) a = 0.f;
|
||||||
|
const float y = filtered * a * OUT_GAIN;
|
||||||
|
return std::isfinite(y) ? y : 0.f;
|
||||||
|
}
|
||||||
|
|
||||||
|
float SynthVoice::waveform(int w, double t, double dt, float pwm) const {
|
||||||
|
switch (w) {
|
||||||
|
case 1: return (float)(2.0 * t - 1.0 - polyBlep(t, dt)); // Saw
|
||||||
|
case 2: return pulse(t, dt, kt::coerceIn(0.5f + pwm * 0.45f, 0.02f, 0.98f)); // Square
|
||||||
|
case 3: return pulse(t, dt, kt::coerceIn(0.25f + pwm * 0.45f, 0.02f, 0.98f)); // Pulse 25%
|
||||||
|
case 4: return pulse(t, dt, kt::coerceIn(0.125f + pwm * 0.45f, 0.02f, 0.98f)); // Pulse 12.5%
|
||||||
|
default: return (float)(1.0 - 4.0 * std::fabs(t - 0.5)); // Triangle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
float SynthVoice::pulse(double t, double dt, float w) {
|
||||||
|
double y = t < (double)w ? 1.0 : -1.0;
|
||||||
|
y += polyBlep(t, dt);
|
||||||
|
double t2 = t + (1.0 - (double)w);
|
||||||
|
if (t2 >= 1.0) t2 -= 1.0;
|
||||||
|
y -= polyBlep(t2, dt);
|
||||||
|
return (float)y;
|
||||||
|
}
|
||||||
|
|
||||||
|
double SynthVoice::polyBlep(double t, double dt) {
|
||||||
|
if (dt <= 0.0) return 0.0;
|
||||||
|
if (t < dt) { double x = t / dt; return x + x - x * x - 1.0; }
|
||||||
|
if (t > 1.0 - dt) { double x = (t - 1.0) / dt; return x * x + x + x + 1.0; }
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
float SynthVoice::lfoValue() const {
|
||||||
|
double p = lfoPhase + (double)patch.lfoPhase;
|
||||||
|
if (p >= 1.0) p -= 1.0;
|
||||||
|
switch (patch.lfoWave) {
|
||||||
|
case 1: return (float)(2.0 * p - 1.0); // Saw
|
||||||
|
case 2: return p < 0.5 ? 1.f : -1.f; // Square
|
||||||
|
case 3: return (float)std::sin(2.0 * PI * p); // Sine
|
||||||
|
case 4: return shValue; // Sample & Hold
|
||||||
|
default: return (float)(1.0 - 4.0 * std::fabs(p - 0.5)); // Triangle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
float SynthVoice::svf(float input) {
|
||||||
|
const float v3 = input - icL;
|
||||||
|
const float v1 = ca1 * icB + ca2 * v3;
|
||||||
|
const float v2 = icL + ca2 * icB + ca3 * v3;
|
||||||
|
icB = 2.f * v1 - icB;
|
||||||
|
icL = 2.f * v2 - icL;
|
||||||
|
if (!std::isfinite(v2)) { icB = 0.f; icL = 0.f; return 0.f; }
|
||||||
|
return v2;
|
||||||
|
}
|
||||||
|
|
||||||
|
float SynthVoice::nextRand() {
|
||||||
|
uint32_t s = rng;
|
||||||
|
s ^= s << 13; s ^= s >> 17; s ^= s << 5;
|
||||||
|
rng = s;
|
||||||
|
return (float)(int32_t)s * 4.656613e-10f; // -1..1
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace sizzle::synth
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Port of audio/SynthVoice.kt: one note of the subtractive synth, or (for a Morph
|
||||||
|
// Pad / Wavetable patch) the Frasil / wavetable voice it holds. noteOn, noteOff,
|
||||||
|
// setPatch and render never allocate or lock.
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include "frasil/FrasilVoice.hpp"
|
||||||
|
#include "synth/SynthPatch.hpp"
|
||||||
|
#include "wavetable/WaveVoice.hpp"
|
||||||
|
|
||||||
|
namespace sizzle::synth {
|
||||||
|
|
||||||
|
class SynthVoice {
|
||||||
|
public:
|
||||||
|
/** [clock] must outlive the voice; [padSeed] is the next seed of the engine's
|
||||||
|
* FrasilSeeds (Kotlin's FrasilVoice(sampleRate) inside the SynthVoice takes it). */
|
||||||
|
SynthVoice(int sampleRate, const frasil::FrasilClock &clock, int32_t padSeed);
|
||||||
|
|
||||||
|
int pitch() const { return pitch_; }
|
||||||
|
/** Which tracker (lane,track) started this voice, or -1 if unowned (live/arp). */
|
||||||
|
int ownerTrack = -1;
|
||||||
|
|
||||||
|
bool isActive() const;
|
||||||
|
/** Gate still open (attack/decay/sustain): the note is held. */
|
||||||
|
bool isGated() const;
|
||||||
|
|
||||||
|
/** Start (or steal-and-restart) this voice with [patch] (copied). */
|
||||||
|
void noteOn(int midi, int velocity, const SynthPatch &patch);
|
||||||
|
void noteOff();
|
||||||
|
/** Hard stop with no release tail (transport stop / voice steal). */
|
||||||
|
void kill();
|
||||||
|
/** Swap in updated params for a still-sounding voice; a patch with the same id
|
||||||
|
* as the current one is ignored (Kotlin's `p === patch`). */
|
||||||
|
void setPatch(const SynthPatch &p);
|
||||||
|
float render();
|
||||||
|
|
||||||
|
/** Equal-tempered MIDI note -> Hz (A4 = 69 = 440 Hz). */
|
||||||
|
static double midiToHz(int midi);
|
||||||
|
|
||||||
|
private:
|
||||||
|
/** Linear ADSR envelope (levels 0..1); level is not reset on gate-on. */
|
||||||
|
class Adsr {
|
||||||
|
public:
|
||||||
|
bool active() const { return stage != 0; }
|
||||||
|
bool gateOpen() const { return stage >= 1 && stage <= 3; }
|
||||||
|
void gateOn(float aa, float dd, float ss, float rr);
|
||||||
|
void gateOff() { if (stage != 0) stage = 4; }
|
||||||
|
void kill() { stage = 0; level = 0.f; }
|
||||||
|
float advance(float dt);
|
||||||
|
private:
|
||||||
|
int stage = 0; // 0 idle, 1 attack, 2 decay, 3 sustain, 4 release
|
||||||
|
float level = 0.f;
|
||||||
|
float a = 0.01f, d = 0.1f, s = 0.7f, r = 0.2f;
|
||||||
|
};
|
||||||
|
|
||||||
|
static constexpr int MODE_SYNTH = 0;
|
||||||
|
static constexpr int MODE_PAD = 1;
|
||||||
|
static constexpr int MODE_WAVE = 2;
|
||||||
|
static constexpr int OSC_COUNT = SynthPatch::OSC_COUNT;
|
||||||
|
static constexpr int MOD_SLOTS = SynthPatch::MOD_SLOTS;
|
||||||
|
|
||||||
|
void computeTuning();
|
||||||
|
float waveform(int wave, double t, double dt, float pwm) const;
|
||||||
|
static float pulse(double t, double dt, float w);
|
||||||
|
static double polyBlep(double t, double dt);
|
||||||
|
float lfoValue() const;
|
||||||
|
float svf(float input);
|
||||||
|
float nextRand();
|
||||||
|
|
||||||
|
const int sampleRate;
|
||||||
|
SynthPatch patch;
|
||||||
|
int pitch_ = -1;
|
||||||
|
float velocity = 0.f;
|
||||||
|
double baseFreq = 440.0;
|
||||||
|
float keyNorm = 0.f;
|
||||||
|
|
||||||
|
double phase[OSC_COUNT] = {};
|
||||||
|
float staticSemis[OSC_COUNT] = {};
|
||||||
|
double staticInc[OSC_COUNT] = {};
|
||||||
|
double modInc[OSC_COUNT] = {};
|
||||||
|
bool pitchModActive = false;
|
||||||
|
|
||||||
|
float icB = 0.f, icL = 0.f;
|
||||||
|
float ca1 = 0.f, ca2 = 0.f, ca3 = 0.f;
|
||||||
|
int ctrl = 0;
|
||||||
|
|
||||||
|
double lfoPhase = 0.0;
|
||||||
|
double lfoInc = 0.0;
|
||||||
|
float shValue = 0.f;
|
||||||
|
uint32_t rng = 0x2545F491u;
|
||||||
|
|
||||||
|
float ampMod = 0.f;
|
||||||
|
bool ampModPrimed = false;
|
||||||
|
const float ampModCoeff;
|
||||||
|
|
||||||
|
Adsr ampEnv;
|
||||||
|
Adsr filtEnv;
|
||||||
|
|
||||||
|
frasil::FrasilVoice pad;
|
||||||
|
wavetable::WaveVoice wave;
|
||||||
|
int mode = MODE_SYNTH;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace sizzle::synth
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
// Unit tests for core/src/sampler: SoundFontLoaderTest.kt translated (hostile SF2
|
||||||
|
// headers must fail fast, never hang or crash), plus WAV decode/encode, SF2/XI
|
||||||
|
// parsing of small synthetic files, and the SampleStore's reclamation rules.
|
||||||
|
// Plain asserts; prints PASS/FAIL per test, exits non-zero on any failure.
|
||||||
|
//
|
||||||
|
// Build (from ios/):
|
||||||
|
// c++ -std=c++17 -O2 -Wall -Wextra -Icore/include -Icore/src -Icore/src/fx \
|
||||||
|
// -Icore/src/sampler -o build/core/sampler_test core/src/Params.cpp core/src/Specs.cpp \
|
||||||
|
// core/src/sampler/SampleStore.cpp core/src/sampler/SoundFontLoader.cpp core/src/sampler/SampleVoice.cpp \
|
||||||
|
// core/tests/sampler_test.cpp
|
||||||
|
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include "SampleStore.hpp"
|
||||||
|
#include "SampleVoice.hpp"
|
||||||
|
#include "SoundFontLoader.hpp"
|
||||||
|
|
||||||
|
using namespace sizzle;
|
||||||
|
using namespace sizzle::sampler;
|
||||||
|
using Bytes = std::vector<uint8_t>;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
int failures = 0;
|
||||||
|
bool current = true;
|
||||||
|
|
||||||
|
#define CHECK(c) do { if (!(c)) { std::printf(" check failed: %s (line %d)\n", #c, __LINE__); current = false; } } while (0)
|
||||||
|
|
||||||
|
void run(const char *name, void (*fn)()) {
|
||||||
|
current = true;
|
||||||
|
fn();
|
||||||
|
std::printf("%s %s\n", current ? "PASS" : "FAIL", name);
|
||||||
|
if (!current) ++failures;
|
||||||
|
}
|
||||||
|
|
||||||
|
void w(Bytes &b, const char *tag) { b.insert(b.end(), tag, tag + std::strlen(tag)); }
|
||||||
|
void le32(Bytes &b, int32_t v) { for (int i = 0; i < 4; ++i) b.push_back((uint8_t)((uint32_t)v >> (8 * i))); }
|
||||||
|
void le16(Bytes &b, int v) { b.push_back((uint8_t)v); b.push_back((uint8_t)(v >> 8)); }
|
||||||
|
void zeros(Bytes &b, size_t n) { b.insert(b.end(), n, 0); }
|
||||||
|
|
||||||
|
/** SoundFontLoaderTest.sf2 { }: "RIFF", size 0, "sfbk", then the body. */
|
||||||
|
Bytes sf2Head() { Bytes b; w(b, "RIFF"); le32(b, 0); w(b, "sfbk"); return b; }
|
||||||
|
|
||||||
|
std::optional<SoundFontLoader::Loaded> load(const Bytes &b) { return SoundFontLoader::load(b.data(), b.size()); }
|
||||||
|
|
||||||
|
// ---------------------------------------------------- SoundFontLoaderTest.kt
|
||||||
|
|
||||||
|
void negativeChunkSizeDoesNotHang() {
|
||||||
|
Bytes b = sf2Head();
|
||||||
|
w(b, "LIST"); le32(b, -8); zeros(b, 64);
|
||||||
|
CHECK(!load(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
void negativeSubChunkSizeDoesNotHang() {
|
||||||
|
Bytes b = sf2Head();
|
||||||
|
w(b, "LIST"); le32(b, 256); w(b, "pdta"); w(b, "shdr"); le32(b, -16); zeros(b, 240);
|
||||||
|
CHECK(!load(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
void zeroSizeChunkDoesNotHang() {
|
||||||
|
Bytes b = sf2Head();
|
||||||
|
for (int i = 0; i < 8; ++i) { w(b, "junk"); le32(b, 0); }
|
||||||
|
CHECK(!load(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
void hugeSampleRegionIsCapped() {
|
||||||
|
Bytes b = sf2Head();
|
||||||
|
w(b, "LIST"); le32(b, 12); w(b, "sdta"); w(b, "smpl"); le32(b, 0);
|
||||||
|
w(b, "LIST"); le32(b, 4 + 8 + 46); w(b, "pdta"); w(b, "shdr"); le32(b, 46);
|
||||||
|
zeros(b, 20); // sample name
|
||||||
|
le32(b, 0); // start
|
||||||
|
le32(b, 0x7FFFFFFF); // end: a 2-billion-frame claim
|
||||||
|
le32(b, 0); le32(b, 0);
|
||||||
|
le32(b, 44100);
|
||||||
|
zeros(b, 46 - 40);
|
||||||
|
auto r = load(b); // must return (capped or rejected) without allocating 8 GB
|
||||||
|
CHECK(!r || (int)r->sample.data.size() <= SoundFontLoader::MAX_FRAMES);
|
||||||
|
}
|
||||||
|
|
||||||
|
void truncatedInputIsRejected() {
|
||||||
|
Bytes full = sf2Head();
|
||||||
|
w(full, "LIST"); le32(full, 12); w(full, "sdta"); w(full, "smpl"); le32(full, 0);
|
||||||
|
for (size_t n = 0; n <= full.size(); ++n) {
|
||||||
|
Bytes cut(full.begin(), full.begin() + (long)n);
|
||||||
|
(void)SoundFontLoader::load(cut.empty() ? nullptr : cut.data(), cut.size()); // must not crash
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- SF2 / XI
|
||||||
|
|
||||||
|
/** A minimal valid SF2: 8 frames of PCM, root 64, 22050 Hz, loop [2, 6). */
|
||||||
|
Bytes goodSf2(int32_t start, int32_t end, int32_t ls, int32_t le, int32_t rate, int key) {
|
||||||
|
Bytes b = sf2Head();
|
||||||
|
const int16_t pcm[8] = {0, 8192, 16384, 32767, -32768, -16384, -8192, 1};
|
||||||
|
w(b, "LIST"); le32(b, 4 + 8 + 16); w(b, "sdta"); w(b, "smpl"); le32(b, 16);
|
||||||
|
for (int16_t v : pcm) le16(b, (uint16_t)v);
|
||||||
|
w(b, "LIST"); le32(b, 4 + 8 + 46); w(b, "pdta"); w(b, "shdr"); le32(b, 46);
|
||||||
|
zeros(b, 20);
|
||||||
|
le32(b, start); le32(b, end); le32(b, ls); le32(b, le); le32(b, rate);
|
||||||
|
b.push_back((uint8_t)key);
|
||||||
|
zeros(b, 46 - 41);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
void sf2FirstSampleRootAndLoop() {
|
||||||
|
auto r = load(goodSf2(0, 8, 2, 6, 22050, 64));
|
||||||
|
CHECK(r.has_value());
|
||||||
|
if (!r) return;
|
||||||
|
CHECK(r->rootNote == 64);
|
||||||
|
CHECK(r->sample.sampleRate == 22050);
|
||||||
|
CHECK(r->sample.data.size() == 8);
|
||||||
|
CHECK(r->sample.data[1] == 8192 / 32768.f);
|
||||||
|
CHECK(r->sample.data[3] == 32767 / 32768.f);
|
||||||
|
CHECK(r->sample.data[4] == -1.f);
|
||||||
|
CHECK(r->sample.loopStart == 2 && r->sample.loopEnd == 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
void sf2RegionLoopAndFallbacks() {
|
||||||
|
// start 2: data from frame 2, loop made relative; key 0 -> 60; rate 1000 -> 44100.
|
||||||
|
auto r = load(goodSf2(2, 8, 3, 7, 1000, 0));
|
||||||
|
CHECK(r.has_value());
|
||||||
|
if (!r) return;
|
||||||
|
CHECK(r->rootNote == 60 && r->sample.sampleRate == 44100);
|
||||||
|
CHECK(r->sample.data.size() == 6 && r->sample.data[0] == 16384 / 32768.f);
|
||||||
|
CHECK(r->sample.loopStart == 1 && r->sample.loopEnd == 5);
|
||||||
|
// A loop outside the region is dropped; end <= start is rejected.
|
||||||
|
auto r2 = load(goodSf2(0, 8, 6, 20, 44100, 60));
|
||||||
|
CHECK(r2 && r2->sample.loopStart == -1 && r2->sample.loopEnd == -1);
|
||||||
|
CHECK(!load(goodSf2(5, 5, 0, 0, 44100, 60)));
|
||||||
|
// A shdr chunk that claims 46 bytes but is cut short is rejected.
|
||||||
|
Bytes cut = goodSf2(0, 8, 2, 6, 22050, 64);
|
||||||
|
cut.resize(cut.size() - 10);
|
||||||
|
CHECK(!load(cut));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An XI file: header, one 40-byte sample header, delta-encoded data. */
|
||||||
|
Bytes xi(bool is16, int loopType, int32_t loopStartB, int32_t loopLenB, int relNote, const std::vector<int> &deltas) {
|
||||||
|
Bytes b;
|
||||||
|
w(b, "Extended Instrument: ");
|
||||||
|
b.resize(296, 0);
|
||||||
|
le16(b, 1); // numSamples at 296
|
||||||
|
const int32_t len = (int32_t)deltas.size() * (is16 ? 2 : 1);
|
||||||
|
le32(b, len); le32(b, loopStartB); le32(b, loopLenB); // 298, 302, 306
|
||||||
|
b.push_back(64); b.push_back(0); // volume, finetune (310, 311)
|
||||||
|
b.push_back((uint8_t)((is16 ? 0x10 : 0) | loopType)); // type at 312
|
||||||
|
b.push_back(128); // panning 313
|
||||||
|
b.push_back((uint8_t)(int8_t)relNote); // relative note 314
|
||||||
|
b.resize(298 + 40, 0);
|
||||||
|
for (int d : deltas) { if (is16) le16(b, d & 0xFFFF); else b.push_back((uint8_t)d); }
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
void xi8BitDeltaLoopAndRoot() {
|
||||||
|
// Deltas 10, 10, -30, 5 -> 10, 20, -10, -5 (8-bit wrapping sums).
|
||||||
|
auto r = load(xi(false, 1, 1, 2, 12, {10, 10, -30, 5}));
|
||||||
|
CHECK(r.has_value());
|
||||||
|
if (!r) return;
|
||||||
|
CHECK(r->sample.sampleRate == 8363 && r->rootNote == 48);
|
||||||
|
CHECK(r->sample.data.size() == 4);
|
||||||
|
CHECK(r->sample.data[0] == 10 / 128.f && r->sample.data[1] == 20 / 128.f);
|
||||||
|
CHECK(r->sample.data[2] == -10 / 128.f && r->sample.data[3] == -5 / 128.f);
|
||||||
|
CHECK(r->sample.loopStart == 1 && r->sample.loopEnd == 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
void xi16BitAndLoopChecks() {
|
||||||
|
// 16-bit deltas wrap mod 65536: 30000 + 10000 -> -25536. Loop bytes halve.
|
||||||
|
auto r = load(xi(true, 2, 2, 4, -3, {30000, 10000, -40000 & 0xFFFF}));
|
||||||
|
CHECK(r.has_value());
|
||||||
|
if (!r) return;
|
||||||
|
CHECK(r->rootNote == 63);
|
||||||
|
CHECK(r->sample.data.size() == 3);
|
||||||
|
CHECK(r->sample.data[0] == 30000 / 32768.f);
|
||||||
|
CHECK(r->sample.data[1] == -25536 / 32768.f);
|
||||||
|
CHECK(r->sample.loopStart == 1 && r->sample.loopEnd == 3);
|
||||||
|
// No loop type, or a loop running past the data, means no loop.
|
||||||
|
auto r2 = load(xi(false, 0, 0, 2, 0, {1, 2, 3}));
|
||||||
|
CHECK(r2 && r2->sample.loopStart == -1);
|
||||||
|
auto r3 = load(xi(false, 1, 2, 5, 0, {1, 2, 3}));
|
||||||
|
CHECK(r3 && r3->sample.loopStart == -1);
|
||||||
|
// A loop length that wraps Int is rejected, not read.
|
||||||
|
auto r4 = load(xi(false, 1, 0x7FFFFFF0, 0x7FFFFFF0, 0, {1, 2, 3}));
|
||||||
|
CHECK(r4 && r4->sample.loopStart == -1);
|
||||||
|
// Header promising more samples than the file holds: data start past the end.
|
||||||
|
Bytes many = xi(false, 0, 0, 0, 0, {1, 2});
|
||||||
|
many[296] = 0xFF;
|
||||||
|
CHECK(!load(many));
|
||||||
|
// Truncated XI files of every length: no crash.
|
||||||
|
Bytes full = xi(true, 1, 0, 2, 0, {1, 2, 3, 4});
|
||||||
|
for (size_t n = 0; n <= full.size(); ++n) { Bytes cut(full.begin(), full.begin() + (long)n); (void)load(cut); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------- WAV
|
||||||
|
|
||||||
|
Bytes wavHeader(int format, int channels, int rate, int bits, int32_t dataSize) {
|
||||||
|
Bytes b;
|
||||||
|
w(b, "RIFF"); le32(b, 36 + dataSize); w(b, "WAVE");
|
||||||
|
w(b, "fmt "); le32(b, 16); le16(b, format); le16(b, channels); le32(b, rate);
|
||||||
|
le32(b, rate * channels * bits / 8); le16(b, channels * bits / 8); le16(b, bits);
|
||||||
|
w(b, "data"); le32(b, dataSize);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
void wavRoundTrip() {
|
||||||
|
Sample s({0.f, 0.5f, -0.5f, 1.f, -1.f, 2.f, -2.f, 0.25f}, 22050);
|
||||||
|
Bytes b = SampleStore::encodeWav(s);
|
||||||
|
CHECK(b.size() == 44 + 16);
|
||||||
|
CHECK(std::memcmp(b.data(), "RIFF", 4) == 0 && std::memcmp(b.data() + 8, "WAVEfmt ", 8) == 0);
|
||||||
|
CHECK(b[4] == 36 + 16 && b[24] == (22050 & 0xFF) && b[34] == 16);
|
||||||
|
CHECK(b[44 + 2] == (16383 & 0xFF) && b[44 + 3] == (16383 >> 8)); // 0.5 -> 16383 (truncated)
|
||||||
|
auto d = SampleStore::decodeWav(b.data(), b.size());
|
||||||
|
CHECK(d.has_value());
|
||||||
|
if (!d) return;
|
||||||
|
CHECK(d->sampleRate == 22050 && d->data.size() == 8);
|
||||||
|
CHECK(d->loopStart == -1 && d->loopEnd == -1);
|
||||||
|
for (size_t i = 0; i < 8; ++i) {
|
||||||
|
float want = std::fmax(-1.f, std::fmin(1.f, s.data[i]));
|
||||||
|
CHECK(std::fabs(d->data[i] - want) <= 1.f / 32767.f);
|
||||||
|
}
|
||||||
|
CHECK(d->data[3] == 32767 / 32768.f && d->data[4] == -32767 / 32768.f);
|
||||||
|
}
|
||||||
|
|
||||||
|
void wavFormats() {
|
||||||
|
{ // 8-bit unsigned, stereo -> mono average
|
||||||
|
Bytes b = wavHeader(1, 2, 8000, 8, 4);
|
||||||
|
b.push_back(255); b.push_back(128); b.push_back(0); b.push_back(64);
|
||||||
|
auto d = SampleStore::decodeWav(b.data(), b.size());
|
||||||
|
CHECK(d && d->data.size() == 2 && d->sampleRate == 8000);
|
||||||
|
if (d) { CHECK(d->data[0] == (127 / 128.f + 0.f) / 2); CHECK(d->data[1] == (-1.f + -64 / 128.f) / 2); }
|
||||||
|
}
|
||||||
|
{ // 24-bit signed
|
||||||
|
Bytes b = wavHeader(1, 1, 48000, 24, 6);
|
||||||
|
b.push_back(0x00); b.push_back(0x00); b.push_back(0x40); // 0x400000
|
||||||
|
b.push_back(0xFF); b.push_back(0xFF); b.push_back(0xFF); // -1
|
||||||
|
auto d = SampleStore::decodeWav(b.data(), b.size());
|
||||||
|
CHECK(d && d->data.size() == 2);
|
||||||
|
if (d) { CHECK(d->data[0] == 0.5f); CHECK(d->data[1] == -1 / 8388608.f); }
|
||||||
|
}
|
||||||
|
{ // 32-bit float and 32-bit int
|
||||||
|
Bytes f = wavHeader(3, 1, 44100, 32, 4);
|
||||||
|
float v = -0.75f; uint32_t u; std::memcpy(&u, &v, 4); le32(f, (int32_t)u);
|
||||||
|
auto d = SampleStore::decodeWav(f.data(), f.size());
|
||||||
|
CHECK(d && d->data.size() == 1 && d->data[0] == -0.75f);
|
||||||
|
Bytes i = wavHeader(1, 1, 44100, 32, 4);
|
||||||
|
le32(i, 0x40000000);
|
||||||
|
auto e = SampleStore::decodeWav(i.data(), i.size());
|
||||||
|
CHECK(e && e->data.size() == 1 && e->data[0] == 0.5f);
|
||||||
|
}
|
||||||
|
{ // unsupported bit depth, zero bytes per sample, missing data chunk, not RIFF
|
||||||
|
Bytes b = wavHeader(1, 1, 44100, 12, 4); zeros(b, 4);
|
||||||
|
CHECK(!SampleStore::decodeWav(b.data(), b.size()));
|
||||||
|
Bytes z = wavHeader(1, 1, 44100, 4, 4); zeros(z, 4);
|
||||||
|
CHECK(!SampleStore::decodeWav(z.data(), z.size()));
|
||||||
|
Bytes n; w(n, "RIFF"); le32(n, 36); w(n, "WAVE"); w(n, "junk"); le32(n, 24); zeros(n, 24);
|
||||||
|
CHECK(!SampleStore::decodeWav(n.data(), n.size()));
|
||||||
|
Bytes x = wavHeader(1, 1, 44100, 16, 4); zeros(x, 4); x[0] = 'X';
|
||||||
|
CHECK(!SampleStore::decodeWav(x.data(), x.size()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void wavHostileHeaders() {
|
||||||
|
// An over-reported data length is clamped to the bytes present.
|
||||||
|
Bytes b = wavHeader(1, 1, 44100, 16, 1000);
|
||||||
|
le16(b, 1000); le16(b, 2000);
|
||||||
|
auto d = SampleStore::decodeWav(b.data(), b.size());
|
||||||
|
CHECK(d && d->data.size() == 2);
|
||||||
|
// A negative chunk size stops the walk (data never found -> null).
|
||||||
|
Bytes neg; w(neg, "RIFF"); le32(neg, 0); w(neg, "WAVE"); w(neg, "junk"); le32(neg, -4); zeros(neg, 40);
|
||||||
|
CHECK(!SampleStore::decodeWav(neg.data(), neg.size()));
|
||||||
|
// An odd chunk ending exactly at the file end: the pad-byte seek is past the
|
||||||
|
// limit, which throws in Kotlin -> null.
|
||||||
|
Bytes odd = wavHeader(1, 1, 44100, 16, 3);
|
||||||
|
odd.push_back(1); odd.push_back(2); odd.push_back(3);
|
||||||
|
CHECK(!SampleStore::decodeWav(odd.data(), odd.size()));
|
||||||
|
// An fmt chunk cut short by the end of the file -> null.
|
||||||
|
Bytes fmt; w(fmt, "RIFF"); le32(fmt, 0); w(fmt, "WAVE"); zeros(fmt, 24); w(fmt, "fmt "); le32(fmt, 16); zeros(fmt, 8);
|
||||||
|
CHECK(!SampleStore::decodeWav(fmt.data(), fmt.size()));
|
||||||
|
// Truncations of a valid file: never crash.
|
||||||
|
Bytes full = SampleStore::encodeWav(Sample({0.1f, 0.2f, 0.3f}, 44100));
|
||||||
|
for (size_t n = 0; n <= full.size(); ++n) (void)SampleStore::decodeWav(full.data(), n);
|
||||||
|
// load() accepts a plain WAV with root 60.
|
||||||
|
auto l = load(full);
|
||||||
|
CHECK(l && l->rootNote == 60 && l->sample.data.size() == 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- SampleStore
|
||||||
|
|
||||||
|
void storeGetPutRemove() {
|
||||||
|
SampleStore st;
|
||||||
|
CHECK(st.get("a") == nullptr && st.get("") == nullptr && st.get(nullptr) == nullptr);
|
||||||
|
const Sample *a = st.put("a", Sample({1.f, 2.f}, 44100));
|
||||||
|
st.put("c", Sample({3.f}, 48000));
|
||||||
|
st.put("b", Sample({4.f}, 48000));
|
||||||
|
CHECK(st.get("a") == a && st.get("b") && st.get("c") && !st.get("d"));
|
||||||
|
CHECK(st.get("b")->data[0] == 4.f);
|
||||||
|
st.put("", Sample({5.f}, 1)); // Kotlin stores it, but get("") is always null
|
||||||
|
CHECK(st.get("") == nullptr);
|
||||||
|
const Sample *a2 = st.put("a", Sample({9.f}, 1));
|
||||||
|
CHECK(st.get("a") == a2 && a2 != a);
|
||||||
|
st.remove("b");
|
||||||
|
CHECK(!st.get("b") && st.get("c"));
|
||||||
|
st.remove("nope");
|
||||||
|
st.remove("");
|
||||||
|
}
|
||||||
|
|
||||||
|
void storeReclaimsOnlyAfterQuiescentAndUnpin() {
|
||||||
|
SampleStore st;
|
||||||
|
st.put("x", Sample(std::vector<float>(1000, 0.5f), 48000, 10, 900));
|
||||||
|
st.quiescent(); st.collect();
|
||||||
|
CHECK(st.retiredCount() == 0);
|
||||||
|
|
||||||
|
// A voice is playing "x" when the UI removes it.
|
||||||
|
SampleVoice v(48000);
|
||||||
|
const Sample *x = st.get("x");
|
||||||
|
CHECK(x != nullptr);
|
||||||
|
v.noteOn(*x, 60, 100, 60, 0.f, 1.f, 1.f, 0.002f, 0.f, 1.f, 0.02f, true, 5.f);
|
||||||
|
CHECK(x->users.load() == 1);
|
||||||
|
st.remove("x");
|
||||||
|
CHECK(!st.get("x"));
|
||||||
|
st.collect();
|
||||||
|
CHECK(st.retiredCount() == 2); // old snapshot + the sample: no quiescent yet
|
||||||
|
st.quiescent(); st.collect();
|
||||||
|
CHECK(st.retiredCount() == 1); // snapshot freed, the sample is still pinned
|
||||||
|
float sum = 0;
|
||||||
|
for (int i = 0; i < 2000; ++i) sum += v.render(); // still plays it (looping)
|
||||||
|
CHECK(v.isActive() && sum > 0.f);
|
||||||
|
v.noteOff();
|
||||||
|
for (int i = 0; i < 48000 && v.isActive(); ++i) v.render();
|
||||||
|
CHECK(!v.isActive());
|
||||||
|
CHECK(x->users.load() == 0);
|
||||||
|
st.collect();
|
||||||
|
CHECK(st.retiredCount() == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void voiceOneShotEndsAndUnpins() {
|
||||||
|
Sample s(std::vector<float>(480, 0.25f), 48000);
|
||||||
|
SampleVoice v(48000);
|
||||||
|
v.noteOn(s, 40, 127, 40, 0.f, 1.f, 1.f);
|
||||||
|
CHECK(v.isGated() && s.users.load() == 1);
|
||||||
|
int n = 0;
|
||||||
|
while (v.isActive() && n < 10000) { v.render(); ++n; }
|
||||||
|
CHECK(!v.isActive() && n <= 480 && s.users.load() == 0);
|
||||||
|
// An empty sample plays nothing (Kotlin would throw in coerceIn).
|
||||||
|
Sample empty;
|
||||||
|
v.noteOn(empty, 40, 127, 40, 0.f, 1.f, 1.f);
|
||||||
|
CHECK(!v.isActive() && empty.users.load() == 0);
|
||||||
|
// kill() lets go too.
|
||||||
|
v.noteOn(s, 40, 127, 40, 0.f, 1.f, 1.f);
|
||||||
|
v.kill();
|
||||||
|
CHECK(!v.isActive() && s.users.load() == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void voiceSampleFromParams() {
|
||||||
|
SampleStore st;
|
||||||
|
st.put("kick", Sample(std::vector<float>(100, 0.1f), 44100, -1, -1));
|
||||||
|
Params p;
|
||||||
|
p.set("pad3", "kick"); p.set("pad3S", 0.25f); p.set("pad3V", 0.5f);
|
||||||
|
VoiceSample vs;
|
||||||
|
CHECK(voiceSample("SAMPLER", p, st, SamplerPads::noteFor(3), vs));
|
||||||
|
CHECK(vs.sample == st.get("kick") && vs.root == 39 && vs.sliceStart == 0.25f && vs.sliceEnd == 1.f && vs.volume == 0.5f);
|
||||||
|
CHECK(vs.attack == 0.002f && vs.release == 0.02f && !vs.loop);
|
||||||
|
CHECK(!voiceSample("SAMPLER", p, st, 35, vs)); // below pad 0
|
||||||
|
CHECK(!voiceSample("SAMPLER", p, st, 52, vs)); // pad 16
|
||||||
|
CHECK(!voiceSample("SAMPLER", p, st, 38, vs)); // pad 2 has no sample
|
||||||
|
CHECK(std::strcmp(SamplerPads::sliceEndKey(15).s, "pad15E") == 0);
|
||||||
|
Params f;
|
||||||
|
f.set("sfSample", "kick"); f.set("sfRoot", 64.7f); f.set("loop", "On");
|
||||||
|
CHECK(voiceSample("SOUNDFONT", f, st, 70, vs));
|
||||||
|
CHECK(vs.root == 64 && vs.volume == 0.8f && vs.attack == 0.005f && vs.decay == 0.10f);
|
||||||
|
CHECK(vs.sustain == 1.f && vs.release == 0.20f && vs.loop && vs.crossfadeMs == 0.f);
|
||||||
|
CHECK(!voiceSample("NES_SYNTH", f, st, 70, vs));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
alarm(30); // the Kotlin tests' timeouts: a hang is a failure (SIGALRM ends the run)
|
||||||
|
run("negativeChunkSizeDoesNotHang", negativeChunkSizeDoesNotHang);
|
||||||
|
run("negativeSubChunkSizeDoesNotHang", negativeSubChunkSizeDoesNotHang);
|
||||||
|
run("zeroSizeChunkDoesNotHang", zeroSizeChunkDoesNotHang);
|
||||||
|
run("hugeSampleRegionIsCapped", hugeSampleRegionIsCapped);
|
||||||
|
run("truncatedInputIsRejected", truncatedInputIsRejected);
|
||||||
|
run("sf2FirstSampleRootAndLoop", sf2FirstSampleRootAndLoop);
|
||||||
|
run("sf2RegionLoopAndFallbacks", sf2RegionLoopAndFallbacks);
|
||||||
|
run("xi8BitDeltaLoopAndRoot", xi8BitDeltaLoopAndRoot);
|
||||||
|
run("xi16BitAndLoopChecks", xi16BitAndLoopChecks);
|
||||||
|
run("wavRoundTrip", wavRoundTrip);
|
||||||
|
run("wavFormats", wavFormats);
|
||||||
|
run("wavHostileHeaders", wavHostileHeaders);
|
||||||
|
run("storeGetPutRemove", storeGetPutRemove);
|
||||||
|
run("storeReclaimsOnlyAfterQuiescentAndUnpin", storeReclaimsOnlyAfterQuiescentAndUnpin);
|
||||||
|
run("voiceOneShotEndsAndUnpins", voiceOneShotEndsAndUnpins);
|
||||||
|
run("voiceSampleFromParams", voiceSampleFromParams);
|
||||||
|
std::printf("\n%s (%d failed)\n", failures ? "FAIL" : "PASS", failures);
|
||||||
|
return failures ? 1 : 0;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user