From 2bc5cb1cbb6f7bda05fbb491a399e13b7a98109f Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Mon, 16 Nov 2026 14:49:46 +0100 Subject: [PATCH] 0.37.0 (71): one engine, one version for Android and iOS - Three source trees: core/ (shared C++ engine, moved from ios/core), app/ (Android UI), ios/app/ (iOS UI) - Android plays through core/ via JNI (EngineHost, jni_engine.cpp): the Oboe callback renders natively; the Kotlin model is mirrored as project text and applied as a diff, so playback continues through edits - The Kotlin engine moves to the unit tests as ReferenceEngine (golden reference) - Shared MasterRecorder in core/src/host, used by both apps; host_test - versions.properties: one versionName/versionCode for both platforms, continuing Android's numbering (iOS 0.6.0/11 -> 0.37.0/71) Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + CHANGELOG.md | 16 +- Makefile | 12 +- app/build.gradle.kts | 4 +- app/src/main/cpp/CMakeLists.txt | 21 +- app/src/main/cpp/jni_engine.cpp | 137 ++ app/src/main/cpp/native_audio.cpp | 88 +- .../tiredsysadmin/android/sizzle/SizzleApp.kt | 2 +- .../android/sizzle/audio/AudioEngine.kt | 1766 ++--------------- .../android/sizzle/audio/NativeAudioBridge.kt | 36 +- .../android/sizzle/audio/NativeEngine.kt | 65 + .../android/sizzle/audio/SampleStore.kt | 8 +- .../android/sizzle/ui/AppViewModel.kt | 3 +- .../android/sizzle/audio/ChannelArpTest.kt | 2 +- .../sizzle/audio/ClockRecordingTest.kt | 4 +- .../android/sizzle/audio/IosGoldenExport.kt | 4 +- .../android/sizzle/audio/IosGoldenSongs.kt | 2 +- .../android/sizzle/audio/ReferenceEngine.kt | 1667 ++++++++++++++++ .../include/sizzle/DeviceSpecs.gen.hpp | 0 {ios/core => core}/include/sizzle/Effect.hpp | 0 {ios/core => core}/include/sizzle/Engine.hpp | 0 .../include/sizzle/Instrument.hpp | 0 {ios/core => core}/include/sizzle/Midi.hpp | 0 {ios/core => core}/include/sizzle/Model.hpp | 0 {ios/core => core}/include/sizzle/Params.hpp | 0 {ios/core => core}/include/sizzle/Sample.hpp | 0 {ios/core => core}/include/sizzle/Specs.hpp | 0 .../include/sizzle/TestVoice.hpp | 0 {ios/core => core}/src/Params.cpp | 0 {ios/core => core}/src/Specs.cpp | 0 {ios/core => core}/src/TestVoices.cpp | 0 .../src/echofield/EchofieldDefs.hpp | 0 .../src/echofield/GrainCloud.cpp | 0 .../src/echofield/GrainCloud.hpp | 0 .../src/echofield/GrainSources.cpp | 0 .../src/echofield/GrainSources.hpp | 0 .../src/echofield/GrainTestVoice.cpp | 0 {ios/core => core}/src/echofield/Sample.hpp | 0 {ios/core => core}/src/engine/ChannelArp.hpp | 0 {ios/core => core}/src/engine/Engine.cpp | 0 {ios/core => core}/src/frasil/FrasilDefs.cpp | 0 .../src/frasil/FrasilTestVoice.cpp | 0 {ios/core => core}/src/frasil/FrasilVoice.cpp | 0 {ios/core => core}/src/frasil/FrasilVoice.hpp | 0 {ios/core => core}/src/fx/AmbienceReverb.cpp | 0 {ios/core => core}/src/fx/Bitcrusher.cpp | 0 {ios/core => core}/src/fx/Filter.cpp | 0 {ios/core => core}/src/fx/GranularGlitch.cpp | 0 {ios/core => core}/src/fx/GraphicEq.cpp | 0 {ios/core => core}/src/fx/KotlinMath.hpp | 0 {ios/core => core}/src/fx/MixTightener.cpp | 0 {ios/core => core}/src/fx/Registry.cpp | 0 {ios/core => core}/src/fx/TapeDelay.cpp | 0 {ios/core => core}/src/fx/TapeEngine.cpp | 0 core/src/host/EngineHost.cpp | 287 +++ core/src/host/EngineHost.hpp | 117 ++ core/src/host/MasterRecorder.cpp | 90 + core/src/host/MasterRecorder.hpp | 54 + .../src/instrument/Instrument.cpp | 0 {ios/core => core}/src/io/KotlinText.cpp | 0 {ios/core => core}/src/io/KotlinText.hpp | 0 {ios/core => core}/src/io/PresetIo.cpp | 0 {ios/core => core}/src/io/PresetIo.hpp | 0 {ios/core => core}/src/io/ProjectIo.cpp | 0 {ios/core => core}/src/io/ProjectIo.hpp | 0 {ios/core => core}/src/io/SngFormat.cpp | 0 {ios/core => core}/src/io/SngFormat.hpp | 0 {ios/core => core}/src/io/Zip.cpp | 0 {ios/core => core}/src/io/Zip.hpp | 0 {ios/core => core}/src/model/Model.cpp | 0 {ios/core => core}/src/model/TimeDivision.hpp | 0 .../core => core}/src/sampler/SampleStore.cpp | 0 .../core => core}/src/sampler/SampleStore.hpp | 0 .../src/sampler/SampleTestVoice.cpp | 0 .../core => core}/src/sampler/SampleVoice.cpp | 0 .../core => core}/src/sampler/SampleVoice.hpp | 0 .../src/sampler/SoundFontLoader.cpp | 0 .../src/sampler/SoundFontLoader.hpp | 0 {ios/core => core}/src/synth/SynthDefs.hpp | 0 {ios/core => core}/src/synth/SynthPatch.cpp | 0 {ios/core => core}/src/synth/SynthPatch.hpp | 0 .../src/synth/SynthTestVoice.cpp | 0 {ios/core => core}/src/synth/SynthVoice.cpp | 0 {ios/core => core}/src/synth/SynthVoice.hpp | 0 .../src/wavetable/JavaRandom.hpp | 0 {ios/core => core}/src/wavetable/WaveDefs.cpp | 0 {ios/core => core}/src/wavetable/WaveDefs.hpp | 0 .../src/wavetable/WaveTables.cpp | 0 .../src/wavetable/WaveTables.hpp | 0 .../src/wavetable/WaveTestVoice.cpp | 0 .../core => core}/src/wavetable/WaveVoice.cpp | 0 .../core => core}/src/wavetable/WaveVoice.hpp | 0 {ios/core => core}/tests/engine_test.cpp | 0 {ios/core => core}/tests/golden_test.cpp | 0 core/tests/host_test.cpp | 95 + {ios/core => core}/tests/io_test.cpp | 0 {ios/core => core}/tests/midi_test.cpp | 0 {ios/core => core}/tests/sampler_test.cpp | 0 {ios/core => core}/tests/zip_test.cpp | 0 docs/DEVELOPER_HANDOVER.md | 55 +- ios/.gitignore | 1 - ios/CHANGELOG.md | 12 +- ios/Makefile | 56 +- ios/README.md | 12 +- ios/app/Host/SizzleSession+Record.mm | 148 +- ios/app/project.yml | 6 +- versions.properties | 28 +- 107 files changed, 2921 insertions(+), 1880 deletions(-) create mode 100644 app/src/main/cpp/jni_engine.cpp create mode 100644 app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeEngine.kt create mode 100644 app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ReferenceEngine.kt rename {ios/core => core}/include/sizzle/DeviceSpecs.gen.hpp (100%) rename {ios/core => core}/include/sizzle/Effect.hpp (100%) rename {ios/core => core}/include/sizzle/Engine.hpp (100%) rename {ios/core => core}/include/sizzle/Instrument.hpp (100%) rename {ios/core => core}/include/sizzle/Midi.hpp (100%) rename {ios/core => core}/include/sizzle/Model.hpp (100%) rename {ios/core => core}/include/sizzle/Params.hpp (100%) rename {ios/core => core}/include/sizzle/Sample.hpp (100%) rename {ios/core => core}/include/sizzle/Specs.hpp (100%) rename {ios/core => core}/include/sizzle/TestVoice.hpp (100%) rename {ios/core => core}/src/Params.cpp (100%) rename {ios/core => core}/src/Specs.cpp (100%) rename {ios/core => core}/src/TestVoices.cpp (100%) rename {ios/core => core}/src/echofield/EchofieldDefs.hpp (100%) rename {ios/core => core}/src/echofield/GrainCloud.cpp (100%) rename {ios/core => core}/src/echofield/GrainCloud.hpp (100%) rename {ios/core => core}/src/echofield/GrainSources.cpp (100%) rename {ios/core => core}/src/echofield/GrainSources.hpp (100%) rename {ios/core => core}/src/echofield/GrainTestVoice.cpp (100%) rename {ios/core => core}/src/echofield/Sample.hpp (100%) rename {ios/core => core}/src/engine/ChannelArp.hpp (100%) rename {ios/core => core}/src/engine/Engine.cpp (100%) rename {ios/core => core}/src/frasil/FrasilDefs.cpp (100%) rename {ios/core => core}/src/frasil/FrasilTestVoice.cpp (100%) rename {ios/core => core}/src/frasil/FrasilVoice.cpp (100%) rename {ios/core => core}/src/frasil/FrasilVoice.hpp (100%) rename {ios/core => core}/src/fx/AmbienceReverb.cpp (100%) rename {ios/core => core}/src/fx/Bitcrusher.cpp (100%) rename {ios/core => core}/src/fx/Filter.cpp (100%) rename {ios/core => core}/src/fx/GranularGlitch.cpp (100%) rename {ios/core => core}/src/fx/GraphicEq.cpp (100%) rename {ios/core => core}/src/fx/KotlinMath.hpp (100%) rename {ios/core => core}/src/fx/MixTightener.cpp (100%) rename {ios/core => core}/src/fx/Registry.cpp (100%) rename {ios/core => core}/src/fx/TapeDelay.cpp (100%) rename {ios/core => core}/src/fx/TapeEngine.cpp (100%) create mode 100644 core/src/host/EngineHost.cpp create mode 100644 core/src/host/EngineHost.hpp create mode 100644 core/src/host/MasterRecorder.cpp create mode 100644 core/src/host/MasterRecorder.hpp rename {ios/core => core}/src/instrument/Instrument.cpp (100%) rename {ios/core => core}/src/io/KotlinText.cpp (100%) rename {ios/core => core}/src/io/KotlinText.hpp (100%) rename {ios/core => core}/src/io/PresetIo.cpp (100%) rename {ios/core => core}/src/io/PresetIo.hpp (100%) rename {ios/core => core}/src/io/ProjectIo.cpp (100%) rename {ios/core => core}/src/io/ProjectIo.hpp (100%) rename {ios/core => core}/src/io/SngFormat.cpp (100%) rename {ios/core => core}/src/io/SngFormat.hpp (100%) rename {ios/core => core}/src/io/Zip.cpp (100%) rename {ios/core => core}/src/io/Zip.hpp (100%) rename {ios/core => core}/src/model/Model.cpp (100%) rename {ios/core => core}/src/model/TimeDivision.hpp (100%) rename {ios/core => core}/src/sampler/SampleStore.cpp (100%) rename {ios/core => core}/src/sampler/SampleStore.hpp (100%) rename {ios/core => core}/src/sampler/SampleTestVoice.cpp (100%) rename {ios/core => core}/src/sampler/SampleVoice.cpp (100%) rename {ios/core => core}/src/sampler/SampleVoice.hpp (100%) rename {ios/core => core}/src/sampler/SoundFontLoader.cpp (100%) rename {ios/core => core}/src/sampler/SoundFontLoader.hpp (100%) rename {ios/core => core}/src/synth/SynthDefs.hpp (100%) rename {ios/core => core}/src/synth/SynthPatch.cpp (100%) rename {ios/core => core}/src/synth/SynthPatch.hpp (100%) rename {ios/core => core}/src/synth/SynthTestVoice.cpp (100%) rename {ios/core => core}/src/synth/SynthVoice.cpp (100%) rename {ios/core => core}/src/synth/SynthVoice.hpp (100%) rename {ios/core => core}/src/wavetable/JavaRandom.hpp (100%) rename {ios/core => core}/src/wavetable/WaveDefs.cpp (100%) rename {ios/core => core}/src/wavetable/WaveDefs.hpp (100%) rename {ios/core => core}/src/wavetable/WaveTables.cpp (100%) rename {ios/core => core}/src/wavetable/WaveTables.hpp (100%) rename {ios/core => core}/src/wavetable/WaveTestVoice.cpp (100%) rename {ios/core => core}/src/wavetable/WaveVoice.cpp (100%) rename {ios/core => core}/src/wavetable/WaveVoice.hpp (100%) rename {ios/core => core}/tests/engine_test.cpp (100%) rename {ios/core => core}/tests/golden_test.cpp (100%) create mode 100644 core/tests/host_test.cpp rename {ios/core => core}/tests/io_test.cpp (100%) rename {ios/core => core}/tests/midi_test.cpp (100%) rename {ios/core => core}/tests/sampler_test.cpp (100%) rename {ios/core => core}/tests/zip_test.cpp (100%) diff --git a/.gitignore b/.gitignore index 5e08edf..e9d93a4 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,6 @@ dist/ # NOTE: gradle/wrapper/gradle-wrapper.jar IS committed (Gradle's recommended # practice) so ./gradlew works on a fresh clone with no extra setup. + +# Reference audio for the C++ core, regenerated by `make -C ios golden` +/core/golden/ diff --git a/CHANGELOG.md b/CHANGELOG.md index d72cf3c..548fdea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,21 @@ Sizzletracker for Android (`cc.tiredsysadmin.android.sizzle`). One entry per version in `versions.properties`; versions before 0.28.0 are described in the git -log (one commit per version). +log (one commit per version). Since 0.37.0 Android and iOS share one version and +one feature set; the iOS side of each version is in `ios/CHANGELOG.md`. + +## 0.37.0 (versionCode 71) + +- **One engine for Android and iOS:** Android now plays through the shared C++ + engine in `core/` (sequencer, mixer, every instrument and effect), the same + code the iOS app runs, instead of the Kotlin engine. Audio is rendered entirely + in native code inside the Oboe callback, so a Java garbage-collector pause can + no longer glitch playback. Edits reach the engine as they happen; playback + carries on through them. +- **One version:** Android and iOS now carry the same version number and + versionCode (continuing Android's), and from now on ship the same features. +- The Kotlin engine stays in the unit tests as the reference the C++ engine is + checked against. ## 0.36.2 (versionCode 70) diff --git a/Makefile b/Makefile index 24d8639..a08811a 100644 --- a/Makefile +++ b/Makefile @@ -22,8 +22,8 @@ ADB := adb VERSIONS := versions.properties APP_ID := $(shell sed -n 's/^[[:space:]]*namespace[[:space:]]*=[[:space:]]*"\(.*\)".*/\1/p' app/build.gradle.kts) -VERSION_NAME := $(shell sed -n 's/^android.versionName[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ') -VERSION_CODE := $(shell sed -n 's/^android.versionCode[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ') +VERSION_NAME := $(shell sed -n 's/^versionName[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ') +VERSION_CODE := $(shell sed -n 's/^versionCode[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ') # Publishing to the private F-Droid repo (CLAUDE.md). Both halves of a release # — the artifact and its metadata — live under the same host. @@ -163,15 +163,15 @@ bump-patch: ; @$(MAKE) --no-print-directory bump FIELD=3 bump: @awk -v field=$(FIELD) ' \ - /^android.versionName/ { \ + /^versionName/ { \ split($$3, v, "."); \ v[field]++; \ for (i = field + 1; i <= 3; i++) v[i] = 0; \ - printf "android.versionName = %d.%d.%d\n", v[1], v[2], v[3]; next } \ - /^android.versionCode/ { printf "android.versionCode = %d\n", $$3 + 1; next } \ + printf "versionName = %d.%d.%d\n", v[1], v[2], v[3]; next } \ + /^versionCode/ { printf "versionCode = %d\n", $$3 + 1; next } \ { print }' $(VERSIONS) > $(VERSIONS).tmp @mv $(VERSIONS).tmp $(VERSIONS) - @sed -n 's/^android\./ android./p' $(VERSIONS) + @grep -E '^version(Name|Code)' $(VERSIONS) | sed 's/^/ /' # ------------------------------------------------------------------ clean clean: diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 3ed960c..1220f97 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -14,8 +14,8 @@ plugins { val appVersions = Properties().apply { rootProject.file("versions.properties").inputStream().use { load(it) } } -val appVersionName: String = appVersions.getProperty("android.versionName").trim() -val appVersionCode: Int = appVersions.getProperty("android.versionCode").trim().toInt() +val appVersionName: String = appVersions.getProperty("versionName").trim() +val appVersionCode: Int = appVersions.getProperty("versionCode").trim().toInt() android { namespace = "cc.tiredsysadmin.android.sizzle" diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 68bed5c..05d1c5f 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -1,15 +1,32 @@ -# Native build for the Oboe (AAudio) low-latency output backend. +# Native build: the shared C++ engine (../../../../core, the same code the iOS app +# runs), its JNI glue (jni_engine.cpp) and the Oboe (AAudio) low-latency output. cmake_minimum_required(VERSION 3.22.1) project(sizzle_native) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + # Oboe ships as a prefab package inside the com.google.oboe:oboe AAR; AGP exposes # it here when `buildFeatures { prefab = true }` is set in build.gradle.kts. find_package(oboe REQUIRED CONFIG) -add_library(sizzle_native SHARED native_audio.cpp) +# The engine as an object library, not a static one: the devices are found through +# weak placeholder makers (core/src/fx/Registry.cpp), so every object must be linked +# in or the placeholders would win. Optimised even in debug builds (the DSP must +# keep up in real time). +set(CORE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../core) +file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CORE_DIR}/src/*.cpp ${CORE_DIR}/src/*/*.cpp) +add_library(sizzle_core OBJECT ${CORE_SRC}) +target_include_directories(sizzle_core PUBLIC ${CORE_DIR}/include ${CORE_DIR}/src ${CORE_DIR}/src/fx) +target_compile_options(sizzle_core PRIVATE -O2 -Wno-unused-parameter) + +add_library(sizzle_native SHARED native_audio.cpp jni_engine.cpp $) +target_include_directories(sizzle_native PRIVATE ${CORE_DIR}/include ${CORE_DIR}/src ${CORE_DIR}/src/fx) +target_compile_options(sizzle_native PRIVATE -O2) target_link_libraries(sizzle_native oboe::oboe + z log) # Align ELF load segments to 16 KB so the library works on Android 15+ devices diff --git a/app/src/main/cpp/jni_engine.cpp b/app/src/main/cpp/jni_engine.cpp new file mode 100644 index 0000000..1a2c369 --- /dev/null +++ b/app/src/main/cpp/jni_engine.cpp @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// JNI for audio/NativeEngine.kt: the Android app drives the shared C++ engine +// (core/src/host/EngineHost) through these. The Kotlin model stays the UI's +// state; NativeEngine mirrors it here as project text (nativeSync). + +#include + +#include +#include +#include + +#include "host/EngineHost.hpp" + +using sizzle::host::EngineHost; + +namespace { + +std::atomic g_host{nullptr}; + +// A finished master take, until Kotlin collects it (nativeTakeFinished). +std::mutex g_takeLock; +std::string g_takePath; +int64_t g_takeStart = 0; +bool g_takeReady = false; + +std::string str(JNIEnv *env, jstring s) { + if (!s) return {}; + const char *c = env->GetStringUTFChars(s, nullptr); + std::string out = c ? c : ""; + if (c) env->ReleaseStringUTFChars(s, c); + return out; +} + +EngineHost *host() { return g_host.load(std::memory_order_acquire); } + +} // namespace + +sizzle::host::EngineHost *sizzleHost() { return host(); } + +#define JNI_FN(ret, name) extern "C" JNIEXPORT ret JNICALL Java_cc_tiredsysadmin_android_sizzle_audio_NativeEngine_##name +#define H if (EngineHost *h = host()) h + +JNI_FN(void, nativeCreate)(JNIEnv *, jobject, jint sampleRate) { + if (host()) return; + auto *h = new EngineHost(sampleRate); // lives as long as the process + h->recorder().onFinished = [](const std::string &path, int64_t start) { + std::lock_guard g(g_takeLock); + g_takePath = path; + g_takeStart = start; + g_takeReady = true; + }; + g_host.store(h, std::memory_order_release); +} + +JNI_FN(void, nativeLoad)(JNIEnv *env, jobject, jstring text) { H->loadProjectText(str(env, text)); } +JNI_FN(void, nativeSync)(JNIEnv *env, jobject, jstring text) { H->syncProjectText(str(env, text)); } +JNI_FN(void, nativeRebuildFxChains)(JNIEnv *, jobject) { H->rebuildFxChains(); } +JNI_FN(void, nativeRebuildArrangement)(JNIEnv *, jobject) { H->rebuildArrangement(); } +JNI_FN(void, nativeRefreshLoopPlaylist)(JNIEnv *, jobject) { H->refreshLoopPlaylist(); } + +JNI_FN(void, nativePlay)(JNIEnv *, jobject, jint beat) { H->play(beat); } +JNI_FN(void, nativePause)(JNIEnv *, jobject) { H->pause(); } +JNI_FN(void, nativeStop)(JNIEnv *, jobject) { H->stop(); } +JNI_FN(void, nativePanic)(JNIEnv *, jobject) { H->panic(); } + +/** Playing in bit 62, the line in bits 31..61, the beat in bits 0..30. */ +JNI_FN(jlong, nativeTransport)(JNIEnv *, jobject) { + EngineHost *h = host(); + if (!h) return 0; + const auto t = h->transport(); + return ((jlong)(t.isPlaying ? 1 : 0) << 62) | ((jlong)(t.currentLine & 0x7FFFFFFF) << 31) | (jlong)(t.currentBeat & 0x7FFFFFFF); +} + +JNI_FN(void, nativeLiveNoteOn)(JNIEnv *, jobject, jint pitch, jint vel) { H->liveNoteOn(pitch, vel); } +JNI_FN(void, nativeLiveNoteOff)(JNIEnv *, jobject, jint pitch) { H->liveNoteOff(pitch); } +JNI_FN(void, nativeAuditionSlotOn)(JNIEnv *, jobject, jint slot, jint midi) { H->auditionSlotOn(slot, midi); } +JNI_FN(void, nativeAuditionSlotOff)(JNIEnv *, jobject, jint midi) { H->auditionSlotOff(midi); } +JNI_FN(void, nativeBusNoteOn)(JNIEnv *, jobject, jint ch, jint midi, jint vel) { H->busNoteOn(ch, midi, vel); } +JNI_FN(void, nativeBusNoteOff)(JNIEnv *, jobject, jint ch, jint midi) { H->busNoteOff(ch, midi); } +JNI_FN(jstring, nativeDescribeBusTargets)(JNIEnv *env, jobject, jint ch, jint midi) { + EngineHost *h = host(); + return env->NewStringUTF(h ? h->describeBusTargets(ch, midi).c_str() : ""); +} + +JNI_FN(jfloat, nativeChannelMeter)(JNIEnv *, jobject, jint ch) { EngineHost *h = host(); return h ? h->channelMeter(ch) : 0.f; } +JNI_FN(jboolean, nativeChannelClipped)(JNIEnv *, jobject, jint ch) { EngineHost *h = host(); return h && h->channelClipped(ch); } +JNI_FN(jint, nativeEffectScope)(JNIEnv *env, jobject, jint slot, jfloatArray out) { + EngineHost *h = host(); + if (!h || !out) return -1; + const jsize cap = env->GetArrayLength(out); + jfloat *buf = env->GetFloatArrayElements(out, nullptr); + const int n = h->effectScope(slot, buf, cap); + env->ReleaseFloatArrayElements(out, buf, 0); + return n; +} +JNI_FN(jfloat, nativeEffectPlayhead)(JNIEnv *, jobject, jint slot) { EngineHost *h = host(); return h ? h->effectPlayhead(slot) : -1.f; } + +JNI_FN(void, nativeSetMidiOutEnabled)(JNIEnv *, jobject, jboolean on) { H->setMidiOutEnabled(on); } +JNI_FN(jint, nativePollMidiOut)(JNIEnv *, jobject) { EngineHost *h = host(); return h ? h->pollMidiOut() : -1; } + +JNI_FN(void, nativePutSample)(JNIEnv *env, jobject, jstring id, jfloatArray data, jint rate, jint loopStart, jint loopEnd) { + EngineHost *h = host(); + if (!h || !data) return; + const jsize n = env->GetArrayLength(data); + std::vector v((size_t)n); + env->GetFloatArrayRegion(data, 0, n, v.data()); + h->putSample(str(env, id), sizzle::Sample(std::move(v), rate, loopStart, loopEnd)); +} +JNI_FN(void, nativeRemoveSample)(JNIEnv *env, jobject, jstring id) { H->removeSample(str(env, id)); } + +JNI_FN(void, nativeSetRecordPath)(JNIEnv *env, jobject, jstring path) { H->recorder().setPath(str(env, path)); } +JNI_FN(void, nativeSetRecordingArm)(JNIEnv *, jobject, jboolean armed, jint tail) { H->setRecordingArm(armed, tail); } +JNI_FN(void, nativeSetRecordTailBars)(JNIEnv *, jobject, jint tail) { H->setRecordTailBars(tail); } +JNI_FN(jboolean, nativeRecordingActive)(JNIEnv *, jobject) { EngineHost *h = host(); return h && h->recorder().isActive(); } +/** "\t" of a take that finished since the last call (path empty + * when writing failed), or null. */ +JNI_FN(jstring, nativeTakeFinished)(JNIEnv *env, jobject) { + std::lock_guard g(g_takeLock); + if (!g_takeReady) return nullptr; + g_takeReady = false; + return env->NewStringUTF((std::to_string(g_takeStart) + "\t" + g_takePath).c_str()); +} +/** Shutting down: finish a take being captured so its file is complete. */ +JNI_FN(void, nativeEndCapture)(JNIEnv *, jobject) { H->recorder().endCapture(); } +JNI_FN(void, nativeExternalClockStart)(JNIEnv *, jobject) { H->externalClockStart(); } +JNI_FN(void, nativeExternalClockStop)(JNIEnv *, jobject) { H->externalClockStop(); } + +/** The AudioTrack fallback's render: [frames] interleaved stereo frames into [out]. */ +JNI_FN(void, nativeRender)(JNIEnv *env, jobject, jfloatArray out, jint frames) { + EngineHost *h = host(); + jfloat *buf = env->GetFloatArrayElements(out, nullptr); + if (h) h->render(buf, frames); + else for (jint i = 0; i < frames * 2; ++i) buf[i] = 0.f; + env->ReleaseFloatArrayElements(out, buf, 0); +} diff --git a/app/src/main/cpp/native_audio.cpp b/app/src/main/cpp/native_audio.cpp index e8ec65a..ec7c358 100644 --- a/app/src/main/cpp/native_audio.cpp +++ b/app/src/main/cpp/native_audio.cpp @@ -3,11 +3,12 @@ // Native Oboe (AAudio) output backend for Sizzletracker. // -// Opens a low-latency mono float Oboe output stream. On each real-time data -// callback it calls back into Kotlin (NativeAudioBridge.renderAudio) to fill a -// reused Java float[] from the shared AudioEngine.fillBlock, then copies that -// into Oboe's output buffer. This keeps ONE implementation of the synth/mixer -// (in Kotlin) while delivering audio through the lower-latency native path. +// Opens a low-latency stereo float Oboe output stream. Each real-time data +// callback renders straight from the shared C++ engine (core/, through the +// EngineHost that jni_engine.cpp owns): no JVM call on the audio thread, so no +// garbage-collector pause can glitch it. + +#include "host/EngineHost.hpp" #include #include @@ -25,13 +26,11 @@ #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) +// The engine host (jni_engine.cpp); null until the app creates it. +sizzle::host::EngineHost *sizzleHost(); + namespace { -JavaVM *g_vm = nullptr; -jobject g_callback = nullptr; // global ref to the NativeAudioBridge -jmethodID g_renderMethod = nullptr; -jfloatArray g_buffer = nullptr; // reused Java float[] of g_frames length -int g_frames = 0; int32_t g_prevXRuns = 0; // last-seen underrun count, for adaptive sizing int32_t g_sampleRate = 48000; // remembered so the stream can be reopened on disconnect std::atomic g_wantRunning{false}; // false once nativeStop is called, so a @@ -39,21 +38,9 @@ std::atomic g_wantRunning{false}; // false once nativeStop is called, so a // the app deliberately shut down // How glitch-resistant the output buffer starts (in device bursts). The buffer -// then grows adaptively (see onAudioReady) if underruns still occur. Profiling -// showed the JVM render is fast on average (<1 ms) but spikes to 3-7 ms when a GC -// pause freezes the callback thread; 4 bursts (~8 ms on a 96-frame device) absorbs -// those from the first note instead of glitching until adaptive growth catches up. +// then grows adaptively (see onAudioReady) if underruns still occur. (Sized when +// the render went through the JVM and its GC pauses; kept, the cost is latency only.) constexpr int32_t kInitialBursts = 8; -constexpr int32_t kMaxBufferFrames = 8192; // cap for the reused Java buffer - -// Fetch a JNIEnv for the (persistent) audio callback thread, attaching once. -JNIEnv *callbackEnv() { - JNIEnv *env = nullptr; - if (g_vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) == JNI_EDETACHED) { - g_vm->AttachCurrentThread(&env, nullptr); - } - return env; -} class SizzleCallback : public oboe::AudioStreamDataCallback { public: @@ -76,19 +63,8 @@ public: stream->getBufferSizeInFrames() + stream->getFramesPerBurst()); } - JNIEnv *env = callbackEnv(); - if (!env || !g_callback || !g_renderMethod || !g_buffer) { - for (int i = 0; i < numFrames * 2; ++i) out[i] = 0.0f; // stereo silence - return oboe::DataCallbackResult::Continue; - } - const int n = numFrames < g_frames ? numFrames : g_frames; - // Ask Kotlin to render n frames; fillBlock writes 2*n interleaved-stereo - // samples into the reused Java buffer ... - env->CallVoidMethod(g_callback, g_renderMethod, g_buffer, n); - // ... then copy them out to Oboe (2 samples/frame) and pad any remainder with - // silence (the Java buffer is sized to the stream capacity, so rare). - env->GetFloatArrayRegion(g_buffer, 0, n * 2, out); - for (int i = n * 2; i < numFrames * 2; ++i) out[i] = 0.0f; + if (sizzle::host::EngineHost *host = sizzleHost()) host->render(out, numFrames); + else for (int i = 0; i < numFrames * 2; ++i) out[i] = 0.0f; // stereo silence // Adaptive buffer sizing (timing path): a callback that renders slower than // its deadline will drain the buffer; a couple in a row means we're about to @@ -174,7 +150,7 @@ public: SizzleErrorCallback g_errorCallback; // Opens, buffers and starts the low-latency output stream. Used both at initial -// start and to recover from a disconnect. Reuses the already-allocated g_buffer. +// start and to recover from a disconnect. bool openAndStartStream() { oboe::AudioStreamBuilder builder; builder.setDirection(oboe::Direction::Output) @@ -200,56 +176,30 @@ bool openAndStartStream() { g_stream.reset(); return false; } - LOGI("Oboe stream started (%d Hz, burst=%d, bufferSize=%d, capacity=%d, javaBuf=%d)", + LOGI("Oboe stream started (%d Hz, burst=%d, bufferSize=%d, capacity=%d)", g_sampleRate, burst, g_stream->getBufferSizeInFrames(), - g_stream->getBufferCapacityInFrames(), g_frames); + g_stream->getBufferCapacityInFrames()); return true; } } // namespace -extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void * /*reserved*/) { - g_vm = vm; - return JNI_VERSION_1_6; -} - extern "C" JNIEXPORT jboolean JNICALL Java_cc_tiredsysadmin_android_sizzle_audio_NativeAudioBridge_nativeStart( - JNIEnv *env, jobject /*thiz*/, jobject callback, jint sampleRate, jint framesPerCallback) { - g_callback = env->NewGlobalRef(callback); - jclass cls = env->GetObjectClass(callback); - g_renderMethod = env->GetMethodID(cls, "renderAudio", "([FI)V"); + JNIEnv * /*env*/, jobject /*thiz*/, jint sampleRate) { g_prevXRuns = 0; g_sampleRate = sampleRate; g_wantRunning = true; - - // Allocate the reused Java render buffer up front, sized to our maximum callback, - // so the stream can be transparently reopened on a disconnect without touching - // JNI from Oboe's (non-Java) error thread. The data callback only ever renders - // min(numFrames, g_frames) frames, and low-latency bursts are far smaller. - g_frames = kMaxBufferFrames; - if (g_frames < framesPerCallback) g_frames = framesPerCallback; - // Interleaved stereo: 2 samples per frame. - g_buffer = static_cast(env->NewGlobalRef(env->NewFloatArray(g_frames * 2))); - - if (!openAndStartStream()) { - env->DeleteGlobalRef(g_buffer); - g_buffer = nullptr; - return JNI_FALSE; - } - return JNI_TRUE; + return openAndStartStream() ? JNI_TRUE : JNI_FALSE; } extern "C" JNIEXPORT void JNICALL Java_cc_tiredsysadmin_android_sizzle_audio_NativeAudioBridge_nativeStop( - JNIEnv *env, jobject /*thiz*/) { + JNIEnv * /*env*/, jobject /*thiz*/) { g_wantRunning = false; // stop the disconnect-recovery from reopening if (g_stream) { g_stream->stop(); g_stream->close(); g_stream.reset(); } - if (g_buffer) { env->DeleteGlobalRef(g_buffer); g_buffer = nullptr; } - if (g_callback) { env->DeleteGlobalRef(g_callback); g_callback = nullptr; } - g_renderMethod = nullptr; } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt index a9a6f76..3e81670 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt @@ -199,7 +199,7 @@ class SizzleApp : Application() { if (MidiTrace.on && audioEngine.recordArmed) MidiTrace.log("clock ${if (start) "Start: armed recording starts" else "Stop: recording ends after its tail"}") main.post { if (start) audioEngine.externalClockStart() else audioEngine.externalClockStop() } } - midiClock.onReceiveTempo = { bpm -> main.post { project.tempoBpm = bpm.coerceIn(20f, 300f) } } + midiClock.onReceiveTempo = { bpm -> main.post { project.tempoBpm = bpm.coerceIn(20f, 300f); audioEngine.requestSync() } } val s = runBlocking { settingsStore.load() } midiClock.sendEnabled = s.sendMidiClock audioEngine.midiOutEnabled = s.sendMidiClock diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt index 349d2a7..0664909 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt @@ -6,472 +6,212 @@ package cc.tiredsysadmin.android.sizzle.audio import android.media.AudioAttributes import android.media.AudioFormat import android.media.AudioTrack -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.wavetable.WavePatch -import cc.tiredsysadmin.android.sizzle.model.Arrangement -import cc.tiredsysadmin.android.sizzle.model.Pattern +import android.os.Handler +import android.os.Looper +import cc.tiredsysadmin.android.sizzle.io.ProjectIo import cc.tiredsysadmin.android.sizzle.model.Project -import cc.tiredsysadmin.android.sizzle.model.SamplerPads -import cc.tiredsysadmin.android.sizzle.model.TimeDivision -import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot -import cc.tiredsysadmin.android.sizzle.model.ToolboxType import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlin.concurrent.thread -import kotlin.math.abs -import kotlin.math.max -import kotlin.math.sin -import kotlin.math.tanh /** - * The real-time sound engine. It owns one [AudioTrack] and a dedicated render - * thread that is completely separate from the UI thread — this is what keeps - * playback smooth while the interface is being touched. + * The app's sound engine: the shared C++ engine in core/ (the one the iOS app + * runs: sequencer, arrangement, mixer, FX chains, every instrument and effect, + * master limiter), driven through [NativeEngine]. Audio leaves through Oboe + * ([NativeAudioBridge]), rendered entirely in native code. * - * The render loop is a classic tracker "sample-accurate sequencer": it counts - * audio samples and, exactly when enough samples have elapsed for one tracker - * line, it advances the playhead and triggers that line's notes. Because timing - * is derived from the audio clock (not `Handler.postDelayed`), there is no drift. + * The Kotlin [Project] stays the UI's state. The engine plays its own copy, kept + * equal by [requestSync] (after every edit, coalesced to one per main-loop turn), + * a check every half second for edits that didn't ask, and a sync before every + * transport or routing call. A sync sends the project text and the engine applies + * only what changed, so playback carries on through edits. * - * PLAYBACK MODES - * -------------- - * - ARRANGEMENT mode (default when the arrangement has any blocks): the - * sequencer walks a pre-expanded playlist of beats (with A/B loop repeats), - * and at each beat every filled lane plays one beat of its pattern. A lane - * keeps its own cursor so a block spanning several consecutive beats advances - * through the pattern beat-by-beat. - * - PATTERN-LOOP mode (when the arrangement is empty): the currently-edited - * pattern loops, so the Tracker tab is always audible while you edit. - * - * Voices are pooled PER MIXER BUS: each of the [TRACK_COUNT] buses owns a pool of - * [POLYPHONY] synth + [POLYPHONY] sample voices, so a single instrument can sound - * up to [POLYPHONY] notes at once (chords, overlapping release tails) rather than - * one. Notes are allocated round-robin, stealing the oldest voice when the pool is - * full — the requested "N sounds per instrument" cap. - * - * INSTRUMENTS: the subtractive [SynthVoice] (NES synth), the Sampler and the - * SoundFont are all rendered here. Each bus pool has both [SynthVoice]s and - * [SampleVoice]s; the channel's instrument type decides which one a note triggers. - * Each mixer channel runs its own insert-effect chain (delay / filter / reverb / - * bitcrusher / EQ) — see [Effects.kt] and [rebuildFxChains]. Swapping this - * Kotlin/AudioTrack loop for an Oboe (C++/AAudio) engine is a later milestone. + * The Kotlin engine this replaced lives on in the tests as ReferenceEngine, the + * reference the C++ is checked against. */ class AudioEngine( private val sampleRate: Int = 48_000, ) { - // Sequencer voices: a per-mixer-bus pool of POLYPHONY synth + POLYPHONY sample - // voices, laid out as bus*POLYPHONY + i. A note plays whatever instrument its - // channel routes to, allocated from that bus's pool, so one instrument can sound - // several notes simultaneously instead of stealing its single voice every time. - private val seqVoices = Array(Pattern.TRACK_COUNT * POLYPHONY) { SynthVoice(sampleRate) } - private val sampleVoices = Array(Pattern.TRACK_COUNT * POLYPHONY) { SampleVoice(sampleRate) } - // Round-robin steal cursors per bus (which pool slot to reuse when all are busy). - private val synthAlloc = IntArray(Pattern.TRACK_COUNT) - private val sampleAlloc = IntArray(Pattern.TRACK_COUNT) - // ... plus a small pool for live auditioning from keyboard / MIDI / pads. - private val liveVoices = Array(LIVE_POLYPHONY) { SynthVoice(sampleRate) } - // Sample voices for previewing sampler instruments (toolbox keyboard / editor). - private val auditionSampleVoices = Array(AUDITION_POLYPHONY) { SampleVoice(sampleRate) } - // Live "mix bus" audition voices: polyphony per mixer channel, laid out as - // channel*BUS_POLYPHONY + i. Rendered INTO the channel sum (pre-FX) so playing - // one auditions the whole bus — the channel's instrument through its FX chain, - // volume, and mute/solo. Driven by the toolbox MIDI piano via busNoteOn/Off. - private val busVoices = Array(Pattern.TRACK_COUNT * BUS_POLYPHONY) { SynthVoice(sampleRate) } - private val busSampleVoices = Array(Pattern.TRACK_COUNT * BUS_POLYPHONY) { SampleVoice(sampleRate) } - // Per-(lane,track) arpeggiator state, driven by advanceArps. - private val arps = Array(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { ChannelArp() } - // Bumped once per triggered line. Notes reaching an arpeggiator with the same - // stamp are the same line's chord (accumulated into one arp); a new stamp starts - // a fresh chord. Lets a held chord arpeggiate all its notes instead of collapsing - // to the last one entered. Audio-thread only. - private var lineTriggerGen = 0 - // Per-(lane,track) MIDI channel the track last played a note on. A note-off cell - // is tied to its track (it has no channel of its own) and releases whatever the - // track last started, on the bus(es) that channel routed to. -1 = nothing yet. - private val trackLastChannel = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { -1 } + private val main = Handler(Looper.getMainLooper()) + private var project: Project? = null + private var lastText: String? = null + private var syncPending = false - // ---- outgoing MIDI (send the sequenced notes to external gear) ---- - // The sequencer runs on the audio thread, which must not do MIDI I/O; note events - // are packed into a lock-free single-producer/single-consumer ring that the MIDI - // clock thread drains via [pollMidiOut]. Only filled when [midiOutEnabled]. Each - // slot packs (status<<16)|(data1<<8)|data2. Note-on/off mirror the tracks' cells - // (mono per track, matching the internal note lifecycle) on the cell's MIDI channel. - @Volatile var midiOutEnabled = false - private val moutRing = IntArray(256) - @Volatile private var moutHead = 0 // producer (audio thread) - @Volatile private var moutTail = 0 // consumer (MIDI clock thread) - private val moutNote = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { -1 } - private val moutCh = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) - - // Grain Cloud (ECHOFIELD port): one shared cloud per mixer channel, held notes - // pitch its grains; plus one for the editor's audition keyboard. A cloud renders - // only while its channel's instrument is a Grain Cloud (cloudOn). - private val clouds = Array(Pattern.TRACK_COUNT) { GrainCloud(sampleRate) } - private val cloudOn = BooleanArray(Pattern.TRACK_COUNT) - private val cloudVer = IntArray(Pattern.TRACK_COUNT) { -1 } - private val cloudTempo = FloatArray(Pattern.TRACK_COUNT) { Float.NaN } - private val auditionCloud = GrainCloud(sampleRate) - private var auditionCloudVer = -1 - private var auditionCloudTempo = Float.NaN - private var auditionCloudActive = false - - // Cached subtractive-synth patch per bus, reparsed only when the slot changes - // (version) or tempo changes — so note triggers don't allocate a patch each time, - // and active voices can be refreshed per block for live parameter feedback. - private val synthPatch = arrayOfNulls(Pattern.TRACK_COUNT) - private val synthPatchVer = IntArray(Pattern.TRACK_COUNT) { -1 } - private val synthPatchTempo = FloatArray(Pattern.TRACK_COUNT) { Float.NaN } - // Same, for the toolbox editor's audition (liveVoices) — tracks the slot currently - // being auditioned so live knob turns are heard while a preview note is held. - private var auditionSlotIdx = -1 - private var auditionPatch: SynthPatch? = null - private var auditionPatchVer = -1 - private var auditionPatchTempo = Float.NaN - - /** Grab a free synth voice from [bus]'s pool, or steal the round-robin one. The - * chosen voice is queued into this block's active list so a note started mid-block - * is rendered from the same sample (see [queueSeq]). */ - private fun allocSynthVoice(bus: Int): SynthVoice { - val base = bus * POLYPHONY - for (i in 0 until POLYPHONY) seqVoices[base + i].let { if (!it.isActive) { queueSeq(base + i); return it } } - val idx = synthAlloc[bus] - synthAlloc[bus] = (idx + 1) % POLYPHONY - return seqVoices[base + idx].also { it.kill(); queueSeq(base + idx) } - } - - /** Grab a free sample voice from [bus]'s pool, or steal the round-robin one. - * The stolen voice is NOT killed here — [SampleVoice.noteOn] declicks the hand-off - * itself (an abrupt kill of a loud voice would click). */ - private fun allocSampleVoice(bus: Int): SampleVoice { - val base = bus * POLYPHONY - for (i in 0 until POLYPHONY) sampleVoices[base + i].let { if (!it.isActive) { queueSmp(base + i); return it } } - val idx = sampleAlloc[bus] - sampleAlloc[bus] = (idx + 1) % POLYPHONY - return sampleVoices[base + idx].also { queueSmp(base + idx) } - } - - /** Append a sequencer synth/sample voice index to this block's active list, unless - * it is already queued this block (generation stamp) — dedup prevents a finished- - * then-reallocated voice from being rendered twice in one block. Audio-thread only - * (called from [playNote] via the allocators, all inside [fillBlock]). */ - private fun queueSeq(i: Int) { if (seqGen[i] != blockGen) { seqGen[i] = blockGen; actSeq[actSeqN++] = i } } - private fun queueSmp(i: Int) { if (smpGen[i] != blockGen) { smpGen[i] = blockGen; actSmp[actSmpN++] = i } } - - /** Release (fade out) every active voice on [bus] — a note-off cell on its channel. */ - private fun releaseBus(bus: Int) { - clouds[bus].releaseSequenced() - val base = bus * POLYPHONY - for (i in 0 until POLYPHONY) { - seqVoices[base + i].noteOff() - sampleVoices[base + i].noteOff() - } - } - - /** One insert-effect instance bound to the toolbox slot that configures it. */ - private class FxUnit(val slot: ToolboxSlot, val effect: AudioEffect) { - // Last slot version / tempo pushed into the effect, so [updateFxParams] can - // skip re-parsing params (which allocates) when nothing changed. - var lastVersion = -1 - var lastTempo = Float.NaN - } - - /** Per-channel effect chains (mixer FX slots resolved to real processors). - * Rebuilt when routing changes; parameters refresh live every block. Stored as - * arrays (not lists) because the audio thread iterates them per sample, and a - * `for (u in list)` allocates an Iterator every time — a per-block heap churn - * that caused GC-pause dropouts. Array for-loops allocate nothing. Each rebuild - * swaps in a fresh array (reference assignment is atomic), like [playlist]. */ - @Volatile private var channelChains: Array> = - Array(Pattern.TRACK_COUNT) { emptyArray() } - - /** Scratch buffer: per-channel sum for one sample (audio-thread only). */ - private val channelSum = FloatArray(Pattern.TRACK_COUNT) - - // ---- master brickwall limiter (feed-forward, look-ahead) ---- - // A short delay line lets the peak detector "see" a loud sample coming and pull - // the gain down BEFORE it reaches the output, so the makeup gain below can be - // pushed hard (bringing quiet instruments up to media loudness) while the output - // is mathematically guaranteed to stay under LIM_CEILING — no clipping, and none - // of the tanh saturation a static soft-clipper would add to a hot single voice. - // Gain has instant attack (drops the moment a peak enters the look-ahead window), - // holds for the window length, then releases smoothly toward unity. Audio-thread - // state only. - private val limDelayL = FloatArray(LIM_LOOKAHEAD) - private val limDelayR = FloatArray(LIM_LOOKAHEAD) - private var limPos = 0 - private var limGain = 1f - private var limHold = 0 - // Limiter output for the current sample (avoids a per-sample Pair allocation). - private var limOutL = 0f - private var limOutR = 0f - - // ---- per-channel VU metering (for the mixer strips' fader VU) ---- - // The audio thread tracks each bus's post-fader/post-FX peak within a block, then - // once per block folds it into a smoothly-decaying meter value (instant attack, - // exponential release) and a clip-hold counter (latched when the bus crosses 0 dBFS - // so a brief overload stays visible). The UI polls [channelMeter]/[channelClipped] - // at frame rate. Plain arrays: single writer (audio thread), display-only readers — - // a stale value for one frame is harmless, so no locking/volatility is needed. - private val chBlockPeak = FloatArray(Pattern.TRACK_COUNT) // scratch, reset each block - private val chMeter = FloatArray(Pattern.TRACK_COUNT) // published decaying peak - private val chClipHold = IntArray(Pattern.TRACK_COUNT) // blocks left to show "clipping" - - // Per-block compact active-voice lists (audio-thread only). Rebuilt once per block: - // the per-sample mix loop iterates ONLY the voices that are actually sounding, so it - // never calls render() on idle pool slots (the whole POLYPHONY*TRACK_COUNT pool was - // scanned every sample before). Each list holds global voice indices; the bus for a - // seq/sample/bus voice is index / POLYPHONY (or / BUS_POLYPHONY). - private val actSeq = IntArray(seqVoices.size); private var actSeqN = 0 - private val actSmp = IntArray(sampleVoices.size); private var actSmpN = 0 - private val actBus = IntArray(busVoices.size); private var actBusN = 0 - private val actBSmp = IntArray(busSampleVoices.size); private var actBSmpN = 0 - private val actLive = IntArray(liveVoices.size); private var actLiveN = 0 - private val actASmp = IntArray(auditionSampleVoices.size); private var actASmpN = 0 - // The sequencer can start a note mid-block; its voice must join this block's list so - // it sounds sample-accurately (not one block late). [queueSeq]/[queueSmp] append it, - // deduped by a per-voice generation stamp: a voice already queued this block (stamp - // == [blockGen]) is not added twice — which would otherwise double-render (and - // double the amplitude of) a voice that finished and was re-allocated within a block. - private val seqGen = IntArray(seqVoices.size) - private val smpGen = IntArray(sampleVoices.size) - private var blockGen = 0 - - /** The song being played. Swapped atomically; read on the audio thread. */ - @Volatile private var project: Project? = null - - @Volatile private var playing = false - @Volatile private var running = false - - // ---- Shared position state (audio-thread only) ---- - private var samplesIntoLine = 0.0 - private var pendingTrigger = true - /** Samples per tracker line, refreshed once per block (see [fillBlock]). */ - private var blockSamplesPerLine = 1.0 - - // ---- Pattern-loop mode ---- - private var currentLine = 0 - - // ---- Arrangement mode ---- - private var arrangementMode = false - /** Beat indices to play, in order, with A/B repeats already expanded. Volatile - * and only ever swapped as a whole reference, so it can be rebuilt live from - * the main thread (e.g. a repeat-count change) while the audio thread reads a - * consistent snapshot — see [refreshLoopPlaylist] and [advanceArrangement]. */ - @Volatile private var playlist: IntArray = IntArray(0) - private var playlistIndex = 0 - private var lineInBeat = 0 - /** Local tick of the *edited* block at the current beat, for the tracker - * playhead. Updated as that block sounds; retained when it isn't. */ - private var arrPlayLine = 0 - - private val _transport = MutableStateFlow(TransportState()) - val transport: StateFlow = _transport - - private var renderThread: Thread? = null - private var track: AudioTrack? = null - - // ------------------------------------------------ master-bus recording - // Captures the final mixed output (post limiter) to a WAV file. Recording is - // "armed" from the mixer toolbar and actually begins when playback starts; it - // ends automatically a configurable FX-tail (in bars) after the sequencer - // stops — whether that stop is a pause/stop button or the arrangement reaching - // its end with looping off. - private val masterRecorder = MasterRecorder(sampleRate) - - /** Directory for the staging temp WAV (the app's cache dir); set at startup. */ - var recTempDir: java.io.File? = null - - /** Invoked (on the writer thread) with the finished temp WAV and the recording's - * start epoch-millis when a take finalizes. The app copies it to its destination. */ - var onRecordingComplete: ((java.io.File, Long) -> Unit)? = null - - /** Invoked (on the main thread, from [play]) the moment a take starts capturing. */ - var onRecordingStarted: (() -> Unit)? = null - - @Volatile var recordArmed = false; private set - @Volatile private var recTailBars = 0 - - /** Arm/disarm recording and set the FX-tail length (bars) captured after a stop. */ - fun setRecordingArm(armed: Boolean, tailBars: Int) { - recordArmed = armed - recTailBars = tailBars.coerceIn(0, 8) - } - - /** Update just the FX-tail length (bars) captured after the sequencer stops. */ - fun setRecordTailBars(tailBars: Int) { recTailBars = tailBars.coerceIn(0, 8) } - - // Audio-thread recording state machine (see [recordSample]). Initialized in - // [maybeStartRecording] before the volatile [recCapturing] flag publishes them. - @Volatile private var recCapturing = false - /** An external MIDI clock is running (between its Start and Stop): an armed - * recording captures while either it or the sequencer runs, and its tail starts - * when both have stopped. */ - @Volatile private var extClockRunning = false - private var recWasPlaying = false - private var recTailRemaining = 0 - - /** If armed and a destination temp dir is set, start capturing the master bus. */ - private fun maybeStartRecording() { - if (!recordArmed) return - val dir = recTempDir ?: return - if (masterRecorder.isActive) return // already recording (e.g. replay in the tail) - val temp = java.io.File(dir, "master-rec.wav") - val startMs = System.currentTimeMillis() - val cb = onRecordingComplete - val ok = masterRecorder.begin(temp) { f -> if (f != null) cb?.invoke(f, startMs) } - if (!ok) return - recTailRemaining = -1 - recWasPlaying = true - recCapturing = true // volatile store publishes the two fields above to the audio thread - onRecordingStarted?.invoke() - } - - /** - * Audio thread: feed one master sample to the recorder and run the stop/tail - * state machine. While the sequencer plays, samples stream straight through. On - * the play->stop edge we latch a tail countdown (bars -> samples at the current - * tempo/signature); the recorder keeps capturing the ringing FX/voice tail until - * it elapses, then finalizes the file. Voices and insert FX render every sample - * regardless of [playing], so the tail contains real decaying reverb/delay audio. - */ - private fun recordSample(proj: Project?, left: Float, right: Float) { - val nowPlaying = playing || extClockRunning - if (recWasPlaying && !nowPlaying) { - recTailRemaining = if (proj == null) 0 - else (recTailBars * proj.timeSignature.linesPerBar * samplesPerLine(proj)).toInt() - } - recWasPlaying = nowPlaying - masterRecorder.write(left, right) - if (!nowPlaying) { - if (recTailRemaining <= 0) { - recCapturing = false - masterRecorder.endCapture() - } else { - recTailRemaining-- - } - } - } - - /** An external MIDI clock sent Start (or Continue): start an armed recording, even - * while Sizzle's own sequencer stays stopped (sound-module mode). */ - fun externalClockStart() { - extClockRunning = true - maybeStartRecording() - } - - /** The external clock sent Stop: an armed recording ends after its FX tail (once - * Sizzle's own sequencer isn't playing either). */ - fun externalClockStop() { extClockRunning = false } + init { NativeEngine.create(sampleRate) } + // ---------------------------------------------------------------- song sync fun setProject(p: Project) { project = p + val text = ProjectIo.save(p) + lastText = text + if (NativeEngine.created) NativeEngine.nativeLoad(text) rebuildArrangement() rebuildFxChains() } - /** - * Resolve each mixer channel's four FX slots into real effect processors. - * Call from the main thread (from [play], [setProject], or after the user - * changes a channel's FX routing). Effect *parameters* update live every - * block, so only add/remove of an effect needs a rebuild. - */ - fun rebuildFxChains() { - val proj = project ?: return - val next = Array(Pattern.TRACK_COUNT) { emptyArray() } - for (ch in 0 until Pattern.TRACK_COUNT) { - val units = ArrayList(proj.mixer.channels[ch].fxSlots.size) - for (slotIndex in proj.mixer.channels[ch].fxSlots) { - if (slotIndex < 0) continue - val slot = proj.toolbox.getOrNull(slotIndex) ?: continue - val type = slot.type ?: continue - AudioEffect.create(type, sampleRate)?.let { fx -> - units.add(FxUnit(slot, fx)) - } + /** The Kotlin project changed: bring the engine's copy up to date soon (once per + * main-loop turn however many edits arrive). Any thread. */ + fun requestSync() { + main.post { + if (syncPending) return@post + syncPending = true + main.post { syncPending = false; syncNow() } + } + } + + /** Bring the engine's copy up to date now (main thread; cheap when unchanged). */ + fun syncNow() { + if (Looper.myLooper() != Looper.getMainLooper()) { requestSync(); return } + val p = project ?: return + val text = ProjectIo.save(p) + if (text == lastText) return + lastText = text + if (NativeEngine.created) NativeEngine.nativeSync(text) + } + + private val safetyNet = object : Runnable { + override fun run() { + if (!running) return + syncNow() + main.postDelayed(this, 500) + } + } + + /** Re-resolve each channel's FX slots (routing changed). Main thread. */ + fun rebuildFxChains() { syncNow(); if (NativeEngine.created) NativeEngine.nativeRebuildFxChains() } + + /** Rebuild the arrangement playlist and reset the position. Main thread. */ + fun rebuildArrangement() { syncNow(); if (NativeEngine.created) NativeEngine.nativeRebuildArrangement() } + + /** Rebuild the playlist (loop region edits) without moving the position. Main thread. */ + fun refreshLoopPlaylist() { syncNow(); if (NativeEngine.created) NativeEngine.nativeRefreshLoopPlaylist() } + + // ---------------------------------------------------------------- transport + private val _transport = MutableStateFlow(TransportState()) + val transport: StateFlow = _transport + + /** Start playback, optionally from [startBeat] (see Engine::play). */ + fun play(startBeat: Int = -1) { syncNow(); if (NativeEngine.created) NativeEngine.nativePlay(startBeat); publish() } + fun pause() { if (NativeEngine.created) NativeEngine.nativePause(); publish() } + /** MIDI panic: hard-silence every voice and cancel the arpeggiators. */ + fun panic() { if (NativeEngine.created) NativeEngine.nativePanic(); publish() } + /** Stop; if already stopped, rewind to the top. */ + fun stop() { if (NativeEngine.created) NativeEngine.nativeStop(); publish() } + + private fun publish() { + if (!NativeEngine.created) return + val t = NativeEngine.nativeTransport() + val state = TransportState( + isPlaying = (t ushr 62) and 1L == 1L, + currentLine = ((t ushr 31) and 0x7FFFFFFF).toInt(), + currentBeat = (t and 0x7FFFFFFF).toInt(), + ) + if (state != _transport.value) _transport.value = state + } + + // ---------------------------------------------------------------- live notes + fun liveNoteOn(pitch: Int, velocity: Int) { if (NativeEngine.created) NativeEngine.nativeLiveNoteOn(pitch, velocity) } + fun liveNoteOff(pitch: Int) { if (NativeEngine.created) NativeEngine.nativeLiveNoteOff(pitch) } + fun auditionSlotOn(slotIndex: Int, midi: Int) { if (NativeEngine.created) NativeEngine.nativeAuditionSlotOn(slotIndex, midi) } + fun auditionSlotOff(midi: Int) { if (NativeEngine.created) NativeEngine.nativeAuditionSlotOff(midi) } + fun busNoteOn(midiChannel: Int, midi: Int, velocity: Int) { + if (NativeEngine.created) NativeEngine.nativeBusNoteOn(midiChannel, midi, velocity) + } + fun busNoteOff(midiChannel: Int, midi: Int) { if (NativeEngine.created) NativeEngine.nativeBusNoteOff(midiChannel, midi) } + /** For a MIDI trace: what busNoteOn would play. */ + fun describeBusTargets(midiChannel: Int, midi: Int): String = + if (NativeEngine.created) NativeEngine.nativeDescribeBusTargets(midiChannel, midi) else "" + + // ---------------------------------------------------------------- display + fun channelMeter(ch: Int): Float = if (NativeEngine.created) NativeEngine.nativeChannelMeter(ch) else 0f + fun channelClipped(ch: Int): Boolean = NativeEngine.created && NativeEngine.nativeChannelClipped(ch) + /** Toolbox [slotIndex]'s live scope into [out] (oldest → newest); count, or -1. */ + fun effectScope(slotIndex: Int, out: FloatArray): Int = + if (NativeEngine.created) NativeEngine.nativeEffectScope(slotIndex, out) else -1 + fun effectPlayhead(slotIndex: Int): Float = + if (NativeEngine.created) NativeEngine.nativeEffectPlayhead(slotIndex) else -1f + + // ---------------------------------------------------------------- MIDI out + /** Queue the sequenced notes for [pollMidiOut] (MIDI clock send). */ + @Volatile var midiOutEnabled = false + set(value) { field = value; if (NativeEngine.created) NativeEngine.nativeSetMidiOutEnabled(value) } + + /** The next outgoing note, (status << 16) | (data1 << 8) | data2, or -1. */ + fun pollMidiOut(): Int = if (NativeEngine.created) NativeEngine.nativePollMidiOut() else -1 + + // ---------------------------------------------------------------- recording + /** Directory for the take being written (the app's cache dir); set at startup. */ + var recTempDir: java.io.File? = null + set(value) { + field = value + if (value != null && NativeEngine.created) { + NativeEngine.nativeSetRecordPath(java.io.File(value, "master-rec.wav").path) } - next[ch] = units.toTypedArray() } - channelChains = next // atomic swap; audio thread sees old or new whole array + + /** The finished take and its start in epoch millis (on a background thread). */ + var onRecordingComplete: ((java.io.File, Long) -> Unit)? = null + /** A take started capturing. */ + var onRecordingStarted: (() -> Unit)? = null + + @Volatile var recordArmed = false; private set + + /** Arm/disarm and set the FX tail (bars) captured after a stop. */ + fun setRecordingArm(armed: Boolean, tailBars: Int) { + recordArmed = armed + if (NativeEngine.created) NativeEngine.nativeSetRecordingArm(armed, tailBars.coerceIn(0, 8)) } - /** - * Recomputes the arrangement playlist and resets sequencer position. Call - * from the main thread (never the audio thread) — from [play] and whenever - * the arrangement or loop settings change. - */ - fun rebuildArrangement() { - val proj = project ?: return - val arr = proj.arrangement - arrangementMode = arr.slots.any { lane -> lane.any { it != Arrangement.EMPTY } } - playlist = buildPlaylist(arr) - playlistIndex = 0 - lineInBeat = 0 - arrPlayLine = 0 + fun setRecordTailBars(tailBars: Int) { + if (NativeEngine.created) NativeEngine.nativeSetRecordTailBars(tailBars.coerceIn(0, 8)) } - /** - * Rebuild the playlist in place from the current loop settings WITHOUT resetting - * the play position (index, cursors, sample counter). Call from the main thread - * after a live edit that only changes the beat sequence — e.g. a loop-region - * repeat-count change — so playback keeps rolling instead of restarting. - * - * The audio thread reads [playlist] as a single volatile snapshot and bounds- - * checks its own index, so swapping the array under it is safe: growing the - * loop appends future repeats seamlessly; shrinking it simply wraps to the loop - * start at the next beat boundary rather than jumping the transport. - */ - fun refreshLoopPlaylist() { - val proj = project ?: return - if (!arrangementMode) return // not looping the arrangement; nothing live to update - playlist = buildPlaylist(proj.arrangement) - } + /** An external MIDI clock's Start: an armed recording starts even with the song stopped. */ + fun externalClockStart() { if (NativeEngine.created) NativeEngine.nativeExternalClockStart() } + fun externalClockStop() { if (NativeEngine.created) NativeEngine.nativeExternalClockStop() } - /** Expand the arrangement (respecting loop + A/B regions) into a flat beat list. */ - private fun buildPlaylist(arr: Arrangement): IntArray { - val a = arr.regionA - val b = arr.regionB - // With no A/B loop regions in play, walk beats 0..last-filled — never out - // through the trailing empty beats of the canvas. Whether this stops or - // repeats is then decided by loopEnabled in advanceArrangement: loop off - // plays it once and stops after the last filled block; loop on repeats the - // filled span. Regions only take effect while looping (as before). - if (!arr.loopEnabled || (!a.isValid && !b.isValid)) { - val end = (arr.lastFilledBeat() + 1).coerceAtLeast(0) - return IntArray(end) { it } - } - val out = ArrayList() - if (a.isValid) repeat(a.repeats) { for (beat in a.start until a.end) out.add(beat) } - if (b.isValid) repeat(b.repeats) { for (beat in b.start until b.end) out.add(beat) } - return out.toIntArray() + private var wasRecording = false + + private fun pollRecording() { + val active = NativeEngine.nativeRecordingActive() + if (active && !wasRecording) onRecordingStarted?.invoke() + wasRecording = active + val done = NativeEngine.nativeTakeFinished() ?: return + val tab = done.indexOf('\t') + val start = done.substring(0, tab).toLongOrNull() ?: 0L + val path = done.substring(tab + 1) + val cb = onRecordingComplete ?: return + if (path.isNotEmpty()) thread(name = "sizzle-rec-save") { cb(java.io.File(path), start) } } // ---------------------------------------------------------------- lifecycle + @Volatile private var running = false private var nativeBridge: NativeAudioBridge? = null + private var poller: Thread? = null + private var renderThread: Thread? = null + private var track: AudioTrack? = null - /** Invoked (off the main thread) if the native Oboe backend can't initialise and - * the engine falls back to the AudioTrack loop, with a user-facing message. */ + /** Invoked (off the main thread) if the native Oboe backend can't start and the + * engine falls back to an AudioTrack loop, with a user-facing message. */ var onNativeInitError: ((String) -> Unit)? = null fun start() { if (running) return running = true - // The low-latency native (Oboe) backend is the default. Fall back to the - // Kotlin AudioTrack loop ONLY if it can't initialise — and report why. - if (NativeAudioBridge.isAvailable()) { - val bridge = NativeAudioBridge(this) - if (bridge.start(sampleRate, BLOCK_FRAMES)) { - nativeBridge = bridge - return + // Transport and recording state for the UI, ~100 times a second. + poller = thread(name = "sizzle-transport", isDaemon = true) { + while (running) { + if (NativeEngine.created) { publish(); pollRecording() } + Thread.sleep(10) } - onNativeInitError?.invoke( - "Low-latency audio (Oboe) failed to start — falling back to standard playback.", - ) + } + main.post(safetyNet) + if (NativeAudioBridge.isAvailable()) { + val bridge = NativeAudioBridge() + if (bridge.start(sampleRate)) { nativeBridge = bridge; return } + onNativeInitError?.invoke("Low-latency audio (Oboe) failed to start — falling back to standard playback.") } else { - onNativeInitError?.invoke( - "Low-latency audio (Oboe) is unavailable on this device — using standard playback.", - ) + onNativeInitError?.invoke("Low-latency audio (Oboe) is unavailable on this device — using standard playback.") } startAudioTrack() } @@ -479,8 +219,7 @@ class AudioEngine( private fun startAudioTrack() { val minBuf = AudioTrack.getMinBufferSize( sampleRate, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_FLOAT, - ).coerceAtLeast(BLOCK_FRAMES * 2 * 4 * 2) // stereo float, a couple of blocks - + ).coerceAtLeast(BLOCK_FRAMES * 2 * 4 * 2) track = AudioTrack.Builder() .setAudioAttributes( AudioAttributes.Builder() @@ -500,19 +239,21 @@ class AudioEngine( .setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY) .build() .also { it.play() } - - applyPreferredOutput() // route to the user-chosen USB/audio device, if any - + applyPreferredOutput() renderThread = thread(name = "sizzle-audio", priority = Thread.MAX_PRIORITY) { - audioTrackLoop() + val buf = FloatArray(BLOCK_FRAMES * 2) + while (running) { + if (NativeEngine.created) NativeEngine.nativeRender(buf, BLOCK_FRAMES) else buf.fill(0f) + track?.write(buf, 0, buf.size, AudioTrack.WRITE_BLOCKING) + } } } - // ---- USB / audio output device routing ---- + // ---- USB / audio output device routing (the AudioTrack fallback) ---- @Volatile private var preferredOutput: android.media.AudioDeviceInfo? = null - /** Route playback to a specific output device (e.g. a USB DAC), or null for - * the system default. Applied immediately and re-applied on engine restart. */ + /** Route playback to a specific output device (e.g. a USB DAC), or null for the + * system default. */ fun setPreferredOutput(device: android.media.AudioDeviceInfo?) { preferredOutput = device applyPreferredOutput() @@ -524,1161 +265,22 @@ class AudioEngine( } } - /** Stop the engine entirely (called from the PlaybackService on shutdown). */ + /** Stop the engine entirely (called when the last owner lets go). */ fun release() { running = false - // Finalize any in-flight recording so the WAV header gets patched and the - // completion callback fires instead of leaving a truncated temp file. - if (recCapturing) { recCapturing = false; masterRecorder.endCapture() } + main.removeCallbacks(safetyNet) + if (NativeEngine.created) { NativeEngine.nativeSetRecordingArm(false, 0); NativeEngine.nativeEndCapture() } nativeBridge?.stop() nativeBridge = null renderThread?.join(500) renderThread = null track?.run { stop(); release() } track = null + poller?.join(100) + poller = null } - // --------------------------------------------------------------- transport - /** - * Start playback. When [startBeat] is >= 0, seek to that beat in the arrangement - * (or that line in pattern-loop mode) so Play resumes from a marker the user - * placed on the arrangement, instead of always from the top. Ignored if it doesn't - * land inside the current playlist / pattern. - */ - fun play(startBeat: Int = -1) { - rebuildArrangement() - rebuildFxChains() - if (startBeat >= 0) { - if (arrangementMode) { - val list = playlist - // Find the first occurrence of that beat in the (possibly A/B-expanded) - // playlist; if it isn't in there just start from the top. - var seek = -1 - for (i in list.indices) if (list[i] == startBeat) { seek = i; break } - if (seek >= 0) { - playlistIndex = seek; lineInBeat = 0; arrPlayLine = 0; samplesIntoLine = 0.0 - } - } else { - val proj = project - if (proj != null) { - val pat = proj.activePattern() - val line = (startBeat * proj.timeSignature.linesPerBeat).coerceIn(0, pat.length - 1) - currentLine = line; samplesIntoLine = 0.0 - } - } - } - pendingTrigger = true - playing = true - maybeStartRecording() - publish() - } - - fun pause() { playing = false; extClockRunning = false; allSeqVoicesOff(); publish() } - - /** - * MIDI panic: immediately hard-silence every voice — sequencer, live (keyboard/ - * MIDI/gamepad), and audition — and cancel all arpeggiators. Clears stuck or - * hung notes at once (e.g. a MIDI note-on whose note-off never arrived). Does - * not stop the transport; if the sequencer is playing it resumes on the next - * tick. - */ - fun panic() { - clouds.forEach { it.kill() } - auditionCloud.kill() - seqVoices.forEach { it.kill() } - sampleVoices.forEach { it.kill() } - liveVoices.forEach { it.kill() } - auditionSampleVoices.forEach { it.kill() } - busVoices.forEach { it.kill() } - busSampleVoices.forEach { it.kill() } - arps.forEach { it.stop() } - trackLastChannel.fill(-1) - allMidiNotesOff() // release any notes sent to external gear - } - - /** Stop playback. If already stopped, rewind to the very beginning. */ - fun stop() { - extClockRunning = false // Sizzle's Stop also ends a take an external clock started - if (!playing && currentLine == 0 && playlistIndex == 0 && lineInBeat == 0) return - val wasStopped = !playing - playing = false - allSeqVoicesOff() - if (wasStopped) { - currentLine = 0; samplesIntoLine = 0.0 - playlistIndex = 0; lineInBeat = 0 - arrPlayLine = 0 - } - publish() - } - - // ------------------------------------------------------ live note audition - fun liveNoteOn(pitch: Int, velocity: Int) { - val v = liveVoices.firstOrNull { !it.isActive } ?: liveVoices[0].also { it.kill() } - v.noteOn(pitch, velocity, SynthPatch.DEFAULT) - } - - fun liveNoteOff(pitch: Int) { - // Prefer a held (gated) voice over one already releasing, so a fast retrigger - // of the same pitch never leaves the held voice stuck (see [auditionSlotOff]). - (liveVoices.firstOrNull { it.pitch == pitch && it.isGated } - ?: liveVoices.firstOrNull { it.isActive && it.pitch == pitch })?.noteOff() - } - - // ------------------------------------------------------------- render loop - /** The Kotlin AudioTrack fallback loop: fill a block and push it. */ - private fun audioTrackLoop() { - val block = FloatArray(BLOCK_FRAMES * 2) // interleaved stereo (L,R per frame) - while (running) { - val t = track ?: break - fillBlock(block, BLOCK_FRAMES) - t.write(block, 0, BLOCK_FRAMES * 2, AudioTrack.WRITE_BLOCKING) - } - } - - /** - * Render [frames] frames of the whole mix into [out] as INTERLEAVED STEREO — - * out[2*i] = left, out[2*i+1] = right, so [out] must hold at least frames*2 - * samples. This is the single source of truth for audio: it is called by the - * Kotlin AudioTrack loop AND by the native Oboe callback (via [NativeAudioBridge]), - * so both backends produce identical sound. Runs on an audio thread — must not - * allocate. Voices and inserts are mono, so both master channels carry the same - * sum; the output/recording path is nonetheless stereo (2 interleaved channels). - */ - fun fillBlock(out: FloatArray, frames: Int) { - val proj = project - FrasilClock.advance(frames, sampleRate) // the Morph Pad's shared TIDE runs on it - // Per-block param housekeeping: LFOs modulate targets first, then effects - // read their (possibly modulated) parameters. - if (proj != null) { - applyLfos(proj) - updateFxParams(proj) - refreshSynthPatches(proj) - // Tempo/signature only change at control rate, so derive the per-line - // sample count once per block instead of re-dividing every sample. - blockSamplesPerLine = samplesPerLine(proj) - } - val anySolo = proj?.mixer?.anySolo() ?: false - // Snapshot the volatile chains once so a concurrent rebuild can't swap them - // mid-block; indexing + array iteration below then allocate nothing. - val chains = channelChains - - // Once per block: collect the indices of the voices that are actually sounding - // into compact lists, so the per-sample loop iterates only those instead of the - // whole pool. Building the lists costs O(pool) once; rendering then costs - // O(active * frames) rather than O(pool * frames). The sequencer appends any - // note it starts mid-block via [queueSeq]/[queueSmp] (see [advanceSequencer]). - blockGen++ - actSeqN = 0; actSmpN = 0; actBusN = 0; actBSmpN = 0; actLiveN = 0; actASmpN = 0 - for (ch in 0 until Pattern.TRACK_COUNT) chBlockPeak[ch] = 0f // reset per-channel VU accumulators - for (i in seqVoices.indices) if (seqVoices[i].isActive) { seqGen[i] = blockGen; actSeq[actSeqN++] = i } - for (i in sampleVoices.indices) if (sampleVoices[i].isActive) { smpGen[i] = blockGen; actSmp[actSmpN++] = i } - for (i in busVoices.indices) if (busVoices[i].isActive) actBus[actBusN++] = i - for (i in busSampleVoices.indices) if (busSampleVoices[i].isActive) actBSmp[actBSmpN++] = i - for (i in liveVoices.indices) if (liveVoices[i].isActive) actLive[actLiveN++] = i - auditionCloudActive = auditionCloud.isActive - for (i in auditionSampleVoices.indices) if (auditionSampleVoices[i].isActive) actASmp[actASmpN++] = i - - for (i in 0 until frames) { - if (playing && proj != null) advanceSequencer(proj) - - var mixL = 0f - var mixR = 0f - if (proj != null) { - channelSum.fill(0f) - // Sum only the voices that are actually sounding this block. Each voice's - // bus is its index / pool stride. Live bus-audition voices feed the same - // per-channel sum, so they run through the channel's FX/volume/mute like - // the sequencer. - for (k in 0 until actSeqN) { val vi = actSeq[k]; channelSum[vi / POLYPHONY] += seqVoices[vi].render() } - for (k in 0 until actSmpN) { val vi = actSmp[k]; channelSum[vi / POLYPHONY] += sampleVoices[vi].render() } - for (k in 0 until actBusN) { val vi = actBus[k]; channelSum[vi / BUS_POLYPHONY] += busVoices[vi].render() } - for (k in 0 until actBSmpN) { val vi = actBSmp[k]; channelSum[vi / BUS_POLYPHONY] += busSampleVoices[vi].render() } - for (ch in 0 until Pattern.TRACK_COUNT) if (cloudOn[ch]) channelSum[ch] += clouds[ch].render() - for (ch in 0 until Pattern.TRACK_COUNT) { - val mc = proj.mixer.channels[ch] - var s = if (mc.audible(anySolo)) channelSum[ch] * mc.volume else 0f - val chain = chains[ch] - for (u in chain) s = u.effect.process(s) - // Isolate a misbehaving effect: a non-finite sample from one - // channel's FX must not poison the whole master sum. - if (!s.isFinite()) s = 0f - // Optional per-bus soft-clip limiter (toolbar toggle). - if (mc.limiter) s = softClip(s) - // Track this bus's peak for the mixer VU (post-fader/post-FX). - val a = if (s < 0f) -s else s - if (a > chBlockPeak[ch]) chBlockPeak[ch] = a - // Voices and inserts are mono; both master channels get the same - // sum. The master output/recording path stays stereo (2 channels). - mixL += s; mixR += s - } - } - for (k in 0 until actLiveN) { val v = liveVoices[actLive[k]].render() * LIVE_GAIN; mixL += v; mixR += v } - if (auditionCloudActive) { val v = auditionCloud.render() * LIVE_GAIN; mixL += v; mixR += v } - for (k in 0 until actASmpN) { val v = auditionSampleVoices[actASmp[k]].render() * LIVE_GAIN; mixL += v; mixR += v } - // Makeup gain (lifts instruments to media loudness) into a look-ahead - // brickwall limiter that guarantees the output stays under the ceiling. - masterLimit(mixL * MASTER_MAKEUP, mixR * MASTER_MAKEUP) - val oL = limOutL - val oR = limOutR - out[2 * i] = oL - out[2 * i + 1] = oR - if (recCapturing) recordSample(proj, oL, oR) - } - - // Fold this block's per-channel peaks into the VU meter values: instant attack - // (jump up to a new peak), exponential release (decay back down), plus a clip - // latch that holds when the bus crossed 0 dBFS so a momentary overload is seen. - for (ch in 0 until Pattern.TRACK_COUNT) { - val peak = chBlockPeak[ch] - val decayed = chMeter[ch] * METER_DECAY - chMeter[ch] = if (peak > decayed) peak else decayed - if (peak >= METER_CLIP_LEVEL) chClipHold[ch] = METER_CLIP_HOLD_BLOCKS - else if (chClipHold[ch] > 0) chClipHold[ch]-- - } - } - - /** Current VU level (peak amplitude, ~0..1+) for mixer bus [ch]; 0 if out of range. */ - fun channelMeter(ch: Int): Float = if (ch in chMeter.indices) chMeter[ch] else 0f - - /** True while bus [ch] is (or recently was) clipping past 0 dBFS — drives the red VU. */ - fun channelClipped(ch: Int): Boolean = ch in chClipHold.indices && chClipHold[ch] > 0 - - /** The live visualization source for toolbox [slotIndex], if that slot is an effect - * in some channel's insert chain and produces one (first match wins). Read on the - * UI thread; the returned processor's viz fields are written by the audio thread. */ - private fun vizFor(slotIndex: Int): VizEffect? { - val chains = channelChains - for (ch in chains) for (u in ch) { - if (u.slot.index == slotIndex) { val e = u.effect; if (e is VizEffect) return e } - } - return null - } - - /** Copy effect [slotIndex]'s scope samples into [out]; -1 if it isn't a live, - * routed viz effect (nothing to draw). */ - fun effectScope(slotIndex: Int, out: FloatArray): Int = vizFor(slotIndex)?.copyScope(out) ?: -1 - - /** Effect [slotIndex]'s playhead (0..1), or -1 if no live viz source. */ - fun effectPlayhead(slotIndex: Int): Float = vizFor(slotIndex)?.playhead() ?: -1f - - /** - * Feed-forward, look-ahead brickwall limiter for the master bus. Results land in - * [limOutL]/[limOutR] (no per-sample allocation). Runs on the audio thread. - * - * How it guarantees "no clipping": the incoming (post-makeup) sample is pushed - * into a [LIM_LOOKAHEAD]-sample delay line, and the gain is driven by the *newest* - * sample while it is applied to the *oldest* (delayed) one. When a sample louder - * than [LIM_CEILING] enters, the gain drops instantly to exactly the amount needed - * to tame it and is *held* for the whole look-ahead window (plus a small margin), - * so by the time that loud sample reaches the output the gain is already pulled - * down — the delayed peak can never exceed the ceiling. Between peaks the gain - * releases smoothly back toward unity, so quiet passages keep the full makeup. - * A final hard clamp is a cheap belt-and-braces guard (it should never engage). - */ - private fun masterLimit(inL: Float, inR: Float) { - val dL = limDelayL[limPos] - val dR = limDelayR[limPos] - limDelayL[limPos] = inL - limDelayR[limPos] = inR - limPos++; if (limPos >= LIM_LOOKAHEAD) limPos = 0 - - val peak = max(abs(inL), abs(inR)) - val target = if (peak > LIM_CEILING) LIM_CEILING / peak else 1f - when { - target < limGain -> { limGain = target; limHold = LIM_LOOKAHEAD + LIM_HOLD_EXTRA } - limHold > 0 -> limHold-- - else -> limGain += (1f - limGain) * LIM_RELEASE - } - - var oL = dL * limGain - var oR = dR * limGain - if (oL > LIM_CEILING) oL = LIM_CEILING else if (oL < -LIM_CEILING) oL = -LIM_CEILING - if (oR > LIM_CEILING) oR = LIM_CEILING else if (oR < -LIM_CEILING) oR = -LIM_CEILING - limOutL = if (oL.isFinite()) oL else 0f - limOutR = if (oR.isFinite()) oR else 0f - } - - /** Push slot parameters (+ tempo) into every live effect processor, but only when - * they actually changed — re-parsing unchanged params every block allocates and - * caused GC-pause dropouts when several effects were stacked. */ - private fun updateFxParams(proj: Project) { - val tempo = proj.tempoBpm - val chains = channelChains - for (ch in 0 until Pattern.TRACK_COUNT) { - val chain = chains[ch] - for (u in chain) { - val v = u.slot.version - if (v != u.lastVersion || tempo != u.lastTempo) { - u.effect.update(u.slot, tempo) - u.lastVersion = v - u.lastTempo = tempo - } - } - } - } - - // Lock-free xorshift RNG for the audio thread. Math.random() is backed by a - // single synchronized java.util.Random, so calling it on the real-time thread - // risks lock contention / priority inversion; this never blocks or allocates. - private var rngState = 0x9E3779B9.toInt() - /** Next pseudo-random float in [0,1). */ - private fun nextRandomUnit(): Float { - var s = rngState - s = s xor (s shl 13); s = s xor (s ushr 17); s = s xor (s shl 5) - rngState = s - return (s.toLong() and 0xFFFFFFFFL).toFloat() * 2.3283064e-10f - } - - // ---- MIDI LFO modulation ---- - private val lfoPhase = DoubleArray(Project.TOOLBOX_SLOTS) - private val lfoSampleHold = DoubleArray(Project.TOOLBOX_SLOTS) { Math.random() * 2 - 1 } - - /** - * Apply every LFO slot's modulation to its target parameter, once per block. - * The target is stored as "slotIndex:paramKey"; the LFO oscillates the value - * around a captured centre by ±depth·(half the param's range). The LFO thus - * "takes over" its target parameter while active. - */ - private fun applyLfos(proj: Project) { - val secondsPerBeat = 60.0 / proj.tempoBpm - val blockSeconds = BLOCK_FRAMES.toDouble() / sampleRate - for (i in proj.toolbox.indices) { - val lfo = proj.toolbox[i] - if (lfo.type != ToolboxType.LFO) continue - val target = lfo.string("target") - val sep = target.indexOf(':') - if (sep <= 0) continue - // Parse the target slot index from target[0 until sep] without a substring - // or a boxed Int? — this runs every block for each active LFO. - var tIdx = 0 - var validIdx = true - for (ci in 0 until sep) { - val ch = target[ci] - if (ch < '0' || ch > '9') { validIdx = false; break } - tIdx = tIdx * 10 + (ch - '0') - } - if (!validIdx || tIdx == i) continue - val tSlot = proj.toolbox.getOrNull(tIdx) ?: continue - val params = tSlot.type?.params ?: continue - // Match the param key by region rather than target.substring(sep + 1): - // this runs every block for each active LFO, and the slot-index parse - // above already goes to this trouble. regionMatches allocates nothing. - val keyFrom = sep + 1 - val keyLen = target.length - keyFrom - // Indexed scan (not firstOrNull {}) so no Iterator allocates per block. - var specIdx = -1 - for (pi in params.indices) { - val k = params[pi].key - if (k.length == keyLen && target.regionMatches(keyFrom, k, 0, keyLen)) { - specIdx = pi; break - } - } - if (specIdx < 0) continue - val spec = params[specIdx] - - val div = TimeDivision.fromIndex(lfo.float("division", 3f).toInt()) - val freq = 1.0 / (div.beatFraction * secondsPerBeat).coerceAtLeast(1e-6) - val advanced = lfoPhase[i] + freq * blockSeconds - if (advanced >= 1.0) lfoSampleHold[i] = nextRandomUnit() * 2.0 - 1.0 - lfoPhase[i] = advanced % 1.0 - val phase = (lfoPhase[i] + lfo.float("phase", 0f)) % 1.0 - - val value = when (lfo.string("wave", "Sine")) { - "Triangle" -> 1.0 - 4.0 * abs(phase - 0.5) - "Saw" -> 2.0 * phase - 1.0 - "Square" -> if (phase < 0.5) 1.0 else -1.0 - "SampleHold" -> lfoSampleHold[i] - else -> sin(2 * Math.PI * phase) - } - val center = lfo.float("center", spec.default).toDouble() - val half = (spec.max - spec.min) / 2.0 - val modulated = (center + lfo.float("depth", 0.5f) * value * half) - .coerceIn(spec.min.toDouble(), spec.max.toDouble()) - tSlot.set(spec.key, modulated.toFloat()) - } - } - - /** Dispatch one sample of sequencer time to the active playback mode. */ - private fun advanceSequencer(proj: Project) { - if (arrangementMode) advanceArrangement(proj) else advancePatternLoop(proj) - advanceArps(proj) // arpeggiators retrigger between note events - } - - // ----- Pattern-loop mode (Tracker tab audition) ----- - private fun advancePatternLoop(proj: Project) { - val pattern = proj.activePattern() - val samplesPerLine = blockSamplesPerLine - - if (pendingTrigger) { - val linesPerBar = proj.timeSignature.linesPerBar - if (linesPerBar > 0 && currentLine % linesPerBar == 0) resetBarArps() - triggerPatternLine(proj, pattern, currentLine) - pendingTrigger = false - } - samplesIntoLine += 1.0 - if (samplesIntoLine >= samplesPerLine) { - samplesIntoLine -= samplesPerLine - currentLine++ - if (currentLine >= pattern.length) currentLine = 0 - pendingTrigger = true - publish() - } - } - - private fun triggerPatternLine(proj: Project, pattern: Pattern, line: Int) { - lineTriggerGen++ // new line — notes below form one chord per arpeggiator - // Pattern-loop plays on lane 0's voices; each cell is routed by its channel. - // Apply note-offs FIRST, then note-ons, so a note-off on one track never - // cancels a note that begins on the same line/bus (a note-off releases the - // whole bus; without this ordering it would kill a just-triggered voice). - for (t in 0 until Pattern.TRACK_COUNT) { - val cell = pattern.cell(t, line) - if (cell.isNoteOff) triggerCell(proj, lane = 0, track = t, cell = cell) - } - for (t in 0 until Pattern.TRACK_COUNT) { - val cell = pattern.cell(t, line) - if (cell.isPlayable) triggerCell(proj, lane = 0, track = t, cell = cell) - } - } - - /** - * Trigger one tracker [cell] from source [track] on [lane]. - * - * A PLAYABLE note is routed to the mixer bus(es) whose MIDI channel matches the - * cell's channel — NOT the source track — so a note plays whatever instrument - * sits on its channel's bus, wherever it's placed in the grid (this decouples - * tracks from buses). Each matching bus applies its own MIDI effects (Transposer - * shifts pitch; an Arpeggiator captures the note, retriggered by [advanceArps]). - * The channel used is remembered per (lane, track). - * - * A NOTE-OFF is tied to its TRACK, not to a channel: it has no channel/velocity - * of its own and simply releases whatever this track last started — on the same - * bus(es) that track's previous note routed to ([trackLastChannel]). - */ - private fun triggerCell(proj: Project, lane: Int, track: Int, cell: cc.tiredsysadmin.android.sizzle.model.Cell) { - val trackKey = lane * Pattern.TRACK_COUNT + track - if (cell.isNoteOff) { releaseTrack(proj, lane, track); return } - if (!cell.isPlayable) return - // Remember the channel so a later note-off on this track releases it. - trackLastChannel[trackKey] = cell.channel - // Send this track's note out to external gear (mono per track): off the note it - // was holding, then on the new one, on the cell's MIDI channel. Mirrors the - // tracks' cells — a channel's Arpeggiator/Transposer are internal FX and aren't - // reflected here. - if (moutNote[trackKey] >= 0) emitNoteOff(moutCh[trackKey], moutNote[trackKey]) - emitNoteOn(cell.channel, cell.note, cell.velocity) - moutNote[trackKey] = cell.note; moutCh[trackKey] = cell.channel - // Mono-per-track: a new note releases whatever this track was still holding, - // so a held note is stopped when the next one appears under the playhead — no - // explicit note-off cell needed. Only this track's own voices are released, so - // notes other tracks hold on the same bus (chords across tracks) keep sounding. - releaseTrackVoices(trackKey) - for (bus in 0 until Pattern.TRACK_COUNT) { - if (proj.mixer.channels[bus].midiChannel != cell.channel) continue - val arp = arps[lane * Pattern.TRACK_COUNT + bus] - val velocity = cell.velocity.coerceIn(0, 127) - val note = (cell.note + channelTranspose(proj, bus)).coerceIn(0, 127) - val arpSlot = channelArpSlot(proj, bus) - if (arpSlot != null) { - val octaves = arpSlot.float("octaves", 1f).toInt() - val div = TimeDivision.fromIndex(arpSlot.float("division", 3f).toInt()) - val stepSamples = div.beatFraction * (60.0 / proj.tempoBpm) * sampleRate - val mode = arpSlot.string("mode", "Up") - val resetBar = arpSlot.string("resetbar", "Off") == "On" - when { - arp.active && arp.genStamp == lineTriggerGen -> { - // Another note of the SAME line's chord — accumulate it so the - // arp cycles the whole chord (not just the last note entered). - arp.addNote(note) - arp.refresh(octaves, mode, stepSamples, resetBar) - } - arp.active -> { - // A new line while still arpeggiating (the pattern looping back - // over a held chord): rebuild the chord from this line but keep - // the running phase, so a looping chord doesn't hard-restart or - // slip when the loop length isn't a multiple of the arp step. - arp.resetChord(note, velocity, octaves, mode, stepSamples, resetBar) - arp.genStamp = lineTriggerGen - } - else -> { - // Fresh arp: start on this note and sound it immediately. - arp.startChord(note, velocity, octaves, mode, stepSamples, resetBar) - arp.genStamp = lineTriggerGen - releaseBus(bus) - playNote(proj, bus, arp.currentNote(), velocity) - } - } - } else { - arp.stop() - playNote(proj, bus, note, velocity, ownerTrack = trackKey) - } - } - } - - /** Release (fade out) every still-*held* sequencer voice started by tracker - * [trackKey] — used to make a track monophonic: its previous note is released when - * it plays a new one. Only gated voices are touched (release tails ring out), and - * matching by owner means sibling tracks' notes on a shared bus are left alone. - * Array loops allocate no iterator — safe on the audio thread. */ - /** - * Release one tracker track of one arrangement lane: its outgoing MIDI note, its - * arpeggiator, and the mixer bus it last played on. This is what a note-off cell - * does, lifted out so an arrangement [Arrangement.NOTE_OFF] marker can do the - * same for every track of its lane. - * - * Releasing the whole bus (not just this track's voices) is deliberate and - * matches the note-off cell it was factored from: a note-off is a "stop sounding" - * instruction to the instrument, not to one column. - */ - private fun releaseTrack(proj: Project, lane: Int, track: Int) { - val trackKey = lane * Pattern.TRACK_COUNT + track - // Release this track's outgoing MIDI note first (external gear). - if (moutNote[trackKey] >= 0) { emitNoteOff(moutCh[trackKey], moutNote[trackKey]); moutNote[trackKey] = -1 } - val ch = trackLastChannel[trackKey] - if (ch < 0) return // this track hasn't played anything yet - for (bus in 0 until Pattern.TRACK_COUNT) { - if (proj.mixer.channels[bus].midiChannel != ch) continue - arps[lane * Pattern.TRACK_COUNT + bus].stop() - releaseBus(bus) - } - } - - /** Release every track of [lane] — an arrangement "off" marker reaching the playhead. */ - private fun releaseLane(proj: Project, lane: Int) { - for (t in 0 until Pattern.TRACK_COUNT) releaseTrack(proj, lane, t) - } - - private fun releaseTrackVoices(trackKey: Int) { - for (c in clouds) c.releaseOwner(trackKey) - for (v in seqVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff() - for (v in sampleVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff() - } - - /** - * Sound a note on a mixer [bus]: allocate a [SampleVoice] from the bus pool when - * the channel's instrument is a Sampler/SoundFont with a loaded sample, otherwise - * a [SynthVoice] for the NES synth. Pooled allocation (up to [POLYPHONY] per bus, - * stealing the oldest when full) is what makes the instrument polyphonic. Shared - * by the sequencer and the arpeggiator. - * - * [ownerTrack] tags the allocated voice with the tracker (lane,track) that started - * it (or -1 for arp/unowned notes), so [releaseTrackVoices] can later release just - * this track's note — see [triggerCell]. - */ - private fun playNote(proj: Project, bus: Int, note: Int, velocity: Int, ownerTrack: Int = -1) { - // The allocators ([allocSynthVoice]/[allocSampleVoice]) queue the chosen voice - // into this block's active list, so a note started mid-block sounds sample- - // accurately within the same block. - val slot = proj.toolbox.getOrNull(proj.mixer.channels[bus].instrumentSlot) - val vs = voiceSample(slot, note) - when { - vs != null -> - allocSampleVoice(bus).also { it.ownerTrack = ownerTrack }.noteOn( - vs.sample, note, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, - vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs) - // Empty bus (no instrument — e.g. the default channel 0) or a Sampler - // with an empty pad → silent, matching the live audition path. - slot?.type == null || slot.type == ToolboxType.SAMPLER -> {} - slot.type == ToolboxType.GRAIN_CLOUD -> - clouds[bus].noteOn(note, velocity, if (ownerTrack >= 0) ownerTrack else GrainCloud.OWNER_SEQ) - // NES synth, or a SoundFont with nothing loaded → the tone generator. - else -> { - allocSynthVoice(bus).also { it.ownerTrack = ownerTrack } - .noteOn(note, velocity, synthPatch[bus] ?: patchForSlot(slot, proj.tempoBpm)) - } - } - } - - /** A sample voice's source + pitch + amplitude-envelope info for a note. */ - private class VoiceSample( - val sample: SampleStore.Sample, val root: Int, - val sliceStart: Float, val sliceEnd: Float, val volume: Float, - val attack: Float = 0.002f, val decay: Float = 0f, - val sustain: Float = 1f, val release: Float = 0.02f, - val loop: Boolean = false, val crossfadeMs: Float = 0f, - ) - - /** - * Resolve the PCM sample a note should play for [slot], or null if the slot - * isn't a loaded sample instrument (the caller then uses the synth). - * - Sampler: the pad [note] maps to (root == note, so it plays unpitched). Pads - * stay one-shot (default envelope), just carrying their per-pad volume/slice. - * - SoundFont: the loaded SF2/XI sample, pitched from its stored root note, with - * the user's volume ADSR envelope applied. - */ - private fun voiceSample(slot: ToolboxSlot?, note: Int): VoiceSample? = when (slot?.type) { - ToolboxType.SAMPLER -> { - val pad = SamplerPads.padFor(note) - if (pad !in 0 until SamplerPads.COUNT) { - null - } else { - SampleStore.get(slot.string(SamplerPads.key(pad)))?.let { - VoiceSample( - it, note, - slot.float(SamplerPads.sliceStartKey(pad), 0f), - slot.float(SamplerPads.sliceEndKey(pad), 1f), - slot.float(SamplerPads.volumeKey(pad), SamplerPads.DEFAULT_VOLUME), - ) - } - } - } - ToolboxType.SOUNDFONT -> - SampleStore.get(slot.string("sfSample"))?.let { - VoiceSample( - it, slot.float("sfRoot", 60f).toInt(), 0f, 1f, slot.float("volume", 0.8f), - attack = slot.float("attack", 0.005f), - decay = slot.float("decay", 0.10f), - sustain = slot.float("sustain", 1f), - release = slot.float("release", 0.20f), - loop = slot.string("loop", "Off") == "On", - crossfadeMs = slot.float("loopXfade", 0f), - ) - } - else -> null - } - - /** Realign every active "reset on bar" arpeggiator to step 0 — called on each - * bar downbeat, before that line's own note triggers (so a fresh note-on on the - * downbeat isn't double-fired). */ - private fun resetBarArps() { - for (i in arps.indices) { - val a = arps[i] - if (a.active && a.resetOnBar) a.resetToBar() - } - } - - /** The channel's Arpeggiator slot (first one found in its FX slots), or null. */ - private fun channelArpSlot(proj: Project, track: Int): ToolboxSlot? { - for (idx in proj.mixer.channels[track].fxSlots) { - if (idx < 0) continue - val slot = proj.toolbox.getOrNull(idx) ?: continue - if (slot.type == ToolboxType.ARPEGGIATOR) return slot - } - return null - } - - /** Advance every active arpeggiator by one sample; retrigger on step boundaries. */ - private fun advanceArps(proj: Project) { - for (i in arps.indices) { - val a = arps[i] - if (!a.active) continue - a.samplesLeft -= 1.0 - if (a.samplesLeft <= 0.0) { - // A pending bar reset plays step 0 as-is; otherwise advance the pattern. - if (!a.consumePendingReset()) a.advance() - val bus = i % Pattern.TRACK_COUNT - // Release the previous step before sounding the next one. Without this - // an arp on a *sustaining* instrument (e.g. an SF2/XI with sustain=1 - // and a long sample) stacks a fresh full-level voice every step until - // the whole 8-voice pool is held wide open — a sustained wall of sound - // that overloads any following FX (a reverb's make-up gain then slams - // the limiter). Releasing keeps the arp monophonic with natural tails. - releaseBus(bus) - playNote(proj, bus, a.currentNote(), a.velocity) - a.samplesLeft += a.stepSamples - } - } - } - - /** Per-(lane,track) arpeggiator: cycles through the held chord's notes across the - * octave range. Notes are kept sorted ascending; the linear step sequence is - * octave-major (all chord notes in octave 0, then octave 1, …), walked up / down / - * up-down / randomly by [advance]. [genStamp] identifies the line whose chord this - * holds (see [lineTriggerGen]). Internal (not private) only so a unit test can - * exercise its pure note-sequencing. */ - internal class ChannelArp { - private val notes = IntArray(MAX_CHORD) - var noteCount = 0; private set - var velocity = 100 - private var octaves = 1; private var mode = 0 - var stepSamples = 0.0; var samplesLeft = 0.0 - private var step = 0; private var dir = 1 - var resetOnBar = false - var genStamp = -1 - private var pendingReset = false - private var rng = 0x2545F491.toInt() - private fun rnd(bound: Int): Int { - var s = rng - s = s xor (s shl 13); s = s xor (s ushr 17); s = s xor (s shl 5) - rng = s - return ((s.toLong() and 0xFFFFFFFFL) % bound).toInt() - } - - /** Active while it holds at least one note. */ - val active: Boolean get() = noteCount > 0 - - /** Start a fresh chord on [note], resetting the phase to step 0. */ - fun startChord(note: Int, vel: Int, octs: Int, modeStr: String, stepSamp: Double, resetBar: Boolean) { - noteCount = 0; addNote(note); velocity = vel; octaves = octs.coerceIn(1, 4) - mode = modeOf(modeStr) - stepSamples = stepSamp.coerceAtLeast(1.0); samplesLeft = stepSamples; step = 0; dir = 1 - resetOnBar = resetBar; pendingReset = false - } - - /** Replace the chord with [note] (the next same-line notes re-accumulate) while - * KEEPING the running phase — used when the pattern loops back over a held - * chord so the pulse stays steady instead of restarting. */ - fun resetChord(note: Int, vel: Int, octs: Int, modeStr: String, stepSamp: Double, resetBar: Boolean) { - noteCount = 0; addNote(note); velocity = vel - refresh(octs, modeStr, stepSamp, resetBar) - } - - /** Add a note to the held chord (sorted ascending, de-duplicated). */ - fun addNote(note: Int) { - val n = note.coerceIn(0, 127) - var i = 0 - while (i < noteCount && notes[i] < n) i++ - if (i < noteCount && notes[i] == n) return // already held - if (noteCount >= MAX_CHORD) return - for (j in noteCount downTo i + 1) notes[j] = notes[j - 1] - notes[i] = n; noteCount++ - } - - /** Update params WITHOUT resetting the running phase. */ - fun refresh(octs: Int, modeStr: String, stepSamp: Double, resetBar: Boolean) { - octaves = octs.coerceIn(1, 4) - mode = modeOf(modeStr) - stepSamples = stepSamp.coerceAtLeast(1.0) - resetOnBar = resetBar - } - - fun resetToBar() { step = 0; dir = 1; samplesLeft = 0.0; pendingReset = true } - fun consumePendingReset(): Boolean { val p = pendingReset; pendingReset = false; return p } - - private fun modeOf(modeStr: String): Int = - when (modeStr) { "Down" -> 1; "UpDown" -> 2; "Random" -> 3; else -> 0 } - - fun stop() { noteCount = 0; genStamp = -1 } - - private fun total(): Int = (noteCount * octaves).coerceAtLeast(1) - - fun currentNote(): Int { - if (noteCount <= 0) return 0 - val idx = step.coerceIn(0, total() - 1) - val oct = idx / noteCount - return (notes[idx % noteCount] + 12 * oct).coerceIn(0, 127) - } - - fun advance() { - val total = total() - when (mode) { - 1 -> step = (step - 1 + total) % total - 2 -> if (total > 1) { - step += dir - if (step >= total - 1) { step = total - 1; dir = -1 } - else if (step <= 0) { step = 0; dir = 1 } - } - 3 -> step = if (total > 1) rnd(total) else 0 - else -> step = (step + 1) % total - } - } - - private companion object { const val MAX_CHORD = 8 } - } - - /** Sum of semitone offsets from any MIDI Transposer effects on this channel. */ - private fun channelTranspose(proj: Project, track: Int): Int { - var semis = 0 - for (idx in proj.mixer.channels[track].fxSlots) { - if (idx < 0) continue - val slot = proj.toolbox.getOrNull(idx) ?: continue - if (slot.type == ToolboxType.TRANSPOSER) { - semis += slot.float("semitones", 0f).toInt() + slot.float("octaves", 0f).toInt() * 12 - } - } - return semis - } - - /** Start auditioning a note on the instrument in toolbox [slotIndex] (used by - * the Toolbox test keyboard and the Sampler editor). Polyphonic. */ - fun auditionSlotOn(slotIndex: Int, midi: Int) { - val proj = project ?: return - val slot = proj.toolbox.getOrNull(slotIndex) - val vs = voiceSample(slot, midi) - if (vs != null) { - val v = auditionSampleVoices.firstOrNull { !it.isActive } ?: auditionSampleVoices[0].also { it.kill() } - v.noteOn(vs.sample, midi, 110, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, - vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs) - return - } - // A Sampler with an empty pad stays silent (audition is a one-shot with no - // note-off, so a sustaining synth voice would ring forever). A SoundFont - // with nothing loaded still falls through to the synth preview below. - if (slot?.type == ToolboxType.SAMPLER) return - if (slot?.type == ToolboxType.GRAIN_CLOUD) { - if (auditionSlotIdx != slotIndex || slot.version != auditionCloudVer) { - auditionCloud.setPatch(GrainPatch.from(slot, project?.tempoBpm ?: 120f)) - auditionCloudVer = slot.version - } - auditionSlotIdx = slotIndex - auditionCloud.noteOn(midi, 110, GrainCloud.OWNER_LIVE) - return - } - // Remember which slot is being auditioned so refreshSynthPatches pushes live - // knob turns into the held preview note. - if (hasSynthPatch(slot?.type)) auditionSlotIdx = slotIndex - val v = liveVoices.firstOrNull { !it.isActive } ?: liveVoices[0].also { it.kill() } - v.noteOn(midi, 110, patchForSlot(slot, project?.tempoBpm ?: 120f)) - } - - /** Release an auditioned note (matches both synth and sample audition pools). - * Releases a *held* (gated) voice of this pitch in preference to one that's already - * ringing out its release tail — otherwise rapid re-tapping / chord-tapping the same - * key lands the note-off on the releasing voice and leaves the held one stuck. */ - fun auditionSlotOff(midi: Int) { - auditionCloud.noteOff(midi) - (liveVoices.firstOrNull { it.pitch == midi && it.isGated } - ?: liveVoices.firstOrNull { it.isActive && it.pitch == midi })?.noteOff() - (auditionSampleVoices.firstOrNull { it.pitch == midi && it.isGated } - ?: auditionSampleVoices.firstOrNull { it.isActive && it.pitch == midi })?.noteOff() - } - - // ---------------------------------------------- live mix-bus audition (MIDI piano) - /** - * Play [midi] on every mixer channel listening on [midiChannel], sounding each - * channel's instrument through its full insert chain, volume and mute/solo — - * i.e. auditioning the actual mix bus, not a raw toolbox slot. - */ - fun busNoteOn(midiChannel: Int, midi: Int, velocity: Int) { - val proj = project ?: return - for (ch in 0 until Pattern.TRACK_COUNT) { - if (proj.mixer.channels[ch].midiChannel != midiChannel) continue - val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot) - // Empty bus (no instrument assigned) → silent. Auditioning a bus should - // only sound when it actually has an instrument, never a fallback synth. - val type = slot?.type ?: continue - val base = ch * BUS_POLYPHONY - val vs = voiceSample(slot, midi) - when { - vs != null -> { - val v = freeBusVoice(busSampleVoices, base) - v.noteOn(vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, - vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs) - } - // Sampler with an empty pad → silent (no synth fallback). - type == ToolboxType.SAMPLER -> {} - type == ToolboxType.GRAIN_CLOUD -> clouds[ch].noteOn(midi, velocity, GrainCloud.OWNER_LIVE) - else -> { - val v = freeBusVoice(busVoices, base) - v.noteOn(midi, velocity, synthPatch[ch] ?: patchForSlot(slot, proj.tempoBpm)) - } - } - } - } - - // First idle voice in the bus's BUS_POLYPHONY slice, stealing slot 0 when all are - // busy. Indexed, because the obvious `(0 until N).map { … }.firstOrNull { … }` - // allocated a range iterator and an ArrayList for every incoming MIDI note — on - // the thread that is supposed to stay allocation-free. Two concrete overloads - // rather than a generic one: the voice pools are differently typed arrays. - private fun freeBusVoice(pool: Array, base: Int): SynthVoice { - for (i in 0 until BUS_POLYPHONY) if (!pool[base + i].isActive) return pool[base + i] - return pool[base].also { it.kill() } - } - - private fun freeBusVoice(pool: Array, base: Int): SampleVoice { - for (i in 0 until BUS_POLYPHONY) if (!pool[base + i].isActive) return pool[base + i] - return pool[base].also { it.kill() } - } - - /** For the MIDI trace only: what [busNoteOn] would do with [midi] on - * [midiChannel], e.g. "strip2 SAMPLER pad2 | strip4 NES_SYNTH" or "no strip". */ - fun describeBusTargets(midiChannel: Int, midi: Int): String { - val proj = project ?: return "no project" - val parts = ArrayList() - for (ch in 0 until Pattern.TRACK_COUNT) { - if (proj.mixer.channels[ch].midiChannel != midiChannel) continue - val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot) - val type = slot?.type - parts += "strip${ch + 1} " + when { - type == null -> "no instrument (silent)" - type == ToolboxType.SAMPLER -> { - val pad = SamplerPads.padFor(midi) - if (voiceSample(slot, midi) != null) "SAMPLER pad${pad + 1}" else "SAMPLER pad${pad + 1} empty (silent)" - } - else -> type.name + if (voiceSample(slot, midi) == null && type == ToolboxType.SOUNDFONT) " no sample" else "" - } - } - return if (parts.isEmpty()) "no strip on channel $midiChannel" else parts.joinToString(" | ") - } - - /** Release [midi] on every mixer channel listening on [midiChannel]. */ - fun busNoteOff(midiChannel: Int, midi: Int) { - val proj = project ?: return - for (ch in 0 until Pattern.TRACK_COUNT) { - if (proj.mixer.channels[ch].midiChannel != midiChannel) continue - clouds[ch].noteOff(midi) - val base = ch * BUS_POLYPHONY - for (i in 0 until BUS_POLYPHONY) { - busVoices[base + i].takeIf { it.isActive && it.pitch == midi }?.noteOff() - busSampleVoices[base + i].takeIf { it.isActive && it.pitch == midi }?.noteOff() - } - } - } - - // ----- Arrangement mode ----- - private fun advanceArrangement(proj: Project) { - val arr = proj.arrangement - // Snapshot the volatile playlist once so a concurrent live rebuild (from - // refreshLoopPlaylist) can't change its size mid-computation. - val list = playlist - if (list.isEmpty()) { playing = false; publish(); return } - val linesPerBeat = proj.timeSignature.linesPerBeat - val samplesPerLine = blockSamplesPerLine - val beat = list[playlistIndex.coerceIn(0, list.size - 1)] - - if (pendingTrigger) { - // Bar downbeat = first line of a beat that starts a bar (in arrangement - // beats). Reset "reset on bar" arps before this line's own triggers. - val beatsPerBar = proj.timeSignature.beatsPerBar - if (lineInBeat == 0 && beatsPerBar > 0 && beat % beatsPerBar == 0) resetBarArps() - triggerArrangementLine(proj, arr, beat, lineInBeat, linesPerBeat) - pendingTrigger = false - } - - samplesIntoLine += 1.0 - if (samplesIntoLine >= samplesPerLine) { - samplesIntoLine -= samplesPerLine - lineInBeat++ - if (lineInBeat >= linesPerBeat) { - lineInBeat = 0 - playlistIndex++ - if (playlistIndex >= list.size) { - if (arr.loopEnabled) { - playlistIndex = 0 - } else { - playing = false; allSeqVoicesOff(); publish(); return - } - } - } - pendingTrigger = true - publish() - } - } - - /** - * Play one tick of every block marked at [beat]. Mirrors the reference - * sizzletracker `playAt`: a marker means the block sounds *that beat*, and a - * contiguous run of markers plays the block from its start beat-by-beat (and - * restarts after any erased gap). The beat-within-block is derived STATELESSLY - * from the run's start each tick — no mutable cursor — so it stays correct - * across loop wraps and region loops (the earlier "only the first beat plays - * on loop" bug came from a cursor that reset every loop cycle). - */ - private fun triggerArrangementLine( - proj: Project, arr: Arrangement, beat: Int, lineInBeat: Int, linesPerBeat: Int, - ) { - lineTriggerGen++ // new line — notes below form one chord per arpeggiator - // Two passes across all lanes: note-offs first, then note-ons, so a note-off - // never cancels a note that begins on the same line/bus (a note-off releases - // the whole bus). See [triggerPatternLine]. - for (pass in 0..1) { - for (lane in 0 until Arrangement.LANE_COUNT) { - if (arr.laneMuted[lane]) continue // muted MIDI lane — skip its blocks - val p = arr.patternAt(lane, beat) - if (p == Arrangement.EMPTY) continue - if (p == Arrangement.NOTE_OFF) { - // Fire once, on the first line of the beat and in the note-off - // pass, so it lands before anything another lane starts here. - if (pass == 0 && lineInBeat == 0) releaseLane(proj, lane) - continue - } - val pat = proj.pattern(p) ?: continue - // Walk back to the start of this block's contiguous run of markers so it - // plays from beat 0 wherever the run begins. An off marker is a boundary, - // not part of the run — a block placed after one restarts from its start. - var runStart = beat - while (runStart > 0 && arr.hasBlockAt(lane, runStart - 1)) runStart-- - val blockBeats = (pat.length / linesPerBeat).coerceAtLeast(1) - val patLine = ((beat - runStart) % blockBeats) * linesPerBeat + lineInBeat - // The edited block drives the tracker playhead (set once, in pass 0). - if (pass == 0 && p == proj.activePatternId) arrPlayLine = patLine.coerceIn(0, pat.length - 1) - if (patLine >= pat.length) continue - for (t in 0 until Pattern.TRACK_COUNT) { - val cell = pat.cell(t, patLine) - if (pass == 0) { if (cell.isNoteOff) triggerCell(proj, lane, t, cell) } - else { if (cell.isPlayable) triggerCell(proj, lane, t, cell) } - } - } - } - } - - /** Parse a slot's synth patch (default init patch if it isn't an NES synth). - * Allocates one [SynthPatch] — used only for the first audition note; the - * sequencer/bus paths use the per-block cache in [refreshSynthPatches]. */ - private fun patchForSlot(slot: ToolboxSlot?, tempoBpm: Float): SynthPatch = when (slot?.type) { - ToolboxType.NES_SYNTH -> SynthPatch.from(slot, tempoBpm) - ToolboxType.MORPH_PAD -> SynthPatch.forPad(FrasilPatch.from(slot)) - ToolboxType.WAVETABLE -> SynthPatch.forWave(WavePatch.from(slot, tempoBpm)) - else -> SynthPatch.DEFAULT - } - - /** The slot types whose notes a [SynthVoice] plays with a parsed [SynthPatch]. */ - private fun hasSynthPatch(type: ToolboxType?) = - type == ToolboxType.NES_SYNTH || type == ToolboxType.MORPH_PAD || type == ToolboxType.WAVETABLE - - /** - * Once per block: refresh each bus's cached synth patch (reparsing only when the - * slot version or tempo changed) and push it into that bus's *active* synth voices - * plus the editor's audition voices. This is what makes filter/level/mod knob - * turns audible on already-sounding notes, and keeps note triggers allocation-free. - * Runs on the audio thread; slot reads are safe against UI edits because the param - * map is concurrent. - */ - private fun refreshSynthPatches(proj: Project) { - val tempo = proj.tempoBpm - for (ch in 0 until Pattern.TRACK_COUNT) { - val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot) - if (slot?.type == ToolboxType.GRAIN_CLOUD) { - if (!cloudOn[ch] || slot.version != cloudVer[ch] || tempo != cloudTempo[ch]) { - clouds[ch].setPatch(GrainPatch.from(slot, tempo)) - cloudVer[ch] = slot.version - cloudTempo[ch] = tempo - } - cloudOn[ch] = true - } else if (cloudOn[ch]) { - cloudOn[ch] = false - clouds[ch].kill() - } - if (slot == null || !hasSynthPatch(slot.type)) { synthPatch[ch] = null; synthPatchVer[ch] = -1; continue } - if (synthPatch[ch] == null || slot.version != synthPatchVer[ch] || tempo != synthPatchTempo[ch]) { - synthPatch[ch] = patchForSlot(slot, tempo) - synthPatchVer[ch] = slot.version - synthPatchTempo[ch] = tempo - } - val p = synthPatch[ch] ?: continue - val sbase = ch * POLYPHONY - for (i in 0 until POLYPHONY) seqVoices[sbase + i].let { if (it.isActive) it.setPatch(p) } - val bbase = ch * BUS_POLYPHONY - for (i in 0 until BUS_POLYPHONY) busVoices[bbase + i].let { if (it.isActive) it.setPatch(p) } - } - // Editor audition voices follow the slot currently being previewed. - val aslot = proj.toolbox.getOrNull(auditionSlotIdx) - if (aslot?.type == ToolboxType.GRAIN_CLOUD && - (aslot.version != auditionCloudVer || tempo != auditionCloudTempo)) { - auditionCloud.setPatch(GrainPatch.from(aslot, tempo)) - auditionCloudVer = aslot.version - auditionCloudTempo = tempo - } - if (aslot != null && hasSynthPatch(aslot.type)) { - if (auditionPatch == null || aslot.version != auditionPatchVer || tempo != auditionPatchTempo) { - auditionPatch = patchForSlot(aslot, tempo) - auditionPatchVer = aslot.version - auditionPatchTempo = tempo - } - auditionPatch?.let { p -> for (v in liveVoices) if (v.isActive) v.setPatch(p) } - } - } - - private fun samplesPerLine(proj: Project): Double = - sampleRate * (60.0 / proj.tempoBpm) / proj.timeSignature.linesPerBeat - - private fun allSeqVoicesOff() { - clouds.forEach { it.releaseSequenced() } - seqVoices.forEach { it.noteOff() } - sampleVoices.forEach { it.noteOff() } - arps.forEach { it.stop() } - allMidiNotesOff() // release any notes we sent to external gear - } - - // ------------------------------------------------------------- outgoing MIDI - /** Enqueue one MIDI message for the send thread (audio-thread producer, no alloc). */ - private fun emitMidi(status: Int, d1: Int, d2: Int) { - if (!midiOutEnabled) return - val h = moutHead - val next = (h + 1) and (moutRing.size - 1) - if (next == moutTail) return // ring full — drop rather than block the audio thread - moutRing[h] = (status shl 16) or ((d1 and 0x7F) shl 8) or (d2 and 0x7F) - moutHead = next - } - - /** Send a note-on for [note] on app channel [ch] (1..16 → MIDI wire 0..15). */ - private fun emitNoteOn(ch: Int, note: Int, vel: Int) { - if (ch < 1) return - emitMidi(0x90 or ((ch - 1) and 0x0F), note.coerceIn(0, 127), vel.coerceIn(1, 127)) - } - - private fun emitNoteOff(ch: Int, note: Int) { - if (ch < 1) return - emitMidi(0x80 or ((ch - 1) and 0x0F), note.coerceIn(0, 127), 0) - } - - /** Release every note we've sent out (on transport stop / pause / panic) so an - * external instrument never hangs after Sizzle stops. */ - private fun allMidiNotesOff() { - for (k in moutNote.indices) if (moutNote[k] >= 0) { emitNoteOff(moutCh[k], moutNote[k]); moutNote[k] = -1 } - } - - /** Drain one queued outgoing MIDI message, or -1 if the queue is empty. Called by - * the MIDI clock thread (single consumer). */ - fun pollMidiOut(): Int { - val t = moutTail - if (t == moutHead) return -1 - val v = moutRing[t] - moutTail = (t + 1) and (moutRing.size - 1) - return v - } - - private fun publish() { - val proj = project - val linesPerBeat = proj?.timeSignature?.linesPerBeat ?: 4 - if (arrangementMode) { - val list = playlist - val beat = if (list.isNotEmpty()) list[playlistIndex.coerceIn(0, list.size - 1)] else 0 - _transport.value = TransportState( - isPlaying = playing, - currentLine = arrPlayLine, - currentBeat = beat, - ) - } else { - _transport.value = TransportState( - isPlaying = playing, - currentLine = currentLine, - currentBeat = currentLine / linesPerBeat, - ) - } - } - - companion object { - private const val BLOCK_FRAMES = 192 // ~4 ms blocks at 48 kHz - private const val POLYPHONY = 8 // max simultaneous voices per instrument (mixer bus) - private const val LIVE_POLYPHONY = 8 - private const val AUDITION_POLYPHONY = 8 - private const val BUS_POLYPHONY = 8 // per-mixer-channel live audition - // Master make-up gain into the look-ahead brickwall limiter ([masterLimit]). - // The old path was a flat 0.5× attenuation into a static soft-clip, which left - // ~9 dB of unused headroom: even the loudest single preset with its mix bus - // maxed peaked around -7 dBFS, well below other media playback. This pushes the - // signal UP (≈ +9.5 dB vs the old 0.5) so a single instrument reaches close to - // full scale, while the limiter guarantees the ceiling is never exceeded on - // busy passages — loudness without clipping. Tunable: raise for even louder / - // denser output, lower to trade loudness back for dynamics. - private const val MASTER_MAKEUP = 1.5f - // Brickwall limiter tuning (see [masterLimit]). - private const val LIM_CEILING = 0.97f // hard output ceiling (~-0.26 dBFS) - private const val LIM_LOOKAHEAD = 64 // delay/look-ahead in samples (~1.3 ms @ 48 kHz) - private const val LIM_HOLD_EXTRA = 8 // extra hold beyond the window so the peak fully clears - private const val LIM_RELEASE = 0.00025f // per-sample rise toward unity (~80 ms release @ 48 kHz) - private const val LIVE_GAIN = 0.5f - // Mixer VU ballistics (per ~4 ms block). Decay ≈ falls to ~5% over ~300 ms; - // clip latches red for ~0.8 s so a brief overload is noticeable. - private const val METER_DECAY = 0.96f - private const val METER_CLIP_LEVEL = 0.999f // bus peak at/above 0 dBFS = clipping - private const val METER_CLIP_HOLD_BLOCKS = 200 // ~0.8 s at 192-frame blocks / 48 kHz - private const val SOFT_KNEE = 0.6f // limiter is transparent below this, saturates above - - /** - * Continuous soft-knee limiter: linear (transparent) up to [SOFT_KNEE], then - * smoothly saturating to +-1 above it. The previous clipper was discontinuous - * at |x|=1 (it snapped the output 1.0 -> 0.5 as the signal crossed full scale), - * which produced audible clicks whenever a hot bus pushed the mix past 1.0. - * This version is value- and slope-continuous, so no crossing can click. - */ - private fun softClip(x: Float): Float { - val a = if (x < 0f) -x else x - if (a <= SOFT_KNEE) return x - val comp = SOFT_KNEE + (1f - SOFT_KNEE) * tanh((a - SOFT_KNEE) / (1f - SOFT_KNEE)) - return if (x < 0f) -comp else comp - } + private companion object { + const val BLOCK_FRAMES = 192 // the engine's block (~4 ms at 48 kHz) } } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeAudioBridge.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeAudioBridge.kt index 35a0e2b..a0ae5fe 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeAudioBridge.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeAudioBridge.kt @@ -4,39 +4,23 @@ package cc.tiredsysadmin.android.sizzle.audio /** - * Bridges the native Oboe (AAudio) output backend to the Kotlin [AudioEngine]. - * - * The C++ side (see `src/main/cpp/native_audio.cpp`) opens a low-latency Oboe - * stream whose real-time data callback calls [renderAudio] via JNI, which simply - * delegates to [AudioEngine.fillBlock]. So the exact same synth/sequencer/mixer - * code produces the audio; only the *delivery* path changes (a native callback - * pulling data, vs. AudioTrack blocking writes), which is what lowers latency. - * - * If the native library fails to load (e.g. the NDK build was skipped) the whole - * feature is inert and the engine transparently uses its AudioTrack loop. + * The native Oboe (AAudio) output (src/main/cpp/native_audio.cpp). Its real-time + * callback renders straight from the shared C++ engine; nothing calls back into + * the JVM on the audio thread. If it can't start, [AudioEngine] falls back to an + * AudioTrack loop that renders through [NativeEngine.nativeRender]. */ -class NativeAudioBridge(private val engine: AudioEngine) { - - /** Invoked from the native audio callback thread. Must not allocate. */ - @Suppress("unused") // called via JNI - fun renderAudio(buffer: FloatArray, frames: Int) { - engine.fillBlock(buffer, frames) - } - - fun start(sampleRate: Int, framesPerCallback: Int): Boolean = - if (LIB_LOADED) nativeStart(this, sampleRate, framesPerCallback) else false +class NativeAudioBridge { + fun start(sampleRate: Int): Boolean = if (NativeEngine.loaded) nativeStart(sampleRate) else false fun stop() { - if (LIB_LOADED) nativeStop() + if (NativeEngine.loaded) nativeStop() } - private external fun nativeStart(callback: NativeAudioBridge, sampleRate: Int, framesPerCallback: Int): Boolean + private external fun nativeStart(sampleRate: Int): Boolean private external fun nativeStop() companion object { - private val LIB_LOADED = runCatching { System.loadLibrary("sizzle_native") }.isSuccess - - /** Whether the native Oboe backend is available on this build/device. */ - fun isAvailable(): Boolean = LIB_LOADED + /** Whether the native library loaded on this build/device. */ + fun isAvailable(): Boolean = NativeEngine.loaded } } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeEngine.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeEngine.kt new file mode 100644 index 0000000..26768c6 --- /dev/null +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/NativeEngine.kt @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.audio + +/** + * JNI to the shared C++ engine (core/src/host/EngineHost through + * src/main/cpp/jni_engine.cpp): the same engine, devices and sequencer the iOS app + * runs. [AudioEngine] is the app's face of it. Every call is a no-op when the + * native library isn't loaded (JVM unit tests). + */ +object NativeEngine { + val loaded: Boolean = runCatching { System.loadLibrary("sizzle_native") }.isSuccess + @Volatile var created = false; private set + + fun create(sampleRate: Int) { + if (!loaded || created) return + nativeCreate(sampleRate) + created = true + // Samples decoded before the engine existed (crash-recovery restore, presets). + SampleStore.forEachSample { id, s -> putSample(id, s) } + } + + fun putSample(id: String, s: SampleStore.Sample) { + if (created) nativePutSample(id, s.data, s.sampleRate, s.loopStart, s.loopEnd) + } + + fun removeSample(id: String) { if (created) nativeRemoveSample(id) } + + external fun nativeCreate(sampleRate: Int) + external fun nativeLoad(text: String) + external fun nativeSync(text: String) + external fun nativeRebuildFxChains() + external fun nativeRebuildArrangement() + external fun nativeRefreshLoopPlaylist() + external fun nativePlay(beat: Int) + external fun nativePause() + external fun nativeStop() + external fun nativePanic() + external fun nativeTransport(): Long + external fun nativeLiveNoteOn(pitch: Int, velocity: Int) + external fun nativeLiveNoteOff(pitch: Int) + external fun nativeAuditionSlotOn(slot: Int, midi: Int) + external fun nativeAuditionSlotOff(midi: Int) + external fun nativeBusNoteOn(channel: Int, midi: Int, velocity: Int) + external fun nativeBusNoteOff(channel: Int, midi: Int) + external fun nativeDescribeBusTargets(channel: Int, midi: Int): String + external fun nativeChannelMeter(ch: Int): Float + external fun nativeChannelClipped(ch: Int): Boolean + external fun nativeEffectScope(slot: Int, out: FloatArray): Int + external fun nativeEffectPlayhead(slot: Int): Float + external fun nativeSetMidiOutEnabled(on: Boolean) + external fun nativePollMidiOut(): Int + external fun nativePutSample(id: String, data: FloatArray, rate: Int, loopStart: Int, loopEnd: Int) + external fun nativeRemoveSample(id: String) + external fun nativeSetRecordPath(path: String) + external fun nativeSetRecordingArm(armed: Boolean, tailBars: Int) + external fun nativeSetRecordTailBars(tailBars: Int) + external fun nativeRecordingActive(): Boolean + external fun nativeTakeFinished(): String? + external fun nativeEndCapture() + external fun nativeExternalClockStart() + external fun nativeExternalClockStop() + external fun nativeRender(out: FloatArray, frames: Int) +} diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/SampleStore.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/SampleStore.kt index 57812ee..365904c 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/SampleStore.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/SampleStore.kt @@ -30,12 +30,16 @@ object SampleStore { private val samples = ConcurrentHashMap() - fun put(id: String, sample: Sample) { samples[id] = sample } + /** Also hands the sample to the native engine, which plays from its own store. */ + fun put(id: String, sample: Sample) { samples[id] = sample; NativeEngine.putSample(id, sample) } + + /** Every stored sample (NativeEngine copies them when it starts). */ + fun forEachSample(action: (String, Sample) -> Unit) { samples.forEach { (id, s) -> action(id, s) } } fun get(id: String): Sample? = if (id.isEmpty()) null else samples[id] /** Drop a cached sample so its PCM can be GC'd. Any voice already playing it * keeps its own reference, so removing a live sample never crashes playback. */ - fun remove(id: String) { if (id.isNotEmpty()) samples.remove(id) } + fun remove(id: String) { if (id.isNotEmpty()) { samples.remove(id); NativeEngine.removeSample(id) } } /** * Decode a WAV file (the common uncompressed formats) into a mono [Sample]. diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt index b5059a9..31f0548 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt @@ -825,7 +825,8 @@ class AppViewModel( viewModelScope.launch { bindingStore.save(keyboardInput, gamepadInput, midiInput) } } - private fun touched() { revision++ } + /** Every edit ends here: redraw, and bring the engine's copy of the song up to date. */ + private fun touched() { revision++; engine.requestSync() } /** Public hook so screens that mutate the model directly (e.g. dropdowns in * the toolbar, mixer faders) can request a redraw. */ diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ChannelArpTest.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ChannelArpTest.kt index da2d6f4..ab35b89 100644 --- a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ChannelArpTest.kt +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ChannelArpTest.kt @@ -14,7 +14,7 @@ import org.junit.Test */ class ChannelArpTest { - private fun arp() = AudioEngine.ChannelArp() + private fun arp() = ReferenceEngine.ChannelArp() /** The Up sequence over a chord × octaves is octave-major over the sorted notes. */ @Test fun upCyclesWholeChordAcrossOctaves() { diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ClockRecordingTest.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ClockRecordingTest.kt index ee2ec2b..2d8b811 100644 --- a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ClockRecordingTest.kt +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ClockRecordingTest.kt @@ -22,7 +22,7 @@ class ClockRecordingTest { private val fs = 48_000 private val block = 192 - private fun engine(dir: File, tailBars: Int, done: (File) -> Unit) = AudioEngine(fs).apply { + private fun engine(dir: File, tailBars: Int, done: (File) -> Unit) = ReferenceEngine(fs).apply { setProject(Project().apply { tempoBpm = 120f }) recTempDir = dir onRecordingComplete = { f, _ -> @@ -33,7 +33,7 @@ class ClockRecordingTest { /** Render [frames], paced (about 10x real time) so the recorder's writer thread * keeps up with its one-second ring, as it does on a device. */ - private fun AudioEngine.run(frames: Int) { + private fun ReferenceEngine.run(frames: Int) { val out = FloatArray(block * 2) repeat(frames / block) { i -> fillBlock(out, block); if (i % 25 == 24) Thread.sleep(10) } } diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenExport.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenExport.kt index c877022..9cd4cd6 100644 --- a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenExport.kt +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenExport.kt @@ -27,11 +27,11 @@ import kotlin.math.roundToInt import kotlin.math.sin /** - * Feeds the iOS port (ios/core): the Kotlin DSP is the reference the C++ port must + * Feeds the shared C++ engine (core/): the Kotlin DSP is the reference the C++ port must * reproduce. Runs only when SIZZLE_GOLDEN_DIR is set (`make -C ios golden`), so the * normal `make check` skips it. Writes: * - * - `ios/core/include/sizzle/DeviceSpecs.gen.hpp` (SIZZLE_SPECS_OUT): every + * - `core/include/sizzle/DeviceSpecs.gen.hpp` (SIZZLE_SPECS_OUT): every * device's parameters and the Mix Tightener presets, so iOS shares one definition; * - into SIZZLE_GOLDEN_DIR: `input.f32` (a fixed test signal) and, per audio * effect and scenario, `__.scn` (its parameters) and diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenSongs.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenSongs.kt index b9f612f..f7cb2c1 100644 --- a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenSongs.kt +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/IosGoldenSongs.kt @@ -82,7 +82,7 @@ class IosGoldenSongs { if (seconds > 0) { meta.append("clock ${java.lang.Double.toString(FrasilClock.seconds)}\n") meta.append("seeds ${counter(FrasilVoice::class.java)} ${counter(GrainCloud::class.java)}\n") - val engine = AudioEngine(SR).apply { setProject(p) } + val engine = ReferenceEngine(SR).apply { setProject(p) } engine.play() val frames = (seconds * SR).toInt() / BLOCK * BLOCK val buf = FloatArray(BLOCK * 2) diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ReferenceEngine.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ReferenceEngine.kt new file mode 100644 index 0000000..cc05c02 --- /dev/null +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/ReferenceEngine.kt @@ -0,0 +1,1667 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.audio + +import android.media.AudioAttributes +import android.media.AudioFormat +import android.media.AudioTrack +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.wavetable.WavePatch +import cc.tiredsysadmin.android.sizzle.model.Arrangement +import cc.tiredsysadmin.android.sizzle.model.Pattern +import cc.tiredsysadmin.android.sizzle.model.Project +import cc.tiredsysadmin.android.sizzle.model.SamplerPads +import cc.tiredsysadmin.android.sizzle.model.TimeDivision +import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot +import cc.tiredsysadmin.android.sizzle.model.ToolboxType +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlin.concurrent.thread +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.sin +import kotlin.math.tanh + +/** + * The real-time sound engine. It owns one [AudioTrack] and a dedicated render + * thread that is completely separate from the UI thread — this is what keeps + * playback smooth while the interface is being touched. + * + * The render loop is a classic tracker "sample-accurate sequencer": it counts + * audio samples and, exactly when enough samples have elapsed for one tracker + * line, it advances the playhead and triggers that line's notes. Because timing + * is derived from the audio clock (not `Handler.postDelayed`), there is no drift. + * + * PLAYBACK MODES + * -------------- + * - ARRANGEMENT mode (default when the arrangement has any blocks): the + * sequencer walks a pre-expanded playlist of beats (with A/B loop repeats), + * and at each beat every filled lane plays one beat of its pattern. A lane + * keeps its own cursor so a block spanning several consecutive beats advances + * through the pattern beat-by-beat. + * - PATTERN-LOOP mode (when the arrangement is empty): the currently-edited + * pattern loops, so the Tracker tab is always audible while you edit. + * + * Voices are pooled PER MIXER BUS: each of the [TRACK_COUNT] buses owns a pool of + * [POLYPHONY] synth + [POLYPHONY] sample voices, so a single instrument can sound + * up to [POLYPHONY] notes at once (chords, overlapping release tails) rather than + * one. Notes are allocated round-robin, stealing the oldest voice when the pool is + * full — the requested "N sounds per instrument" cap. + * + * INSTRUMENTS: the subtractive [SynthVoice] (NES synth), the Sampler and the + * SoundFont are all rendered here. Each bus pool has both [SynthVoice]s and + * [SampleVoice]s; the channel's instrument type decides which one a note triggers. + * Each mixer channel runs its own insert-effect chain (delay / filter / reverb / + * bitcrusher / EQ) — see [Effects.kt] and [rebuildFxChains]. Swapping this + * Kotlin/AudioTrack loop for an Oboe (C++/AAudio) engine is a later milestone. + */ +// The Kotlin engine as it was before Android moved to the shared C++ engine +// (core/, through audio/AudioEngine + jni_engine.cpp). Kept in the tests only, as +// the reference the C++ port is checked against (IosGolden*), and for the engine +// behaviour tests (arp, clock recording). +class ReferenceEngine( + private val sampleRate: Int = 48_000, +) { + // Sequencer voices: a per-mixer-bus pool of POLYPHONY synth + POLYPHONY sample + // voices, laid out as bus*POLYPHONY + i. A note plays whatever instrument its + // channel routes to, allocated from that bus's pool, so one instrument can sound + // several notes simultaneously instead of stealing its single voice every time. + private val seqVoices = Array(Pattern.TRACK_COUNT * POLYPHONY) { SynthVoice(sampleRate) } + private val sampleVoices = Array(Pattern.TRACK_COUNT * POLYPHONY) { SampleVoice(sampleRate) } + // Round-robin steal cursors per bus (which pool slot to reuse when all are busy). + private val synthAlloc = IntArray(Pattern.TRACK_COUNT) + private val sampleAlloc = IntArray(Pattern.TRACK_COUNT) + // ... plus a small pool for live auditioning from keyboard / MIDI / pads. + private val liveVoices = Array(LIVE_POLYPHONY) { SynthVoice(sampleRate) } + // Sample voices for previewing sampler instruments (toolbox keyboard / editor). + private val auditionSampleVoices = Array(AUDITION_POLYPHONY) { SampleVoice(sampleRate) } + // Live "mix bus" audition voices: polyphony per mixer channel, laid out as + // channel*BUS_POLYPHONY + i. Rendered INTO the channel sum (pre-FX) so playing + // one auditions the whole bus — the channel's instrument through its FX chain, + // volume, and mute/solo. Driven by the toolbox MIDI piano via busNoteOn/Off. + private val busVoices = Array(Pattern.TRACK_COUNT * BUS_POLYPHONY) { SynthVoice(sampleRate) } + private val busSampleVoices = Array(Pattern.TRACK_COUNT * BUS_POLYPHONY) { SampleVoice(sampleRate) } + // Per-(lane,track) arpeggiator state, driven by advanceArps. + private val arps = Array(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { ChannelArp() } + // Bumped once per triggered line. Notes reaching an arpeggiator with the same + // stamp are the same line's chord (accumulated into one arp); a new stamp starts + // a fresh chord. Lets a held chord arpeggiate all its notes instead of collapsing + // to the last one entered. Audio-thread only. + private var lineTriggerGen = 0 + // Per-(lane,track) MIDI channel the track last played a note on. A note-off cell + // is tied to its track (it has no channel of its own) and releases whatever the + // track last started, on the bus(es) that channel routed to. -1 = nothing yet. + private val trackLastChannel = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { -1 } + + // ---- outgoing MIDI (send the sequenced notes to external gear) ---- + // The sequencer runs on the audio thread, which must not do MIDI I/O; note events + // are packed into a lock-free single-producer/single-consumer ring that the MIDI + // clock thread drains via [pollMidiOut]. Only filled when [midiOutEnabled]. Each + // slot packs (status<<16)|(data1<<8)|data2. Note-on/off mirror the tracks' cells + // (mono per track, matching the internal note lifecycle) on the cell's MIDI channel. + @Volatile var midiOutEnabled = false + private val moutRing = IntArray(256) + @Volatile private var moutHead = 0 // producer (audio thread) + @Volatile private var moutTail = 0 // consumer (MIDI clock thread) + private val moutNote = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { -1 } + private val moutCh = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) + + // Grain Cloud (ECHOFIELD port): one shared cloud per mixer channel, held notes + // pitch its grains; plus one for the editor's audition keyboard. A cloud renders + // only while its channel's instrument is a Grain Cloud (cloudOn). + private val clouds = Array(Pattern.TRACK_COUNT) { GrainCloud(sampleRate) } + private val cloudOn = BooleanArray(Pattern.TRACK_COUNT) + private val cloudVer = IntArray(Pattern.TRACK_COUNT) { -1 } + private val cloudTempo = FloatArray(Pattern.TRACK_COUNT) { Float.NaN } + private val auditionCloud = GrainCloud(sampleRate) + private var auditionCloudVer = -1 + private var auditionCloudTempo = Float.NaN + private var auditionCloudActive = false + + // Cached subtractive-synth patch per bus, reparsed only when the slot changes + // (version) or tempo changes — so note triggers don't allocate a patch each time, + // and active voices can be refreshed per block for live parameter feedback. + private val synthPatch = arrayOfNulls(Pattern.TRACK_COUNT) + private val synthPatchVer = IntArray(Pattern.TRACK_COUNT) { -1 } + private val synthPatchTempo = FloatArray(Pattern.TRACK_COUNT) { Float.NaN } + // Same, for the toolbox editor's audition (liveVoices) — tracks the slot currently + // being auditioned so live knob turns are heard while a preview note is held. + private var auditionSlotIdx = -1 + private var auditionPatch: SynthPatch? = null + private var auditionPatchVer = -1 + private var auditionPatchTempo = Float.NaN + + /** Grab a free synth voice from [bus]'s pool, or steal the round-robin one. The + * chosen voice is queued into this block's active list so a note started mid-block + * is rendered from the same sample (see [queueSeq]). */ + private fun allocSynthVoice(bus: Int): SynthVoice { + val base = bus * POLYPHONY + for (i in 0 until POLYPHONY) seqVoices[base + i].let { if (!it.isActive) { queueSeq(base + i); return it } } + val idx = synthAlloc[bus] + synthAlloc[bus] = (idx + 1) % POLYPHONY + return seqVoices[base + idx].also { it.kill(); queueSeq(base + idx) } + } + + /** Grab a free sample voice from [bus]'s pool, or steal the round-robin one. + * The stolen voice is NOT killed here — [SampleVoice.noteOn] declicks the hand-off + * itself (an abrupt kill of a loud voice would click). */ + private fun allocSampleVoice(bus: Int): SampleVoice { + val base = bus * POLYPHONY + for (i in 0 until POLYPHONY) sampleVoices[base + i].let { if (!it.isActive) { queueSmp(base + i); return it } } + val idx = sampleAlloc[bus] + sampleAlloc[bus] = (idx + 1) % POLYPHONY + return sampleVoices[base + idx].also { queueSmp(base + idx) } + } + + /** Append a sequencer synth/sample voice index to this block's active list, unless + * it is already queued this block (generation stamp) — dedup prevents a finished- + * then-reallocated voice from being rendered twice in one block. Audio-thread only + * (called from [playNote] via the allocators, all inside [fillBlock]). */ + private fun queueSeq(i: Int) { if (seqGen[i] != blockGen) { seqGen[i] = blockGen; actSeq[actSeqN++] = i } } + private fun queueSmp(i: Int) { if (smpGen[i] != blockGen) { smpGen[i] = blockGen; actSmp[actSmpN++] = i } } + + /** Release (fade out) every active voice on [bus] — a note-off cell on its channel. */ + private fun releaseBus(bus: Int) { + clouds[bus].releaseSequenced() + val base = bus * POLYPHONY + for (i in 0 until POLYPHONY) { + seqVoices[base + i].noteOff() + sampleVoices[base + i].noteOff() + } + } + + /** One insert-effect instance bound to the toolbox slot that configures it. */ + private class FxUnit(val slot: ToolboxSlot, val effect: AudioEffect) { + // Last slot version / tempo pushed into the effect, so [updateFxParams] can + // skip re-parsing params (which allocates) when nothing changed. + var lastVersion = -1 + var lastTempo = Float.NaN + } + + /** Per-channel effect chains (mixer FX slots resolved to real processors). + * Rebuilt when routing changes; parameters refresh live every block. Stored as + * arrays (not lists) because the audio thread iterates them per sample, and a + * `for (u in list)` allocates an Iterator every time — a per-block heap churn + * that caused GC-pause dropouts. Array for-loops allocate nothing. Each rebuild + * swaps in a fresh array (reference assignment is atomic), like [playlist]. */ + @Volatile private var channelChains: Array> = + Array(Pattern.TRACK_COUNT) { emptyArray() } + + /** Scratch buffer: per-channel sum for one sample (audio-thread only). */ + private val channelSum = FloatArray(Pattern.TRACK_COUNT) + + // ---- master brickwall limiter (feed-forward, look-ahead) ---- + // A short delay line lets the peak detector "see" a loud sample coming and pull + // the gain down BEFORE it reaches the output, so the makeup gain below can be + // pushed hard (bringing quiet instruments up to media loudness) while the output + // is mathematically guaranteed to stay under LIM_CEILING — no clipping, and none + // of the tanh saturation a static soft-clipper would add to a hot single voice. + // Gain has instant attack (drops the moment a peak enters the look-ahead window), + // holds for the window length, then releases smoothly toward unity. Audio-thread + // state only. + private val limDelayL = FloatArray(LIM_LOOKAHEAD) + private val limDelayR = FloatArray(LIM_LOOKAHEAD) + private var limPos = 0 + private var limGain = 1f + private var limHold = 0 + // Limiter output for the current sample (avoids a per-sample Pair allocation). + private var limOutL = 0f + private var limOutR = 0f + + // ---- per-channel VU metering (for the mixer strips' fader VU) ---- + // The audio thread tracks each bus's post-fader/post-FX peak within a block, then + // once per block folds it into a smoothly-decaying meter value (instant attack, + // exponential release) and a clip-hold counter (latched when the bus crosses 0 dBFS + // so a brief overload stays visible). The UI polls [channelMeter]/[channelClipped] + // at frame rate. Plain arrays: single writer (audio thread), display-only readers — + // a stale value for one frame is harmless, so no locking/volatility is needed. + private val chBlockPeak = FloatArray(Pattern.TRACK_COUNT) // scratch, reset each block + private val chMeter = FloatArray(Pattern.TRACK_COUNT) // published decaying peak + private val chClipHold = IntArray(Pattern.TRACK_COUNT) // blocks left to show "clipping" + + // Per-block compact active-voice lists (audio-thread only). Rebuilt once per block: + // the per-sample mix loop iterates ONLY the voices that are actually sounding, so it + // never calls render() on idle pool slots (the whole POLYPHONY*TRACK_COUNT pool was + // scanned every sample before). Each list holds global voice indices; the bus for a + // seq/sample/bus voice is index / POLYPHONY (or / BUS_POLYPHONY). + private val actSeq = IntArray(seqVoices.size); private var actSeqN = 0 + private val actSmp = IntArray(sampleVoices.size); private var actSmpN = 0 + private val actBus = IntArray(busVoices.size); private var actBusN = 0 + private val actBSmp = IntArray(busSampleVoices.size); private var actBSmpN = 0 + private val actLive = IntArray(liveVoices.size); private var actLiveN = 0 + private val actASmp = IntArray(auditionSampleVoices.size); private var actASmpN = 0 + // The sequencer can start a note mid-block; its voice must join this block's list so + // it sounds sample-accurately (not one block late). [queueSeq]/[queueSmp] append it, + // deduped by a per-voice generation stamp: a voice already queued this block (stamp + // == [blockGen]) is not added twice — which would otherwise double-render (and + // double the amplitude of) a voice that finished and was re-allocated within a block. + private val seqGen = IntArray(seqVoices.size) + private val smpGen = IntArray(sampleVoices.size) + private var blockGen = 0 + + /** The song being played. Swapped atomically; read on the audio thread. */ + @Volatile private var project: Project? = null + + @Volatile private var playing = false + @Volatile private var running = false + + // ---- Shared position state (audio-thread only) ---- + private var samplesIntoLine = 0.0 + private var pendingTrigger = true + /** Samples per tracker line, refreshed once per block (see [fillBlock]). */ + private var blockSamplesPerLine = 1.0 + + // ---- Pattern-loop mode ---- + private var currentLine = 0 + + // ---- Arrangement mode ---- + private var arrangementMode = false + /** Beat indices to play, in order, with A/B repeats already expanded. Volatile + * and only ever swapped as a whole reference, so it can be rebuilt live from + * the main thread (e.g. a repeat-count change) while the audio thread reads a + * consistent snapshot — see [refreshLoopPlaylist] and [advanceArrangement]. */ + @Volatile private var playlist: IntArray = IntArray(0) + private var playlistIndex = 0 + private var lineInBeat = 0 + /** Local tick of the *edited* block at the current beat, for the tracker + * playhead. Updated as that block sounds; retained when it isn't. */ + private var arrPlayLine = 0 + + private val _transport = MutableStateFlow(TransportState()) + val transport: StateFlow = _transport + + private var renderThread: Thread? = null + private var track: AudioTrack? = null + + // ------------------------------------------------ master-bus recording + // Captures the final mixed output (post limiter) to a WAV file. Recording is + // "armed" from the mixer toolbar and actually begins when playback starts; it + // ends automatically a configurable FX-tail (in bars) after the sequencer + // stops — whether that stop is a pause/stop button or the arrangement reaching + // its end with looping off. + private val masterRecorder = MasterRecorder(sampleRate) + + /** Directory for the staging temp WAV (the app's cache dir); set at startup. */ + var recTempDir: java.io.File? = null + + /** Invoked (on the writer thread) with the finished temp WAV and the recording's + * start epoch-millis when a take finalizes. The app copies it to its destination. */ + var onRecordingComplete: ((java.io.File, Long) -> Unit)? = null + + /** Invoked (on the main thread, from [play]) the moment a take starts capturing. */ + var onRecordingStarted: (() -> Unit)? = null + + @Volatile var recordArmed = false; private set + @Volatile private var recTailBars = 0 + + /** Arm/disarm recording and set the FX-tail length (bars) captured after a stop. */ + fun setRecordingArm(armed: Boolean, tailBars: Int) { + recordArmed = armed + recTailBars = tailBars.coerceIn(0, 8) + } + + /** Update just the FX-tail length (bars) captured after the sequencer stops. */ + fun setRecordTailBars(tailBars: Int) { recTailBars = tailBars.coerceIn(0, 8) } + + // Audio-thread recording state machine (see [recordSample]). Initialized in + // [maybeStartRecording] before the volatile [recCapturing] flag publishes them. + @Volatile private var recCapturing = false + /** An external MIDI clock is running (between its Start and Stop): an armed + * recording captures while either it or the sequencer runs, and its tail starts + * when both have stopped. */ + @Volatile private var extClockRunning = false + private var recWasPlaying = false + private var recTailRemaining = 0 + + /** If armed and a destination temp dir is set, start capturing the master bus. */ + private fun maybeStartRecording() { + if (!recordArmed) return + val dir = recTempDir ?: return + if (masterRecorder.isActive) return // already recording (e.g. replay in the tail) + val temp = java.io.File(dir, "master-rec.wav") + val startMs = System.currentTimeMillis() + val cb = onRecordingComplete + val ok = masterRecorder.begin(temp) { f -> if (f != null) cb?.invoke(f, startMs) } + if (!ok) return + recTailRemaining = -1 + recWasPlaying = true + recCapturing = true // volatile store publishes the two fields above to the audio thread + onRecordingStarted?.invoke() + } + + /** + * Audio thread: feed one master sample to the recorder and run the stop/tail + * state machine. While the sequencer plays, samples stream straight through. On + * the play->stop edge we latch a tail countdown (bars -> samples at the current + * tempo/signature); the recorder keeps capturing the ringing FX/voice tail until + * it elapses, then finalizes the file. Voices and insert FX render every sample + * regardless of [playing], so the tail contains real decaying reverb/delay audio. + */ + private fun recordSample(proj: Project?, left: Float, right: Float) { + val nowPlaying = playing || extClockRunning + if (recWasPlaying && !nowPlaying) { + recTailRemaining = if (proj == null) 0 + else (recTailBars * proj.timeSignature.linesPerBar * samplesPerLine(proj)).toInt() + } + recWasPlaying = nowPlaying + masterRecorder.write(left, right) + if (!nowPlaying) { + if (recTailRemaining <= 0) { + recCapturing = false + masterRecorder.endCapture() + } else { + recTailRemaining-- + } + } + } + + /** An external MIDI clock sent Start (or Continue): start an armed recording, even + * while Sizzle's own sequencer stays stopped (sound-module mode). */ + fun externalClockStart() { + extClockRunning = true + maybeStartRecording() + } + + /** The external clock sent Stop: an armed recording ends after its FX tail (once + * Sizzle's own sequencer isn't playing either). */ + fun externalClockStop() { extClockRunning = false } + + fun setProject(p: Project) { + project = p + rebuildArrangement() + rebuildFxChains() + } + + /** + * Resolve each mixer channel's four FX slots into real effect processors. + * Call from the main thread (from [play], [setProject], or after the user + * changes a channel's FX routing). Effect *parameters* update live every + * block, so only add/remove of an effect needs a rebuild. + */ + fun rebuildFxChains() { + val proj = project ?: return + val next = Array(Pattern.TRACK_COUNT) { emptyArray() } + for (ch in 0 until Pattern.TRACK_COUNT) { + val units = ArrayList(proj.mixer.channels[ch].fxSlots.size) + for (slotIndex in proj.mixer.channels[ch].fxSlots) { + if (slotIndex < 0) continue + val slot = proj.toolbox.getOrNull(slotIndex) ?: continue + val type = slot.type ?: continue + AudioEffect.create(type, sampleRate)?.let { fx -> + units.add(FxUnit(slot, fx)) + } + } + next[ch] = units.toTypedArray() + } + channelChains = next // atomic swap; audio thread sees old or new whole array + } + + /** + * Recomputes the arrangement playlist and resets sequencer position. Call + * from the main thread (never the audio thread) — from [play] and whenever + * the arrangement or loop settings change. + */ + fun rebuildArrangement() { + val proj = project ?: return + val arr = proj.arrangement + arrangementMode = arr.slots.any { lane -> lane.any { it != Arrangement.EMPTY } } + playlist = buildPlaylist(arr) + playlistIndex = 0 + lineInBeat = 0 + arrPlayLine = 0 + } + + /** + * Rebuild the playlist in place from the current loop settings WITHOUT resetting + * the play position (index, cursors, sample counter). Call from the main thread + * after a live edit that only changes the beat sequence — e.g. a loop-region + * repeat-count change — so playback keeps rolling instead of restarting. + * + * The audio thread reads [playlist] as a single volatile snapshot and bounds- + * checks its own index, so swapping the array under it is safe: growing the + * loop appends future repeats seamlessly; shrinking it simply wraps to the loop + * start at the next beat boundary rather than jumping the transport. + */ + fun refreshLoopPlaylist() { + val proj = project ?: return + if (!arrangementMode) return // not looping the arrangement; nothing live to update + playlist = buildPlaylist(proj.arrangement) + } + + /** Expand the arrangement (respecting loop + A/B regions) into a flat beat list. */ + private fun buildPlaylist(arr: Arrangement): IntArray { + val a = arr.regionA + val b = arr.regionB + // With no A/B loop regions in play, walk beats 0..last-filled — never out + // through the trailing empty beats of the canvas. Whether this stops or + // repeats is then decided by loopEnabled in advanceArrangement: loop off + // plays it once and stops after the last filled block; loop on repeats the + // filled span. Regions only take effect while looping (as before). + if (!arr.loopEnabled || (!a.isValid && !b.isValid)) { + val end = (arr.lastFilledBeat() + 1).coerceAtLeast(0) + return IntArray(end) { it } + } + val out = ArrayList() + if (a.isValid) repeat(a.repeats) { for (beat in a.start until a.end) out.add(beat) } + if (b.isValid) repeat(b.repeats) { for (beat in b.start until b.end) out.add(beat) } + return out.toIntArray() + } + + // ---------------------------------------------------------------- lifecycle + /** Kept for the tests that set it; the reference engine has no native backend. */ + var onNativeInitError: ((String) -> Unit)? = null + + fun start() { + if (running) return + running = true + startAudioTrack() + } + + private fun startAudioTrack() { + val minBuf = AudioTrack.getMinBufferSize( + sampleRate, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_FLOAT, + ).coerceAtLeast(BLOCK_FRAMES * 2 * 4 * 2) // stereo float, a couple of blocks + + track = AudioTrack.Builder() + .setAudioAttributes( + AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_MEDIA) + .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) + .build(), + ) + .setAudioFormat( + AudioFormat.Builder() + .setSampleRate(sampleRate) + .setEncoding(AudioFormat.ENCODING_PCM_FLOAT) + .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO) + .build(), + ) + .setBufferSizeInBytes(minBuf) + .setTransferMode(AudioTrack.MODE_STREAM) + .setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY) + .build() + .also { it.play() } + + applyPreferredOutput() // route to the user-chosen USB/audio device, if any + + renderThread = thread(name = "sizzle-audio", priority = Thread.MAX_PRIORITY) { + audioTrackLoop() + } + } + + // ---- USB / audio output device routing ---- + @Volatile private var preferredOutput: android.media.AudioDeviceInfo? = null + + /** Route playback to a specific output device (e.g. a USB DAC), or null for + * the system default. Applied immediately and re-applied on engine restart. */ + fun setPreferredOutput(device: android.media.AudioDeviceInfo?) { + preferredOutput = device + applyPreferredOutput() + } + + private fun applyPreferredOutput() { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) { + track?.setPreferredDevice(preferredOutput) + } + } + + /** Stop the engine entirely (called from the PlaybackService on shutdown). */ + fun release() { + running = false + // Finalize any in-flight recording so the WAV header gets patched and the + // completion callback fires instead of leaving a truncated temp file. + if (recCapturing) { recCapturing = false; masterRecorder.endCapture() } + renderThread?.join(500) + renderThread = null + track?.run { stop(); release() } + track = null + } + + // --------------------------------------------------------------- transport + /** + * Start playback. When [startBeat] is >= 0, seek to that beat in the arrangement + * (or that line in pattern-loop mode) so Play resumes from a marker the user + * placed on the arrangement, instead of always from the top. Ignored if it doesn't + * land inside the current playlist / pattern. + */ + fun play(startBeat: Int = -1) { + rebuildArrangement() + rebuildFxChains() + if (startBeat >= 0) { + if (arrangementMode) { + val list = playlist + // Find the first occurrence of that beat in the (possibly A/B-expanded) + // playlist; if it isn't in there just start from the top. + var seek = -1 + for (i in list.indices) if (list[i] == startBeat) { seek = i; break } + if (seek >= 0) { + playlistIndex = seek; lineInBeat = 0; arrPlayLine = 0; samplesIntoLine = 0.0 + } + } else { + val proj = project + if (proj != null) { + val pat = proj.activePattern() + val line = (startBeat * proj.timeSignature.linesPerBeat).coerceIn(0, pat.length - 1) + currentLine = line; samplesIntoLine = 0.0 + } + } + } + pendingTrigger = true + playing = true + maybeStartRecording() + publish() + } + + fun pause() { playing = false; extClockRunning = false; allSeqVoicesOff(); publish() } + + /** + * MIDI panic: immediately hard-silence every voice — sequencer, live (keyboard/ + * MIDI/gamepad), and audition — and cancel all arpeggiators. Clears stuck or + * hung notes at once (e.g. a MIDI note-on whose note-off never arrived). Does + * not stop the transport; if the sequencer is playing it resumes on the next + * tick. + */ + fun panic() { + clouds.forEach { it.kill() } + auditionCloud.kill() + seqVoices.forEach { it.kill() } + sampleVoices.forEach { it.kill() } + liveVoices.forEach { it.kill() } + auditionSampleVoices.forEach { it.kill() } + busVoices.forEach { it.kill() } + busSampleVoices.forEach { it.kill() } + arps.forEach { it.stop() } + trackLastChannel.fill(-1) + allMidiNotesOff() // release any notes sent to external gear + } + + /** Stop playback. If already stopped, rewind to the very beginning. */ + fun stop() { + extClockRunning = false // Sizzle's Stop also ends a take an external clock started + if (!playing && currentLine == 0 && playlistIndex == 0 && lineInBeat == 0) return + val wasStopped = !playing + playing = false + allSeqVoicesOff() + if (wasStopped) { + currentLine = 0; samplesIntoLine = 0.0 + playlistIndex = 0; lineInBeat = 0 + arrPlayLine = 0 + } + publish() + } + + // ------------------------------------------------------ live note audition + fun liveNoteOn(pitch: Int, velocity: Int) { + val v = liveVoices.firstOrNull { !it.isActive } ?: liveVoices[0].also { it.kill() } + v.noteOn(pitch, velocity, SynthPatch.DEFAULT) + } + + fun liveNoteOff(pitch: Int) { + // Prefer a held (gated) voice over one already releasing, so a fast retrigger + // of the same pitch never leaves the held voice stuck (see [auditionSlotOff]). + (liveVoices.firstOrNull { it.pitch == pitch && it.isGated } + ?: liveVoices.firstOrNull { it.isActive && it.pitch == pitch })?.noteOff() + } + + // ------------------------------------------------------------- render loop + /** The Kotlin AudioTrack fallback loop: fill a block and push it. */ + private fun audioTrackLoop() { + val block = FloatArray(BLOCK_FRAMES * 2) // interleaved stereo (L,R per frame) + while (running) { + val t = track ?: break + fillBlock(block, BLOCK_FRAMES) + t.write(block, 0, BLOCK_FRAMES * 2, AudioTrack.WRITE_BLOCKING) + } + } + + /** + * Render [frames] frames of the whole mix into [out] as INTERLEAVED STEREO — + * out[2*i] = left, out[2*i+1] = right, so [out] must hold at least frames*2 + * samples. This is the single source of truth for audio: it is called by the + * Kotlin AudioTrack loop AND by the native Oboe callback (via [NativeAudioBridge]), + * so both backends produce identical sound. Runs on an audio thread — must not + * allocate. Voices and inserts are mono, so both master channels carry the same + * sum; the output/recording path is nonetheless stereo (2 interleaved channels). + */ + fun fillBlock(out: FloatArray, frames: Int) { + val proj = project + FrasilClock.advance(frames, sampleRate) // the Morph Pad's shared TIDE runs on it + // Per-block param housekeeping: LFOs modulate targets first, then effects + // read their (possibly modulated) parameters. + if (proj != null) { + applyLfos(proj) + updateFxParams(proj) + refreshSynthPatches(proj) + // Tempo/signature only change at control rate, so derive the per-line + // sample count once per block instead of re-dividing every sample. + blockSamplesPerLine = samplesPerLine(proj) + } + val anySolo = proj?.mixer?.anySolo() ?: false + // Snapshot the volatile chains once so a concurrent rebuild can't swap them + // mid-block; indexing + array iteration below then allocate nothing. + val chains = channelChains + + // Once per block: collect the indices of the voices that are actually sounding + // into compact lists, so the per-sample loop iterates only those instead of the + // whole pool. Building the lists costs O(pool) once; rendering then costs + // O(active * frames) rather than O(pool * frames). The sequencer appends any + // note it starts mid-block via [queueSeq]/[queueSmp] (see [advanceSequencer]). + blockGen++ + actSeqN = 0; actSmpN = 0; actBusN = 0; actBSmpN = 0; actLiveN = 0; actASmpN = 0 + for (ch in 0 until Pattern.TRACK_COUNT) chBlockPeak[ch] = 0f // reset per-channel VU accumulators + for (i in seqVoices.indices) if (seqVoices[i].isActive) { seqGen[i] = blockGen; actSeq[actSeqN++] = i } + for (i in sampleVoices.indices) if (sampleVoices[i].isActive) { smpGen[i] = blockGen; actSmp[actSmpN++] = i } + for (i in busVoices.indices) if (busVoices[i].isActive) actBus[actBusN++] = i + for (i in busSampleVoices.indices) if (busSampleVoices[i].isActive) actBSmp[actBSmpN++] = i + for (i in liveVoices.indices) if (liveVoices[i].isActive) actLive[actLiveN++] = i + auditionCloudActive = auditionCloud.isActive + for (i in auditionSampleVoices.indices) if (auditionSampleVoices[i].isActive) actASmp[actASmpN++] = i + + for (i in 0 until frames) { + if (playing && proj != null) advanceSequencer(proj) + + var mixL = 0f + var mixR = 0f + if (proj != null) { + channelSum.fill(0f) + // Sum only the voices that are actually sounding this block. Each voice's + // bus is its index / pool stride. Live bus-audition voices feed the same + // per-channel sum, so they run through the channel's FX/volume/mute like + // the sequencer. + for (k in 0 until actSeqN) { val vi = actSeq[k]; channelSum[vi / POLYPHONY] += seqVoices[vi].render() } + for (k in 0 until actSmpN) { val vi = actSmp[k]; channelSum[vi / POLYPHONY] += sampleVoices[vi].render() } + for (k in 0 until actBusN) { val vi = actBus[k]; channelSum[vi / BUS_POLYPHONY] += busVoices[vi].render() } + for (k in 0 until actBSmpN) { val vi = actBSmp[k]; channelSum[vi / BUS_POLYPHONY] += busSampleVoices[vi].render() } + for (ch in 0 until Pattern.TRACK_COUNT) if (cloudOn[ch]) channelSum[ch] += clouds[ch].render() + for (ch in 0 until Pattern.TRACK_COUNT) { + val mc = proj.mixer.channels[ch] + var s = if (mc.audible(anySolo)) channelSum[ch] * mc.volume else 0f + val chain = chains[ch] + for (u in chain) s = u.effect.process(s) + // Isolate a misbehaving effect: a non-finite sample from one + // channel's FX must not poison the whole master sum. + if (!s.isFinite()) s = 0f + // Optional per-bus soft-clip limiter (toolbar toggle). + if (mc.limiter) s = softClip(s) + // Track this bus's peak for the mixer VU (post-fader/post-FX). + val a = if (s < 0f) -s else s + if (a > chBlockPeak[ch]) chBlockPeak[ch] = a + // Voices and inserts are mono; both master channels get the same + // sum. The master output/recording path stays stereo (2 channels). + mixL += s; mixR += s + } + } + for (k in 0 until actLiveN) { val v = liveVoices[actLive[k]].render() * LIVE_GAIN; mixL += v; mixR += v } + if (auditionCloudActive) { val v = auditionCloud.render() * LIVE_GAIN; mixL += v; mixR += v } + for (k in 0 until actASmpN) { val v = auditionSampleVoices[actASmp[k]].render() * LIVE_GAIN; mixL += v; mixR += v } + // Makeup gain (lifts instruments to media loudness) into a look-ahead + // brickwall limiter that guarantees the output stays under the ceiling. + masterLimit(mixL * MASTER_MAKEUP, mixR * MASTER_MAKEUP) + val oL = limOutL + val oR = limOutR + out[2 * i] = oL + out[2 * i + 1] = oR + if (recCapturing) recordSample(proj, oL, oR) + } + + // Fold this block's per-channel peaks into the VU meter values: instant attack + // (jump up to a new peak), exponential release (decay back down), plus a clip + // latch that holds when the bus crossed 0 dBFS so a momentary overload is seen. + for (ch in 0 until Pattern.TRACK_COUNT) { + val peak = chBlockPeak[ch] + val decayed = chMeter[ch] * METER_DECAY + chMeter[ch] = if (peak > decayed) peak else decayed + if (peak >= METER_CLIP_LEVEL) chClipHold[ch] = METER_CLIP_HOLD_BLOCKS + else if (chClipHold[ch] > 0) chClipHold[ch]-- + } + } + + /** Current VU level (peak amplitude, ~0..1+) for mixer bus [ch]; 0 if out of range. */ + fun channelMeter(ch: Int): Float = if (ch in chMeter.indices) chMeter[ch] else 0f + + /** True while bus [ch] is (or recently was) clipping past 0 dBFS — drives the red VU. */ + fun channelClipped(ch: Int): Boolean = ch in chClipHold.indices && chClipHold[ch] > 0 + + /** The live visualization source for toolbox [slotIndex], if that slot is an effect + * in some channel's insert chain and produces one (first match wins). Read on the + * UI thread; the returned processor's viz fields are written by the audio thread. */ + private fun vizFor(slotIndex: Int): VizEffect? { + val chains = channelChains + for (ch in chains) for (u in ch) { + if (u.slot.index == slotIndex) { val e = u.effect; if (e is VizEffect) return e } + } + return null + } + + /** Copy effect [slotIndex]'s scope samples into [out]; -1 if it isn't a live, + * routed viz effect (nothing to draw). */ + fun effectScope(slotIndex: Int, out: FloatArray): Int = vizFor(slotIndex)?.copyScope(out) ?: -1 + + /** Effect [slotIndex]'s playhead (0..1), or -1 if no live viz source. */ + fun effectPlayhead(slotIndex: Int): Float = vizFor(slotIndex)?.playhead() ?: -1f + + /** + * Feed-forward, look-ahead brickwall limiter for the master bus. Results land in + * [limOutL]/[limOutR] (no per-sample allocation). Runs on the audio thread. + * + * How it guarantees "no clipping": the incoming (post-makeup) sample is pushed + * into a [LIM_LOOKAHEAD]-sample delay line, and the gain is driven by the *newest* + * sample while it is applied to the *oldest* (delayed) one. When a sample louder + * than [LIM_CEILING] enters, the gain drops instantly to exactly the amount needed + * to tame it and is *held* for the whole look-ahead window (plus a small margin), + * so by the time that loud sample reaches the output the gain is already pulled + * down — the delayed peak can never exceed the ceiling. Between peaks the gain + * releases smoothly back toward unity, so quiet passages keep the full makeup. + * A final hard clamp is a cheap belt-and-braces guard (it should never engage). + */ + private fun masterLimit(inL: Float, inR: Float) { + val dL = limDelayL[limPos] + val dR = limDelayR[limPos] + limDelayL[limPos] = inL + limDelayR[limPos] = inR + limPos++; if (limPos >= LIM_LOOKAHEAD) limPos = 0 + + val peak = max(abs(inL), abs(inR)) + val target = if (peak > LIM_CEILING) LIM_CEILING / peak else 1f + when { + target < limGain -> { limGain = target; limHold = LIM_LOOKAHEAD + LIM_HOLD_EXTRA } + limHold > 0 -> limHold-- + else -> limGain += (1f - limGain) * LIM_RELEASE + } + + var oL = dL * limGain + var oR = dR * limGain + if (oL > LIM_CEILING) oL = LIM_CEILING else if (oL < -LIM_CEILING) oL = -LIM_CEILING + if (oR > LIM_CEILING) oR = LIM_CEILING else if (oR < -LIM_CEILING) oR = -LIM_CEILING + limOutL = if (oL.isFinite()) oL else 0f + limOutR = if (oR.isFinite()) oR else 0f + } + + /** Push slot parameters (+ tempo) into every live effect processor, but only when + * they actually changed — re-parsing unchanged params every block allocates and + * caused GC-pause dropouts when several effects were stacked. */ + private fun updateFxParams(proj: Project) { + val tempo = proj.tempoBpm + val chains = channelChains + for (ch in 0 until Pattern.TRACK_COUNT) { + val chain = chains[ch] + for (u in chain) { + val v = u.slot.version + if (v != u.lastVersion || tempo != u.lastTempo) { + u.effect.update(u.slot, tempo) + u.lastVersion = v + u.lastTempo = tempo + } + } + } + } + + // Lock-free xorshift RNG for the audio thread. Math.random() is backed by a + // single synchronized java.util.Random, so calling it on the real-time thread + // risks lock contention / priority inversion; this never blocks or allocates. + private var rngState = 0x9E3779B9.toInt() + /** Next pseudo-random float in [0,1). */ + private fun nextRandomUnit(): Float { + var s = rngState + s = s xor (s shl 13); s = s xor (s ushr 17); s = s xor (s shl 5) + rngState = s + return (s.toLong() and 0xFFFFFFFFL).toFloat() * 2.3283064e-10f + } + + // ---- MIDI LFO modulation ---- + private val lfoPhase = DoubleArray(Project.TOOLBOX_SLOTS) + private val lfoSampleHold = DoubleArray(Project.TOOLBOX_SLOTS) { Math.random() * 2 - 1 } + + /** + * Apply every LFO slot's modulation to its target parameter, once per block. + * The target is stored as "slotIndex:paramKey"; the LFO oscillates the value + * around a captured centre by ±depth·(half the param's range). The LFO thus + * "takes over" its target parameter while active. + */ + private fun applyLfos(proj: Project) { + val secondsPerBeat = 60.0 / proj.tempoBpm + val blockSeconds = BLOCK_FRAMES.toDouble() / sampleRate + for (i in proj.toolbox.indices) { + val lfo = proj.toolbox[i] + if (lfo.type != ToolboxType.LFO) continue + val target = lfo.string("target") + val sep = target.indexOf(':') + if (sep <= 0) continue + // Parse the target slot index from target[0 until sep] without a substring + // or a boxed Int? — this runs every block for each active LFO. + var tIdx = 0 + var validIdx = true + for (ci in 0 until sep) { + val ch = target[ci] + if (ch < '0' || ch > '9') { validIdx = false; break } + tIdx = tIdx * 10 + (ch - '0') + } + if (!validIdx || tIdx == i) continue + val tSlot = proj.toolbox.getOrNull(tIdx) ?: continue + val params = tSlot.type?.params ?: continue + // Match the param key by region rather than target.substring(sep + 1): + // this runs every block for each active LFO, and the slot-index parse + // above already goes to this trouble. regionMatches allocates nothing. + val keyFrom = sep + 1 + val keyLen = target.length - keyFrom + // Indexed scan (not firstOrNull {}) so no Iterator allocates per block. + var specIdx = -1 + for (pi in params.indices) { + val k = params[pi].key + if (k.length == keyLen && target.regionMatches(keyFrom, k, 0, keyLen)) { + specIdx = pi; break + } + } + if (specIdx < 0) continue + val spec = params[specIdx] + + val div = TimeDivision.fromIndex(lfo.float("division", 3f).toInt()) + val freq = 1.0 / (div.beatFraction * secondsPerBeat).coerceAtLeast(1e-6) + val advanced = lfoPhase[i] + freq * blockSeconds + if (advanced >= 1.0) lfoSampleHold[i] = nextRandomUnit() * 2.0 - 1.0 + lfoPhase[i] = advanced % 1.0 + val phase = (lfoPhase[i] + lfo.float("phase", 0f)) % 1.0 + + val value = when (lfo.string("wave", "Sine")) { + "Triangle" -> 1.0 - 4.0 * abs(phase - 0.5) + "Saw" -> 2.0 * phase - 1.0 + "Square" -> if (phase < 0.5) 1.0 else -1.0 + "SampleHold" -> lfoSampleHold[i] + else -> sin(2 * Math.PI * phase) + } + val center = lfo.float("center", spec.default).toDouble() + val half = (spec.max - spec.min) / 2.0 + val modulated = (center + lfo.float("depth", 0.5f) * value * half) + .coerceIn(spec.min.toDouble(), spec.max.toDouble()) + tSlot.set(spec.key, modulated.toFloat()) + } + } + + /** Dispatch one sample of sequencer time to the active playback mode. */ + private fun advanceSequencer(proj: Project) { + if (arrangementMode) advanceArrangement(proj) else advancePatternLoop(proj) + advanceArps(proj) // arpeggiators retrigger between note events + } + + // ----- Pattern-loop mode (Tracker tab audition) ----- + private fun advancePatternLoop(proj: Project) { + val pattern = proj.activePattern() + val samplesPerLine = blockSamplesPerLine + + if (pendingTrigger) { + val linesPerBar = proj.timeSignature.linesPerBar + if (linesPerBar > 0 && currentLine % linesPerBar == 0) resetBarArps() + triggerPatternLine(proj, pattern, currentLine) + pendingTrigger = false + } + samplesIntoLine += 1.0 + if (samplesIntoLine >= samplesPerLine) { + samplesIntoLine -= samplesPerLine + currentLine++ + if (currentLine >= pattern.length) currentLine = 0 + pendingTrigger = true + publish() + } + } + + private fun triggerPatternLine(proj: Project, pattern: Pattern, line: Int) { + lineTriggerGen++ // new line — notes below form one chord per arpeggiator + // Pattern-loop plays on lane 0's voices; each cell is routed by its channel. + // Apply note-offs FIRST, then note-ons, so a note-off on one track never + // cancels a note that begins on the same line/bus (a note-off releases the + // whole bus; without this ordering it would kill a just-triggered voice). + for (t in 0 until Pattern.TRACK_COUNT) { + val cell = pattern.cell(t, line) + if (cell.isNoteOff) triggerCell(proj, lane = 0, track = t, cell = cell) + } + for (t in 0 until Pattern.TRACK_COUNT) { + val cell = pattern.cell(t, line) + if (cell.isPlayable) triggerCell(proj, lane = 0, track = t, cell = cell) + } + } + + /** + * Trigger one tracker [cell] from source [track] on [lane]. + * + * A PLAYABLE note is routed to the mixer bus(es) whose MIDI channel matches the + * cell's channel — NOT the source track — so a note plays whatever instrument + * sits on its channel's bus, wherever it's placed in the grid (this decouples + * tracks from buses). Each matching bus applies its own MIDI effects (Transposer + * shifts pitch; an Arpeggiator captures the note, retriggered by [advanceArps]). + * The channel used is remembered per (lane, track). + * + * A NOTE-OFF is tied to its TRACK, not to a channel: it has no channel/velocity + * of its own and simply releases whatever this track last started — on the same + * bus(es) that track's previous note routed to ([trackLastChannel]). + */ + private fun triggerCell(proj: Project, lane: Int, track: Int, cell: cc.tiredsysadmin.android.sizzle.model.Cell) { + val trackKey = lane * Pattern.TRACK_COUNT + track + if (cell.isNoteOff) { releaseTrack(proj, lane, track); return } + if (!cell.isPlayable) return + // Remember the channel so a later note-off on this track releases it. + trackLastChannel[trackKey] = cell.channel + // Send this track's note out to external gear (mono per track): off the note it + // was holding, then on the new one, on the cell's MIDI channel. Mirrors the + // tracks' cells — a channel's Arpeggiator/Transposer are internal FX and aren't + // reflected here. + if (moutNote[trackKey] >= 0) emitNoteOff(moutCh[trackKey], moutNote[trackKey]) + emitNoteOn(cell.channel, cell.note, cell.velocity) + moutNote[trackKey] = cell.note; moutCh[trackKey] = cell.channel + // Mono-per-track: a new note releases whatever this track was still holding, + // so a held note is stopped when the next one appears under the playhead — no + // explicit note-off cell needed. Only this track's own voices are released, so + // notes other tracks hold on the same bus (chords across tracks) keep sounding. + releaseTrackVoices(trackKey) + for (bus in 0 until Pattern.TRACK_COUNT) { + if (proj.mixer.channels[bus].midiChannel != cell.channel) continue + val arp = arps[lane * Pattern.TRACK_COUNT + bus] + val velocity = cell.velocity.coerceIn(0, 127) + val note = (cell.note + channelTranspose(proj, bus)).coerceIn(0, 127) + val arpSlot = channelArpSlot(proj, bus) + if (arpSlot != null) { + val octaves = arpSlot.float("octaves", 1f).toInt() + val div = TimeDivision.fromIndex(arpSlot.float("division", 3f).toInt()) + val stepSamples = div.beatFraction * (60.0 / proj.tempoBpm) * sampleRate + val mode = arpSlot.string("mode", "Up") + val resetBar = arpSlot.string("resetbar", "Off") == "On" + when { + arp.active && arp.genStamp == lineTriggerGen -> { + // Another note of the SAME line's chord — accumulate it so the + // arp cycles the whole chord (not just the last note entered). + arp.addNote(note) + arp.refresh(octaves, mode, stepSamples, resetBar) + } + arp.active -> { + // A new line while still arpeggiating (the pattern looping back + // over a held chord): rebuild the chord from this line but keep + // the running phase, so a looping chord doesn't hard-restart or + // slip when the loop length isn't a multiple of the arp step. + arp.resetChord(note, velocity, octaves, mode, stepSamples, resetBar) + arp.genStamp = lineTriggerGen + } + else -> { + // Fresh arp: start on this note and sound it immediately. + arp.startChord(note, velocity, octaves, mode, stepSamples, resetBar) + arp.genStamp = lineTriggerGen + releaseBus(bus) + playNote(proj, bus, arp.currentNote(), velocity) + } + } + } else { + arp.stop() + playNote(proj, bus, note, velocity, ownerTrack = trackKey) + } + } + } + + /** Release (fade out) every still-*held* sequencer voice started by tracker + * [trackKey] — used to make a track monophonic: its previous note is released when + * it plays a new one. Only gated voices are touched (release tails ring out), and + * matching by owner means sibling tracks' notes on a shared bus are left alone. + * Array loops allocate no iterator — safe on the audio thread. */ + /** + * Release one tracker track of one arrangement lane: its outgoing MIDI note, its + * arpeggiator, and the mixer bus it last played on. This is what a note-off cell + * does, lifted out so an arrangement [Arrangement.NOTE_OFF] marker can do the + * same for every track of its lane. + * + * Releasing the whole bus (not just this track's voices) is deliberate and + * matches the note-off cell it was factored from: a note-off is a "stop sounding" + * instruction to the instrument, not to one column. + */ + private fun releaseTrack(proj: Project, lane: Int, track: Int) { + val trackKey = lane * Pattern.TRACK_COUNT + track + // Release this track's outgoing MIDI note first (external gear). + if (moutNote[trackKey] >= 0) { emitNoteOff(moutCh[trackKey], moutNote[trackKey]); moutNote[trackKey] = -1 } + val ch = trackLastChannel[trackKey] + if (ch < 0) return // this track hasn't played anything yet + for (bus in 0 until Pattern.TRACK_COUNT) { + if (proj.mixer.channels[bus].midiChannel != ch) continue + arps[lane * Pattern.TRACK_COUNT + bus].stop() + releaseBus(bus) + } + } + + /** Release every track of [lane] — an arrangement "off" marker reaching the playhead. */ + private fun releaseLane(proj: Project, lane: Int) { + for (t in 0 until Pattern.TRACK_COUNT) releaseTrack(proj, lane, t) + } + + private fun releaseTrackVoices(trackKey: Int) { + for (c in clouds) c.releaseOwner(trackKey) + for (v in seqVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff() + for (v in sampleVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff() + } + + /** + * Sound a note on a mixer [bus]: allocate a [SampleVoice] from the bus pool when + * the channel's instrument is a Sampler/SoundFont with a loaded sample, otherwise + * a [SynthVoice] for the NES synth. Pooled allocation (up to [POLYPHONY] per bus, + * stealing the oldest when full) is what makes the instrument polyphonic. Shared + * by the sequencer and the arpeggiator. + * + * [ownerTrack] tags the allocated voice with the tracker (lane,track) that started + * it (or -1 for arp/unowned notes), so [releaseTrackVoices] can later release just + * this track's note — see [triggerCell]. + */ + private fun playNote(proj: Project, bus: Int, note: Int, velocity: Int, ownerTrack: Int = -1) { + // The allocators ([allocSynthVoice]/[allocSampleVoice]) queue the chosen voice + // into this block's active list, so a note started mid-block sounds sample- + // accurately within the same block. + val slot = proj.toolbox.getOrNull(proj.mixer.channels[bus].instrumentSlot) + val vs = voiceSample(slot, note) + when { + vs != null -> + allocSampleVoice(bus).also { it.ownerTrack = ownerTrack }.noteOn( + vs.sample, note, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, + vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs) + // Empty bus (no instrument — e.g. the default channel 0) or a Sampler + // with an empty pad → silent, matching the live audition path. + slot?.type == null || slot.type == ToolboxType.SAMPLER -> {} + slot.type == ToolboxType.GRAIN_CLOUD -> + clouds[bus].noteOn(note, velocity, if (ownerTrack >= 0) ownerTrack else GrainCloud.OWNER_SEQ) + // NES synth, or a SoundFont with nothing loaded → the tone generator. + else -> { + allocSynthVoice(bus).also { it.ownerTrack = ownerTrack } + .noteOn(note, velocity, synthPatch[bus] ?: patchForSlot(slot, proj.tempoBpm)) + } + } + } + + /** A sample voice's source + pitch + amplitude-envelope info for a note. */ + private class VoiceSample( + val sample: SampleStore.Sample, val root: Int, + val sliceStart: Float, val sliceEnd: Float, val volume: Float, + val attack: Float = 0.002f, val decay: Float = 0f, + val sustain: Float = 1f, val release: Float = 0.02f, + val loop: Boolean = false, val crossfadeMs: Float = 0f, + ) + + /** + * Resolve the PCM sample a note should play for [slot], or null if the slot + * isn't a loaded sample instrument (the caller then uses the synth). + * - Sampler: the pad [note] maps to (root == note, so it plays unpitched). Pads + * stay one-shot (default envelope), just carrying their per-pad volume/slice. + * - SoundFont: the loaded SF2/XI sample, pitched from its stored root note, with + * the user's volume ADSR envelope applied. + */ + private fun voiceSample(slot: ToolboxSlot?, note: Int): VoiceSample? = when (slot?.type) { + ToolboxType.SAMPLER -> { + val pad = SamplerPads.padFor(note) + if (pad !in 0 until SamplerPads.COUNT) { + null + } else { + SampleStore.get(slot.string(SamplerPads.key(pad)))?.let { + VoiceSample( + it, note, + slot.float(SamplerPads.sliceStartKey(pad), 0f), + slot.float(SamplerPads.sliceEndKey(pad), 1f), + slot.float(SamplerPads.volumeKey(pad), SamplerPads.DEFAULT_VOLUME), + ) + } + } + } + ToolboxType.SOUNDFONT -> + SampleStore.get(slot.string("sfSample"))?.let { + VoiceSample( + it, slot.float("sfRoot", 60f).toInt(), 0f, 1f, slot.float("volume", 0.8f), + attack = slot.float("attack", 0.005f), + decay = slot.float("decay", 0.10f), + sustain = slot.float("sustain", 1f), + release = slot.float("release", 0.20f), + loop = slot.string("loop", "Off") == "On", + crossfadeMs = slot.float("loopXfade", 0f), + ) + } + else -> null + } + + /** Realign every active "reset on bar" arpeggiator to step 0 — called on each + * bar downbeat, before that line's own note triggers (so a fresh note-on on the + * downbeat isn't double-fired). */ + private fun resetBarArps() { + for (i in arps.indices) { + val a = arps[i] + if (a.active && a.resetOnBar) a.resetToBar() + } + } + + /** The channel's Arpeggiator slot (first one found in its FX slots), or null. */ + private fun channelArpSlot(proj: Project, track: Int): ToolboxSlot? { + for (idx in proj.mixer.channels[track].fxSlots) { + if (idx < 0) continue + val slot = proj.toolbox.getOrNull(idx) ?: continue + if (slot.type == ToolboxType.ARPEGGIATOR) return slot + } + return null + } + + /** Advance every active arpeggiator by one sample; retrigger on step boundaries. */ + private fun advanceArps(proj: Project) { + for (i in arps.indices) { + val a = arps[i] + if (!a.active) continue + a.samplesLeft -= 1.0 + if (a.samplesLeft <= 0.0) { + // A pending bar reset plays step 0 as-is; otherwise advance the pattern. + if (!a.consumePendingReset()) a.advance() + val bus = i % Pattern.TRACK_COUNT + // Release the previous step before sounding the next one. Without this + // an arp on a *sustaining* instrument (e.g. an SF2/XI with sustain=1 + // and a long sample) stacks a fresh full-level voice every step until + // the whole 8-voice pool is held wide open — a sustained wall of sound + // that overloads any following FX (a reverb's make-up gain then slams + // the limiter). Releasing keeps the arp monophonic with natural tails. + releaseBus(bus) + playNote(proj, bus, a.currentNote(), a.velocity) + a.samplesLeft += a.stepSamples + } + } + } + + /** Per-(lane,track) arpeggiator: cycles through the held chord's notes across the + * octave range. Notes are kept sorted ascending; the linear step sequence is + * octave-major (all chord notes in octave 0, then octave 1, …), walked up / down / + * up-down / randomly by [advance]. [genStamp] identifies the line whose chord this + * holds (see [lineTriggerGen]). Internal (not private) only so a unit test can + * exercise its pure note-sequencing. */ + internal class ChannelArp { + private val notes = IntArray(MAX_CHORD) + var noteCount = 0; private set + var velocity = 100 + private var octaves = 1; private var mode = 0 + var stepSamples = 0.0; var samplesLeft = 0.0 + private var step = 0; private var dir = 1 + var resetOnBar = false + var genStamp = -1 + private var pendingReset = false + private var rng = 0x2545F491.toInt() + private fun rnd(bound: Int): Int { + var s = rng + s = s xor (s shl 13); s = s xor (s ushr 17); s = s xor (s shl 5) + rng = s + return ((s.toLong() and 0xFFFFFFFFL) % bound).toInt() + } + + /** Active while it holds at least one note. */ + val active: Boolean get() = noteCount > 0 + + /** Start a fresh chord on [note], resetting the phase to step 0. */ + fun startChord(note: Int, vel: Int, octs: Int, modeStr: String, stepSamp: Double, resetBar: Boolean) { + noteCount = 0; addNote(note); velocity = vel; octaves = octs.coerceIn(1, 4) + mode = modeOf(modeStr) + stepSamples = stepSamp.coerceAtLeast(1.0); samplesLeft = stepSamples; step = 0; dir = 1 + resetOnBar = resetBar; pendingReset = false + } + + /** Replace the chord with [note] (the next same-line notes re-accumulate) while + * KEEPING the running phase — used when the pattern loops back over a held + * chord so the pulse stays steady instead of restarting. */ + fun resetChord(note: Int, vel: Int, octs: Int, modeStr: String, stepSamp: Double, resetBar: Boolean) { + noteCount = 0; addNote(note); velocity = vel + refresh(octs, modeStr, stepSamp, resetBar) + } + + /** Add a note to the held chord (sorted ascending, de-duplicated). */ + fun addNote(note: Int) { + val n = note.coerceIn(0, 127) + var i = 0 + while (i < noteCount && notes[i] < n) i++ + if (i < noteCount && notes[i] == n) return // already held + if (noteCount >= MAX_CHORD) return + for (j in noteCount downTo i + 1) notes[j] = notes[j - 1] + notes[i] = n; noteCount++ + } + + /** Update params WITHOUT resetting the running phase. */ + fun refresh(octs: Int, modeStr: String, stepSamp: Double, resetBar: Boolean) { + octaves = octs.coerceIn(1, 4) + mode = modeOf(modeStr) + stepSamples = stepSamp.coerceAtLeast(1.0) + resetOnBar = resetBar + } + + fun resetToBar() { step = 0; dir = 1; samplesLeft = 0.0; pendingReset = true } + fun consumePendingReset(): Boolean { val p = pendingReset; pendingReset = false; return p } + + private fun modeOf(modeStr: String): Int = + when (modeStr) { "Down" -> 1; "UpDown" -> 2; "Random" -> 3; else -> 0 } + + fun stop() { noteCount = 0; genStamp = -1 } + + private fun total(): Int = (noteCount * octaves).coerceAtLeast(1) + + fun currentNote(): Int { + if (noteCount <= 0) return 0 + val idx = step.coerceIn(0, total() - 1) + val oct = idx / noteCount + return (notes[idx % noteCount] + 12 * oct).coerceIn(0, 127) + } + + fun advance() { + val total = total() + when (mode) { + 1 -> step = (step - 1 + total) % total + 2 -> if (total > 1) { + step += dir + if (step >= total - 1) { step = total - 1; dir = -1 } + else if (step <= 0) { step = 0; dir = 1 } + } + 3 -> step = if (total > 1) rnd(total) else 0 + else -> step = (step + 1) % total + } + } + + private companion object { const val MAX_CHORD = 8 } + } + + /** Sum of semitone offsets from any MIDI Transposer effects on this channel. */ + private fun channelTranspose(proj: Project, track: Int): Int { + var semis = 0 + for (idx in proj.mixer.channels[track].fxSlots) { + if (idx < 0) continue + val slot = proj.toolbox.getOrNull(idx) ?: continue + if (slot.type == ToolboxType.TRANSPOSER) { + semis += slot.float("semitones", 0f).toInt() + slot.float("octaves", 0f).toInt() * 12 + } + } + return semis + } + + /** Start auditioning a note on the instrument in toolbox [slotIndex] (used by + * the Toolbox test keyboard and the Sampler editor). Polyphonic. */ + fun auditionSlotOn(slotIndex: Int, midi: Int) { + val proj = project ?: return + val slot = proj.toolbox.getOrNull(slotIndex) + val vs = voiceSample(slot, midi) + if (vs != null) { + val v = auditionSampleVoices.firstOrNull { !it.isActive } ?: auditionSampleVoices[0].also { it.kill() } + v.noteOn(vs.sample, midi, 110, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, + vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs) + return + } + // A Sampler with an empty pad stays silent (audition is a one-shot with no + // note-off, so a sustaining synth voice would ring forever). A SoundFont + // with nothing loaded still falls through to the synth preview below. + if (slot?.type == ToolboxType.SAMPLER) return + if (slot?.type == ToolboxType.GRAIN_CLOUD) { + if (auditionSlotIdx != slotIndex || slot.version != auditionCloudVer) { + auditionCloud.setPatch(GrainPatch.from(slot, project?.tempoBpm ?: 120f)) + auditionCloudVer = slot.version + } + auditionSlotIdx = slotIndex + auditionCloud.noteOn(midi, 110, GrainCloud.OWNER_LIVE) + return + } + // Remember which slot is being auditioned so refreshSynthPatches pushes live + // knob turns into the held preview note. + if (hasSynthPatch(slot?.type)) auditionSlotIdx = slotIndex + val v = liveVoices.firstOrNull { !it.isActive } ?: liveVoices[0].also { it.kill() } + v.noteOn(midi, 110, patchForSlot(slot, project?.tempoBpm ?: 120f)) + } + + /** Release an auditioned note (matches both synth and sample audition pools). + * Releases a *held* (gated) voice of this pitch in preference to one that's already + * ringing out its release tail — otherwise rapid re-tapping / chord-tapping the same + * key lands the note-off on the releasing voice and leaves the held one stuck. */ + fun auditionSlotOff(midi: Int) { + auditionCloud.noteOff(midi) + (liveVoices.firstOrNull { it.pitch == midi && it.isGated } + ?: liveVoices.firstOrNull { it.isActive && it.pitch == midi })?.noteOff() + (auditionSampleVoices.firstOrNull { it.pitch == midi && it.isGated } + ?: auditionSampleVoices.firstOrNull { it.isActive && it.pitch == midi })?.noteOff() + } + + // ---------------------------------------------- live mix-bus audition (MIDI piano) + /** + * Play [midi] on every mixer channel listening on [midiChannel], sounding each + * channel's instrument through its full insert chain, volume and mute/solo — + * i.e. auditioning the actual mix bus, not a raw toolbox slot. + */ + fun busNoteOn(midiChannel: Int, midi: Int, velocity: Int) { + val proj = project ?: return + for (ch in 0 until Pattern.TRACK_COUNT) { + if (proj.mixer.channels[ch].midiChannel != midiChannel) continue + val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot) + // Empty bus (no instrument assigned) → silent. Auditioning a bus should + // only sound when it actually has an instrument, never a fallback synth. + val type = slot?.type ?: continue + val base = ch * BUS_POLYPHONY + val vs = voiceSample(slot, midi) + when { + vs != null -> { + val v = freeBusVoice(busSampleVoices, base) + v.noteOn(vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, + vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs) + } + // Sampler with an empty pad → silent (no synth fallback). + type == ToolboxType.SAMPLER -> {} + type == ToolboxType.GRAIN_CLOUD -> clouds[ch].noteOn(midi, velocity, GrainCloud.OWNER_LIVE) + else -> { + val v = freeBusVoice(busVoices, base) + v.noteOn(midi, velocity, synthPatch[ch] ?: patchForSlot(slot, proj.tempoBpm)) + } + } + } + } + + // First idle voice in the bus's BUS_POLYPHONY slice, stealing slot 0 when all are + // busy. Indexed, because the obvious `(0 until N).map { … }.firstOrNull { … }` + // allocated a range iterator and an ArrayList for every incoming MIDI note — on + // the thread that is supposed to stay allocation-free. Two concrete overloads + // rather than a generic one: the voice pools are differently typed arrays. + private fun freeBusVoice(pool: Array, base: Int): SynthVoice { + for (i in 0 until BUS_POLYPHONY) if (!pool[base + i].isActive) return pool[base + i] + return pool[base].also { it.kill() } + } + + private fun freeBusVoice(pool: Array, base: Int): SampleVoice { + for (i in 0 until BUS_POLYPHONY) if (!pool[base + i].isActive) return pool[base + i] + return pool[base].also { it.kill() } + } + + /** For the MIDI trace only: what [busNoteOn] would do with [midi] on + * [midiChannel], e.g. "strip2 SAMPLER pad2 | strip4 NES_SYNTH" or "no strip". */ + fun describeBusTargets(midiChannel: Int, midi: Int): String { + val proj = project ?: return "no project" + val parts = ArrayList() + for (ch in 0 until Pattern.TRACK_COUNT) { + if (proj.mixer.channels[ch].midiChannel != midiChannel) continue + val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot) + val type = slot?.type + parts += "strip${ch + 1} " + when { + type == null -> "no instrument (silent)" + type == ToolboxType.SAMPLER -> { + val pad = SamplerPads.padFor(midi) + if (voiceSample(slot, midi) != null) "SAMPLER pad${pad + 1}" else "SAMPLER pad${pad + 1} empty (silent)" + } + else -> type.name + if (voiceSample(slot, midi) == null && type == ToolboxType.SOUNDFONT) " no sample" else "" + } + } + return if (parts.isEmpty()) "no strip on channel $midiChannel" else parts.joinToString(" | ") + } + + /** Release [midi] on every mixer channel listening on [midiChannel]. */ + fun busNoteOff(midiChannel: Int, midi: Int) { + val proj = project ?: return + for (ch in 0 until Pattern.TRACK_COUNT) { + if (proj.mixer.channels[ch].midiChannel != midiChannel) continue + clouds[ch].noteOff(midi) + val base = ch * BUS_POLYPHONY + for (i in 0 until BUS_POLYPHONY) { + busVoices[base + i].takeIf { it.isActive && it.pitch == midi }?.noteOff() + busSampleVoices[base + i].takeIf { it.isActive && it.pitch == midi }?.noteOff() + } + } + } + + // ----- Arrangement mode ----- + private fun advanceArrangement(proj: Project) { + val arr = proj.arrangement + // Snapshot the volatile playlist once so a concurrent live rebuild (from + // refreshLoopPlaylist) can't change its size mid-computation. + val list = playlist + if (list.isEmpty()) { playing = false; publish(); return } + val linesPerBeat = proj.timeSignature.linesPerBeat + val samplesPerLine = blockSamplesPerLine + val beat = list[playlistIndex.coerceIn(0, list.size - 1)] + + if (pendingTrigger) { + // Bar downbeat = first line of a beat that starts a bar (in arrangement + // beats). Reset "reset on bar" arps before this line's own triggers. + val beatsPerBar = proj.timeSignature.beatsPerBar + if (lineInBeat == 0 && beatsPerBar > 0 && beat % beatsPerBar == 0) resetBarArps() + triggerArrangementLine(proj, arr, beat, lineInBeat, linesPerBeat) + pendingTrigger = false + } + + samplesIntoLine += 1.0 + if (samplesIntoLine >= samplesPerLine) { + samplesIntoLine -= samplesPerLine + lineInBeat++ + if (lineInBeat >= linesPerBeat) { + lineInBeat = 0 + playlistIndex++ + if (playlistIndex >= list.size) { + if (arr.loopEnabled) { + playlistIndex = 0 + } else { + playing = false; allSeqVoicesOff(); publish(); return + } + } + } + pendingTrigger = true + publish() + } + } + + /** + * Play one tick of every block marked at [beat]. Mirrors the reference + * sizzletracker `playAt`: a marker means the block sounds *that beat*, and a + * contiguous run of markers plays the block from its start beat-by-beat (and + * restarts after any erased gap). The beat-within-block is derived STATELESSLY + * from the run's start each tick — no mutable cursor — so it stays correct + * across loop wraps and region loops (the earlier "only the first beat plays + * on loop" bug came from a cursor that reset every loop cycle). + */ + private fun triggerArrangementLine( + proj: Project, arr: Arrangement, beat: Int, lineInBeat: Int, linesPerBeat: Int, + ) { + lineTriggerGen++ // new line — notes below form one chord per arpeggiator + // Two passes across all lanes: note-offs first, then note-ons, so a note-off + // never cancels a note that begins on the same line/bus (a note-off releases + // the whole bus). See [triggerPatternLine]. + for (pass in 0..1) { + for (lane in 0 until Arrangement.LANE_COUNT) { + if (arr.laneMuted[lane]) continue // muted MIDI lane — skip its blocks + val p = arr.patternAt(lane, beat) + if (p == Arrangement.EMPTY) continue + if (p == Arrangement.NOTE_OFF) { + // Fire once, on the first line of the beat and in the note-off + // pass, so it lands before anything another lane starts here. + if (pass == 0 && lineInBeat == 0) releaseLane(proj, lane) + continue + } + val pat = proj.pattern(p) ?: continue + // Walk back to the start of this block's contiguous run of markers so it + // plays from beat 0 wherever the run begins. An off marker is a boundary, + // not part of the run — a block placed after one restarts from its start. + var runStart = beat + while (runStart > 0 && arr.hasBlockAt(lane, runStart - 1)) runStart-- + val blockBeats = (pat.length / linesPerBeat).coerceAtLeast(1) + val patLine = ((beat - runStart) % blockBeats) * linesPerBeat + lineInBeat + // The edited block drives the tracker playhead (set once, in pass 0). + if (pass == 0 && p == proj.activePatternId) arrPlayLine = patLine.coerceIn(0, pat.length - 1) + if (patLine >= pat.length) continue + for (t in 0 until Pattern.TRACK_COUNT) { + val cell = pat.cell(t, patLine) + if (pass == 0) { if (cell.isNoteOff) triggerCell(proj, lane, t, cell) } + else { if (cell.isPlayable) triggerCell(proj, lane, t, cell) } + } + } + } + } + + /** Parse a slot's synth patch (default init patch if it isn't an NES synth). + * Allocates one [SynthPatch] — used only for the first audition note; the + * sequencer/bus paths use the per-block cache in [refreshSynthPatches]. */ + private fun patchForSlot(slot: ToolboxSlot?, tempoBpm: Float): SynthPatch = when (slot?.type) { + ToolboxType.NES_SYNTH -> SynthPatch.from(slot, tempoBpm) + ToolboxType.MORPH_PAD -> SynthPatch.forPad(FrasilPatch.from(slot)) + ToolboxType.WAVETABLE -> SynthPatch.forWave(WavePatch.from(slot, tempoBpm)) + else -> SynthPatch.DEFAULT + } + + /** The slot types whose notes a [SynthVoice] plays with a parsed [SynthPatch]. */ + private fun hasSynthPatch(type: ToolboxType?) = + type == ToolboxType.NES_SYNTH || type == ToolboxType.MORPH_PAD || type == ToolboxType.WAVETABLE + + /** + * Once per block: refresh each bus's cached synth patch (reparsing only when the + * slot version or tempo changed) and push it into that bus's *active* synth voices + * plus the editor's audition voices. This is what makes filter/level/mod knob + * turns audible on already-sounding notes, and keeps note triggers allocation-free. + * Runs on the audio thread; slot reads are safe against UI edits because the param + * map is concurrent. + */ + private fun refreshSynthPatches(proj: Project) { + val tempo = proj.tempoBpm + for (ch in 0 until Pattern.TRACK_COUNT) { + val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot) + if (slot?.type == ToolboxType.GRAIN_CLOUD) { + if (!cloudOn[ch] || slot.version != cloudVer[ch] || tempo != cloudTempo[ch]) { + clouds[ch].setPatch(GrainPatch.from(slot, tempo)) + cloudVer[ch] = slot.version + cloudTempo[ch] = tempo + } + cloudOn[ch] = true + } else if (cloudOn[ch]) { + cloudOn[ch] = false + clouds[ch].kill() + } + if (slot == null || !hasSynthPatch(slot.type)) { synthPatch[ch] = null; synthPatchVer[ch] = -1; continue } + if (synthPatch[ch] == null || slot.version != synthPatchVer[ch] || tempo != synthPatchTempo[ch]) { + synthPatch[ch] = patchForSlot(slot, tempo) + synthPatchVer[ch] = slot.version + synthPatchTempo[ch] = tempo + } + val p = synthPatch[ch] ?: continue + val sbase = ch * POLYPHONY + for (i in 0 until POLYPHONY) seqVoices[sbase + i].let { if (it.isActive) it.setPatch(p) } + val bbase = ch * BUS_POLYPHONY + for (i in 0 until BUS_POLYPHONY) busVoices[bbase + i].let { if (it.isActive) it.setPatch(p) } + } + // Editor audition voices follow the slot currently being previewed. + val aslot = proj.toolbox.getOrNull(auditionSlotIdx) + if (aslot?.type == ToolboxType.GRAIN_CLOUD && + (aslot.version != auditionCloudVer || tempo != auditionCloudTempo)) { + auditionCloud.setPatch(GrainPatch.from(aslot, tempo)) + auditionCloudVer = aslot.version + auditionCloudTempo = tempo + } + if (aslot != null && hasSynthPatch(aslot.type)) { + if (auditionPatch == null || aslot.version != auditionPatchVer || tempo != auditionPatchTempo) { + auditionPatch = patchForSlot(aslot, tempo) + auditionPatchVer = aslot.version + auditionPatchTempo = tempo + } + auditionPatch?.let { p -> for (v in liveVoices) if (v.isActive) v.setPatch(p) } + } + } + + private fun samplesPerLine(proj: Project): Double = + sampleRate * (60.0 / proj.tempoBpm) / proj.timeSignature.linesPerBeat + + private fun allSeqVoicesOff() { + clouds.forEach { it.releaseSequenced() } + seqVoices.forEach { it.noteOff() } + sampleVoices.forEach { it.noteOff() } + arps.forEach { it.stop() } + allMidiNotesOff() // release any notes we sent to external gear + } + + // ------------------------------------------------------------- outgoing MIDI + /** Enqueue one MIDI message for the send thread (audio-thread producer, no alloc). */ + private fun emitMidi(status: Int, d1: Int, d2: Int) { + if (!midiOutEnabled) return + val h = moutHead + val next = (h + 1) and (moutRing.size - 1) + if (next == moutTail) return // ring full — drop rather than block the audio thread + moutRing[h] = (status shl 16) or ((d1 and 0x7F) shl 8) or (d2 and 0x7F) + moutHead = next + } + + /** Send a note-on for [note] on app channel [ch] (1..16 → MIDI wire 0..15). */ + private fun emitNoteOn(ch: Int, note: Int, vel: Int) { + if (ch < 1) return + emitMidi(0x90 or ((ch - 1) and 0x0F), note.coerceIn(0, 127), vel.coerceIn(1, 127)) + } + + private fun emitNoteOff(ch: Int, note: Int) { + if (ch < 1) return + emitMidi(0x80 or ((ch - 1) and 0x0F), note.coerceIn(0, 127), 0) + } + + /** Release every note we've sent out (on transport stop / pause / panic) so an + * external instrument never hangs after Sizzle stops. */ + private fun allMidiNotesOff() { + for (k in moutNote.indices) if (moutNote[k] >= 0) { emitNoteOff(moutCh[k], moutNote[k]); moutNote[k] = -1 } + } + + /** Drain one queued outgoing MIDI message, or -1 if the queue is empty. Called by + * the MIDI clock thread (single consumer). */ + fun pollMidiOut(): Int { + val t = moutTail + if (t == moutHead) return -1 + val v = moutRing[t] + moutTail = (t + 1) and (moutRing.size - 1) + return v + } + + private fun publish() { + val proj = project + val linesPerBeat = proj?.timeSignature?.linesPerBeat ?: 4 + if (arrangementMode) { + val list = playlist + val beat = if (list.isNotEmpty()) list[playlistIndex.coerceIn(0, list.size - 1)] else 0 + _transport.value = TransportState( + isPlaying = playing, + currentLine = arrPlayLine, + currentBeat = beat, + ) + } else { + _transport.value = TransportState( + isPlaying = playing, + currentLine = currentLine, + currentBeat = currentLine / linesPerBeat, + ) + } + } + + companion object { + private const val BLOCK_FRAMES = 192 // ~4 ms blocks at 48 kHz + private const val POLYPHONY = 8 // max simultaneous voices per instrument (mixer bus) + private const val LIVE_POLYPHONY = 8 + private const val AUDITION_POLYPHONY = 8 + private const val BUS_POLYPHONY = 8 // per-mixer-channel live audition + // Master make-up gain into the look-ahead brickwall limiter ([masterLimit]). + // The old path was a flat 0.5× attenuation into a static soft-clip, which left + // ~9 dB of unused headroom: even the loudest single preset with its mix bus + // maxed peaked around -7 dBFS, well below other media playback. This pushes the + // signal UP (≈ +9.5 dB vs the old 0.5) so a single instrument reaches close to + // full scale, while the limiter guarantees the ceiling is never exceeded on + // busy passages — loudness without clipping. Tunable: raise for even louder / + // denser output, lower to trade loudness back for dynamics. + private const val MASTER_MAKEUP = 1.5f + // Brickwall limiter tuning (see [masterLimit]). + private const val LIM_CEILING = 0.97f // hard output ceiling (~-0.26 dBFS) + private const val LIM_LOOKAHEAD = 64 // delay/look-ahead in samples (~1.3 ms @ 48 kHz) + private const val LIM_HOLD_EXTRA = 8 // extra hold beyond the window so the peak fully clears + private const val LIM_RELEASE = 0.00025f // per-sample rise toward unity (~80 ms release @ 48 kHz) + private const val LIVE_GAIN = 0.5f + // Mixer VU ballistics (per ~4 ms block). Decay ≈ falls to ~5% over ~300 ms; + // clip latches red for ~0.8 s so a brief overload is noticeable. + private const val METER_DECAY = 0.96f + private const val METER_CLIP_LEVEL = 0.999f // bus peak at/above 0 dBFS = clipping + private const val METER_CLIP_HOLD_BLOCKS = 200 // ~0.8 s at 192-frame blocks / 48 kHz + private const val SOFT_KNEE = 0.6f // limiter is transparent below this, saturates above + + /** + * Continuous soft-knee limiter: linear (transparent) up to [SOFT_KNEE], then + * smoothly saturating to +-1 above it. The previous clipper was discontinuous + * at |x|=1 (it snapped the output 1.0 -> 0.5 as the signal crossed full scale), + * which produced audible clicks whenever a hot bus pushed the mix past 1.0. + * This version is value- and slope-continuous, so no crossing can click. + */ + private fun softClip(x: Float): Float { + val a = if (x < 0f) -x else x + if (a <= SOFT_KNEE) return x + val comp = SOFT_KNEE + (1f - SOFT_KNEE) * tanh((a - SOFT_KNEE) / (1f - SOFT_KNEE)) + return if (x < 0f) -comp else comp + } + } +} diff --git a/ios/core/include/sizzle/DeviceSpecs.gen.hpp b/core/include/sizzle/DeviceSpecs.gen.hpp similarity index 100% rename from ios/core/include/sizzle/DeviceSpecs.gen.hpp rename to core/include/sizzle/DeviceSpecs.gen.hpp diff --git a/ios/core/include/sizzle/Effect.hpp b/core/include/sizzle/Effect.hpp similarity index 100% rename from ios/core/include/sizzle/Effect.hpp rename to core/include/sizzle/Effect.hpp diff --git a/ios/core/include/sizzle/Engine.hpp b/core/include/sizzle/Engine.hpp similarity index 100% rename from ios/core/include/sizzle/Engine.hpp rename to core/include/sizzle/Engine.hpp diff --git a/ios/core/include/sizzle/Instrument.hpp b/core/include/sizzle/Instrument.hpp similarity index 100% rename from ios/core/include/sizzle/Instrument.hpp rename to core/include/sizzle/Instrument.hpp diff --git a/ios/core/include/sizzle/Midi.hpp b/core/include/sizzle/Midi.hpp similarity index 100% rename from ios/core/include/sizzle/Midi.hpp rename to core/include/sizzle/Midi.hpp diff --git a/ios/core/include/sizzle/Model.hpp b/core/include/sizzle/Model.hpp similarity index 100% rename from ios/core/include/sizzle/Model.hpp rename to core/include/sizzle/Model.hpp diff --git a/ios/core/include/sizzle/Params.hpp b/core/include/sizzle/Params.hpp similarity index 100% rename from ios/core/include/sizzle/Params.hpp rename to core/include/sizzle/Params.hpp diff --git a/ios/core/include/sizzle/Sample.hpp b/core/include/sizzle/Sample.hpp similarity index 100% rename from ios/core/include/sizzle/Sample.hpp rename to core/include/sizzle/Sample.hpp diff --git a/ios/core/include/sizzle/Specs.hpp b/core/include/sizzle/Specs.hpp similarity index 100% rename from ios/core/include/sizzle/Specs.hpp rename to core/include/sizzle/Specs.hpp diff --git a/ios/core/include/sizzle/TestVoice.hpp b/core/include/sizzle/TestVoice.hpp similarity index 100% rename from ios/core/include/sizzle/TestVoice.hpp rename to core/include/sizzle/TestVoice.hpp diff --git a/ios/core/src/Params.cpp b/core/src/Params.cpp similarity index 100% rename from ios/core/src/Params.cpp rename to core/src/Params.cpp diff --git a/ios/core/src/Specs.cpp b/core/src/Specs.cpp similarity index 100% rename from ios/core/src/Specs.cpp rename to core/src/Specs.cpp diff --git a/ios/core/src/TestVoices.cpp b/core/src/TestVoices.cpp similarity index 100% rename from ios/core/src/TestVoices.cpp rename to core/src/TestVoices.cpp diff --git a/ios/core/src/echofield/EchofieldDefs.hpp b/core/src/echofield/EchofieldDefs.hpp similarity index 100% rename from ios/core/src/echofield/EchofieldDefs.hpp rename to core/src/echofield/EchofieldDefs.hpp diff --git a/ios/core/src/echofield/GrainCloud.cpp b/core/src/echofield/GrainCloud.cpp similarity index 100% rename from ios/core/src/echofield/GrainCloud.cpp rename to core/src/echofield/GrainCloud.cpp diff --git a/ios/core/src/echofield/GrainCloud.hpp b/core/src/echofield/GrainCloud.hpp similarity index 100% rename from ios/core/src/echofield/GrainCloud.hpp rename to core/src/echofield/GrainCloud.hpp diff --git a/ios/core/src/echofield/GrainSources.cpp b/core/src/echofield/GrainSources.cpp similarity index 100% rename from ios/core/src/echofield/GrainSources.cpp rename to core/src/echofield/GrainSources.cpp diff --git a/ios/core/src/echofield/GrainSources.hpp b/core/src/echofield/GrainSources.hpp similarity index 100% rename from ios/core/src/echofield/GrainSources.hpp rename to core/src/echofield/GrainSources.hpp diff --git a/ios/core/src/echofield/GrainTestVoice.cpp b/core/src/echofield/GrainTestVoice.cpp similarity index 100% rename from ios/core/src/echofield/GrainTestVoice.cpp rename to core/src/echofield/GrainTestVoice.cpp diff --git a/ios/core/src/echofield/Sample.hpp b/core/src/echofield/Sample.hpp similarity index 100% rename from ios/core/src/echofield/Sample.hpp rename to core/src/echofield/Sample.hpp diff --git a/ios/core/src/engine/ChannelArp.hpp b/core/src/engine/ChannelArp.hpp similarity index 100% rename from ios/core/src/engine/ChannelArp.hpp rename to core/src/engine/ChannelArp.hpp diff --git a/ios/core/src/engine/Engine.cpp b/core/src/engine/Engine.cpp similarity index 100% rename from ios/core/src/engine/Engine.cpp rename to core/src/engine/Engine.cpp diff --git a/ios/core/src/frasil/FrasilDefs.cpp b/core/src/frasil/FrasilDefs.cpp similarity index 100% rename from ios/core/src/frasil/FrasilDefs.cpp rename to core/src/frasil/FrasilDefs.cpp diff --git a/ios/core/src/frasil/FrasilTestVoice.cpp b/core/src/frasil/FrasilTestVoice.cpp similarity index 100% rename from ios/core/src/frasil/FrasilTestVoice.cpp rename to core/src/frasil/FrasilTestVoice.cpp diff --git a/ios/core/src/frasil/FrasilVoice.cpp b/core/src/frasil/FrasilVoice.cpp similarity index 100% rename from ios/core/src/frasil/FrasilVoice.cpp rename to core/src/frasil/FrasilVoice.cpp diff --git a/ios/core/src/frasil/FrasilVoice.hpp b/core/src/frasil/FrasilVoice.hpp similarity index 100% rename from ios/core/src/frasil/FrasilVoice.hpp rename to core/src/frasil/FrasilVoice.hpp diff --git a/ios/core/src/fx/AmbienceReverb.cpp b/core/src/fx/AmbienceReverb.cpp similarity index 100% rename from ios/core/src/fx/AmbienceReverb.cpp rename to core/src/fx/AmbienceReverb.cpp diff --git a/ios/core/src/fx/Bitcrusher.cpp b/core/src/fx/Bitcrusher.cpp similarity index 100% rename from ios/core/src/fx/Bitcrusher.cpp rename to core/src/fx/Bitcrusher.cpp diff --git a/ios/core/src/fx/Filter.cpp b/core/src/fx/Filter.cpp similarity index 100% rename from ios/core/src/fx/Filter.cpp rename to core/src/fx/Filter.cpp diff --git a/ios/core/src/fx/GranularGlitch.cpp b/core/src/fx/GranularGlitch.cpp similarity index 100% rename from ios/core/src/fx/GranularGlitch.cpp rename to core/src/fx/GranularGlitch.cpp diff --git a/ios/core/src/fx/GraphicEq.cpp b/core/src/fx/GraphicEq.cpp similarity index 100% rename from ios/core/src/fx/GraphicEq.cpp rename to core/src/fx/GraphicEq.cpp diff --git a/ios/core/src/fx/KotlinMath.hpp b/core/src/fx/KotlinMath.hpp similarity index 100% rename from ios/core/src/fx/KotlinMath.hpp rename to core/src/fx/KotlinMath.hpp diff --git a/ios/core/src/fx/MixTightener.cpp b/core/src/fx/MixTightener.cpp similarity index 100% rename from ios/core/src/fx/MixTightener.cpp rename to core/src/fx/MixTightener.cpp diff --git a/ios/core/src/fx/Registry.cpp b/core/src/fx/Registry.cpp similarity index 100% rename from ios/core/src/fx/Registry.cpp rename to core/src/fx/Registry.cpp diff --git a/ios/core/src/fx/TapeDelay.cpp b/core/src/fx/TapeDelay.cpp similarity index 100% rename from ios/core/src/fx/TapeDelay.cpp rename to core/src/fx/TapeDelay.cpp diff --git a/ios/core/src/fx/TapeEngine.cpp b/core/src/fx/TapeEngine.cpp similarity index 100% rename from ios/core/src/fx/TapeEngine.cpp rename to core/src/fx/TapeEngine.cpp diff --git a/core/src/host/EngineHost.cpp b/core/src/host/EngineHost.cpp new file mode 100644 index 0000000..b46649b --- /dev/null +++ b/core/src/host/EngineHost.cpp @@ -0,0 +1,287 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "host/EngineHost.hpp" + +#include +#include + +#include "echofield/GrainSources.hpp" +#include "io/ProjectIo.hpp" +#include "wavetable/WaveDefs.hpp" +#include "wavetable/WaveTables.hpp" + +namespace sizzle::host { + +namespace { + +constexpr int kChunk = engine::Engine::BLOCK_FRAMES; // the MIDI LFO steps by it (see ios/PORTING.md) + +/// The store WaveTables reads custom tables from (one host per process). +std::atomic gStore{nullptr}; + +bool storeSource(const char *id, std::vector &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; +} + +// ---- equality, field by field (Params by position: an unchanged map saves in +// the same order; a reordered one is just copied again) + +bool same(const Params &a, const Params &b) { + if (a.size() != b.size()) return false; + for (int i = 0; i < a.size(); ++i) + if (std::strcmp(a.keyAt(i), b.keyAt(i)) || std::strcmp(a.valueAt(i), b.valueAt(i))) return false; + return true; +} + +bool same(const model::ToolboxSlot &a, const model::ToolboxSlot &b) { + return a.type == b.type && a.name == b.name && same(a.values, b.values); +} + +bool sameCells(const model::Pattern &a, const model::Pattern &b) { + for (int t = 0; t < model::Pattern::TRACK_COUNT; ++t) { + if (a.tracks[t].size() != b.tracks[t].size()) return false; + for (size_t l = 0; l < a.tracks[t].size(); ++l) { + const model::Cell &x = a.tracks[t][l], &y = b.tracks[t][l]; + if (x.note != y.note || x.velocity != y.velocity || x.channel != y.channel) return false; + } + } + return true; +} + +bool same(const model::LoopRegion &a, const model::LoopRegion &b) { + return a.enabled == b.enabled && a.start == b.start && a.end == b.end && a.repeats == b.repeats; +} + +bool same(const model::Arrangement &a, const model::Arrangement &b) { + return a.slots == b.slots && a.laneMuted == b.laneMuted && a.lengthBars == b.lengthBars && + a.loopEnabled == b.loopEnabled && same(a.regionA, b.regionA) && same(a.regionB, b.regionB); +} + +bool same(const model::Mixer &a, const model::Mixer &b) { + for (int c = 0; c < model::Mixer::CHANNEL_COUNT; ++c) { + const auto &x = a.channels[c], &y = b.channels[c]; + if (x.instrumentSlot != y.instrumentSlot || x.fxSlots != y.fxSlots || x.midiChannel != y.midiChannel || + x.volume != y.volume || x.mute != y.mute || x.solo != y.solo || x.limiter != y.limiter) return false; + } + return true; +} + +/// WaveVoice's frame length: wtframe's choice ("Auto" or unknown -> 0). +int frameLenOf(const model::ToolboxSlot &slot) { + namespace WD = wavetable::WaveDefs; + const char *v = slot.s("wtframe", WD::FRAME_SIZES[0]); + for (int i = 1; i < WD::FRAME_SIZE_COUNT; ++i) + if (!std::strcmp(v, WD::FRAME_SIZES[i])) return std::atoi(WD::FRAME_SIZES[i]); + return 0; +} + +bool playsCustom(const model::ToolboxSlot &slot) { + namespace WT = wavetable::WaveTables; + return slot.type == "WAVETABLE" && *slot.s(wavetable::WaveDefs::SAMPLE_KEY, "") && + (!std::strcmp(slot.s("o1table", ""), WT::CUSTOM) || !std::strcmp(slot.s("o2table", ""), WT::CUSTOM)); +} + +} // namespace + +EngineHost::EngineHost(int sampleRate) + : sampleRate_(sampleRate), + store_(std::make_unique()), + project_(std::make_unique()), + shadow_(std::make_unique()), + recorder_(std::make_unique(sampleRate)) { + wavetable::WaveTables::prewarm(); + echofield::GrainSources::prewarm(); + gStore.store(store_.get()); + wavetable::WaveTables::setSampleSource(&storeSource); + engine_ = std::make_unique(sampleRate, store_.get()); + engine_->setProject(project_.get()); + engine_->setMasterSink(recorder_.get()); +} + +EngineHost::~EngineHost() { + { + std::lock_guard b(builderLock_); + if (builder_.joinable()) builder_.join(); + } + engine_.reset(); + gStore.store(nullptr); +} + +// ---------------------------------------------------------------- song + +void EngineHost::loadProjectText(const std::string &text) { + auto fresh = std::make_unique(); + io::ProjectIo::loadInto(*fresh, text); + { + std::lock_guard g(lock_); + engine_->stop(); + *project_ = model::Project(); + io::ProjectIo::loadInto(*project_, text); + engine_->setProject(project_.get()); + } + shadow_ = std::move(fresh); + lastText_ = text; + scheduleTables(); +} + +void EngineHost::syncProjectText(const std::string &text) { + if (text == lastText_) return; + auto fresh = std::make_unique(); + io::ProjectIo::loadInto(*fresh, text); + const model::Project &old = *shadow_; + + // What differs from the last sync, worked out without the lock. + const bool scalars = fresh->name != old.name || fresh->tempoBpm != old.tempoBpm || + fresh->timeSignature != old.timeSignature || fresh->scale != old.scale || + fresh->rootNote != old.rootNote || fresh->activePatternId != old.activePatternId; + const bool patternSet = fresh->patterns.size() != old.patterns.size(); + std::vector cells, patterns; // same shape, other cells / other shape + if (!patternSet) { + for (size_t i = 0; i < fresh->patterns.size(); ++i) { + const auto &a = fresh->patterns[i], &b = old.patterns[i]; + if (a.id != b.id || a.name != b.name || a.length != b.length) patterns.push_back(i); + else if (!sameCells(a, b)) cells.push_back(i); + } + } + const bool arrangement = !same(fresh->arrangement, old.arrangement); + const bool mixer = !same(fresh->mixer, old.mixer); + std::vector slots; + for (size_t i = 0; i < fresh->toolbox.size(); ++i) + if (!same(fresh->toolbox[i], old.toolbox[i])) slots.push_back(i); + + { + std::lock_guard g(lock_); + model::Project &p = *project_; + if (scalars) { + p.name = fresh->name; + p.tempoBpm = fresh->tempoBpm; + p.timeSignature = fresh->timeSignature; + p.scale = fresh->scale; + p.rootNote = fresh->rootNote; + p.activePatternId = fresh->activePatternId; + } + if (patternSet) p.patterns = fresh->patterns; + for (size_t i : patterns) p.patterns[i] = fresh->patterns[i]; + for (size_t i : cells) // same lengths: copy in place, no allocation + for (int t = 0; t < model::Pattern::TRACK_COUNT; ++t) + std::copy(fresh->patterns[i].tracks[t].begin(), fresh->patterns[i].tracks[t].end(), p.patterns[i].tracks[t].begin()); + if (arrangement) p.arrangement = fresh->arrangement; + if (mixer) p.mixer = fresh->mixer; + for (size_t i : slots) { + model::ToolboxSlot &s = p.toolbox[i]; + s.type = fresh->toolbox[i].type; + s.name = fresh->toolbox[i].name; + s.values = fresh->toolbox[i].values; + ++s.version; // the engine re-reads a slot when its version moves + } + } + shadow_ = std::move(fresh); + lastText_ = text; + if (!slots.empty()) scheduleTables(); +} + +std::string EngineHost::projectText() { + std::lock_guard g(lock_); + return io::ProjectIo::save(*project_); +} + +void EngineHost::rebuildFxChains() { std::lock_guard g(lock_); engine_->rebuildFxChains(); } +void EngineHost::rebuildArrangement() { std::lock_guard g(lock_); engine_->rebuildArrangement(); } +void EngineHost::refreshLoopPlaylist() { std::lock_guard g(lock_); engine_->refreshLoopPlaylist(); } + +void EngineHost::play(int startBeat) { std::lock_guard g(lock_); engine_->play(startBeat); } +void EngineHost::pause() { std::lock_guard g(lock_); engine_->pause(); } +void EngineHost::stop() { std::lock_guard g(lock_); engine_->stop(); } +void EngineHost::panic() { std::lock_guard g(lock_); engine_->panic(); } + +void EngineHost::setRecordingArm(bool armed, int tailBars) { engine_->setRecordingArm(armed, tailBars); } +void EngineHost::setRecordTailBars(int tailBars) { engine_->setRecordTailBars(tailBars); } + +std::string EngineHost::describeBusTargets(int midiChannel, int midi) { + std::lock_guard g(lock_); + return engine_->describeBusTargets(midiChannel, midi); +} + +// ---------------------------------------------------------------- notes + +void EngineHost::push(NoteEvent e) { + std::lock_guard g(pushLock_); + const 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); +} + +void EngineHost::liveNoteOn(int pitch, int velocity) { push({4, pitch, velocity, 0}); } +void EngineHost::liveNoteOff(int pitch) { push({5, pitch, 0, 0}); } +void EngineHost::auditionSlotOn(int slot, int midi) { push({2, slot, midi, 0}); } +void EngineHost::auditionSlotOff(int midi) { push({3, 0, midi, 0}); } +void EngineHost::busNoteOn(int ch, int midi, int velocity) { push({0, ch, midi, velocity}); } +void EngineHost::busNoteOff(int ch, int midi) { push({1, ch, midi, 0}); } + +// ---------------------------------------------------------------- audio + +void EngineHost::render(float *out, int frames) { + std::unique_lock g(lock_, std::try_to_lock); + if (!g.owns_lock()) { // an edit is being applied: this block is silent (notes wait) + std::memset(out, 0, sizeof(float) * 2 * (size_t)frames); + return; + } + engine::Engine &e = *engine_; + uint32_t t = tail_.load(std::memory_order_relaxed); + const uint32_t h = head_.load(std::memory_order_acquire); + for (; t != h; ++t) { + const NoteEvent &n = ring_[t % ring_.size()]; + 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; + case 4: e.liveNoteOn(n.a, n.b); break; + case 5: e.liveNoteOff(n.a); break; + } + } + tail_.store(t, std::memory_order_release); + for (int done = 0; done < frames;) { + const int n = std::min(kChunk, frames - done); + e.fillBlock(out + 2 * done, n); + done += n; + } +} + +// ---------------------------------------------------------------- samples + +void EngineHost::putSample(const std::string &id, Sample sample) { + store_->put(id, std::move(sample)); + scheduleTables(); +} + +void EngineHost::removeSample(const std::string &id) { store_->remove(id); } + +/// Ask WaveTables for every Custom table the song plays (recording the request), +/// then build what's missing on a background thread, one build at a time. +void EngineHost::scheduleTables() { + bool missing = false; + { + std::lock_guard g(lock_); + for (const auto &slot : project_->toolbox) + if (playsCustom(slot) && !wavetable::WaveTables::forSample(slot.s(wavetable::WaveDefs::SAMPLE_KEY, ""), frameLenOf(slot))) + missing = true; + } + std::lock_guard b(builderLock_); + if (!missing || building_.exchange(true)) return; + if (builder_.joinable()) builder_.join(); + builder_ = std::thread([this] { + wavetable::WaveTables::buildRequested(); + building_.store(false); + }); +} + +} // namespace sizzle::host diff --git a/core/src/host/EngineHost.hpp b/core/src/host/EngineHost.hpp new file mode 100644 index 0000000..d99c331 --- /dev/null +++ b/core/src/host/EngineHost.hpp @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// The engine as an app hosts it: the song, the sample store, the engine, live +// notes queued to the audio thread, the master recorder and custom wavetable +// building, behind one lock the audio thread only ever try-locks (a block that +// meets an edit plays silence instead of waiting). +// +// The Android app drives it through JNI (app/src/main/cpp/jni_engine.cpp): its +// Kotlin model stays the UI's state and is mirrored here as project text +// (syncProjectText), applied as a diff so an edit holds the lock for microseconds. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "host/MasterRecorder.hpp" +#include "sampler/SampleStore.hpp" +#include "sizzle/Engine.hpp" +#include "sizzle/Model.hpp" + +namespace sizzle::host { + +class EngineHost { +public: + explicit EngineHost(int sampleRate); + ~EngineHost(); + EngineHost(const EngineHost &) = delete; + EngineHost &operator=(const EngineHost &) = delete; + + int sampleRate() const { return sampleRate_; } + + // ---- the song (main thread) + /** Replace the song with [text] (a .szg project), stopping playback. */ + void loadProjectText(const std::string &text); + /** Make the song equal [text], changing only what differs from the last text: + * playback continues. Cheap when nothing changed. */ + void syncProjectText(const std::string &text); + void rebuildFxChains(); + void rebuildArrangement(); + void refreshLoopPlaylist(); + + // ---- transport (main thread) + void play(int startBeat = -1); + void pause(); + void stop(); + void panic(); + engine::TransportState transport() const { return engine_->transport(); } + bool isPlaying() const { return engine_->isPlaying(); } + + // ---- live notes (any thread; queued to the audio thread) + void liveNoteOn(int pitch, int velocity); + void liveNoteOff(int pitch); + void auditionSlotOn(int slot, int midi); + void auditionSlotOff(int midi); + void busNoteOn(int midiChannel, int midi, int velocity); + void busNoteOff(int midiChannel, int midi); + std::string describeBusTargets(int midiChannel, int midi); + + // ---- audio thread + /** [frames] interleaved stereo frames into [out], in the engine's 192-frame blocks. */ + void render(float *out, int frames); + + // ---- display (any thread) + float channelMeter(int ch) const { return engine_->channelMeter(ch); } + bool channelClipped(int ch) const { return engine_->channelClipped(ch); } + int effectScope(int slot, float *out, int capacity) const { return engine_->effectScope(slot, out, capacity); } + float effectPlayhead(int slot) const { return engine_->effectPlayhead(slot); } + + // ---- outgoing MIDI + void setMidiOutEnabled(bool on) { engine_->setMidiOutEnabled(on); } + int pollMidiOut() { return engine_->pollMidiOut(); } + + // ---- samples (not the audio thread) + void putSample(const std::string &id, Sample sample); + void removeSample(const std::string &id); + sampler::SampleStore &store() { return *store_; } + /** The engine's song as project text (tests, diagnostics). */ + std::string projectText(); + + // ---- master recording + MasterRecorder &recorder() { return *recorder_; } + void setRecordingArm(bool armed, int tailBars); + void setRecordTailBars(int tailBars); + void externalClockStart() { engine_->externalClockStart(); } + void externalClockStop() { engine_->externalClockStop(); } + +private: + struct NoteEvent { int kind, a, b, c; }; + void push(NoteEvent e); + void scheduleTables(); + + const int sampleRate_; + std::unique_ptr store_; + std::unique_ptr project_; // the engine's song (under lock_) + std::unique_ptr shadow_; // the last synced text, parsed (main thread) + std::string lastText_; + std::unique_ptr engine_; + std::unique_ptr recorder_; + std::mutex lock_; + + // Live notes: producers serialised by pushLock_, the audio thread drains. + std::array ring_{}; + std::atomic head_{0}, tail_{0}; + std::mutex pushLock_; + + std::thread builder_; + std::atomic building_{false}; + std::mutex builderLock_; // scheduleTables runs on the main thread and wherever samples arrive +}; + +} // namespace sizzle::host diff --git a/core/src/host/MasterRecorder.cpp b/core/src/host/MasterRecorder.cpp new file mode 100644 index 0000000..132327e --- /dev/null +++ b/core/src/host/MasterRecorder.cpp @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "host/MasterRecorder.hpp" + +#include +#include +#include + +namespace sizzle::host { + +MasterRecorder::MasterRecorder(int sampleRate) : sr_(sampleRate), ring_((size_t)std::max(2, sampleRate * 4)) {} + +MasterRecorder::~MasterRecorder() { + capturing_.store(false); + if (writer_.joinable()) writer_.join(); +} + +bool MasterRecorder::begin() { + if (active_.load() || path_.empty()) return false; + if (writer_.joinable()) writer_.join(); // the previous take's thread is done (active_ is false) + writePos_.store(0); + readPos_.store(0); + active_.store(true); + capturing_.store(true); + const int64_t start = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + const std::string path = path_; + writer_ = std::thread([this, path, start] { + const bool ok = writeLoop(path); + active_.store(false); + if (onFinished) onFinished(ok ? path : std::string(), start); + }); + if (onStarted) onStarted(); + return true; +} + +void MasterRecorder::write(float left, float right) { + if (!capturing_.load(std::memory_order_relaxed)) return; + const uint64_t w = writePos_.load(std::memory_order_relaxed); + if (w - readPos_.load(std::memory_order_acquire) > ring_.size() - 2) return; // writer starved: drop + ring_[w % ring_.size()] = left; + ring_[(w + 1) % ring_.size()] = right; + writePos_.store(w + 2, std::memory_order_release); +} + +bool MasterRecorder::writeLoop(const std::string &path) { + FILE *f = std::fopen(path.c_str(), "wb"); + if (!f) { capturing_.store(false); return false; } + writeHeader(f, 0); + uint64_t samples = 0; + constexpr size_t chunk = 4096; + uint8_t out[chunk * 2]; + bool ok = true; + for (;;) { + const uint64_t w = writePos_.load(std::memory_order_acquire); + const uint64_t r = readPos_.load(std::memory_order_relaxed); + if (r < w) { + const size_t n = (size_t)std::min(w - r, chunk); + for (size_t i = 0; i < n; ++i) { + const float s = std::clamp(ring_[(r + i) % ring_.size()], -1.f, 1.f); + const int v = (int)(s * 32767.f); + out[i * 2] = (uint8_t)(v & 0xFF); + out[i * 2 + 1] = (uint8_t)((v >> 8) & 0xFF); + } + if (std::fwrite(out, 2, n, f) != n) ok = false; + samples += n; + readPos_.store(r + n, std::memory_order_release); + } else if (!capturing_.load()) { + break; + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + } + writeHeader(f, samples); + return std::fclose(f) == 0 && ok; +} + +void MasterRecorder::writeHeader(FILE *f, uint64_t sampleCount) { + const uint32_t data = (uint32_t)(sampleCount * 2); + auto u32 = [f](uint32_t v) { uint8_t b[4] = {(uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24)}; std::fwrite(b, 1, 4, f); }; + auto u16 = [f](uint16_t v) { uint8_t b[2] = {(uint8_t)v, (uint8_t)(v >> 8)}; std::fwrite(b, 1, 2, f); }; + std::fseek(f, 0, SEEK_SET); + std::fwrite("RIFF", 1, 4, f); u32(36 + data); std::fwrite("WAVE", 1, 4, f); + std::fwrite("fmt ", 1, 4, f); u32(16); u16(1); u16(2); u32((uint32_t)sr_); u32((uint32_t)sr_ * 4); u16(4); u16(16); + std::fwrite("data", 1, 4, f); u32(data); + std::fseek(f, 0, SEEK_END); +} + +} // namespace sizzle::host diff --git a/core/src/host/MasterRecorder.hpp b/core/src/host/MasterRecorder.hpp new file mode 100644 index 0000000..55d9c9c --- /dev/null +++ b/core/src/host/MasterRecorder.hpp @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// The engine's MasterSink as a WAV writer (MasterRecorder.kt): the audio thread +// writes interleaved stereo floats into a single-producer/single-consumer ring +// (about two seconds), a writer thread drains it into a 16-bit stereo WAV at +// [path] and patches the header sizes at the end. No allocation, locks or I/O on +// the audio thread. Used by both apps' engine hosts. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "sizzle/Engine.hpp" + +namespace sizzle::host { + +class MasterRecorder final : public engine::MasterSink { +public: + explicit MasterRecorder(int sampleRate); + ~MasterRecorder() override; + + /** Where the next take is written (set before arming). */ + void setPath(std::string path) { path_ = std::move(path); } + /** Called when a take starts capturing (the thread that started it: main or MIDI). */ + std::function onStarted; + /** Called on the writer thread when the file is finished: its path, or "" when + * writing failed, and the take's start in milliseconds since the epoch. */ + std::function onFinished; + + bool isActive() const override { return active_.load(); } + bool begin() override; + void write(float left, float right) override; + void endCapture() override { capturing_.store(false); } + +private: + bool writeLoop(const std::string &path); + void writeHeader(FILE *f, uint64_t sampleCount); + + const int sr_; + std::vector ring_; + std::string path_; + std::atomic writePos_{0}, readPos_{0}; + std::atomic capturing_{false}, active_{false}; + std::thread writer_; +}; + +} // namespace sizzle::host diff --git a/ios/core/src/instrument/Instrument.cpp b/core/src/instrument/Instrument.cpp similarity index 100% rename from ios/core/src/instrument/Instrument.cpp rename to core/src/instrument/Instrument.cpp diff --git a/ios/core/src/io/KotlinText.cpp b/core/src/io/KotlinText.cpp similarity index 100% rename from ios/core/src/io/KotlinText.cpp rename to core/src/io/KotlinText.cpp diff --git a/ios/core/src/io/KotlinText.hpp b/core/src/io/KotlinText.hpp similarity index 100% rename from ios/core/src/io/KotlinText.hpp rename to core/src/io/KotlinText.hpp diff --git a/ios/core/src/io/PresetIo.cpp b/core/src/io/PresetIo.cpp similarity index 100% rename from ios/core/src/io/PresetIo.cpp rename to core/src/io/PresetIo.cpp diff --git a/ios/core/src/io/PresetIo.hpp b/core/src/io/PresetIo.hpp similarity index 100% rename from ios/core/src/io/PresetIo.hpp rename to core/src/io/PresetIo.hpp diff --git a/ios/core/src/io/ProjectIo.cpp b/core/src/io/ProjectIo.cpp similarity index 100% rename from ios/core/src/io/ProjectIo.cpp rename to core/src/io/ProjectIo.cpp diff --git a/ios/core/src/io/ProjectIo.hpp b/core/src/io/ProjectIo.hpp similarity index 100% rename from ios/core/src/io/ProjectIo.hpp rename to core/src/io/ProjectIo.hpp diff --git a/ios/core/src/io/SngFormat.cpp b/core/src/io/SngFormat.cpp similarity index 100% rename from ios/core/src/io/SngFormat.cpp rename to core/src/io/SngFormat.cpp diff --git a/ios/core/src/io/SngFormat.hpp b/core/src/io/SngFormat.hpp similarity index 100% rename from ios/core/src/io/SngFormat.hpp rename to core/src/io/SngFormat.hpp diff --git a/ios/core/src/io/Zip.cpp b/core/src/io/Zip.cpp similarity index 100% rename from ios/core/src/io/Zip.cpp rename to core/src/io/Zip.cpp diff --git a/ios/core/src/io/Zip.hpp b/core/src/io/Zip.hpp similarity index 100% rename from ios/core/src/io/Zip.hpp rename to core/src/io/Zip.hpp diff --git a/ios/core/src/model/Model.cpp b/core/src/model/Model.cpp similarity index 100% rename from ios/core/src/model/Model.cpp rename to core/src/model/Model.cpp diff --git a/ios/core/src/model/TimeDivision.hpp b/core/src/model/TimeDivision.hpp similarity index 100% rename from ios/core/src/model/TimeDivision.hpp rename to core/src/model/TimeDivision.hpp diff --git a/ios/core/src/sampler/SampleStore.cpp b/core/src/sampler/SampleStore.cpp similarity index 100% rename from ios/core/src/sampler/SampleStore.cpp rename to core/src/sampler/SampleStore.cpp diff --git a/ios/core/src/sampler/SampleStore.hpp b/core/src/sampler/SampleStore.hpp similarity index 100% rename from ios/core/src/sampler/SampleStore.hpp rename to core/src/sampler/SampleStore.hpp diff --git a/ios/core/src/sampler/SampleTestVoice.cpp b/core/src/sampler/SampleTestVoice.cpp similarity index 100% rename from ios/core/src/sampler/SampleTestVoice.cpp rename to core/src/sampler/SampleTestVoice.cpp diff --git a/ios/core/src/sampler/SampleVoice.cpp b/core/src/sampler/SampleVoice.cpp similarity index 100% rename from ios/core/src/sampler/SampleVoice.cpp rename to core/src/sampler/SampleVoice.cpp diff --git a/ios/core/src/sampler/SampleVoice.hpp b/core/src/sampler/SampleVoice.hpp similarity index 100% rename from ios/core/src/sampler/SampleVoice.hpp rename to core/src/sampler/SampleVoice.hpp diff --git a/ios/core/src/sampler/SoundFontLoader.cpp b/core/src/sampler/SoundFontLoader.cpp similarity index 100% rename from ios/core/src/sampler/SoundFontLoader.cpp rename to core/src/sampler/SoundFontLoader.cpp diff --git a/ios/core/src/sampler/SoundFontLoader.hpp b/core/src/sampler/SoundFontLoader.hpp similarity index 100% rename from ios/core/src/sampler/SoundFontLoader.hpp rename to core/src/sampler/SoundFontLoader.hpp diff --git a/ios/core/src/synth/SynthDefs.hpp b/core/src/synth/SynthDefs.hpp similarity index 100% rename from ios/core/src/synth/SynthDefs.hpp rename to core/src/synth/SynthDefs.hpp diff --git a/ios/core/src/synth/SynthPatch.cpp b/core/src/synth/SynthPatch.cpp similarity index 100% rename from ios/core/src/synth/SynthPatch.cpp rename to core/src/synth/SynthPatch.cpp diff --git a/ios/core/src/synth/SynthPatch.hpp b/core/src/synth/SynthPatch.hpp similarity index 100% rename from ios/core/src/synth/SynthPatch.hpp rename to core/src/synth/SynthPatch.hpp diff --git a/ios/core/src/synth/SynthTestVoice.cpp b/core/src/synth/SynthTestVoice.cpp similarity index 100% rename from ios/core/src/synth/SynthTestVoice.cpp rename to core/src/synth/SynthTestVoice.cpp diff --git a/ios/core/src/synth/SynthVoice.cpp b/core/src/synth/SynthVoice.cpp similarity index 100% rename from ios/core/src/synth/SynthVoice.cpp rename to core/src/synth/SynthVoice.cpp diff --git a/ios/core/src/synth/SynthVoice.hpp b/core/src/synth/SynthVoice.hpp similarity index 100% rename from ios/core/src/synth/SynthVoice.hpp rename to core/src/synth/SynthVoice.hpp diff --git a/ios/core/src/wavetable/JavaRandom.hpp b/core/src/wavetable/JavaRandom.hpp similarity index 100% rename from ios/core/src/wavetable/JavaRandom.hpp rename to core/src/wavetable/JavaRandom.hpp diff --git a/ios/core/src/wavetable/WaveDefs.cpp b/core/src/wavetable/WaveDefs.cpp similarity index 100% rename from ios/core/src/wavetable/WaveDefs.cpp rename to core/src/wavetable/WaveDefs.cpp diff --git a/ios/core/src/wavetable/WaveDefs.hpp b/core/src/wavetable/WaveDefs.hpp similarity index 100% rename from ios/core/src/wavetable/WaveDefs.hpp rename to core/src/wavetable/WaveDefs.hpp diff --git a/ios/core/src/wavetable/WaveTables.cpp b/core/src/wavetable/WaveTables.cpp similarity index 100% rename from ios/core/src/wavetable/WaveTables.cpp rename to core/src/wavetable/WaveTables.cpp diff --git a/ios/core/src/wavetable/WaveTables.hpp b/core/src/wavetable/WaveTables.hpp similarity index 100% rename from ios/core/src/wavetable/WaveTables.hpp rename to core/src/wavetable/WaveTables.hpp diff --git a/ios/core/src/wavetable/WaveTestVoice.cpp b/core/src/wavetable/WaveTestVoice.cpp similarity index 100% rename from ios/core/src/wavetable/WaveTestVoice.cpp rename to core/src/wavetable/WaveTestVoice.cpp diff --git a/ios/core/src/wavetable/WaveVoice.cpp b/core/src/wavetable/WaveVoice.cpp similarity index 100% rename from ios/core/src/wavetable/WaveVoice.cpp rename to core/src/wavetable/WaveVoice.cpp diff --git a/ios/core/src/wavetable/WaveVoice.hpp b/core/src/wavetable/WaveVoice.hpp similarity index 100% rename from ios/core/src/wavetable/WaveVoice.hpp rename to core/src/wavetable/WaveVoice.hpp diff --git a/ios/core/tests/engine_test.cpp b/core/tests/engine_test.cpp similarity index 100% rename from ios/core/tests/engine_test.cpp rename to core/tests/engine_test.cpp diff --git a/ios/core/tests/golden_test.cpp b/core/tests/golden_test.cpp similarity index 100% rename from ios/core/tests/golden_test.cpp rename to core/tests/golden_test.cpp diff --git a/core/tests/host_test.cpp b/core/tests/host_test.cpp new file mode 100644 index 0000000..8865825 --- /dev/null +++ b/core/tests/host_test.cpp @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// host::EngineHost: renders a song exactly as the bare engine does, and a synced +// project text ends up as the engine's song without stopping playback. +// argv[1]: the reference songs folder (core/golden/songs). + +#include "host/EngineHost.hpp" +#include "echofield/GrainSources.hpp" +#include "io/ProjectIo.hpp" +#include "wavetable/WaveTables.hpp" + +#include +#include +#include +#include +#include + +using namespace sizzle; + +static int failures = 0; +#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0) + +static std::string readFile(const std::string &path) { + std::ifstream f(path, std::ios::binary); + std::stringstream ss; + ss << f.rdbuf(); + return ss.str(); +} + +int main(int argc, char **argv) { + if (argc < 2) { std::printf("usage: host_test \n"); return 2; } + // midifx: arp, transposer and the MIDI LFO (which writes its target slot as it plays). + const std::string text = readFile(std::string(argv[1]) + "/midifx.szg"); + const std::string plain = readFile(std::string(argv[1]) + "/mix.szg"); + CHECK(!text.empty() && !plain.empty()); + wavetable::WaveTables::prewarmBlocking(); // the host builds them in the background + echofield::GrainSources::prewarmBlocking(); + constexpr int SR = 48000, FRAMES = 48000; + + // 1. The host renders what the engine renders (odd buffer sizes, 192-frame blocks inside). + { + host::EngineHost h(SR); + h.loadProjectText(text); + h.rebuildArrangement(); + h.rebuildFxChains(); + h.play(); + std::vector a(FRAMES * 2); + for (int done = 0; done < FRAMES;) { + const int n = std::min(384, FRAMES - done); // whole blocks: the LFO steps per block + h.render(a.data() + 2 * done, n); + done += n; + } + model::Project p; + io::ProjectIo::loadInto(p, text); + engine::Engine e(SR); + e.setProject(&p); + e.rebuildArrangement(); + e.rebuildFxChains(); + e.play(); + std::vector b(FRAMES * 2); + for (int done = 0; done < FRAMES; done += 192) e.fillBlock(b.data() + 2 * done, std::min(192, FRAMES - done)); + double peak = 0, diff = 0; + for (size_t i = 0; i < a.size(); ++i) { peak = std::max(peak, (double)std::fabs(a[i])); diff = std::max(diff, (double)std::fabs(a[i] - b[i])); } + CHECK(peak > 0.01); + CHECK(diff == 0); + } + + // 2. Syncing an edited song changes the engine's song, playing on. + { + const std::string &text = plain; // no LFO rewriting a slot meanwhile + host::EngineHost h(SR); + h.loadProjectText(text); + h.play(); + std::vector buf(2 * 4800); + h.render(buf.data(), 4800); + model::Project p; + io::ProjectIo::loadInto(p, text); + p.tempoBpm = 97.f; + p.patterns[0].tracks[1][3] = model::Cell{64, 90, 2}; + p.mixer.channels[2].volume = 0.5f; + p.toolbox[0].set("cutoff", 0.25f); + p.arrangement.set(3, 5, 2); + const std::string edited = io::ProjectIo::save(p); + h.syncProjectText(edited); + CHECK(h.isPlaying()); + h.render(buf.data(), 4800); + CHECK(h.projectText() == edited); + h.syncProjectText(text); // and back + CHECK(h.projectText() == io::ProjectIo::save([&] { model::Project q; io::ProjectIo::loadInto(q, text); return q; }())); + } + + std::printf(failures ? "host_test: %d failure(s)\n" : "host_test: ok\n", failures); + return failures ? 1 : 0; +} diff --git a/ios/core/tests/io_test.cpp b/core/tests/io_test.cpp similarity index 100% rename from ios/core/tests/io_test.cpp rename to core/tests/io_test.cpp diff --git a/ios/core/tests/midi_test.cpp b/core/tests/midi_test.cpp similarity index 100% rename from ios/core/tests/midi_test.cpp rename to core/tests/midi_test.cpp diff --git a/ios/core/tests/sampler_test.cpp b/core/tests/sampler_test.cpp similarity index 100% rename from ios/core/tests/sampler_test.cpp rename to core/tests/sampler_test.cpp diff --git a/ios/core/tests/zip_test.cpp b/core/tests/zip_test.cpp similarity index 100% rename from ios/core/tests/zip_test.cpp rename to core/tests/zip_test.cpp diff --git a/docs/DEVELOPER_HANDOVER.md b/docs/DEVELOPER_HANDOVER.md index 29face2..b6cf76d 100644 --- a/docs/DEVELOPER_HANDOVER.md +++ b/docs/DEVELOPER_HANDOVER.md @@ -77,16 +77,20 @@ when it names the published APK. One source means the artifact name and the manifest can never disagree. ```properties -android.versionName = 0.22.0 -android.versionCode = 49 +versionName = 0.37.0 +versionCode = 71 ``` +Since 0.37.0 the version is **shared by Android and iOS** (`ios/Makefile` reads +the same two keys and `make -C ios bump-minor` bumps them through the root +Makefile): both apps ship the same features, so every change bumps once, for both. + The file also carries `macos` / `linux` / `bsd` / `windows` slots, set to `-` until such a port exists, so a port starts from a tracked version instead of inventing one. Semantic versioning, applied on every change: **minor** for a feature, **patch** -for a fix or polish. `android.versionCode` always moves by exactly `+1` — both +for a fix or polish. `versionCode` always moves by exactly `+1` — both F-Droid and the Android package manager order installs by that integer alone, and a skipped or reused code cannot be taken back once published. `make bump-minor` / `bump-patch` / `bump-major` does both halves correctly; editing @@ -377,19 +381,42 @@ in a `LaunchedEffect`, opens the editor, and on CLOSE / Back returns to `returnT The mixer's INSTRUMENT and FX dropdowns use it on long-press (`RetroDropdown`'s optional `onLongClick`, with a haptic tick; a tap still opens the menu). -### 5.4.2 iOS/iPadOS AUv3 port +### 5.4.2 Three source trees: shared engine, Android UI, iOS UI (0.37.0) -`ios/` is a separate tree with its own Makefile: Sizzle's devices as AUv3 plugins -in an iPadOS 15+ app installed with TrollStore (0.1.0 ships the eight audio -effects). The DSP is a C++ port of the Kotlin code in `ios/core`, verified -against audio the Kotlin code renders: `app/src/test/.../audio/IosGoldenExport.kt` -writes the reference files and `ios/core/include/sizzle/DeviceSpecs.gen.hpp` when -`SIZZLE_GOLDEN_DIR` is set (`make -C ios golden`); without it the test is skipped. +- **`core/`** — the C++ engine both apps play through: model and file formats, + sequencer and mixer (`engine/`), every instrument and effect, the sample store, + MIDI parsing, ZIP, and `host/` (EngineHost: the song, the engine, live-note + queues, the master recorder and custom wavetable builds behind one lock the + audio thread only try-locks). Tests: `make -C ios core-test` (on the Mac). +- **`app/`** — the Android app: Compose UI, the Kotlin model (the UI's state), + file I/O, input and playback services. `audio/AudioEngine.kt` is the engine's + face: it drives `core/` through `NativeEngine` (JNI, `src/main/cpp/jni_engine.cpp`), + and `native_audio.cpp` renders from it inside the Oboe callback. CMake builds + `core/` into `libsizzle_native.so` as an object library (the device makers are + weak placeholders in `core/src/fx/Registry.cpp`; a static library would link the + placeholders). +- **`ios/app/`** — the iOS app: SwiftUI, the AUv3 plugins, and the + Objective-C++ session around the same core. -What this means for Android work: a change to an effect's DSP or to a device's -parameters makes the iOS reference stale. Run `make -C ios golden core-test` -afterwards and port the change, or note it in `ios/README.md`. See that file for -the design, the porting rules and the test steps. +How the Kotlin model reaches the engine: after every edit (`AppViewModel.touched` +→ `AudioEngine.requestSync`, coalesced to one per main-loop turn), before every +transport or routing call, and every 500 ms as a safety net, `AudioEngine` sends +`ProjectIo.save(project)` to `EngineHost::syncProjectText`. The host parses it +off the lock, compares it with the last text it applied (song settings, each +pattern, arrangement, mixer, each toolbox slot) and copies only what changed +under the lock, so an edit holds the audio thread off for microseconds and +playback continues. Samples go across as they enter `SampleStore` (`put` / +`remove` mirror into the native store). Transport, meters, scope and finished +recordings are polled from a 10 ms thread. + +The Kotlin engine (`ReferenceEngine` and the voices and effects under `audio/`, +`frasil/`, `echofield/`, `wavetable/`) is now only a reference: the +`IosGolden*` unit tests render it so the C++ can be checked bit for bit +(`make -C ios golden core-test`). The UI still uses a few of those Kotlin classes +to draw (wavetable frames, Grain Cloud source peaks, sample decoding). + +**Parity rule:** every feature or fix lands in both apps in the same change, with +one shared version bump. Engine and DSP work goes into `core/` only. ### 5.5 Sizzle as a background MIDI sound module diff --git a/ios/.gitignore b/ios/.gitignore index 613d80a..924054e 100644 --- a/ios/.gitignore +++ b/ios/.gitignore @@ -2,4 +2,3 @@ build/ dist/ # generated from spike/project.yml by `make project` *.xcodeproj/ -core/golden/ diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index 96dcf6c..821cdb4 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -1,7 +1,17 @@ # Changelog Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in -`../versions.properties` (`ios.versionName` / `ios.versionCode`). +`../versions.properties`. Since 0.37.0 the version (`versionName` / `versionCode`) +is shared with Android, continuing Android's numbering, and both apps ship the +same features; the Android side of each version is in `../CHANGELOG.md`. + +## 0.37.0 (build 71) + +- Same version as Android from now on (iOS 0.6.0 build 11 → 0.37.0 build 71). +- The C++ core moved from `ios/core` to the repo's top-level `core/`: it is the + engine of both apps now (Android plays through it too). +- Master recording uses the shared recorder (`core/src/host/MasterRecorder`); + nothing changes in use. ## 0.6.0 (build 11) diff --git a/ios/Makefile b/ios/Makefile index 905ee1e..0acee79 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -24,22 +24,22 @@ SHELL := /bin/sh VERSIONS := ../versions.properties -VERSION := $(shell sed -n 's/^ios.versionName[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ') -BUILD_NO := $(shell sed -n 's/^ios.versionCode[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ') +VERSION := $(shell sed -n 's/^versionName[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ') +BUILD_NO := $(shell sed -n 's/^versionCode[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ') APP_ID := cc.tiredsysadmin.ios.sizzle PROJECT := app/Sizzle.xcodeproj -APP_SRC := $(shell find app core/src core/include -type f -not -path '*.xcodeproj/*') +APP_SRC := $(shell find app ../core/src ../core/include -type f -not -path '*.xcodeproj/*') 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/*/*.cpp) -CORE_HDR := $(wildcard core/include/sizzle/*.hpp core/src/*/*.hpp) +# C++ DSP core: reference audio lives in ../core/golden/ (regenerated, not committed). +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 -Icore/src/fx -lz -GOLDEN := core/golden -SPECS_GEN := core/include/sizzle/DeviceSpecs.gen.hpp +CXXFLAGS := -std=c++17 -O2 -Wall -Wextra -I../core/include -I../core/src -I../core/src/fx -lz +GOLDEN := ../core/golden +SPECS_GEN := ../core/include/sizzle/DeviceSpecs.gen.hpp # Gradle needs the Android SDK; same default location as the Android Makefile. ANDROID_SDK ?= $(or $(ANDROID_HOME),$(HOME)/Library/Android/sdk) @@ -62,29 +62,33 @@ golden: ./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 +build/core/golden_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/golden_test.cpp mkdir -p build/core - $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) core/tests/golden_test.cpp + $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/golden_test.cpp -build/core/sampler_test: $(CORE_SRC) $(CORE_HDR) core/tests/sampler_test.cpp +build/core/sampler_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/sampler_test.cpp mkdir -p build/core - $(CXX) $(CXXFLAGS) -Icore/src/sampler -o $@ $(CORE_SRC) core/tests/sampler_test.cpp + $(CXX) $(CXXFLAGS) -I../core/src/sampler -o $@ $(CORE_SRC) ../core/tests/sampler_test.cpp -build/core/engine_test: $(CORE_SRC) $(CORE_HDR) core/tests/engine_test.cpp +build/core/engine_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/engine_test.cpp mkdir -p build/core - $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) core/tests/engine_test.cpp + $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/engine_test.cpp -build/core/io_test: $(CORE_SRC) $(CORE_HDR) core/tests/io_test.cpp +build/core/io_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/io_test.cpp mkdir -p build/core - $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) core/tests/io_test.cpp + $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/io_test.cpp -build/core/midi_test: core/include/sizzle/Midi.hpp core/tests/midi_test.cpp +build/core/host_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/host_test.cpp mkdir -p build/core - $(CXX) $(CXXFLAGS) -o $@ core/tests/midi_test.cpp + $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/host_test.cpp -build/core/zip_test: core/src/io/Zip.cpp core/src/io/Zip.hpp core/tests/zip_test.cpp +build/core/midi_test: ../core/include/sizzle/Midi.hpp ../core/tests/midi_test.cpp + mkdir -p build/core + $(CXX) $(CXXFLAGS) -o $@ ../core/tests/midi_test.cpp + +build/core/zip_test: ../core/src/io/Zip.cpp ../core/src/io/Zip.hpp ../core/tests/zip_test.cpp mkdir -p build/core/zipfix/dir - $(CXX) $(CXXFLAGS) -o $@ core/src/io/Zip.cpp core/tests/zip_test.cpp -lz + $(CXX) $(CXXFLAGS) -o $@ ../core/src/io/Zip.cpp ../core/tests/zip_test.cpp -lz # A Java-written archive (ZipOutputStream, like Android's) for zip_test, and ours checked by unzip. zip-test: build/core/zip_test @@ -94,13 +98,14 @@ zip-test: build/core/zip_test build/core/zip_test build/core/java.zip build/core/ours.zip unzip -tq build/core/ours.zip -core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test zip-test +core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test build/core/host_test zip-test @test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden build/core/golden_test $(GOLDEN) $(TYPES) build/core/sampler_test build/core/engine_test $(GOLDEN)/songs build/core/io_test $(GOLDEN)/songs ../app/src/test/resources/mikroseq build/core/midi_test + build/core/host_test $(GOLDEN)/songs # ------------------------------------------------------------------ app AU_SRC := app/FX/SizzleDeviceAU.mm app/FX/SizzleEffectAU.mm app/FX/SizzleInstrumentAU.mm app/FX/SizzleDeviceAU+Sources.mm @@ -174,11 +179,8 @@ $(IPA): $(PROJECT)/project.pbxproj $(APP_SRC) $(VERSIONS) bump-major: ; @$(MAKE) --no-print-directory bump FIELD=1 bump-minor: ; @$(MAKE) --no-print-directory bump FIELD=2 bump-patch: ; @$(MAKE) --no-print-directory bump FIELD=3 -bump: - @new=$$(echo $(VERSION) | awk -F. -v f=$(FIELD) '{ if (f==1) {$$1++; $$2=0; $$3=0} else if (f==2) {$$2++; $$3=0} else {$$3++} print $$1"."$$2"."$$3 }'); \ - code=$$(( $(BUILD_NO) + 1 )); \ - sed -i '' -e "s/^ios.versionName .*/ios.versionName = $$new/" -e "s/^ios.versionCode .*/ios.versionCode = $$code/" $(VERSIONS); \ - echo "ios $$new (build $$code)" +bump: # one version for Android and iOS: the root Makefile owns it + @$(MAKE) -C .. --no-print-directory bump FIELD=$(FIELD) # ------------------------------------------------------------------ spike $(SPIKE_PROJ)/project.pbxproj: spike/project.yml diff --git a/ios/README.md b/ios/README.md index b46f64d..fd32bf2 100644 --- a/ios/README.md +++ b/ios/README.md @@ -7,9 +7,9 @@ Makefile (`make -C ios help`). | Path | What it is | |---|---| -| `core/` | The C++ DSP core: a port of the Android app's Kotlin DSP | -| `core/include/sizzle/DeviceSpecs.gen.hpp` | Every device's parameters, generated from `ToolboxType` (Kotlin) | -| `core/tests/golden_test.cpp` | Compares the core with audio the Kotlin code renders | +| `../core/` | The shared C++ engine (Android plays through it too): a port of the Android app's Kotlin DSP | +| `../core/include/sizzle/DeviceSpecs.gen.hpp` | Every device's parameters, generated from `ToolboxType` (Kotlin) | +| `../core/tests/golden_test.cpp` | Compares the core with audio the Kotlin code renders | | `app/components.txt` | The plugin list (AU type, subtype, device, name) | | `app/FX/` | The plugin extension: `SizzleDeviceAU` (shared: parameters, presets, state), `SizzleEffectAU` (aufx), `SizzleInstrumentAU` (aumu), `SizzleFXViewController` (factory + editor). The app compiles the same classes to host them itself | | `app/Host/SizzleSession*` | The bridge to the C++ song + engine (audio output, song lock, live-note queue); one category per screen | @@ -21,7 +21,7 @@ Makefile (`make -C ios help`). | `tools/gen_components.py` | `components.txt` → the extension's Info.plist and `Components.gen.h` | | `spike/` | The TrollStore AUv3 feasibility spike (see the end of this file) | -Versions: `ios.versionName` / `ios.versionCode` in `../versions.properties` +Versions: `versionName` / `versionCode` in `../versions.properties`, shared with Android (`make -C ios bump-minor` etc.); the .ipa is named by versionCode. Changes are listed in `CHANGELOG.md` here. @@ -35,7 +35,7 @@ test in the Android app, skipped by the normal `make check`), which: - renders a fixed 1.5 s test signal (decaying saw burst, noise, sine sweep, silences for tails) through every effect at its defaults and two variants that move every parameter (the Mix Tightener uses three of its presets instead), into - `core/golden/` (not committed; regenerate any time). + `../core/golden/` (not committed; regenerate any time). `make core-test` renders the same scenarios through the C++ core and requires a largest difference below 1e-4. Today all 25 pass; most are bit-exact, the rest @@ -44,7 +44,7 @@ differ by about one float ulp. Porting rules that make this possible: - translate line for line, keeping Kotlin's types: `Float` → `float`, `Double` → `double`, so every expression runs in the same precision; - `kotlin.math` on a Float goes through Java's double `Math` and rounds back: - use the helpers in `core/src/fx/KotlinMath.hpp` (`roundToInt` is floor(x+0.5), + use the helpers in `../core/src/fx/KotlinMath.hpp` (`roundToInt` is floor(x+0.5), `toInt` truncates and saturates); - Kotlin `Int` wraps and `ushr` is a logical shift: use `uint32_t` for the xorshift generators; diff --git a/ios/app/Host/SizzleSession+Record.mm b/ios/app/Host/SizzleSession+Record.mm index 35628b4..b3b631e 100644 --- a/ios/app/Host/SizzleSession+Record.mm +++ b/ios/app/Host/SizzleSession+Record.mm @@ -5,128 +5,31 @@ #import "SizzleSession+Internal.h" #include -#include -#include -#include -#include -#include +#include using namespace sizzle; +#include "host/MasterRecorder.hpp" + namespace { -/// MasterRecorder.kt: a single-producer / single-consumer ring of interleaved -/// stereo floats (about two seconds), drained by a writer thread into a 16-bit -/// stereo WAV whose header sizes are patched at the end. -class MasterRecorder final : public engine::MasterSink { -public: - MasterRecorder(int sampleRate, NSURL *dir) : sr(sampleRate), ring((size_t)std::max(2, sampleRate * 4)), dir(dir) {} - ~MasterRecorder() override { capturing.store(false); if (writer.joinable()) writer.join(); } +using sizzle::host::MasterRecorder; - bool isActive() const override { return active.load(); } - - /// Main thread (Play) or the MIDI thread (an external clock Start). - bool begin() override { - if (active.load()) return false; - if (writer.joinable()) writer.join(); // the previous take's thread has finished (active is false) - writePos.store(0); readPos.store(0); - active.store(true); - capturing.store(true); - NSDate *start = [NSDate date]; - NSURL *temp = [dir URLByAppendingPathComponent:@".take.wav"]; - writer = std::thread([this, temp, start] { - const bool ok = writeLoop(temp.fileSystemRepresentation); - NSURL *done = ok ? finish(temp, start) : nil; - active.store(false); - dispatch_async(dispatch_get_main_queue(), ^{ - if (done) lastTake = done; - [[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil]; - }); - }); - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil]; - }); - return true; - } - - /// Audio thread: no allocation, no locks; drops the frame if the writer starved. - void write(float left, float right) override { - if (!capturing.load(std::memory_order_relaxed)) return; - const uint64_t w = writePos.load(std::memory_order_relaxed); - if (w - readPos.load(std::memory_order_acquire) > ring.size() - 2) return; - ring[w % ring.size()] = left; - ring[(w + 1) % ring.size()] = right; - writePos.store(w + 2, std::memory_order_release); - } - - void endCapture() override { capturing.store(false); } - - NSURL *lastTake = nil; // main thread - -private: - bool writeLoop(const char *path) { - FILE *f = std::fopen(path, "wb"); - if (!f) { capturing.store(false); return false; } - writeHeader(f, 0); - uint64_t samples = 0; - constexpr size_t chunk = 4096; - int16_t out[chunk]; - bool ok = true; - for (;;) { - const uint64_t w = writePos.load(std::memory_order_acquire); - const uint64_t r = readPos.load(std::memory_order_relaxed); - if (r < w) { - const size_t n = (size_t)std::min(w - r, chunk); - for (size_t i = 0; i < n; ++i) { - const float s = std::clamp(ring[(r + i) % ring.size()], -1.f, 1.f); - out[i] = (int16_t)(int)(s * 32767.f); // little-endian host - } - if (std::fwrite(out, 2, n, f) != n) ok = false; - samples += n; - readPos.store(r + n, std::memory_order_release); - } else if (!capturing.load()) { - break; - } else { - std::this_thread::sleep_for(std::chrono::milliseconds(5)); - } - } - writeHeader(f, samples); - ok = std::fclose(f) == 0 && ok; - return ok; - } - - void writeHeader(FILE *f, uint64_t sampleCount) { - const uint32_t data = (uint32_t)(sampleCount * 2); - auto u32 = [f](uint32_t v) { uint8_t b[4] = {(uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24)}; std::fwrite(b, 1, 4, f); }; - auto u16 = [f](uint16_t v) { uint8_t b[2] = {(uint8_t)v, (uint8_t)(v >> 8)}; std::fwrite(b, 1, 2, f); }; - std::fseek(f, 0, SEEK_SET); - std::fwrite("RIFF", 1, 4, f); u32(36 + data); std::fwrite("WAVE", 1, 4, f); - std::fwrite("fmt ", 1, 4, f); u32(16); u16(1); u16(2); u32((uint32_t)sr); u32((uint32_t)sr * 4); u16(4); u16(16); - std::fwrite("data", 1, 4, f); u32(data); - std::fseek(f, 0, SEEK_END); - } - - /// Give the finished take its date-time name (Android: sizzle-yyyyMMdd-HHmmss.wav). - NSURL *finish(NSURL *temp, NSDate *start) { - NSDateFormatter *df = [NSDateFormatter new]; - df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; - df.dateFormat = @"yyyyMMdd-HHmmss"; - NSString *base = [@"sizzle-" stringByAppendingString:[df stringFromDate:start]]; - NSURL *dst = [dir URLByAppendingPathComponent:[base stringByAppendingPathExtension:@"wav"]]; - for (int i = 2; [NSFileManager.defaultManager fileExistsAtPath:dst.path]; ++i) - dst = [dir URLByAppendingPathComponent:[NSString stringWithFormat:@"%@-%d.wav", base, i]]; - return [NSFileManager.defaultManager moveItemAtURL:temp toURL:dst error:nil] ? dst : nil; - } - - const int sr; - std::vector ring; - NSURL *dir; - std::atomic writePos{0}, readPos{0}; - std::atomic capturing{false}, active{false}; - std::thread writer; -}; +/// Android's take name: sizzle-yyyyMMdd-HHmmss.wav (-2, -3, ... if taken). +NSURL *finishTake(NSURL *dir, const std::string &path, int64_t startMillis) { + NSDateFormatter *df = [NSDateFormatter new]; + df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; + df.dateFormat = @"yyyyMMdd-HHmmss"; + NSString *base = [@"sizzle-" stringByAppendingString:[df stringFromDate:[NSDate dateWithTimeIntervalSince1970:startMillis / 1000.0]]]; + NSURL *dst = [dir URLByAppendingPathComponent:[base stringByAppendingPathExtension:@"wav"]]; + for (int i = 2; [NSFileManager.defaultManager fileExistsAtPath:dst.path]; ++i) + dst = [dir URLByAppendingPathComponent:[NSString stringWithFormat:@"%@-%d.wav", base, i]]; + NSURL *src = [NSURL fileURLWithPath:@(path.c_str())]; + return [NSFileManager.defaultManager moveItemAtURL:src toURL:dst error:nil] ? dst : nil; +} MasterRecorder *gRecorder = nullptr; // lives as long as the app (the session never goes away) +NSURL *gLastTake = nil; bool gArmed = false; NSInteger gTail = 2; @@ -147,7 +50,20 @@ NSInteger gTail = 2; const int tail = (int)gTail; [self edit:^(model::Project &, engine::Engine &e) { if (!gRecorder) { - gRecorder = new MasterRecorder(e.sampleRate(), dir); + gRecorder = new MasterRecorder(e.sampleRate()); + gRecorder->setPath([dir URLByAppendingPathComponent:@".take.wav"].path.UTF8String); + gRecorder->onStarted = [] { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil]; + }); + }; + gRecorder->onFinished = [dir](const std::string &path, int64_t start) { + NSURL *done = path.empty() ? nil : finishTake(dir, path, start); + dispatch_async(dispatch_get_main_queue(), ^{ + if (done) gLastTake = done; + [[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil]; + }); + }; e.setMasterSink(gRecorder); } e.setRecordingArm(armed, tail); @@ -161,6 +77,6 @@ NSInteger gTail = 2; - (void)setRecordTailBars:(NSInteger)bars { gTail = std::clamp(bars, 0, 4); [self rec_apply]; } - (BOOL)masterRecording { return gRecorder && gRecorder->isActive(); } -- (nullable NSURL *)lastRecordingURL { return gRecorder ? gRecorder->lastTake : nil; } +- (nullable NSURL *)lastRecordingURL { return gLastTake; } @end diff --git a/ios/app/project.yml b/ios/app/project.yml index 1d3325a..86c41d7 100644 --- a/ios/app/project.yml +++ b/ios/app/project.yml @@ -1,6 +1,6 @@ # XcodeGen spec for Sizzle on iOS/iPadOS (see ios/README.md). `make -C ios project` # generates Sizzle.xcodeproj (git-ignored). Versions are passed in by the Makefile -# from versions.properties (ios.versionName / ios.versionCode). +# from versions.properties (versionName / versionCode, shared with Android). name: Sizzle options: bundleIdPrefix: cc.tiredsysadmin.ios @@ -14,13 +14,13 @@ settings: DEVELOPMENT_TEAM: "" CLANG_CXX_LANGUAGE_STANDARD: c++17 CLANG_ENABLE_OBJC_ARC: YES - HEADER_SEARCH_PATHS: ["$(SRCROOT)/../core/include", "$(SRCROOT)/../core/src", "$(SRCROOT)/../core/src/fx"] + HEADER_SEARCH_PATHS: ["$(SRCROOT)/../../core/include", "$(SRCROOT)/../../core/src", "$(SRCROOT)/../../core/src/fx"] targets: SizzleCore: type: library.static platform: iOS sources: - - path: ../core/src + - path: ../../core/src excludes: ["**/*.md"] settings: base: diff --git a/versions.properties b/versions.properties index 46f7016..4418150 100644 --- a/versions.properties +++ b/versions.properties @@ -1,24 +1,24 @@ -# Per-platform version tracking (see CLAUDE.md -> Naming and versioning). +# Version tracking (see CLAUDE.md -> Naming and versioning). # -# Single source of truth: app/build.gradle.kts reads android.* from here, and -# the Makefile reads it for artifact naming and for the `bump-*` targets. Edit +# One version for Android and iOS (since 0.37.0): both apps ship the same +# features from the same shared engine (core/), so they carry the same +# versionName and versionCode, continuing Android's numbering (the older app). +# app/build.gradle.kts reads them, the root Makefile names the APK and bumps them +# (`make bump-minor`; `make -C ios bump-minor` does the same), and ios/Makefile +# passes them to Xcode and names the .ipa. Edit # this file (or run `make bump-minor`), never the numbers in build.gradle.kts. # # Semantic versioning: MAJOR.MINOR.PATCH — minor for a feature, patch for a fix -# or polish. android.versionCode is monotonic and bumps by 1 on every release, +# or polish. versionCode is monotonic and bumps by 1 on every release, # because F-Droid and the Android package manager order installs by it alone. -android.versionName = 0.36.2 -android.versionCode = 70 +versionName = 0.37.0 +versionCode = 71 -# No desktop builds exist yet. These lines are the agreed slots so a port starts -# with a version instead of inventing one; `-` means "not built on this -# platform". Namespace for every platform: cc.tiredsysadmin..sizzle. -# iOS/iPadOS (cc.tiredsysadmin.ios.sizzle): the AUv3 plugin app in ios/app; the -# Makefile there passes these to Xcode and names the .ipa by versionCode. (The -# TrollStore spike in ios/spike keeps its own version in its project.yml.) -ios.versionName = 0.6.0 -ios.versionCode = 11 +# Namespace for every platform: cc.tiredsysadmin..sizzle. Android: +# cc.tiredsysadmin.android.sizzle (app/), iOS/iPadOS: cc.tiredsysadmin.ios.sizzle +# (ios/app; the TrollStore spike in ios/spike keeps its own version in its +# project.yml). No desktop builds exist yet; `-` means "not built on this platform". macos.versionName = - linux.versionName = - bsd.versionName = -