Files
ReactorcoremeltdownandClaude Opus 5.5 5240019b47 0.39.1 (74): preset bundles between Android and iOS, both ways
iOS couldn't import Android's Sampler preset bundle (a ZIP with the .szp and
its WAVs) and shared sample presets as bare text naming iOS sample ids.

- core/src/io/PresetBundle: import/export in Android's bundle layout
  (padNFile / sfFile), used by iOS IMPORT and SHARE
- bundle_test imports a bundle written by Android's PresetLibrary
  (IosGoldenPresetBundle); PresetBundleInteropTest imports the iOS-written
  fixture with Android's importZip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:39:33 +01:00

329 lines
15 KiB
Plaintext

// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#import "SizzleSession+Mix.h"
#import "SizzleSession+Internal.h"
#include <algorithm>
#include <cmath>
#include <set>
#include <string>
#include <vector>
#include "io/PresetBundle.hpp"
#include "io/PresetIo.hpp"
#include "sizzle/DeviceSpecs.gen.hpp"
using namespace sizzle;
/// SizzleSession.mm's own: put back into the store the samples the song refers to.
@interface SizzleSession (MixPrivate)
- (void)rehydrateSamples;
- (NSURL *)sampleURL:(const std::string &)id;
@end
namespace {
std::string padKey(NSInteger pad) { return "pad" + std::to_string(pad); }
/// PresetLibrary.sanitize: [A-Za-z0-9._ -] kept, anything else "_", blank "preset".
NSString *sanitize(NSString *name) {
NSString *t = [name stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
NSMutableString *out = [NSMutableString string];
for (NSUInteger i = 0; i < t.length; ++i) {
unichar c = [t characterAtIndex:i];
BOOL ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == ' ' || c == '-';
[out appendString:ok ? [NSString stringWithCharacters:&c length:1] : @"_"];
}
return out.length ? out : @"preset";
}
} // namespace
@implementation SizzleSession (Mix)
#pragma mark - samples
/// The sample id a slot key holds ("" when none).
- (std::string)mixSampleId:(NSInteger)slot key:(NSString *)key {
__block std::string id;
std::string k = key.UTF8String;
[self read:^(const model::Project &p, const engine::Engine &) {
if (slot >= 0 && slot < model::Project::TOOLBOX_SLOTS) id = p.toolbox[(size_t)slot].s(k.c_str(), "");
}];
return id;
}
- (const Sample *)mixSample:(NSInteger)slot key:(NSString *)key {
std::string id = [self mixSampleId:slot key:key];
return id.empty() ? nullptr : [self sampleStore].get(id.c_str());
}
- (NSInteger)sampleFramesOfSlot:(NSInteger)slot key:(NSString *)key {
const Sample *s = [self mixSample:slot key:key];
return s ? (NSInteger)s->data.size() : 0;
}
- (NSInteger)sampleRateOfSlot:(NSInteger)slot key:(NSString *)key {
const Sample *s = [self mixSample:slot key:key];
return s ? s->sampleRate : 0;
}
- (NSData *)samplePeaksOfSlot:(NSInteger)slot key:(NSString *)key buckets:(NSInteger)buckets {
const Sample *s = [self mixSample:slot key:key];
if (!s || buckets <= 0) return nil;
const std::vector<float> &data = s->data;
std::vector<float> out((size_t)buckets * 2, 0.f);
if (!data.empty()) {
size_t step = std::max<size_t>(1, data.size() / (size_t)buckets);
for (size_t b = 0; b < (size_t)buckets; ++b) {
size_t start = b * step;
if (start >= data.size()) break;
size_t end = std::min(start + step, data.size());
float mn = 1.f, mx = -1.f;
for (size_t i = start; i < end; ++i) { mn = std::min(mn, data[i]); mx = std::max(mx, data[i]); }
out[2 * b] = std::clamp(mn, -1.f, 1.f);
out[2 * b + 1] = std::clamp(mx, -1.f, 1.f);
}
}
return [NSData dataWithBytes:out.data() length:out.size() * sizeof(float)];
}
/// Store [sample] as a new sample for the pad (a fresh id, so pads sharing the old one keep it).
- (BOOL)mixReplacePad:(NSInteger)pad ofSlot:(NSInteger)slot with:(const Sample &)sample name:(NSString *)name {
std::vector<uint8_t> wav = sampler::SampleStore::encodeWav(sample);
return [self loadSampleData:[NSData dataWithBytes:wav.data() length:wav.size()] name:name intoSlot:slot pad:pad error:nil];
}
- (BOOL)trimPad:(NSInteger)pad ofSlot:(NSInteger)slot {
NSString *key = @(padKey(pad).c_str());
const Sample *s = [self mixSample:slot key:key];
if (!s) return NO;
size_t len = s->data.size();
if (len <= 1) return NO;
std::string sk = padKey(pad) + "S", ek = padKey(pad) + "E";
__block float a = 0, b = 1;
[self read:^(const model::Project &p, const engine::Engine &) {
a = std::clamp(p.toolbox[(size_t)slot].f(sk.c_str(), 0.f), 0.f, 1.f);
b = std::clamp(p.toolbox[(size_t)slot].f(ek.c_str(), 1.f), 0.f, 1.f);
}];
size_t start = std::min((size_t)(std::min(a, b) * (float)len), len - 1);
size_t end = std::clamp((size_t)(std::max(a, b) * (float)len), start + 1, len);
if (start == 0 && end == len) return NO; // the slice already spans the whole sample
Sample cut;
cut.data.assign(s->data.begin() + (long)start, s->data.begin() + (long)end);
cut.sampleRate = s->sampleRate;
if (![self mixReplacePad:pad ofSlot:slot with:cut name:@"trim"]) return NO;
[self edit:^(model::Project &p, engine::Engine &) {
p.toolbox[(size_t)slot].set(sk.c_str(), 0.f);
p.toolbox[(size_t)slot].set(ek.c_str(), 1.f);
}];
return YES;
}
- (BOOL)normalizePad:(NSInteger)pad ofSlot:(NSInteger)slot {
const Sample *s = [self mixSample:slot key:@(padKey(pad).c_str())];
if (!s || s->data.empty()) return NO;
float peak = 0;
for (float v : s->data) peak = std::max(peak, std::fabs(v));
if (peak <= 0) return NO; // silent: nothing to normalise
float gain = 1.f / peak;
if (gain >= 0.999f && gain <= 1.001f) return NO; // already at full scale
Sample out;
out.data.resize(s->data.size());
for (size_t i = 0; i < s->data.size(); ++i) out.data[i] = std::clamp(s->data[i] * gain, -1.f, 1.f);
out.sampleRate = s->sampleRate;
return [self mixReplacePad:pad ofSlot:slot with:out name:@"norm"];
}
- (void)clearPad:(NSInteger)pad ofSlot:(NSInteger)slot {
std::string k = padKey(pad), sk = k + "S", ek = k + "E";
[self edit:^(model::Project &p, engine::Engine &) {
if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return;
model::ToolboxSlot &s = p.toolbox[(size_t)slot];
Params kept; // Params has no remove: copy everything else
for (int i = 0; i < s.values.size(); ++i) {
const char *key = s.values.keyAt(i);
if (k == key || sk == key || ek == key) continue;
kept.set(key, s.values.valueAt(i));
}
s.values = kept;
++s.version;
}];
}
#pragma mark - LFO
- (void)setLfoTargetOfSlot:(NSInteger)slot target:(NSInteger)target key:(NSString *)key {
std::string k = key.UTF8String;
[self edit:^(model::Project &p, engine::Engine &) {
if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return;
model::ToolboxSlot &lfo = p.toolbox[(size_t)slot];
if (target < 0 || target >= model::Project::TOOLBOX_SLOTS) { lfo.set("target", ""); return; }
const model::ToolboxSlot &t = p.toolbox[(size_t)target];
float def = 0;
if (const DeviceSpec *d = findDevice(t.type.c_str()))
for (int i = 0; i < d->paramCount; ++i) if (k == d->params[i].key) def = d->params[i].def;
lfo.set("target", (std::to_string(target) + ":" + k).c_str());
lfo.set("center", t.f(k.c_str(), def));
}];
}
#pragma mark - preset library
- (NSURL *)mixPresetDir:(NSString *)type {
NSURL *docs = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject;
NSURL *dir = [[docs URLByAppendingPathComponent:@"presets"] URLByAppendingPathComponent:type];
[NSFileManager.defaultManager createDirectoryAtURL:dir withIntermediateDirectories:YES attributes:nil error:nil];
return dir;
}
- (NSURL *)mixPresetURL:(NSString *)type name:(NSString *)name {
return [[self mixPresetDir:type] URLByAppendingPathComponent:[sanitize(name) stringByAppendingString:@".szp"]];
}
/// PresetLibrary.seedType: write the type's factory presets once; the marker lists
/// the names already written so a preset the user deletes isn't brought back.
- (void)mixSeedType:(NSString *)type {
NSURL *marker = [[self mixPresetDir:type] URLByAppendingPathComponent:@".seeded"];
NSString *text = [NSString stringWithContentsOfURL:marker encoding:NSUTF8StringEncoding error:nil];
NSMutableSet<NSString *> *seeded = [NSMutableSet set];
for (NSString *line in [text componentsSeparatedByString:@"\n"]) {
NSString *t = [line stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
if (t.length && ![t isEqualToString:@"1"]) [seeded addObject:t];
}
BOOL changed = NO;
std::string ty = type.UTF8String;
for (int i = 0; i < gen::factoryPresetCount; ++i) {
const auto &f = gen::factoryPresets[i];
if (ty != f.type) continue;
NSString *name = @(f.name);
if ([seeded containsObject:name]) continue;
NSURL *url = [self mixPresetURL:type name:name];
if (![NSFileManager.defaultManager fileExistsAtPath:url.path]) {
model::ToolboxSlot s;
s.fill(ty);
for (int k = 0; f.values[k] && f.values[k + 1]; k += 2) s.set(f.values[k], f.values[k + 1]);
s.name = f.name;
[@(io::PresetIo::exportText(s).c_str()) writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
[seeded addObject:name];
changed = YES;
}
if (changed || !text)
[[seeded.allObjects componentsJoinedByString:@"\n"] writeToURL:marker atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (NSArray<NSString *> *)libraryPresetsForType:(NSString *)type {
if (!type.length) return @[];
[self mixSeedType:type];
NSArray<NSURL *> *files = [NSFileManager.defaultManager contentsOfDirectoryAtURL:[self mixPresetDir:type]
includingPropertiesForKeys:nil options:0 error:nil];
NSMutableArray<NSString *> *names = [NSMutableArray array];
for (NSURL *u in files) if ([u.pathExtension isEqualToString:@"szp"]) [names addObject:u.URLByDeletingPathExtension.lastPathComponent];
return [names sortedArrayUsingSelector:@selector(compare:)];
}
- (BOOL)savePresetOfSlot:(NSInteger)slot name:(NSString *)name {
NSString *type = [self typeOfSlot:slot];
if (!type.length) return NO;
std::string n = name.UTF8String;
__block std::string text;
[self edit:^(model::Project &p, engine::Engine &) {
model::ToolboxSlot &s = p.toolbox[(size_t)slot];
s.name = n;
text = io::PresetIo::exportText(s);
}];
return [@(text.c_str()) writeToURL:[self mixPresetURL:type name:name] atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (BOOL)loadPreset:(NSString *)name intoSlot:(NSInteger)slot {
NSString *type = [self typeOfSlot:slot];
if (!type.length) return NO;
NSString *text = [NSString stringWithContentsOfURL:[self mixPresetURL:type name:name] encoding:NSUTF8StringEncoding error:nil];
if (!text) return NO;
std::string t = text.UTF8String ?: "", n = name.UTF8String;
__block BOOL ok = NO;
[self edit:^(model::Project &p, engine::Engine &e) {
model::ToolboxSlot &s = p.toolbox[(size_t)slot];
ok = io::PresetIo::importText(s, t);
if (ok) { s.name = n; e.rebuildFxChains(); }
}];
if (ok) [self rehydrateSamples];
return ok;
}
- (BOOL)deletePreset:(NSString *)name type:(NSString *)type {
return [NSFileManager.defaultManager removeItemAtURL:[self mixPresetURL:type name:name] error:nil];
}
- (BOOL)importPresetText:(NSString *)text intoSlot:(NSInteger)slot {
if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return NO;
std::string t = text.UTF8String ?: "";
__block BOOL ok = NO;
[self edit:^(model::Project &p, engine::Engine &e) {
ok = io::PresetIo::importText(p.toolbox[(size_t)slot], t);
if (ok) e.rebuildFxChains();
}];
if (!ok) return NO;
[self rehydrateSamples];
NSString *name = [self nameOfSlot:slot];
return [self savePresetOfSlot:slot name:name.length ? name : [self typeOfSlot:slot]];
}
- (BOOL)importPresetData:(NSData *)data intoSlot:(NSInteger)slot {
if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return NO;
if (data.length < 4 || memcmp(data.bytes, "PK\x03\x04", 4)) {
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return text && [self importPresetText:text intoSlot:slot];
}
// A bundle: each sound becomes one of the song's samples (store + Documents/samples).
__block model::ToolboxSlot fresh;
[self read:^(const model::Project &p, const engine::Engine &) { fresh = p.toolbox[(size_t)slot]; }];
sampler::SampleStore &store = [self sampleStore];
const bool ok = io::PresetBundle::importInto(fresh, (const uint8_t *)data.bytes, data.length,
[self, &store](const std::string &file, Sample sample) {
std::string stem = file.substr(0, file.rfind('.'));
std::string id = stem + "#" + NSUUID.UUID.UUIDString.UTF8String;
const auto wav = sampler::SampleStore::encodeWav(sample);
[[NSData dataWithBytes:wav.data() length:wav.size()] writeToURL:[self sampleURL:id] atomically:YES];
store.put(id, std::move(sample));
return id;
});
if (!ok) return NO;
[self edit:^(model::Project &p, engine::Engine &e) {
p.toolbox[(size_t)slot] = fresh;
++p.toolbox[(size_t)slot].version;
e.rebuildFxChains();
}];
NSString *name = [self nameOfSlot:slot];
return [self savePresetOfSlot:slot name:name.length ? name : [self typeOfSlot:slot]];
}
- (nullable NSURL *)presetShareURLForType:(NSString *)type name:(NSString *)name {
NSURL *file = [self presetFileForType:type name:name];
if (!file || !io::PresetBundle::carriesSamples(type.UTF8String)) return file;
NSString *text = [NSString stringWithContentsOfURL:file encoding:NSUTF8StringEncoding error:nil];
model::ToolboxSlot slot;
if (!text || !io::PresetIo::importText(slot, text.UTF8String)) return file;
sampler::SampleStore &store = [self sampleStore];
NSString *base = sanitize(name);
const auto zip = io::PresetBundle::exportFrom(slot, base.UTF8String, [self, &store](const std::string &id) {
if (NSData *d = [NSData dataWithContentsOfURL:[self sampleURL:id]])
return std::vector<uint8_t>((const uint8_t *)d.bytes, (const uint8_t *)d.bytes + d.length);
const Sample *s = store.get(id.c_str());
return s ? sampler::SampleStore::encodeWav(*s) : std::vector<uint8_t>();
});
NSURL *dir = [NSFileManager.defaultManager.temporaryDirectory URLByAppendingPathComponent:@"PresetShare" isDirectory:YES];
[NSFileManager.defaultManager removeItemAtURL:dir error:nil];
[NSFileManager.defaultManager createDirectoryAtURL:dir withIntermediateDirectories:YES attributes:nil error:nil];
NSURL *out = [dir URLByAppendingPathComponent:[base stringByAppendingPathExtension:@"zip"]];
return [[NSData dataWithBytes:zip.data() length:zip.size()] writeToURL:out atomically:YES] ? out : nil;
}
- (NSURL *)presetFileForType:(NSString *)type name:(NSString *)name {
NSURL *u = [self mixPresetURL:type name:name];
return [NSFileManager.defaultManager fileExistsAtPath:u.path] ? u : nil;
}
@end