Ported from the Android tabs by parallel agents (each screen with its own SizzleSession category); slot editors use the card editor with a preset library; songs load/save in the Android project format. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
277 lines
12 KiB
Plaintext
277 lines
12 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/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;
|
|
@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]];
|
|
}
|
|
|
|
- (NSURL *)presetFileForType:(NSString *)type name:(NSString *)name {
|
|
NSURL *u = [self mixPresetURL:type name:name];
|
|
return [NSFileManager.defaultManager fileExistsAtPath:u.path] ? u : nil;
|
|
}
|
|
|
|
@end
|