iOS 0.5.0: hand-built editors (Tape Delay, Tape Engine, Mix Tightener, Granular scope, Wavetable tables, Grain Cloud source)
Effect visualisation through the C++ effect, engine and AU; custom wavetables and grain sources load and persist with the song; the app's slot editor hosts the file picker for bespoke views. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
3b035d6a7d
commit
435305e42a
@@ -0,0 +1,44 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
|
||||
/// The Wavetable's tables and the Grain Cloud's sources for a toolbox slot of the
|
||||
/// song, and loading your own (SizzleSession+Sources).
|
||||
extension SlotDataSource: SampleLengthSource {
|
||||
func wavetableFrames(osc: Int) -> (frames: Int, size: Int, data: [Float])? {
|
||||
var frames = 0, size = 0
|
||||
guard let d = session.wavetable(ofSlot: slot, osc: osc, frames: &frames, size: &size) else { return nil }
|
||||
return (frames, size, WavetableBespoke.floats(d))
|
||||
}
|
||||
|
||||
func samplePeaks(key: String, buckets: Int) -> [Float]? {
|
||||
session.samplePeaks(ofSlot: slot, key: key, buckets: buckets).map(WavetableBespoke.floats)
|
||||
}
|
||||
|
||||
func sampleSeconds(key: String) -> Double? {
|
||||
let s = session.sampleSeconds(ofSlot: slot, key: key)
|
||||
return s > 0 ? s : nil
|
||||
}
|
||||
|
||||
/// "wavetable" (LOAD TABLE) or "grainSource" (the Grain Cloud's LOAD WAV): the
|
||||
/// picked file (security-scoped, at most 64 MB) into this slot.
|
||||
func loadFile(_ url: URL, kind: String) -> String? {
|
||||
guard kind == "wavetable" || kind == "grainSource" else { return "Not available here yet." }
|
||||
let scoped = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
let maxBytes = 64 * 1024 * 1024
|
||||
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0
|
||||
guard size <= maxBytes, let data = try? Data(contentsOf: url), data.count <= maxBytes else {
|
||||
return "Couldn't read the file, or it's larger than 64 MB."
|
||||
}
|
||||
let name = url.deletingPathExtension().lastPathComponent
|
||||
do {
|
||||
if kind == "wavetable" { try session.loadWavetableData(data, name: name, intoSlot: slot) }
|
||||
else { try session.loadGrainSourceData(data, name: name, intoSlot: slot) }
|
||||
return nil
|
||||
} catch {
|
||||
return error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
|
||||
/// The live effect scope of a song slot (the Granular Glitch's), straight from the
|
||||
/// engine's channel chains: nil until the slot sits on a mixer channel's FX.
|
||||
extension SlotDataSource {
|
||||
func effectScope(capacity: Int) -> (samples: [Float], playhead: Float)? {
|
||||
guard capacity > 0 else { return nil }
|
||||
var buf = [Float](repeating: 0, count: capacity)
|
||||
let n = buf.withUnsafeMutableBufferPointer { p in
|
||||
session.copyEffectScope(ofSlot: slot, into: p.baseAddress!, capacity: p.count)
|
||||
}
|
||||
guard n >= 0 else { return nil }
|
||||
return (Array(buf.prefix(n)), session.effectPlayhead(ofSlot: slot))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#import "ObjC/SPKTry.h"
|
||||
#import "SizzleHost.h"
|
||||
#import "SizzleFXViewController.h"
|
||||
#import "SizzleDeviceAU+Sources.h"
|
||||
#import "SizzleSession.h"
|
||||
#import "SizzleSession+Tracker.h"
|
||||
#import "SizzleSession+Mix.h"
|
||||
|
||||
@@ -25,10 +25,11 @@ struct SlotEditor: View {
|
||||
/// the presentation binding before calling the completion handler.
|
||||
@State private var importing: ImportKind?
|
||||
@State private var pickerShown = false
|
||||
@State private var deviceCallback: ((URL) -> Void)?
|
||||
@State private var importError: String?
|
||||
|
||||
enum ImportKind: Identifiable {
|
||||
case preset, padSample, soundFont
|
||||
case preset, padSample, soundFont, device // device: a bespoke view's own load (deviceFilePicker)
|
||||
var id: Self { self }
|
||||
}
|
||||
|
||||
@@ -65,7 +66,8 @@ struct SlotEditor: View {
|
||||
}
|
||||
.background(Theme.background.opacity(0.96))
|
||||
.fileImporter(isPresented: $pickerShown, allowedContentTypes: importTypes, allowsMultipleSelection: false) { result in
|
||||
if case .success(let urls) = result, let url = urls.first, let kind = importing { load(url, kind) }
|
||||
guard case .success(let urls) = result, let url = urls.first, let kind = importing else { return }
|
||||
if kind == .device { deviceCallback?(url) } else { load(url, kind) }
|
||||
}
|
||||
.alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }),
|
||||
actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") })
|
||||
@@ -97,6 +99,11 @@ struct SlotEditor: View {
|
||||
// The card editor brings its own padding and header row; with no name and
|
||||
// no preset menu (the bar above has them) the row is empty, so pull it up.
|
||||
DeviceEditor(model: model, showsHeader: false).padding(.horizontal, -10)
|
||||
.environment(\.deviceFilePicker) { done in
|
||||
deviceCallback = done
|
||||
importing = .device
|
||||
pickerShown = true
|
||||
}
|
||||
.frame(minHeight: 0, maxHeight: .infinity, alignment: .top).clipped()
|
||||
if type == "LFO" { LfoTargetPicker(lfo: slot) }
|
||||
}
|
||||
@@ -108,7 +115,7 @@ struct SlotEditor: View {
|
||||
private var importTypes: [UTType] {
|
||||
switch importing {
|
||||
case .padSample: return [.audio, .wav]
|
||||
case .preset, .soundFont, .none: return [.item]
|
||||
case .preset, .soundFont, .device, .none: return [.item]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,6 +151,8 @@ struct SlotEditor: View {
|
||||
if (try? session.loadSampleData(data, name: name, intoSlot: slot, pad: 0)) == nil {
|
||||
importError = "Couldn't load this instrument. Supported formats are .sf2, .xi and uncompressed .wav."
|
||||
}
|
||||
case .device:
|
||||
break // handed to the bespoke view (deviceCallback)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +184,7 @@ struct SlotEditor: View {
|
||||
},
|
||||
applyPreset: { name in _ = session.loadPreset(name, intoSlot: slot) },
|
||||
reread: read)
|
||||
.withData(SlotDataSource(session: session, slot: slot))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,38 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// API for the device editors' Sources views beyond SizzleSession.h.
|
||||
/// The Wavetable's and the Grain Cloud's own sounds (AppViewModel.loadWavetable /
|
||||
/// loadGrainSample) and what their editors draw of them.
|
||||
///
|
||||
/// Custom wavetables: the WAV is kept like any other sample (sample store and
|
||||
/// Documents/samples/<id>.wav, the slot's `sfSample`), and its table is built off
|
||||
/// the audio thread: right after a load, and whenever the song changes and a
|
||||
/// Wavetable slot plays a Custom table that isn't built yet (a loaded song, a new
|
||||
/// frame length). The audio thread only ever finds a built table or none (silent).
|
||||
@interface SizzleSession (Sources)
|
||||
|
||||
/// A wavetable WAV (Serum's, WaveEdit's or power-of-two frames) becomes Wavetable
|
||||
/// [slot]'s Custom table: `sfSample` = the stored sample, `wtframe` = the detected
|
||||
/// frame length (or Auto), `o1table` = Custom. The table is built in the background.
|
||||
- (BOOL)loadWavetableData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot error:(NSError **)error;
|
||||
|
||||
/// A WAV (or an SF2/XI's sample) becomes Grain Cloud [slot]'s own source
|
||||
/// (`sfSample`, `source` = Custom).
|
||||
- (BOOL)loadGrainSourceData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot error:(NSError **)error;
|
||||
|
||||
/// Oscillator [osc]'s table of Wavetable [slot], level 0: [frames] x [size] floats.
|
||||
/// Nil while it isn't built (a Custom table is then built in the background; ask again).
|
||||
- (nullable NSData *)wavetableOfSlot:(NSInteger)slot osc:(NSInteger)osc
|
||||
frames:(NSInteger *)frames size:(NSInteger *)size;
|
||||
|
||||
/// Peak envelope (|x| max per bucket, 0..1, [buckets] floats) of the sample [slot]'s
|
||||
/// setting [key] names: a Grain Cloud's `source` (a built-in source, or with Custom
|
||||
/// its own sample), otherwise a sample id (`sfSample`, `padN`). Nil while it has none.
|
||||
- (nullable NSData *)samplePeaksOfSlot:(NSInteger)slot key:(NSString *)key buckets:(NSInteger)buckets;
|
||||
|
||||
/// Length in seconds of that same sample, or 0.
|
||||
- (double)sampleSecondsOfSlot:(NSInteger)slot key:(NSString *)key;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
@@ -4,7 +4,279 @@
|
||||
#import "SizzleSession+Sources.h"
|
||||
#import "SizzleSession+Internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#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/<id>.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<sampler::SampleStore *> gStore{nullptr};
|
||||
|
||||
/// WaveTables::SampleSource: a copy of sample [id]'s data from the store (pinned while copied).
|
||||
bool storeSource(const char *id, std::vector<float> &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<std::pair<std::string, int>> 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<std::pair<std::string, NSURL *>> 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<uint8_t> 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> 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> 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
|
||||
|
||||
@@ -7,6 +7,15 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// API for the device editors' Viz views beyond SizzleSession.h.
|
||||
@interface SizzleSession (Viz)
|
||||
|
||||
/// Toolbox [slot]'s live effect scope (AudioEngine.effectScope): copies up to
|
||||
/// [capacity] samples, oldest to newest, into [out] and returns the count, or -1
|
||||
/// while the slot isn't a scope effect on a mixer channel (nothing to draw).
|
||||
/// Lock-free (doesn't take the song lock), so it can be polled at display rate.
|
||||
- (NSInteger)copyEffectScopeOfSlot:(NSInteger)slot into:(float *)out capacity:(NSInteger)capacity;
|
||||
/// Its read head within the scope window, 0 (oldest) to 1 (newest), or -1.
|
||||
- (float)effectPlayheadOfSlot:(NSInteger)slot;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
@@ -3,8 +3,35 @@
|
||||
|
||||
#import "SizzleSession+Viz.h"
|
||||
#import "SizzleSession+Internal.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
static char kVizEngineKey;
|
||||
|
||||
@implementation SizzleSession (Viz)
|
||||
|
||||
/// The engine, without the song lock: polling under it at display rate would make
|
||||
/// the audio thread (which only try-locks) drop a block now and then. The engine is
|
||||
/// created once with the session and lives as long as it, so its address is fetched
|
||||
/// once under the lock and kept; Engine::effectScope / effectPlayhead are lock-free.
|
||||
- (const engine::Engine *)vizEngine {
|
||||
NSValue *v = objc_getAssociatedObject(self, &kVizEngineKey);
|
||||
if (!v) {
|
||||
__block const engine::Engine *e = nullptr;
|
||||
[self read:^(const model::Project &, const engine::Engine &eng) { e = ŋ }];
|
||||
v = [NSValue valueWithPointer:e];
|
||||
objc_setAssociatedObject(self, &kVizEngineKey, v, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
return (const engine::Engine *)v.pointerValue;
|
||||
}
|
||||
|
||||
- (NSInteger)copyEffectScopeOfSlot:(NSInteger)slot into:(float *)out capacity:(NSInteger)capacity {
|
||||
return self.vizEngine->effectScope((int)slot, out, (int)capacity);
|
||||
}
|
||||
|
||||
- (float)effectPlayheadOfSlot:(NSInteger)slot {
|
||||
return self.vizEngine->effectPlayhead((int)slot);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
Reference in New Issue
Block a user