A RANDOM button in the preset bar of the Synth, Morph Pad, Grain Cloud, Wavetable and Ambience Reverb editors: it rolls a playable patch and names it. The rules live in core/src/model/Randomizer.cpp and are shared, so a seed gives the same patch on both platforms. Android reaches it over JNI as preset text and imports it; iOS writes the Params into the slot. Neither touches the slot's own files — a loaded sample or an imported wavetable survives a roll, because the dice are for the settings, not for the sounds. Scattering values over the parameter ranges produces silence and the occasional scream, so the rules encode three things instead: something always sounds (a layer is always up, an envelope that decays to nothing gets a body, a filter is never shut, a reverb is never fully dry); levels share a budget and resonance, drive and saturation stay out of the range where a patch screams; and tunings come from consonant intervals rather than a uniform draw. core/tests/randomizer_test.cpp is the specification: it renders every device over hundreds of seeds through the real voice and fails on anything out of range, silent, clipping or non-finite. Every bound that looks arbitrary was put there by a seed it caught — a band-pass parked above the note (peak 0.010 against a 0.3 median), a Vel -> Cutoff mod slot closing the filter (0.41 -> 0.02), a choir-only Morph Pad through its own band-pass, and MORPH TO, which a roll now leaves alone because MORPH TIME carries a held note all the way onto a factory drone at a level the randomizer never chose (1.33 with every layer of its own at zero). --dump <TYPE> <seed> [key=value ...] re-renders one roll with overrides, which is how each of those was found. Also fixes the shared engine not compiling outside Apple's toolchain: a missing <cstdint> in core/include/sizzle/Model.hpp. No change to the apps, but the engine's tests and benchmark now build with GCC too — which is how the rules above were iterated while the Mac was unreachable. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
664 lines
30 KiB
Plaintext
664 lines
30 KiB
Plaintext
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
#import "SizzleSession+Internal.h"
|
|
#import <AVFoundation/AVFoundation.h>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <atomic>
|
|
#include <cstring>
|
|
#include <mutex>
|
|
#include <optional>
|
|
#include <string>
|
|
#include <vector>
|
|
#include "io/ProjectIo.hpp"
|
|
#include "io/SngFormat.hpp"
|
|
#include "sampler/SampleStore.hpp"
|
|
#include "sampler/SoundFontLoader.hpp"
|
|
#include "echofield/GrainSources.hpp"
|
|
#include "wavetable/WaveTables.hpp"
|
|
#include "sizzle/DeviceSpecs.gen.hpp"
|
|
#include "sizzle/Engine.hpp"
|
|
#include "sizzle/Model.hpp"
|
|
#include "sizzle/Randomizer.hpp"
|
|
|
|
using namespace sizzle;
|
|
|
|
NSNotificationName const SizzleSessionDidChange = @"SizzleSessionDidChange";
|
|
|
|
namespace {
|
|
|
|
/// Live note events from the UI / MIDI, drained by the audio thread before each
|
|
/// render (the engine's live-note calls must run on the audio thread).
|
|
struct NoteEvent { int kind, a, b, c; }; // kind: 0 bus on, 1 bus off, 2 audition on, 3 audition off
|
|
struct NoteQueue {
|
|
std::array<NoteEvent, 512> ring;
|
|
std::atomic<uint32_t> head{0}, tail{0};
|
|
void push(NoteEvent e) {
|
|
uint32_t h = head.load(std::memory_order_relaxed);
|
|
if (h - tail.load(std::memory_order_acquire) >= ring.size()) return; // full: drop
|
|
ring[h % ring.size()] = e;
|
|
head.store(h + 1, std::memory_order_release);
|
|
}
|
|
template <class F> void drain(F f) {
|
|
uint32_t t = tail.load(std::memory_order_relaxed), h = head.load(std::memory_order_acquire);
|
|
for (; t != h; ++t) f(ring[t % ring.size()]);
|
|
tail.store(t, std::memory_order_release);
|
|
}
|
|
};
|
|
|
|
/// The app paused the output on purpose (background, idle): don't restart it on a route change.
|
|
bool gAudioSuspended = false;
|
|
|
|
constexpr int kChunk = 192; // Android's block size: keeps the MIDI LFO's rate (see PORTING.md)
|
|
|
|
NSError *sessionError(NSString *msg) {
|
|
return [NSError errorWithDomain:@"cc.tiredsysadmin.ios.sizzle" code:2 userInfo:@{NSLocalizedDescriptionKey: msg}];
|
|
}
|
|
|
|
/// Slot keys that hold a sample id (Sampler pads, SF2/XI loader, Grain Cloud custom source).
|
|
bool isSampleKey(const char *key) {
|
|
if (!std::strcmp(key, "sfSample")) return true;
|
|
if (!std::strncmp(key, "pad", 3)) {
|
|
const char *p = key + 3;
|
|
if (!*p) return false;
|
|
while (*p >= '0' && *p <= '9') ++p;
|
|
return *p == '\0';
|
|
}
|
|
return false;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
@implementation SizzleDeviceType {
|
|
@public
|
|
NSString *_type, *_displayName;
|
|
BOOL _isInstrument, _isMidiEffect;
|
|
}
|
|
- (NSString *)type { return _type; }
|
|
- (NSString *)displayName { return _displayName; }
|
|
- (BOOL)isInstrument { return _isInstrument; }
|
|
- (BOOL)isMidiEffect { return _isMidiEffect; }
|
|
@end
|
|
|
|
@implementation SizzleParamSpec {
|
|
@public
|
|
NSString *_key, *_label;
|
|
float _def, _min, _max;
|
|
BOOL _isInt;
|
|
NSArray<NSString *> *_choices;
|
|
}
|
|
- (NSString *)key { return _key; }
|
|
- (NSString *)label { return _label; }
|
|
- (float)defaultValue { return _def; }
|
|
- (float)minValue { return _min; }
|
|
- (float)maxValue { return _max; }
|
|
- (BOOL)isInt { return _isInt; }
|
|
- (NSArray<NSString *> *)choices { return _choices; }
|
|
@end
|
|
|
|
@implementation SizzleSession {
|
|
std::mutex _lock; // the song: UI writes under it, audio try-locks
|
|
std::unique_ptr<model::Project> _project;
|
|
std::unique_ptr<sampler::SampleStore> _store;
|
|
std::unique_ptr<engine::Engine> _engine;
|
|
NoteQueue _notes;
|
|
NoteQueue _midiNotes; // pushed by the MIDI threads (serialised by the sound module's lock)
|
|
std::vector<float> _scratch;
|
|
AVAudioEngine *_audio;
|
|
AVAudioSourceNode *_source;
|
|
NSUInteger _revision;
|
|
NSURL *_docs;
|
|
}
|
|
|
|
+ (SizzleSession *)shared {
|
|
static SizzleSession *s;
|
|
static dispatch_once_t once;
|
|
dispatch_once(&once, ^{ s = [SizzleSession new]; });
|
|
return s;
|
|
}
|
|
|
|
- (instancetype)init {
|
|
self = [super init];
|
|
if (!self) return nil;
|
|
_docs = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject;
|
|
[NSFileManager.defaultManager createDirectoryAtURL:[_docs URLByAppendingPathComponent:@"songs"] withIntermediateDirectories:YES attributes:nil error:nil];
|
|
[NSFileManager.defaultManager createDirectoryAtURL:[_docs URLByAppendingPathComponent:@"samples"] withIntermediateDirectories:YES attributes:nil error:nil];
|
|
wavetable::WaveTables::prewarm();
|
|
echofield::GrainSources::prewarm();
|
|
_project = std::make_unique<model::Project>();
|
|
_store = std::make_unique<sampler::SampleStore>();
|
|
[self startAudio];
|
|
NSString *autosaved = [NSString stringWithContentsOfURL:[_docs URLByAppendingPathComponent:@"autosave.szg"] encoding:NSUTF8StringEncoding error:nil];
|
|
if (autosaved) [self loadProjectText:autosaved error:nil];
|
|
return self;
|
|
}
|
|
|
|
#pragma mark - audio
|
|
|
|
- (void)startAudio {
|
|
#if TARGET_OS_IPHONE
|
|
AVAudioSession *s = [AVAudioSession sharedInstance];
|
|
[s setCategory:AVAudioSessionCategoryPlayback error:nil];
|
|
[s setPreferredSampleRate:48000 error:nil];
|
|
[s setPreferredIOBufferDuration:256.0 / 48000.0 error:nil];
|
|
[s setActive:YES error:nil];
|
|
#endif
|
|
_audio = [AVAudioEngine new];
|
|
double sr = [_audio.outputNode outputFormatForBus:0].sampleRate;
|
|
if (sr <= 0) sr = 48000;
|
|
_engine = std::make_unique<engine::Engine>((int)sr, _store.get());
|
|
_engine->setProject(_project.get());
|
|
_scratch.assign(kChunk * 2, 0.f);
|
|
|
|
__unsafe_unretained SizzleSession *weakSelf = self; // the session lives for the whole app
|
|
AVAudioFormat *fmt = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:sr channels:2];
|
|
_source = [[AVAudioSourceNode alloc] initWithFormat:fmt renderBlock:^OSStatus(BOOL *isSilence, const AudioTimeStamp *ts,
|
|
AVAudioFrameCount frames, AudioBufferList *out) {
|
|
return [weakSelf render:frames into:out silence:isSilence];
|
|
}];
|
|
[_audio attachNode:_source];
|
|
[_audio connect:_source to:_audio.mainMixerNode format:fmt];
|
|
if (getenv("SIZZLE_NO_AUDIO")) return; // the Mac snapshot tool: no sound
|
|
NSError *err = nil;
|
|
if (![_audio startAndReturnError:&err]) NSLog(@"Sizzle audio: %@", err);
|
|
// A route or category change (the sample recorder switches to play-and-record,
|
|
// headphones, an audio interface) stops the engine; an interruption (a call)
|
|
// ends with it stopped. Start it again either way.
|
|
AVAudioEngine *audio = _audio;
|
|
void (^restart)(NSNotification *) = ^(NSNotification *) {
|
|
if (audio.isRunning || gAudioSuspended) return;
|
|
#if TARGET_OS_IPHONE
|
|
[[AVAudioSession sharedInstance] setActive:YES error:nil];
|
|
#endif
|
|
NSError *e = nil;
|
|
if (![audio startAndReturnError:&e]) NSLog(@"Sizzle audio restart: %@", e);
|
|
};
|
|
NSNotificationCenter *nc = NSNotificationCenter.defaultCenter;
|
|
[nc addObserverForName:AVAudioEngineConfigurationChangeNotification object:_audio queue:NSOperationQueue.mainQueue usingBlock:restart];
|
|
#if TARGET_OS_IPHONE
|
|
[nc addObserverForName:AVAudioSessionInterruptionNotification object:nil queue:NSOperationQueue.mainQueue
|
|
usingBlock:^(NSNotification *n) {
|
|
if ([n.userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue] == AVAudioSessionInterruptionTypeEnded) restart(n);
|
|
}];
|
|
#endif
|
|
}
|
|
|
|
/// The audio thread. Never blocks: if the song is being edited, this block is silent.
|
|
- (OSStatus)render:(AVAudioFrameCount)frames into:(AudioBufferList *)out silence:(BOOL *)isSilence {
|
|
float *L = (float *)out->mBuffers[0].mData;
|
|
float *R = out->mNumberBuffers > 1 ? (float *)out->mBuffers[1].mData : nullptr;
|
|
std::unique_lock<std::mutex> guard(_lock, std::try_to_lock);
|
|
if (!guard.owns_lock()) {
|
|
std::memset(L, 0, frames * sizeof(float));
|
|
if (R) std::memset(R, 0, frames * sizeof(float));
|
|
*isSilence = YES;
|
|
return noErr;
|
|
}
|
|
engine::Engine *e = _engine.get();
|
|
_notes.drain([e](const NoteEvent &n) {
|
|
switch (n.kind) {
|
|
case 0: e->busNoteOn(n.a, n.b, n.c); break;
|
|
case 1: e->busNoteOff(n.a, n.b); break;
|
|
case 2: e->auditionSlotOn(n.a, n.b); break;
|
|
case 3: e->auditionSlotOff(n.b); break;
|
|
}
|
|
});
|
|
_midiNotes.drain([e](const NoteEvent &n) {
|
|
if (n.kind == 0) e->busNoteOn(n.a, n.b, n.c); else e->busNoteOff(n.a, n.b);
|
|
});
|
|
float *buf = _scratch.data();
|
|
for (AVAudioFrameCount done = 0; done < frames;) {
|
|
int n = (int)std::min<AVAudioFrameCount>(kChunk, frames - done);
|
|
e->fillBlock(buf, n);
|
|
for (int i = 0; i < n; ++i) {
|
|
L[done + i] = buf[2 * i];
|
|
if (R) R[done + i] = buf[2 * i + 1];
|
|
}
|
|
done += (AVAudioFrameCount)n;
|
|
}
|
|
return noErr;
|
|
}
|
|
|
|
#pragma mark - change plumbing
|
|
|
|
/// Run [body] on the song under the lock, then announce the change.
|
|
- (void)edit:(void (^)(model::Project &p, engine::Engine &e))body {
|
|
{
|
|
std::lock_guard<std::mutex> g(_lock);
|
|
body(*_project, *_engine);
|
|
}
|
|
[self changed];
|
|
}
|
|
|
|
- (void)read:(void (^)(const model::Project &p, const engine::Engine &e))body {
|
|
std::lock_guard<std::mutex> g(_lock);
|
|
body(*_project, *_engine);
|
|
}
|
|
|
|
- (sampler::SampleStore &)sampleStore { return *_store; }
|
|
|
|
- (void)changed {
|
|
++_revision;
|
|
[NSNotificationCenter.defaultCenter postNotificationName:SizzleSessionDidChange object:self];
|
|
}
|
|
|
|
- (NSUInteger)revision { return _revision; }
|
|
|
|
#pragma mark - song settings
|
|
|
|
- (NSString *)songName { return @(_project->name.c_str()); }
|
|
- (void)setSongName:(NSString *)name { std::string n = name.UTF8String; [self edit:^(model::Project &p, engine::Engine &) { p.name = n; }]; }
|
|
- (float)tempo { return _project->tempoBpm; }
|
|
- (void)setTempo:(float)tempo { [self edit:^(model::Project &p, engine::Engine &) { p.tempoBpm = std::clamp(tempo, 20.f, 300.f); }]; }
|
|
- (NSInteger)signature { return (NSInteger)_project->timeSignature; }
|
|
- (void)setSignature:(NSInteger)sig {
|
|
if (sig < 0 || sig >= model::TIME_SIGNATURE_COUNT) return;
|
|
[self edit:^(model::Project &p, engine::Engine &e) {
|
|
p.timeSignature = (model::TimeSignature)sig;
|
|
e.rebuildArrangement();
|
|
}];
|
|
}
|
|
- (NSInteger)scale { return (NSInteger)_project->scale; }
|
|
- (void)setScale:(NSInteger)s { if (s >= 0 && s < model::SCALE_COUNT) [self edit:^(model::Project &p, engine::Engine &) { p.scale = (model::Scale)s; }]; }
|
|
- (NSInteger)rootNote { return _project->rootNote; }
|
|
- (void)setRootNote:(NSInteger)r { [self edit:^(model::Project &p, engine::Engine &) { p.rootNote = (int)((r % 12 + 12) % 12); }]; }
|
|
- (NSInteger)activePattern { return _project->activePatternId; }
|
|
- (void)setActivePattern:(NSInteger)id { [self edit:^(model::Project &p, engine::Engine &) { if (p.pattern((int)id)) p.activePatternId = (int)id; }]; }
|
|
|
|
+ (NSArray<NSString *> *)signatureLabels {
|
|
NSMutableArray *a = [NSMutableArray array];
|
|
for (int i = 0; i < model::TIME_SIGNATURE_COUNT; ++i) [a addObject:@(model::info((model::TimeSignature)i).label)];
|
|
return a;
|
|
}
|
|
+ (NSArray<NSString *> *)scaleLabels {
|
|
NSMutableArray *a = [NSMutableArray array];
|
|
for (int i = 0; i < model::SCALE_COUNT; ++i) [a addObject:@(model::info((model::Scale)i).label)];
|
|
return a;
|
|
}
|
|
- (NSInteger)linesPerBeat { return model::info(_project->timeSignature).linesPerBeat; }
|
|
- (NSInteger)beatsPerBar { return model::info(_project->timeSignature).beatsPerBar; }
|
|
- (NSArray<NSNumber *> *)lengthOptions {
|
|
const auto &i = model::info(_project->timeSignature);
|
|
return @[@(i.lengthOptions[0]), @(i.lengthOptions[1]), @(i.lengthOptions[2])];
|
|
}
|
|
- (NSArray<NSNumber *> *)scalePitchClasses {
|
|
const auto &s = model::info(_project->scale);
|
|
NSMutableArray *a = [NSMutableArray array];
|
|
for (int i = 0; i < s.count; ++i) [a addObject:@((s.intervals[i] + _project->rootNote) % 12)];
|
|
return a;
|
|
}
|
|
|
|
#pragma mark - patterns
|
|
|
|
- (NSInteger)lengthOfPattern:(NSInteger)pattern {
|
|
const model::Pattern *p = _project->pattern((int)pattern);
|
|
return p ? p->length : 0;
|
|
}
|
|
- (void)setLength:(NSInteger)lines ofPattern:(NSInteger)pattern {
|
|
if (lines < 1 || lines > 512) return;
|
|
[self edit:^(model::Project &p, engine::Engine &) { if (auto *pt = p.pattern((int)pattern)) pt->resize((int)lines); }];
|
|
}
|
|
- (NSString *)nameOfPattern:(NSInteger)pattern {
|
|
const model::Pattern *p = _project->pattern((int)pattern);
|
|
return p ? @(p->name.c_str()) : @"";
|
|
}
|
|
- (SizzleCell)cellInPattern:(NSInteger)pattern track:(NSInteger)track line:(NSInteger)line {
|
|
const model::Pattern *p = _project->pattern((int)pattern);
|
|
if (!p || track < 0 || track >= model::Pattern::TRACK_COUNT || line < 0 || line >= p->length) return {-1, 127, 0};
|
|
const model::Cell &c = p->cell((int)track, (int)line);
|
|
return {c.note, c.velocity, c.channel};
|
|
}
|
|
- (void)setCell:(SizzleCell)cell inPattern:(NSInteger)pattern track:(NSInteger)track line:(NSInteger)line {
|
|
[self edit:^(model::Project &p, engine::Engine &) {
|
|
model::Pattern *pt = p.pattern((int)pattern);
|
|
if (!pt || track < 0 || track >= model::Pattern::TRACK_COUNT || line < 0 || line >= pt->length) return;
|
|
model::Cell &c = pt->cell((int)track, (int)line);
|
|
c.note = std::clamp(cell.note, -2, 127);
|
|
c.velocity = std::clamp(cell.velocity, 0, 127);
|
|
c.channel = std::clamp(cell.channel, 0, 16);
|
|
}];
|
|
}
|
|
|
|
#pragma mark - arrangement
|
|
|
|
- (NSInteger)arrangementLane:(NSInteger)lane beat:(NSInteger)beat {
|
|
if (lane < 0 || lane >= model::Arrangement::LANE_COUNT) return -1;
|
|
return _project->arrangement.patternAt((int)lane, (int)beat);
|
|
}
|
|
- (void)setArrangementLane:(NSInteger)lane beat:(NSInteger)beat pattern:(NSInteger)pattern {
|
|
[self edit:^(model::Project &p, engine::Engine &e) { p.arrangement.set((int)lane, (int)beat, (int)pattern); e.rebuildArrangement(); }];
|
|
}
|
|
- (BOOL)isLaneMuted:(NSInteger)lane { return lane >= 0 && lane < 8 && _project->arrangement.laneMuted[(size_t)lane]; }
|
|
- (void)setLane:(NSInteger)lane muted:(BOOL)muted {
|
|
if (lane < 0 || lane >= 8) return;
|
|
[self edit:^(model::Project &p, engine::Engine &) { p.arrangement.laneMuted[(size_t)lane] = muted; }];
|
|
}
|
|
- (BOOL)arrangementLoop { return _project->arrangement.loopEnabled; }
|
|
- (void)setArrangementLoop:(BOOL)on { [self edit:^(model::Project &p, engine::Engine &e) { p.arrangement.loopEnabled = on; e.refreshLoopPlaylist(); }]; }
|
|
- (NSInteger)arrangementBars { return _project->arrangement.lengthBars; }
|
|
- (void)setArrangementBars:(NSInteger)bars {
|
|
[self edit:^(model::Project &p, engine::Engine &) { p.arrangement.lengthBars = (int)std::clamp<NSInteger>(bars, 1, model::Arrangement::MAX_BARS); }];
|
|
}
|
|
- (NSInteger)lastFilledBeat { return _project->arrangement.lastFilledBeat(); }
|
|
- (const model::LoopRegion &)region:(NSInteger)r { return r == 1 ? _project->arrangement.regionB : _project->arrangement.regionA; }
|
|
- (BOOL)regionEnabled:(NSInteger)r { return [self region:r].enabled; }
|
|
- (NSInteger)regionStart:(NSInteger)r { return [self region:r].start; }
|
|
- (NSInteger)regionEnd:(NSInteger)r { return [self region:r].end; }
|
|
- (NSInteger)regionRepeats:(NSInteger)r { return [self region:r].repeats; }
|
|
- (void)setRegion:(NSInteger)r enabled:(BOOL)en start:(NSInteger)s end:(NSInteger)e repeats:(NSInteger)rep {
|
|
[self edit:^(model::Project &p, engine::Engine &eng) {
|
|
model::LoopRegion &g = r == 1 ? p.arrangement.regionB : p.arrangement.regionA;
|
|
g.enabled = en; g.start = (int)s; g.end = (int)e; g.repeats = (int)std::clamp<NSInteger>(rep, 1, 99);
|
|
eng.refreshLoopPlaylist();
|
|
}];
|
|
}
|
|
|
|
#pragma mark - transport
|
|
|
|
- (void)play { [self edit:^(model::Project &, engine::Engine &e) { e.play(); }]; }
|
|
- (void)playFromBeat:(NSInteger)beat { [self edit:^(model::Project &, engine::Engine &e) { e.play((int)beat); }]; }
|
|
- (void)pause { [self edit:^(model::Project &, engine::Engine &e) { e.pause(); }]; }
|
|
- (void)stop { [self edit:^(model::Project &, engine::Engine &e) { e.stop(); }]; }
|
|
- (void)panic { [self edit:^(model::Project &, engine::Engine &e) { e.panic(); }]; }
|
|
- (BOOL)isPlaying { return _engine->isPlaying(); }
|
|
|
|
- (BOOL)audioSuspended { return !_audio.isRunning; }
|
|
- (void)setAudioSuspended:(BOOL)suspended {
|
|
if (getenv("SIZZLE_NO_AUDIO")) return;
|
|
gAudioSuspended = suspended;
|
|
if (suspended) { [_audio pause]; return; }
|
|
if (_audio.isRunning) return;
|
|
#if TARGET_OS_IPHONE
|
|
[[AVAudioSession sharedInstance] setActive:YES error:nil];
|
|
#endif
|
|
NSError *e = nil;
|
|
if (![_audio startAndReturnError:&e]) NSLog(@"Sizzle audio resume: %@", e);
|
|
}
|
|
|
|
#pragma mark - MIDI threads (SizzleSession+Internal.h)
|
|
- (void)midiNoteOn:(int)note velocity:(int)velocity channel:(int)channel { _midiNotes.push({0, channel, note, velocity}); }
|
|
- (void)midiNoteOff:(int)note channel:(int)channel { _midiNotes.push({1, channel, note, 0}); }
|
|
- (engine::Engine *)enginePointer { return _engine.get(); }
|
|
- (const model::Project *)projectPointer { return _project.get(); }
|
|
- (NSInteger)currentLine { return _engine->transport().currentLine; }
|
|
- (NSInteger)currentBeat { return _engine->transport().currentBeat; }
|
|
|
|
#pragma mark - mixer
|
|
|
|
- (model::MixerChannel *)ch:(NSInteger)c { return c >= 0 && c < 4 ? &_project->mixer.channels[(size_t)c] : nullptr; }
|
|
- (NSInteger)instrumentSlotOfChannel:(NSInteger)c { auto *m = [self ch:c]; return m ? m->instrumentSlot : -1; }
|
|
- (void)setInstrumentSlot:(NSInteger)slot ofChannel:(NSInteger)c {
|
|
[self edit:^(model::Project &p, engine::Engine &e) { if (c >= 0 && c < 4) { p.mixer.channels[(size_t)c].instrumentSlot = (int)slot; e.rebuildFxChains(); } }];
|
|
}
|
|
- (NSInteger)fxSlot:(NSInteger)i ofChannel:(NSInteger)c { auto *m = [self ch:c]; return m && i >= 0 && i < 4 ? m->fxSlots[(size_t)i] : -1; }
|
|
- (void)setFxSlot:(NSInteger)i to:(NSInteger)slot ofChannel:(NSInteger)c {
|
|
[self edit:^(model::Project &p, engine::Engine &e) {
|
|
if (c >= 0 && c < 4 && i >= 0 && i < 4) { p.mixer.channels[(size_t)c].fxSlots[(size_t)i] = (int)slot; e.rebuildFxChains(); }
|
|
}];
|
|
}
|
|
- (NSInteger)midiChannelOfChannel:(NSInteger)c { auto *m = [self ch:c]; return m ? m->midiChannel : 0; }
|
|
- (void)setMidiChannel:(NSInteger)midi ofChannel:(NSInteger)c {
|
|
[self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].midiChannel = (int)std::clamp<NSInteger>(midi, 0, 16); }];
|
|
}
|
|
- (float)volumeOfChannel:(NSInteger)c { auto *m = [self ch:c]; return m ? m->volume : 0; }
|
|
- (void)setVolume:(float)v ofChannel:(NSInteger)c {
|
|
[self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].volume = std::clamp(v, 0.f, 1.5f); }];
|
|
}
|
|
- (BOOL)isMuted:(NSInteger)c { auto *m = [self ch:c]; return m && m->mute; }
|
|
- (void)setChannel:(NSInteger)c muted:(BOOL)v { [self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].mute = v; }]; }
|
|
- (BOOL)isSolo:(NSInteger)c { auto *m = [self ch:c]; return m && m->solo; }
|
|
- (void)setChannel:(NSInteger)c solo:(BOOL)v { [self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].solo = v; }]; }
|
|
- (BOOL)hasLimiter:(NSInteger)c { auto *m = [self ch:c]; return m && m->limiter; }
|
|
- (void)setChannel:(NSInteger)c limiter:(BOOL)v { [self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].limiter = v; }]; }
|
|
- (float)meterOfChannel:(NSInteger)c { return _engine->channelMeter((int)c); }
|
|
- (BOOL)clippedChannel:(NSInteger)c { return _engine->channelClipped((int)c); }
|
|
|
|
#pragma mark - toolbox
|
|
|
|
+ (NSArray<SizzleDeviceType *> *)deviceTypes {
|
|
NSMutableArray *a = [NSMutableArray array];
|
|
for (int i = 0; i < gen::deviceCount; ++i) {
|
|
const DeviceSpec &d = gen::devices[i];
|
|
SizzleDeviceType *t = [SizzleDeviceType new];
|
|
t->_type = @(d.type);
|
|
t->_displayName = @(d.displayName);
|
|
t->_isInstrument = d.kind == Kind::Instrument;
|
|
t->_isMidiEffect = !std::strcmp(d.type, "ARPEGGIATOR") || !std::strcmp(d.type, "TRANSPOSER") || !std::strcmp(d.type, "LFO");
|
|
[a addObject:t];
|
|
}
|
|
return a;
|
|
}
|
|
|
|
- (NSString *)typeOfSlot:(NSInteger)slot { return slot >= 0 && slot < 16 ? @(_project->toolbox[(size_t)slot].type.c_str()) : @""; }
|
|
- (NSString *)nameOfSlot:(NSInteger)slot { return slot >= 0 && slot < 16 ? @(_project->toolbox[(size_t)slot].name.c_str()) : @""; }
|
|
- (void)fillSlot:(NSInteger)slot withType:(NSString *)type {
|
|
std::string t = type.UTF8String;
|
|
[self edit:^(model::Project &p, engine::Engine &e) { if (slot >= 0 && slot < 16) { p.toolbox[(size_t)slot].fill(t); e.rebuildFxChains(); } }];
|
|
}
|
|
- (void)clearSlot:(NSInteger)slot {
|
|
[self edit:^(model::Project &p, engine::Engine &e) {
|
|
if (slot < 0 || slot >= 16) return;
|
|
p.toolbox[(size_t)slot].clearSlot();
|
|
for (auto &c : p.mixer.channels) { // nothing may route to an empty slot
|
|
if (c.instrumentSlot == slot) c.instrumentSlot = -1;
|
|
for (auto &f : c.fxSlots) if (f == slot) f = -1;
|
|
}
|
|
e.rebuildFxChains();
|
|
}];
|
|
}
|
|
- (NSString *)valueOfSlot:(NSInteger)slot key:(NSString *)key {
|
|
if (slot < 0 || slot >= 16) return @"";
|
|
return @(_project->toolbox[(size_t)slot].s(key.UTF8String, ""));
|
|
}
|
|
- (void)setValue:(NSString *)value ofSlot:(NSInteger)slot key:(NSString *)key {
|
|
std::string k = key.UTF8String, v = value.UTF8String;
|
|
[self edit:^(model::Project &p, engine::Engine &) { if (slot >= 0 && slot < 16) p.toolbox[(size_t)slot].set(k.c_str(), v.c_str()); }];
|
|
}
|
|
- (void)setNumber:(float)value ofSlot:(NSInteger)slot key:(NSString *)key {
|
|
std::string k = key.UTF8String;
|
|
[self edit:^(model::Project &p, engine::Engine &) { if (slot >= 0 && slot < 16) p.toolbox[(size_t)slot].set(k.c_str(), value); }];
|
|
}
|
|
|
|
+ (NSArray<SizzleParamSpec *> *)paramSpecsForType:(NSString *)type {
|
|
const DeviceSpec *d = findDevice(type.UTF8String);
|
|
NSMutableArray *a = [NSMutableArray array];
|
|
for (int i = 0; d && i < d->paramCount; ++i) {
|
|
const ParamSpec &p = d->params[i];
|
|
SizzleParamSpec *s = [SizzleParamSpec new];
|
|
s->_key = @(p.key); s->_label = @(p.label);
|
|
s->_def = p.def; s->_min = p.isEnum() ? 0 : p.min; s->_max = p.isEnum() ? (float)(p.choiceCount() - 1) : p.max;
|
|
s->_isInt = p.isInt || p.isEnum();
|
|
NSMutableArray *c = [NSMutableArray array];
|
|
for (int k = 0; p.isEnum() && p.choices[k]; ++k) [c addObject:@(p.choices[k])];
|
|
s->_choices = c;
|
|
[a addObject:s];
|
|
}
|
|
return a;
|
|
}
|
|
|
|
- (NSArray<NSString *> *)factoryPresetsForType:(NSString *)type {
|
|
NSMutableArray *a = [NSMutableArray array];
|
|
for (int i = 0; i < gen::factoryPresetCount; ++i)
|
|
if (!std::strcmp(gen::factoryPresets[i].type, type.UTF8String)) [a addObject:@(gen::factoryPresets[i].name)];
|
|
return a;
|
|
}
|
|
- (void)applyFactoryPreset:(NSString *)name toSlot:(NSInteger)slot {
|
|
std::string n = name.UTF8String;
|
|
[self edit:^(model::Project &p, engine::Engine &e) {
|
|
if (slot < 0 || slot >= 16) return;
|
|
model::ToolboxSlot &s = p.toolbox[(size_t)slot];
|
|
for (int i = 0; i < gen::factoryPresetCount; ++i) {
|
|
if (s.type != gen::factoryPresets[i].type || n != gen::factoryPresets[i].name) continue;
|
|
const char *const *kv = gen::factoryPresets[i].values;
|
|
for (int k = 0; kv[k] && kv[k + 1]; k += 2) s.set(kv[k], kv[k + 1]);
|
|
s.name = n;
|
|
}
|
|
e.rebuildFxChains();
|
|
}];
|
|
}
|
|
|
|
- (BOOL)canRandomizeType:(NSString *)type {
|
|
return type.length && model::canRandomize(type.UTF8String) ? YES : NO;
|
|
}
|
|
|
|
- (nullable NSString *)randomizeSlot:(NSInteger)slot {
|
|
if (slot < 0 || slot >= 16) return nil;
|
|
const std::string type = [self typeOfSlot:slot].UTF8String;
|
|
if (!model::canRandomize(type.c_str())) return nil;
|
|
|
|
const uint32_t seed = arc4random();
|
|
Params rolled;
|
|
if (!model::randomize(type.c_str(), seed, rolled)) return nil;
|
|
const std::string name = model::randomName(type.c_str(), seed);
|
|
|
|
[self edit:^(model::Project &p, engine::Engine &e) {
|
|
model::ToolboxSlot &s = p.toolbox[(size_t)slot];
|
|
// Only the keys the roll produced are written, and those are exactly the
|
|
// device's own parameters. Anything else the slot holds — the sample a Grain
|
|
// Cloud reads, the WAV behind a custom wavetable — is therefore left in
|
|
// place: the roll is of the settings, not of the sounds. Writing through
|
|
// set() also bumps the slot version, so the engine re-reads it.
|
|
for (int i = 0; i < rolled.size(); ++i) s.set(rolled.keyAt(i), rolled.valueAt(i));
|
|
s.name = name;
|
|
e.rebuildFxChains();
|
|
}];
|
|
return @(name.c_str());
|
|
}
|
|
|
|
#pragma mark - live notes
|
|
|
|
- (void)noteOn:(NSInteger)note velocity:(NSInteger)velocity midiChannel:(NSInteger)ch {
|
|
_notes.push({0, (int)ch, (int)note, (int)velocity});
|
|
}
|
|
- (void)noteOff:(NSInteger)note midiChannel:(NSInteger)ch { _notes.push({1, (int)ch, (int)note, 0}); }
|
|
- (void)auditionSlot:(NSInteger)slot note:(NSInteger)note on:(BOOL)on { _notes.push({on ? 2 : 3, (int)slot, (int)note, 0}); }
|
|
|
|
#pragma mark - songs
|
|
|
|
- (NSURL *)songURL:(NSString *)name {
|
|
NSString *safe = [[name componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/\\:"]] componentsJoinedByString:@"_"];
|
|
return [[_docs URLByAppendingPathComponent:@"songs"] URLByAppendingPathComponent:[safe stringByAppendingPathExtension:@"szg"]];
|
|
}
|
|
|
|
- (NSArray<NSString *> *)songNames {
|
|
NSArray *files = [NSFileManager.defaultManager contentsOfDirectoryAtURL:[_docs URLByAppendingPathComponent:@"songs"] includingPropertiesForKeys:nil options:0 error:nil];
|
|
NSMutableArray *names = [NSMutableArray array];
|
|
for (NSURL *u in files) if ([u.pathExtension isEqualToString:@"szg"]) [names addObject:u.URLByDeletingPathExtension.lastPathComponent];
|
|
return [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
|
|
}
|
|
|
|
- (NSString *)projectText {
|
|
std::lock_guard<std::mutex> g(_lock);
|
|
return @(io::ProjectIo::save(*_project).c_str());
|
|
}
|
|
|
|
- (NSString *)sngText {
|
|
std::lock_guard<std::mutex> g(_lock);
|
|
return @(io::SngFormat::exportText(*_project).c_str());
|
|
}
|
|
|
|
- (BOOL)saveSongNamed:(NSString *)name error:(NSError **)error {
|
|
self.songName = name;
|
|
return [[self projectText] writeToURL:[self songURL:name] atomically:YES encoding:NSUTF8StringEncoding error:error];
|
|
}
|
|
|
|
- (BOOL)loadSongNamed:(NSString *)name error:(NSError **)error {
|
|
NSString *text = [NSString stringWithContentsOfURL:[self songURL:name] encoding:NSUTF8StringEncoding error:error];
|
|
if (!text || ![self loadProjectText:text error:error]) return NO;
|
|
self.songName = name; // as Android's loadSong: the file's name wins
|
|
return YES;
|
|
}
|
|
|
|
- (BOOL)deleteSongNamed:(NSString *)name error:(NSError **)error {
|
|
BOOL ok = [NSFileManager.defaultManager removeItemAtURL:[self songURL:name] error:error];
|
|
if (ok) [self changed];
|
|
return ok;
|
|
}
|
|
|
|
- (void)newSong {
|
|
[self edit:^(model::Project &p, engine::Engine &e) {
|
|
e.stop();
|
|
p = model::Project();
|
|
e.setProject(&p);
|
|
}];
|
|
}
|
|
|
|
- (BOOL)loadProjectText:(NSString *)text error:(NSError **)error {
|
|
std::string t = text.UTF8String ?: "";
|
|
[self edit:^(model::Project &p, engine::Engine &e) {
|
|
e.stop();
|
|
p = model::Project();
|
|
io::ProjectIo::loadInto(p, t);
|
|
e.setProject(&p);
|
|
}];
|
|
[self rehydrateSamples];
|
|
return YES;
|
|
}
|
|
|
|
- (BOOL)importSngText:(NSString *)text error:(NSError **)error {
|
|
std::string t = text.UTF8String ?: "";
|
|
if (!io::SngFormat::looksLikeSng(t)) { if (error) *error = sessionError(@"This doesn't look like a Sizzle .sng song."); return NO; }
|
|
[self edit:^(model::Project &p, engine::Engine &e) {
|
|
e.stop();
|
|
io::SngFormat::importInto(p, t);
|
|
e.setProject(&p);
|
|
}];
|
|
return YES;
|
|
}
|
|
|
|
- (void)autosave {
|
|
[[self projectText] writeToURL:[_docs URLByAppendingPathComponent:@"autosave.szg"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
|
|
}
|
|
|
|
#pragma mark - samples
|
|
|
|
- (NSURL *)sampleURL:(const std::string &)id {
|
|
NSString *safe = [[@(id.c_str()) componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/\\:"]] componentsJoinedByString:@"_"];
|
|
return [[_docs URLByAppendingPathComponent:@"samples"] URLByAppendingPathComponent:[safe stringByAppendingPathExtension:@"wav"]];
|
|
}
|
|
|
|
/// Put back into the store every sample the song refers to, from Documents/samples.
|
|
- (void)rehydrateSamples {
|
|
std::vector<std::string> ids;
|
|
{
|
|
std::lock_guard<std::mutex> g(_lock);
|
|
for (auto &slot : _project->toolbox)
|
|
for (int i = 0; i < slot.values.size(); ++i)
|
|
if (isSampleKey(slot.values.keyAt(i)) && *slot.values.valueAt(i)) ids.emplace_back(slot.values.valueAt(i));
|
|
}
|
|
for (auto &id : ids) {
|
|
if (_store->get(id.c_str())) continue;
|
|
NSData *d = [NSData dataWithContentsOfURL:[self sampleURL:id]];
|
|
if (!d) continue;
|
|
if (auto s = sampler::SampleStore::decodeWav((const uint8_t *)d.bytes, d.length)) _store->put(id, std::move(*s));
|
|
}
|
|
}
|
|
|
|
- (BOOL)loadSampleData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot pad:(NSInteger)pad error:(NSError **)error {
|
|
NSString *type = [self typeOfSlot:slot];
|
|
BOOL sf = [type isEqualToString:@"SOUNDFONT"];
|
|
if (!sf && ![type isEqualToString:@"SAMPLER"]) { if (error) *error = sessionError(@"Pick a Sampler or an SF2/XI loader slot."); return NO; }
|
|
const uint8_t *bytes = (const uint8_t *)data.bytes;
|
|
std::optional<Sample> sample;
|
|
int root = 60;
|
|
if (sf) {
|
|
if (auto l = sampler::SoundFontLoader::load(bytes, data.length)) { sample = std::move(l->sample); root = l->rootNote; }
|
|
}
|
|
if (!sample) sample = sampler::SampleStore::decodeWav(bytes, data.length);
|
|
if (!sample) { if (error) *error = sessionError(sf ? @"Not an SF2, XI or WAV file Sizzle can read." : @"Not a WAV file Sizzle can read."); return NO; }
|
|
std::string id = std::string(name.UTF8String) + "#" + NSUUID.UUID.UUIDString.UTF8String;
|
|
std::vector<uint8_t> wav = sampler::SampleStore::encodeWav(*sample);
|
|
[[NSData dataWithBytes:wav.data() length:wav.size()] writeToURL:[self sampleURL:id] atomically:YES];
|
|
_store->put(id, std::move(*sample));
|
|
[self edit:^(model::Project &p, engine::Engine &) {
|
|
model::ToolboxSlot &s = p.toolbox[(size_t)slot];
|
|
if (sf) { s.set("sfSample", id.c_str()); s.set("sfRoot", (float)root); }
|
|
else s.set(("pad" + std::to_string(pad)).c_str(), id.c_str());
|
|
}];
|
|
return YES;
|
|
}
|
|
|
|
@end
|