// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later #import "SizzleSession+Sources.h" #import "SizzleSession+Internal.h" #include #include #include #include #include #include #include #include "echofield/EchofieldDefs.hpp" #include "echofield/GrainSources.hpp" #include "sampler/SoundFontLoader.hpp" #include "wavetable/WaveDefs.hpp" #include "wavetable/WaveTables.hpp" using namespace sizzle; using wavetable::WaveTable; namespace WaveTables = wavetable::WaveTables; namespace WaveDefs = wavetable::WaveDefs; // Defined in SizzleSession.mm (Documents/samples/.wav). @interface SizzleSession (SourcesPrivate) - (NSURL *)sampleURL:(const std::string &)id; @end namespace { /// The store WaveTables' SampleSource reads (the session's; it lives for the whole app). std::atomic gStore{nullptr}; /// WaveTables::SampleSource: a copy of sample [id]'s data from the store (pinned while copied). bool storeSource(const char *id, std::vector &out) { sampler::SampleStore *store = gStore.load(); const Sample *s = store ? store->get(id) : nullptr; if (!s) return false; sampler::SampleStore::pin(s); out = s->data; sampler::SampleStore::unpin(s); return true; } /// Where custom tables are built (one at a time, never the audio thread). dispatch_queue_t builderQueue() { static dispatch_queue_t q; static dispatch_once_t once; dispatch_once(&once, ^{ q = dispatch_queue_create("sizzle.wavetables", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0)); }); return q; } NSError *sourcesError(NSString *msg) { return [NSError errorWithDomain:@"Sizzle" code:1 userInfo:@{NSLocalizedDescriptionKey: msg}]; } /// WaveVoice's frame length: wtframe's choice ("Auto" or unknown -> 0). int frameLenOf(const model::ToolboxSlot &slot) { const char *v = slot.s("wtframe", WaveDefs::FRAME_SIZES[0]); for (int i = 1; i < WaveDefs::FRAME_SIZE_COUNT; ++i) if (!std::strcmp(v, WaveDefs::FRAME_SIZES[i])) return std::atoi(WaveDefs::FRAME_SIZES[i]); return 0; } bool playsCustom(const model::ToolboxSlot &slot) { return slot.type == "WAVETABLE" && *slot.s(WaveDefs::SAMPLE_KEY, "") && (!std::strcmp(slot.s("o1table", ""), WaveTables::CUSTOM) || !std::strcmp(slot.s("o2table", ""), WaveTables::CUSTOM)); } /// |x| max per bucket, 0..1, the buckets spread evenly over the sample. NSData *peaksOf(const float *x, size_t n, NSInteger buckets) { if (!x || n == 0 || buckets <= 0) return nil; NSMutableData *d = [NSMutableData dataWithLength:(NSUInteger)buckets * sizeof(float)]; float *out = (float *)d.mutableBytes; for (NSInteger b = 0; b < buckets; ++b) { size_t a = n * (size_t)b / (size_t)buckets; size_t e = std::max(a + 1, n * (size_t)(b + 1) / (size_t)buckets); float m = 0.f; for (size_t i = a; i < e && i < n; ++i) m = std::max(m, std::fabs(x[i])); out[b] = std::min(m, 1.f); } return d; } /// A sample id from the file's name (ASCII, short: WaveTables keys compare 63 bytes). std::string newSampleId(NSString *name) { std::string base; for (const char *c = name.UTF8String ?: ""; *c && base.size() < 16; ++c) if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z') || (*c >= '0' && *c <= '9') || *c == '-' || *c == '_') base += *c; if (base.empty()) base = "source"; return base + "#" + NSUUID.UUID.UUIDString.UTF8String; } } // namespace @implementation SizzleSession (Sources) /// Install the custom-table source and build what songs ask for as they change /// (a loaded song, a new frame length). Runs at image load; the session itself /// arrives with its first change notification (posted from init when it loads the /// autosave), so nothing here creates it. + (void)load { WaveTables::setSampleSource(&storeSource); @autoreleasepool { [NSNotificationCenter.defaultCenter addObserverForName:SizzleSessionDidChange object:nil queue:nil usingBlock:^(NSNotification *note) { SizzleSession *s = note.object; if (![s isKindOfClass:SizzleSession.class]) return; dispatch_async(dispatch_get_main_queue(), ^{ [s src_scheduleTableScan]; }); }]; } } /// Coalesce change notifications (knob drags post many) into one scan. - (void)src_scheduleTableScan { static BOOL pending = NO; if (pending) return; pending = YES; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ pending = NO; [self src_buildMissingTables]; }); } /// Every Custom table the song plays that isn't built yet: queue it (WaveTables' /// request), make sure its sample is in the store, then build on the builder queue. - (void)src_buildMissingTables { gStore.store(&[self sampleStore]); __block std::vector> wants; [self read:^(const model::Project &p, const engine::Engine &) { for (auto &slot : p.toolbox) if (playsCustom(slot)) wants.emplace_back(slot.s(WaveDefs::SAMPLE_KEY, ""), frameLenOf(slot)); }]; std::vector> missing; for (auto &w : wants) if (!WaveTables::forSample(w.first.c_str(), w.second)) missing.emplace_back(w.first, [self sampleURL:w.first]); if (missing.empty()) return; sampler::SampleStore *store = &[self sampleStore]; dispatch_async(builderQueue(), ^{ for (auto &m : missing) { if (store->get(m.first.c_str())) continue; NSData *d = [NSData dataWithContentsOfURL:m.second]; if (!d) continue; if (auto s = sampler::SampleStore::decodeWav((const uint8_t *)d.bytes, d.length)) store->put(m.first, std::move(*s)); } WaveTables::buildRequested(); }); } /// Keep [sample] as one of the song's samples (Documents/samples + the store); its id. - (std::string)src_keepSample:(Sample &)sample name:(NSString *)name { std::string id = newSampleId(name); std::vector wav = sampler::SampleStore::encodeWav(sample); [[NSData dataWithBytes:wav.data() length:wav.size()] writeToURL:[self sampleURL:id] atomically:YES]; [self sampleStore].put(id, std::move(sample)); return id; } - (BOOL)loadWavetableData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot error:(NSError **)error { if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS || ![[self typeOfSlot:slot] isEqualToString:@"WAVETABLE"]) { if (error) *error = sourcesError(@"Pick a Wavetable slot."); return NO; } const uint8_t *bytes = (const uint8_t *)data.bytes; std::optional sample = sampler::SampleStore::decodeWav(bytes, data.length); if (!sample || sample->data.size() < 64) { if (error) *error = sourcesError(@"Couldn't load this wavetable. Use an uncompressed .wav (Serum, WaveEdit, or frames of 256–2048 samples)."); return NO; } int detected = WaveTables::detectFrameLength(bytes, data.length, (int)sample->data.size()); std::string label = WaveDefs::FRAME_SIZES[0]; for (int i = 1; i < WaveDefs::FRAME_SIZE_COUNT; ++i) if (std::to_string(detected) == WaveDefs::FRAME_SIZES[i]) label = WaveDefs::FRAME_SIZES[i]; int frameLen = label == WaveDefs::FRAME_SIZES[0] ? 0 : detected; gStore.store(&[self sampleStore]); std::string id = [self src_keepSample:*sample name:name]; [self edit:^(model::Project &p, engine::Engine &) { model::ToolboxSlot &s = p.toolbox[(size_t)slot]; s.set(WaveDefs::SAMPLE_KEY, id.c_str()); s.set("wtframe", label.c_str()); s.set("o1table", WaveTables::CUSTOM); }]; // Built off the audio thread; until then the oscillator is silent (and asks once). dispatch_async(builderQueue(), ^{ if (!WaveTables::forSample(id.c_str(), frameLen)) WaveTables::buildRequested(); }); return YES; } - (BOOL)loadGrainSourceData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot error:(NSError **)error { if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS || ![[self typeOfSlot:slot] isEqualToString:@"GRAIN_CLOUD"]) { if (error) *error = sourcesError(@"Pick a Grain Cloud slot."); return NO; } const uint8_t *bytes = (const uint8_t *)data.bytes; std::optional sample = sampler::SampleStore::decodeWav(bytes, data.length); if (!sample) { if (auto l = sampler::SoundFontLoader::load(bytes, data.length)) sample = std::move(l->sample); } if (!sample) { if (error) *error = sourcesError(@"Couldn't load this sound. Supported formats are uncompressed .wav, .sf2 and .xi."); return NO; } std::string id = [self src_keepSample:*sample name:name]; [self edit:^(model::Project &p, engine::Engine &) { model::ToolboxSlot &s = p.toolbox[(size_t)slot]; s.set(echofield::SAMPLE_KEY, id.c_str()); s.set("source", echofield::CUSTOM); }]; return YES; } - (nullable NSData *)wavetableOfSlot:(NSInteger)slot osc:(NSInteger)osc frames:(NSInteger *)frames size:(NSInteger *)size { if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return nil; __block std::string table, id; __block int frameLen = 0; std::string key = "o" + std::to_string(osc) + "table"; [self read:^(const model::Project &p, const engine::Engine &) { const model::ToolboxSlot &s = p.toolbox[(size_t)slot]; table = s.s(key.c_str(), WaveDefs::TABLES[0]); id = s.s(WaveDefs::SAMPLE_KEY, ""); frameLen = frameLenOf(s); }]; const WaveTable *t; if (table == WaveTables::CUSTOM) { t = WaveTables::forSample(id.c_str(), frameLen); if (!t && !id.empty()) [self src_scheduleTableScan]; } else { t = WaveTables::factory(table.c_str()); } if (!t) return nil; int n = t->size(0); if (frames) *frames = t->frames; if (size) *size = n; return [NSData dataWithBytes:t->data(0) length:(NSUInteger)t->frames * (NSUInteger)n * sizeof(float)]; } /// Run [body] on the sample [slot]'s [key] names (pinned while it runs); NO if none. - (BOOL)src_withSampleOfSlot:(NSInteger)slot key:(NSString *)key body:(void (^)(const Sample &s))body { if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return NO; __block std::string value, id, type; std::string k = key.UTF8String ?: ""; [self read:^(const model::Project &p, const engine::Engine &) { const model::ToolboxSlot &s = p.toolbox[(size_t)slot]; type = s.type; value = s.s(k.c_str(), k == "source" ? echofield::SOURCES[0] : ""); id = s.s(echofield::SAMPLE_KEY, ""); }]; if (type == "GRAIN_CLOUD" && k == "source") { if (value != echofield::CUSTOM) { const Sample *g = echofield::GrainSources::get(value.c_str()); // built once, never freed if (g) body(*g); return g != nullptr; } value = id; } const Sample *s = [self sampleStore].get(value.c_str()); if (!s) return NO; sampler::SampleStore::pin(s); body(*s); sampler::SampleStore::unpin(s); return YES; } - (nullable NSData *)samplePeaksOfSlot:(NSInteger)slot key:(NSString *)key buckets:(NSInteger)buckets { __block NSData *out = nil; [self src_withSampleOfSlot:slot key:key body:^(const Sample &s) { out = peaksOf(s.data.data(), s.data.size(), buckets); }]; return out; } - (double)sampleSecondsOfSlot:(NSInteger)slot key:(NSString *)key { __block double secs = 0; [self src_withSampleOfSlot:slot key:key body:^(const Sample &s) { secs = s.sampleRate > 0 ? (double)s.data.size() / s.sampleRate : 0; }]; return secs; } @end