From bf5f2b53af13c2b66e7e61a94fd3406bd290c23c Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Sun, 15 Nov 2026 21:49:02 +0100 Subject: [PATCH] iOS port plan and instrument reference harness PORTING.md: native SwiftUI app on a C++ engine verified against Kotlin. IosGoldenInstruments renders note scripts through the Kotlin voices; the C++ runner plays the same scripts through TestVoice makers (weak placeholders until each port lands). Co-Authored-By: Claude Opus 5.5 --- .../sizzle/audio/IosGoldenInstruments.kt | 147 ++++++++++++++++++ ios/Makefile | 8 +- ios/PORTING.md | 64 ++++++++ ios/app/project.yml | 2 +- ios/core/include/sizzle/TestVoice.hpp | 45 ++++++ ios/core/src/TestVoices.cpp | 28 ++++ ios/core/tests/golden_test.cpp | 43 ++++- 7 files changed, 327 insertions(+), 10 deletions(-) create mode 100644 app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenInstruments.kt create mode 100644 ios/PORTING.md create mode 100644 ios/core/include/sizzle/TestVoice.hpp create mode 100644 ios/core/src/TestVoices.cpp diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenInstruments.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenInstruments.kt new file mode 100644 index 0000000..0ba87b3 --- /dev/null +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenInstruments.kt @@ -0,0 +1,147 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.audio + +import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs +import cc.tiredsysadmin.android.sizzle.echofield.GrainCloud +import cc.tiredsysadmin.android.sizzle.echofield.GrainPatch +import cc.tiredsysadmin.android.sizzle.frasil.FrasilClock +import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch +import cc.tiredsysadmin.android.sizzle.frasil.FrasilVoice +import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot +import cc.tiredsysadmin.android.sizzle.model.ToolboxType +import cc.tiredsysadmin.android.sizzle.wavetable.WavePatch +import cc.tiredsysadmin.android.sizzle.wavetable.WaveTables +import cc.tiredsysadmin.android.sizzle.wavetable.WaveVoice +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.roundToInt + +/** + * Reference renders of the instrument voices for the iOS port (see ios/PORTING.md), + * next to IosGoldenExport's effects. Runs only when SIZZLE_GOLDEN_DIR is set. + * + * Each scenario plays a fixed note script through one voice, the way AudioEngine + * drives it: the patch is built from the slot exactly as the engine does + * (patchForSlot / GrainPatch.from), and the Morph Pad's shared FrasilClock advances + * once per 256-frame block before the block renders. Files, in SIZZLE_GOLDEN_DIR: + * + * ___.scn kind, type, sr, tempo, block, the FrasilClock start + * ("clock"), the slot's values ("p"), the note + * script ("on ", "off ") + * and the length ("frames") + * ___.f32 the output, raw little-endian float32 + * + * Kinds: SYNTH = SynthVoice with the engine's patch (Synth, Morph Pad, Wavetable); + * FRASIL = FrasilVoice alone; WAVE = WaveVoice alone; GRAIN = GrainCloud. + */ +class IosGoldenInstruments { + + private data class Ev(val frame: Int, val on: Boolean, val midi: Int, val vel: Int) + + /** Two notes: the second starts after the first's release has begun, so both + * attack, release and retrigger paths run. GRAIN adds an overlapping third. */ + private fun script(kind: String): List { + val s = mutableListOf( + Ev(0, true, 60, 100), Ev(at(0.35), false, 60, 0), + Ev(at(0.50), true, 67, 64), Ev(at(0.90), false, 67, 0), + ) + if (kind == "GRAIN") { s += Ev(at(0.10), true, 64, 90); s += Ev(at(0.60), false, 64, 0) } + return s.sortedBy { it.frame } + } + + private fun at(seconds: Double) = (seconds * SR).roundToInt() + + @Test fun export() { + val dir = System.getenv("SIZZLE_GOLDEN_DIR") + assumeTrue("set SIZZLE_GOLDEN_DIR to export", dir != null) + val out = File(dir!!).apply { mkdirs() } + WaveTables.prewarmBlocking() + GrainSources.prewarmBlocking() + + val kinds = listOf( + "SYNTH" to ToolboxType.NES_SYNTH, "SYNTH" to ToolboxType.MORPH_PAD, "SYNTH" to ToolboxType.WAVETABLE, + "FRASIL" to ToolboxType.MORPH_PAD, "WAVE" to ToolboxType.WAVETABLE, "GRAIN" to ToolboxType.GRAIN_CLOUD, + ) + for ((kind, type) in kinds) for ((variant, values) in variants(type)) { + val slot = ToolboxSlot(0).apply { fill(type) } + values.forEach { (k, v) -> slot.set(k, v) } + val events = script(kind) + val clock0 = FrasilClock.seconds + val y = render(kind, type, slot, events) + val base = "${kind}_${type.name}__$variant" + File(out, "$base.scn").writeText(buildString { + append("kind $kind\ntype ${type.name}\nsr $SR\ntempo $TEMPO\nblock $BLOCK\n") + append("clock ${java.lang.Double.toString(clock0)}\nframes $FRAMES\n") + slot.values.toSortedMap().forEach { (k, v) -> append("p $k $v\n") } + events.forEach { e -> append(if (e.on) "on ${e.frame} ${e.midi} ${e.vel}\n" else "off ${e.frame} ${e.midi}\n") } + }) + val bb = ByteBuffer.allocate(y.size * 4).order(ByteOrder.LITTLE_ENDIAN) + y.forEach { bb.putFloat(it) } + File(out, "$base.f32").writeBytes(bb.array()) + } + } + + private fun render(kind: String, type: ToolboxType, slot: ToolboxSlot, events: List): FloatArray { + val synth = SynthVoice(SR) + val frasil = FrasilVoice(SR) + val wave = WaveVoice(SR) + val cloud = GrainCloud(SR) + val synthPatch = when (type) { + ToolboxType.NES_SYNTH -> SynthPatch.from(slot, TEMPO) + ToolboxType.MORPH_PAD -> SynthPatch.forPad(FrasilPatch.from(slot)) + ToolboxType.WAVETABLE -> SynthPatch.forWave(WavePatch.from(slot, TEMPO)) + else -> SynthPatch.DEFAULT + } + val frasilPatch = if (type == ToolboxType.MORPH_PAD) FrasilPatch.from(slot) else null + val wavePatch = if (type == ToolboxType.WAVETABLE) WavePatch.from(slot, TEMPO) else null + if (kind == "GRAIN") cloud.setPatch(GrainPatch.from(slot, TEMPO)) + + val y = FloatArray(FRAMES) + var next = 0 + for (i in 0 until FRAMES) { + if (i % BLOCK == 0) FrasilClock.advance(BLOCK, SR) + while (next < events.size && events[next].frame == i) { + val e = events[next++] + when (kind) { + "SYNTH" -> if (e.on) synth.noteOn(e.midi, e.vel, synthPatch) else synth.noteOff() + "FRASIL" -> if (e.on) frasil.noteOn(e.midi, e.vel / 127f, frasilPatch!!) else frasil.noteOff() + "WAVE" -> if (e.on) wave.noteOn(e.midi, e.vel / 127f, wavePatch!!) else wave.noteOff() + "GRAIN" -> if (e.on) cloud.noteOn(e.midi, e.vel, GrainCloud.OWNER_LIVE) else cloud.noteOff(e.midi) + } + } + y[i] = when (kind) { + "SYNTH" -> synth.render() + "FRASIL" -> frasil.render() + "WAVE" -> wave.render() + else -> cloud.render() + } + } + return y + } + + /** Defaults, then every listed parameter at 75 % / 25 % of its range (enums at + * other choices, never "Custom", which needs a user sample). */ + private fun variants(type: ToolboxType): List>> { + fun variant(frac: Float, choice: (List) -> String) = type.params.associate { s -> + s.key to if (s.isEnum) choice(s.choices.filter { it != EchofieldDefs.CUSTOM && it != WaveTables.CUSTOM }) + else (s.min + frac * (s.max - s.min)).let { if (s.isInt) it.roundToInt().toFloat() else it }.toString() + } + return listOf( + "default" to emptyMap(), + "high" to variant(0.75f) { it.last() }, + "low" to variant(0.25f) { it[minOf(1, it.lastIndex)] }, + ) + } + + private companion object { + const val SR = 48_000 + const val TEMPO = 120f + const val BLOCK = 256 + const val FRAMES = 72_000 // 1.5 s + } +} diff --git a/ios/Makefile b/ios/Makefile index a61757d..5076641 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -34,10 +34,10 @@ DEV_APP := build/dev/Build/Products/Release-iphoneos/Sizzle.app IPA := dist/$(APP_ID)_$(BUILD_NO).ipa # C++ DSP core: reference audio lives in core/golden/ (regenerated, not committed). -CORE_SRC := $(wildcard core/src/*.cpp core/src/fx/*.cpp) -CORE_HDR := $(wildcard core/include/sizzle/*.hpp core/src/fx/*.hpp) +CORE_SRC := $(wildcard core/src/*.cpp core/src/*/*.cpp) +CORE_HDR := $(wildcard core/include/sizzle/*.hpp core/src/*/*.hpp) CXX ?= c++ -CXXFLAGS := -std=c++17 -O2 -Wall -Wextra -Icore/include -Icore/src/fx +CXXFLAGS := -std=c++17 -O2 -Wall -Wextra -Icore/include -Icore/src -Icore/src/fx GOLDEN := core/golden SPECS_GEN := core/include/sizzle/DeviceSpecs.gen.hpp # Gradle needs the Android SDK; same default location as the Android Makefile. @@ -59,7 +59,7 @@ help: golden: cd .. && ANDROID_HOME=$(ANDROID_SDK) SIZZLE_GOLDEN_DIR=$(CURDIR)/$(GOLDEN) \ SIZZLE_SPECS_OUT=$(CURDIR)/$(SPECS_GEN) \ - ./gradlew -q :app:testDebugUnitTest --tests '*IosGoldenExport*' --rerun + ./gradlew -q :app:testDebugUnitTest --tests '*IosGolden*' --rerun @ls $(GOLDEN)/*.scn | wc -l | xargs echo "reference scenarios:" build/core/golden_test: $(CORE_SRC) $(CORE_HDR) core/tests/golden_test.cpp diff --git a/ios/PORTING.md b/ios/PORTING.md new file mode 100644 index 0000000..baa127b --- /dev/null +++ b/ios/PORTING.md @@ -0,0 +1,64 @@ +# Porting Sizzle to iOS/iPadOS + +The whole Android app (`../app`, ~20k lines of Kotlin) as a native iOS/iPadOS 15+ +app. Target hardware includes the iPad mini 4 (A8, 2 GB RAM). Decided 2026-11-15: + +- **Interface:** native, SwiftUI with UIKit where SwiftUI is too slow on an A8 + (the tracker grid). Written fresh, following the Android screens. +- **Engine, model and file formats:** C++ in `core/`, each part checked against + the Kotlin app's own output (reference audio and reference files), like the + effects in 0.1.x. Swift talks to the core through an Objective-C++ facade. +- **Plugins:** the AUv3 extension keeps shipping Sizzle's devices to other hosts; + the app itself hosts the same code in-process (no per-plugin process cost, no + dependence on the system plugin registry). + +The Kotlin app stays the reference. When it changes, the reference files are +regenerated (`make -C ios golden`) and the C++ follows. + +## Map: Android → iOS + +| Android (Kotlin) | Lines | iOS | How it's checked | +|---|---|---|---| +| `audio/Effects.kt`, `AmbienceReverb.kt` | 1,150 | `core/src/fx` (done in 0.1.0) | reference audio per effect | +| `audio/SynthVoice.kt`, `SynthPatch.kt` | 500 | `core/src/synth` | reference audio per voice | +| `frasil/` (Morph Pad) | 950 | `core/src/frasil` | reference audio per voice | +| `wavetable/` | 730 | `core/src/wavetable` | reference audio per voice, table data | +| `echofield/`, `audio/GrainSources.kt` (Grain Cloud) | 1,100 | `core/src/echofield` | reference audio per voice | +| `audio/SampleVoice.kt`, `SampleStore.kt`, `SoundFontLoader.kt` | 570 | `core/src/sampler` | reference audio with generated samples / test SF2 | +| `model/` | 1,360 | `core/src/model` | via file round trips and full-song renders | +| `audio/AudioEngine.kt` (sequencer, mixer, routing, arp, clock) | 1,680 | `core/src/engine` | full-song renders (`samples/*.sng`, generated songs) | +| `io/` (.sng, projects, presets, bundles, backups) | 1,800 | `core/src/io` | Kotlin-written files parsed and re-written byte-identical | +| `input/` (MIDI in/out, clock, gamepad, key bindings) | 1,350 | CoreMIDI, GameController (Obj-C++/Swift) | unit tests on the parsers; on device | +| `playback/` (background service, sound module) | 430 | AVAudioSession, background audio | on device | +| `ui/` + `AppViewModel` | 8,000 | `app/` SwiftUI | on device / simulator screenshots | + +## Milestones + +Each milestone ends with a build that runs on the iPad. + +1. **Instruments in C++.** Synth, Morph Pad, Wavetable, Grain Cloud, then Sampler + and SF2/XI, each matching Kotlin voice renders. Plus AUv3 instruments (`aumu`) + and the in-app host's first form: a device list with a keyboard, so each one + can be played on the iPad and measured on the A8. +2. **Model, files and engine.** Project model, .sng / project / preset formats + (byte-identical round trips with Kotlin-written files), and the sequencer and + mixer engine (full-song renders match Kotlin). MIDI effects (arp, transposer, + LFO) come with the engine. +3. **App shell and tracker.** Tabs (Tracker, Mix, Toolbox, Setup), transport, + pattern grid, arrangement roll, keyboards, song load/save. Audio through + AVAudioEngine; background audio. +4. **Toolbox and mixer.** Device editors (cards from the DeviceLayouts data, then + the bespoke editors), presets, mixer with FX routing. +5. **Everything else.** MIDI in/out and clock sync, gamepad and key bindings, + recording, sample recorder, sharing/import, backups, themes, settings. + +## Rules for ports + +- Translate line for line and keep Kotlin's types (`Float` → `float`, `Double` → + `double`); use `core/src/fx/KotlinMath.hpp` for kotlin.math semantics; + `uint32_t` for xorshift; port `java.util.Random` exactly where it is seeded. +- No allocation or locks on the audio path; allocate in constructors / `prepare`. +- A port is done when its reference scenarios pass (`make -C ios core-test`). + Never loosen the tolerance; find the precision difference instead. +- Global Kotlin state (e.g. `FrasilClock`) becomes explicit state passed in or + owned by the engine, and the reference files record its starting value. diff --git a/ios/app/project.yml b/ios/app/project.yml index dab068c..796baaf 100644 --- a/ios/app/project.yml +++ b/ios/app/project.yml @@ -14,7 +14,7 @@ settings: DEVELOPMENT_TEAM: "" CLANG_CXX_LANGUAGE_STANDARD: c++17 CLANG_ENABLE_OBJC_ARC: YES - HEADER_SEARCH_PATHS: ["$(SRCROOT)/../core/include", "$(SRCROOT)/../core/src/fx"] + HEADER_SEARCH_PATHS: ["$(SRCROOT)/../core/include", "$(SRCROOT)/../core/src", "$(SRCROOT)/../core/src/fx"] targets: SizzleCore: type: library.static diff --git a/ios/core/include/sizzle/TestVoice.hpp b/ios/core/include/sizzle/TestVoice.hpp new file mode 100644 index 0000000..1922fcc --- /dev/null +++ b/ios/core/include/sizzle/TestVoice.hpp @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +// The hook the reference tests use to play a note script through one instrument +// voice (see IosGoldenInstruments.kt and tests/golden_test.cpp). Each instrument +// port provides its maker (strong definition) in its own source file; the weak +// placeholders in src/TestVoices.cpp return nullptr for kinds not ported yet. + +#include +#include "sizzle/Params.hpp" + +namespace sizzle { + +class TestVoice { +public: + virtual ~TestVoice() = default; + /** Called before each block of [frames] (AudioEngine advances shared clocks + * such as the Morph Pad's FrasilClock here). */ + virtual void blockStart(int frames) { (void)frames; } + virtual void noteOn(int midi, int velocity) = 0; + virtual void noteOff(int midi) = 0; + virtual float render() = 0; +}; + +struct TestVoiceSetup { + const char *type; // ToolboxType name, e.g. "MORPH_PAD" + const Params *params; // the slot's values + int sampleRate; + float tempoBpm; + double clock0; // FrasilClock.seconds when the scenario started +}; + +/** kind "SYNTH": SynthVoice with the engine's patch for [setup.type]. */ +std::unique_ptr makeSynthTestVoice(const TestVoiceSetup &setup); +/** kind "FRASIL": FrasilVoice alone (Morph Pad). */ +std::unique_ptr makeFrasilTestVoice(const TestVoiceSetup &setup); +/** kind "WAVE": WaveVoice alone (Wavetable). */ +std::unique_ptr makeWaveTestVoice(const TestVoiceSetup &setup); +/** kind "GRAIN": GrainCloud (Grain Cloud), notes owned by live input. */ +std::unique_ptr makeGrainTestVoice(const TestVoiceSetup &setup); + +std::unique_ptr makeTestVoice(const char *kind, const TestVoiceSetup &setup); + +} // namespace sizzle diff --git a/ios/core/src/TestVoices.cpp b/ios/core/src/TestVoices.cpp new file mode 100644 index 0000000..5aa9912 --- /dev/null +++ b/ios/core/src/TestVoices.cpp @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// Weak placeholders for the TestVoice makers (see TestVoice.hpp): a port's strong +// definition replaces its placeholder at link time. + +#include +#include "sizzle/TestVoice.hpp" + +#define SIZZLE_TEST_MAKER(fn) \ + __attribute__((weak)) std::unique_ptr fn(const TestVoiceSetup &) { return nullptr; } + +namespace sizzle { + +SIZZLE_TEST_MAKER(makeSynthTestVoice) +SIZZLE_TEST_MAKER(makeFrasilTestVoice) +SIZZLE_TEST_MAKER(makeWaveTestVoice) +SIZZLE_TEST_MAKER(makeGrainTestVoice) + +std::unique_ptr makeTestVoice(const char *kind, const TestVoiceSetup &s) { + if (!std::strcmp(kind, "SYNTH")) return makeSynthTestVoice(s); + if (!std::strcmp(kind, "FRASIL")) return makeFrasilTestVoice(s); + if (!std::strcmp(kind, "WAVE")) return makeWaveTestVoice(s); + if (!std::strcmp(kind, "GRAIN")) return makeGrainTestVoice(s); + return nullptr; +} + +} // namespace sizzle diff --git a/ios/core/tests/golden_test.cpp b/ios/core/tests/golden_test.cpp index 9d3966e..1b990ff 100644 --- a/ios/core/tests/golden_test.cpp +++ b/ios/core/tests/golden_test.cpp @@ -1,8 +1,9 @@ // SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later -// Renders every reference scenario exported by IosGoldenExport (Kotlin) through the -// C++ core and compares sample by sample. +// Renders every reference scenario exported by IosGoldenExport / IosGoldenInstruments +// (Kotlin) through the C++ core and compares sample by sample. Effect scenarios +// process input.f32; instrument scenarios ("kind" line) play their note script. // // golden_test [TYPE ...] // @@ -20,6 +21,7 @@ #include #include #include "sizzle/Effect.hpp" +#include "sizzle/TestVoice.hpp" using namespace sizzle; @@ -51,9 +53,12 @@ int main(int argc, char **argv) { int pass = 0, fail = 0, skip = 0; for (const auto &base : scns) { std::ifstream f(dir + "/" + base + ".scn"); - std::string line, type; - int sr = 48000; + std::string line, type, kind; + int sr = 48000, block = 256, frames = 0; float tempo = 120.f; + double clock0 = 0; + struct Ev { int frame; bool on; int midi, vel; }; + std::vector evs; Params p; while (std::getline(f, line)) { std::istringstream ls(line); @@ -61,13 +66,41 @@ int main(int argc, char **argv) { if (tag == "type") ls >> type; else if (tag == "sr") ls >> sr; else if (tag == "tempo") ls >> tempo; + else if (tag == "kind") ls >> kind; + else if (tag == "block") ls >> block; + else if (tag == "frames") ls >> frames; + else if (tag == "clock") ls >> clock0; + else if (tag == "on") { Ev e{0, true, 0, 0}; ls >> e.frame >> e.midi >> e.vel; evs.push_back(e); } + else if (tag == "off") { Ev e{0, false, 0, 0}; ls >> e.frame >> e.midi; evs.push_back(e); } else if (tag == "p") { std::string key, val; ls >> key; std::getline(ls, val); if (!val.empty() && val[0] == ' ') val.erase(0, 1); p.set(key.c_str(), val.c_str()); } } - if (!only.empty() && std::find(only.begin(), only.end(), type) == only.end()) continue; + std::string label = kind.empty() ? type : kind + "_" + type; + if (!only.empty() && std::find(only.begin(), only.end(), type) == only.end() + && std::find(only.begin(), only.end(), label) == only.end()) continue; + if (!kind.empty()) { + TestVoiceSetup setup{type.c_str(), &p, sr, tempo, clock0}; + auto v = makeTestVoice(kind.c_str(), setup); + if (!v) { std::printf("SKIP %-36s (not ported)\n", base.c_str()); ++skip; continue; } + std::vector want = readF32(dir + "/" + base + ".f32"); + double maxErr = 0; size_t at = 0, next = 0; + for (int i = 0; i < frames && i < (int)want.size(); ++i) { + if (i % block == 0) v->blockStart(block); + while (next < evs.size() && evs[next].frame == i) { + const Ev &e = evs[next++]; + if (e.on) v->noteOn(e.midi, e.vel); else v->noteOff(e.midi); + } + double err = std::fabs((double)v->render() - (double)want[i]); + if (!(err <= maxErr)) { maxErr = err; at = (size_t)i; } + } + bool ok = maxErr < 1e-4 && (int)want.size() == frames; + std::printf("%s %-36s max diff %.3g at sample %zu\n", ok ? "PASS" : "FAIL", base.c_str(), maxErr, at); + ok ? ++pass : ++fail; + continue; + } auto fx = Effect::create(type.c_str(), sr); if (!fx) { std::printf("SKIP %-36s (not ported)\n", base.c_str()); ++skip; continue; } std::vector want = readF32(dir + "/" + base + ".f32");