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 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
64e21e0bcc
commit
2bc5cb1cbb
@@ -16,3 +16,6 @@ dist/
|
|||||||
|
|
||||||
# NOTE: gradle/wrapper/gradle-wrapper.jar IS committed (Gradle's recommended
|
# NOTE: gradle/wrapper/gradle-wrapper.jar IS committed (Gradle's recommended
|
||||||
# practice) so ./gradlew works on a fresh clone with no extra setup.
|
# 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/
|
||||||
|
|||||||
+15
-1
@@ -2,7 +2,21 @@
|
|||||||
|
|
||||||
Sizzletracker for Android (`cc.tiredsysadmin.android.sizzle`). One entry per
|
Sizzletracker for Android (`cc.tiredsysadmin.android.sizzle`). One entry per
|
||||||
version in `versions.properties`; versions before 0.28.0 are described in the git
|
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)
|
## 0.36.2 (versionCode 70)
|
||||||
|
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ ADB := adb
|
|||||||
|
|
||||||
VERSIONS := versions.properties
|
VERSIONS := versions.properties
|
||||||
APP_ID := $(shell sed -n 's/^[[:space:]]*namespace[[:space:]]*=[[:space:]]*"\(.*\)".*/\1/p' app/build.gradle.kts)
|
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_NAME := $(shell sed -n 's/^versionName[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ')
|
||||||
VERSION_CODE := $(shell sed -n 's/^android.versionCode[[: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
|
# Publishing to the private F-Droid repo (CLAUDE.md). Both halves of a release
|
||||||
# — the artifact and its metadata — live under the same host.
|
# — the artifact and its metadata — live under the same host.
|
||||||
@@ -163,15 +163,15 @@ bump-patch: ; @$(MAKE) --no-print-directory bump FIELD=3
|
|||||||
|
|
||||||
bump:
|
bump:
|
||||||
@awk -v field=$(FIELD) ' \
|
@awk -v field=$(FIELD) ' \
|
||||||
/^android.versionName/ { \
|
/^versionName/ { \
|
||||||
split($$3, v, "."); \
|
split($$3, v, "."); \
|
||||||
v[field]++; \
|
v[field]++; \
|
||||||
for (i = field + 1; i <= 3; i++) v[i] = 0; \
|
for (i = field + 1; i <= 3; i++) v[i] = 0; \
|
||||||
printf "android.versionName = %d.%d.%d\n", v[1], v[2], v[3]; next } \
|
printf "versionName = %d.%d.%d\n", v[1], v[2], v[3]; next } \
|
||||||
/^android.versionCode/ { printf "android.versionCode = %d\n", $$3 + 1; next } \
|
/^versionCode/ { printf "versionCode = %d\n", $$3 + 1; next } \
|
||||||
{ print }' $(VERSIONS) > $(VERSIONS).tmp
|
{ print }' $(VERSIONS) > $(VERSIONS).tmp
|
||||||
@mv $(VERSIONS).tmp $(VERSIONS)
|
@mv $(VERSIONS).tmp $(VERSIONS)
|
||||||
@sed -n 's/^android\./ android./p' $(VERSIONS)
|
@grep -E '^version(Name|Code)' $(VERSIONS) | sed 's/^/ /'
|
||||||
|
|
||||||
# ------------------------------------------------------------------ clean
|
# ------------------------------------------------------------------ clean
|
||||||
clean:
|
clean:
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ plugins {
|
|||||||
val appVersions = Properties().apply {
|
val appVersions = Properties().apply {
|
||||||
rootProject.file("versions.properties").inputStream().use { load(it) }
|
rootProject.file("versions.properties").inputStream().use { load(it) }
|
||||||
}
|
}
|
||||||
val appVersionName: String = appVersions.getProperty("android.versionName").trim()
|
val appVersionName: String = appVersions.getProperty("versionName").trim()
|
||||||
val appVersionCode: Int = appVersions.getProperty("android.versionCode").trim().toInt()
|
val appVersionCode: Int = appVersions.getProperty("versionCode").trim().toInt()
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "cc.tiredsysadmin.android.sizzle"
|
namespace = "cc.tiredsysadmin.android.sizzle"
|
||||||
|
|||||||
@@ -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)
|
cmake_minimum_required(VERSION 3.22.1)
|
||||||
project(sizzle_native)
|
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
|
# 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.
|
# it here when `buildFeatures { prefab = true }` is set in build.gradle.kts.
|
||||||
find_package(oboe REQUIRED CONFIG)
|
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_OBJECTS:sizzle_core>)
|
||||||
|
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
|
target_link_libraries(sizzle_native
|
||||||
oboe::oboe
|
oboe::oboe
|
||||||
|
z
|
||||||
log)
|
log)
|
||||||
|
|
||||||
# Align ELF load segments to 16 KB so the library works on Android 15+ devices
|
# Align ELF load segments to 16 KB so the library works on Android 15+ devices
|
||||||
|
|||||||
@@ -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 <jni.h>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "host/EngineHost.hpp"
|
||||||
|
|
||||||
|
using sizzle::host::EngineHost;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
std::atomic<EngineHost *> 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<std::mutex> 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<float> 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(); }
|
||||||
|
/** "<start millis>\t<path>" 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<std::mutex> 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);
|
||||||
|
}
|
||||||
@@ -3,11 +3,12 @@
|
|||||||
|
|
||||||
// Native Oboe (AAudio) output backend for Sizzletracker.
|
// Native Oboe (AAudio) output backend for Sizzletracker.
|
||||||
//
|
//
|
||||||
// Opens a low-latency mono float Oboe output stream. On each real-time data
|
// Opens a low-latency stereo float Oboe output stream. Each real-time data
|
||||||
// callback it calls back into Kotlin (NativeAudioBridge.renderAudio) to fill a
|
// callback renders straight from the shared C++ engine (core/, through the
|
||||||
// reused Java float[] from the shared AudioEngine.fillBlock, then copies that
|
// EngineHost that jni_engine.cpp owns): no JVM call on the audio thread, so no
|
||||||
// into Oboe's output buffer. This keeps ONE implementation of the synth/mixer
|
// garbage-collector pause can glitch it.
|
||||||
// (in Kotlin) while delivering audio through the lower-latency native path.
|
|
||||||
|
#include "host/EngineHost.hpp"
|
||||||
|
|
||||||
#include <jni.h>
|
#include <jni.h>
|
||||||
#include <android/log.h>
|
#include <android/log.h>
|
||||||
@@ -25,13 +26,11 @@
|
|||||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
||||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, 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 {
|
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_prevXRuns = 0; // last-seen underrun count, for adaptive sizing
|
||||||
int32_t g_sampleRate = 48000; // remembered so the stream can be reopened on disconnect
|
int32_t g_sampleRate = 48000; // remembered so the stream can be reopened on disconnect
|
||||||
std::atomic<bool> g_wantRunning{false}; // false once nativeStop is called, so a
|
std::atomic<bool> g_wantRunning{false}; // false once nativeStop is called, so a
|
||||||
@@ -39,21 +38,9 @@ std::atomic<bool> g_wantRunning{false}; // false once nativeStop is called, so a
|
|||||||
// the app deliberately shut down
|
// the app deliberately shut down
|
||||||
|
|
||||||
// How glitch-resistant the output buffer starts (in device bursts). The buffer
|
// How glitch-resistant the output buffer starts (in device bursts). The buffer
|
||||||
// then grows adaptively (see onAudioReady) if underruns still occur. Profiling
|
// then grows adaptively (see onAudioReady) if underruns still occur. (Sized when
|
||||||
// showed the JVM render is fast on average (<1 ms) but spikes to 3-7 ms when a GC
|
// the render went through the JVM and its GC pauses; kept, the cost is latency only.)
|
||||||
// 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.
|
|
||||||
constexpr int32_t kInitialBursts = 8;
|
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<void **>(&env), JNI_VERSION_1_6) == JNI_EDETACHED) {
|
|
||||||
g_vm->AttachCurrentThread(&env, nullptr);
|
|
||||||
}
|
|
||||||
return env;
|
|
||||||
}
|
|
||||||
|
|
||||||
class SizzleCallback : public oboe::AudioStreamDataCallback {
|
class SizzleCallback : public oboe::AudioStreamDataCallback {
|
||||||
public:
|
public:
|
||||||
@@ -76,19 +63,8 @@ public:
|
|||||||
stream->getBufferSizeInFrames() + stream->getFramesPerBurst());
|
stream->getBufferSizeInFrames() + stream->getFramesPerBurst());
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEnv *env = callbackEnv();
|
if (sizzle::host::EngineHost *host = sizzleHost()) host->render(out, numFrames);
|
||||||
if (!env || !g_callback || !g_renderMethod || !g_buffer) {
|
else for (int i = 0; i < numFrames * 2; ++i) out[i] = 0.0f; // stereo silence
|
||||||
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;
|
|
||||||
|
|
||||||
// Adaptive buffer sizing (timing path): a callback that renders slower than
|
// 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
|
// its deadline will drain the buffer; a couple in a row means we're about to
|
||||||
@@ -174,7 +150,7 @@ public:
|
|||||||
SizzleErrorCallback g_errorCallback;
|
SizzleErrorCallback g_errorCallback;
|
||||||
|
|
||||||
// Opens, buffers and starts the low-latency output stream. Used both at initial
|
// 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() {
|
bool openAndStartStream() {
|
||||||
oboe::AudioStreamBuilder builder;
|
oboe::AudioStreamBuilder builder;
|
||||||
builder.setDirection(oboe::Direction::Output)
|
builder.setDirection(oboe::Direction::Output)
|
||||||
@@ -200,56 +176,30 @@ bool openAndStartStream() {
|
|||||||
g_stream.reset();
|
g_stream.reset();
|
||||||
return false;
|
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_sampleRate, burst, g_stream->getBufferSizeInFrames(),
|
||||||
g_stream->getBufferCapacityInFrames(), g_frames);
|
g_stream->getBufferCapacityInFrames());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void * /*reserved*/) {
|
|
||||||
g_vm = vm;
|
|
||||||
return JNI_VERSION_1_6;
|
|
||||||
}
|
|
||||||
|
|
||||||
extern "C" JNIEXPORT jboolean JNICALL
|
extern "C" JNIEXPORT jboolean JNICALL
|
||||||
Java_cc_tiredsysadmin_android_sizzle_audio_NativeAudioBridge_nativeStart(
|
Java_cc_tiredsysadmin_android_sizzle_audio_NativeAudioBridge_nativeStart(
|
||||||
JNIEnv *env, jobject /*thiz*/, jobject callback, jint sampleRate, jint framesPerCallback) {
|
JNIEnv * /*env*/, jobject /*thiz*/, jint sampleRate) {
|
||||||
g_callback = env->NewGlobalRef(callback);
|
|
||||||
jclass cls = env->GetObjectClass(callback);
|
|
||||||
g_renderMethod = env->GetMethodID(cls, "renderAudio", "([FI)V");
|
|
||||||
g_prevXRuns = 0;
|
g_prevXRuns = 0;
|
||||||
g_sampleRate = sampleRate;
|
g_sampleRate = sampleRate;
|
||||||
g_wantRunning = true;
|
g_wantRunning = true;
|
||||||
|
return openAndStartStream() ? JNI_TRUE : JNI_FALSE;
|
||||||
// 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<jfloatArray>(env->NewGlobalRef(env->NewFloatArray(g_frames * 2)));
|
|
||||||
|
|
||||||
if (!openAndStartStream()) {
|
|
||||||
env->DeleteGlobalRef(g_buffer);
|
|
||||||
g_buffer = nullptr;
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" JNIEXPORT void JNICALL
|
extern "C" JNIEXPORT void JNICALL
|
||||||
Java_cc_tiredsysadmin_android_sizzle_audio_NativeAudioBridge_nativeStop(
|
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
|
g_wantRunning = false; // stop the disconnect-recovery from reopening
|
||||||
if (g_stream) {
|
if (g_stream) {
|
||||||
g_stream->stop();
|
g_stream->stop();
|
||||||
g_stream->close();
|
g_stream->close();
|
||||||
g_stream.reset();
|
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;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"}")
|
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() }
|
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() }
|
val s = runBlocking { settingsStore.load() }
|
||||||
midiClock.sendEnabled = s.sendMidiClock
|
midiClock.sendEnabled = s.sendMidiClock
|
||||||
audioEngine.midiOutEnabled = s.sendMidiClock
|
audioEngine.midiOutEnabled = s.sendMidiClock
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -4,39 +4,23 @@
|
|||||||
package cc.tiredsysadmin.android.sizzle.audio
|
package cc.tiredsysadmin.android.sizzle.audio
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bridges the native Oboe (AAudio) output backend to the Kotlin [AudioEngine].
|
* 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 C++ side (see `src/main/cpp/native_audio.cpp`) opens a low-latency Oboe
|
* the JVM on the audio thread. If it can't start, [AudioEngine] falls back to an
|
||||||
* stream whose real-time data callback calls [renderAudio] via JNI, which simply
|
* AudioTrack loop that renders through [NativeEngine.nativeRender].
|
||||||
* 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.
|
|
||||||
*/
|
*/
|
||||||
class NativeAudioBridge(private val engine: AudioEngine) {
|
class NativeAudioBridge {
|
||||||
|
fun start(sampleRate: Int): Boolean = if (NativeEngine.loaded) nativeStart(sampleRate) else false
|
||||||
/** 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
|
|
||||||
|
|
||||||
fun stop() {
|
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()
|
private external fun nativeStop()
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private val LIB_LOADED = runCatching { System.loadLibrary("sizzle_native") }.isSuccess
|
/** Whether the native library loaded on this build/device. */
|
||||||
|
fun isAvailable(): Boolean = NativeEngine.loaded
|
||||||
/** Whether the native Oboe backend is available on this build/device. */
|
|
||||||
fun isAvailable(): Boolean = LIB_LOADED
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -30,12 +30,16 @@ object SampleStore {
|
|||||||
|
|
||||||
private val samples = ConcurrentHashMap<String, Sample>()
|
private val samples = ConcurrentHashMap<String, Sample>()
|
||||||
|
|
||||||
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]
|
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
|
/** 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. */
|
* 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].
|
* Decode a WAV file (the common uncompressed formats) into a mono [Sample].
|
||||||
|
|||||||
@@ -825,7 +825,8 @@ class AppViewModel(
|
|||||||
viewModelScope.launch { bindingStore.save(keyboardInput, gamepadInput, midiInput) }
|
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
|
/** Public hook so screens that mutate the model directly (e.g. dropdowns in
|
||||||
* the toolbar, mixer faders) can request a redraw. */
|
* the toolbar, mixer faders) can request a redraw. */
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import org.junit.Test
|
|||||||
*/
|
*/
|
||||||
class ChannelArpTest {
|
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. */
|
/** The Up sequence over a chord × octaves is octave-major over the sorted notes. */
|
||||||
@Test fun upCyclesWholeChordAcrossOctaves() {
|
@Test fun upCyclesWholeChordAcrossOctaves() {
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ class ClockRecordingTest {
|
|||||||
private val fs = 48_000
|
private val fs = 48_000
|
||||||
private val block = 192
|
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 })
|
setProject(Project().apply { tempoBpm = 120f })
|
||||||
recTempDir = dir
|
recTempDir = dir
|
||||||
onRecordingComplete = { f, _ ->
|
onRecordingComplete = { f, _ ->
|
||||||
@@ -33,7 +33,7 @@ class ClockRecordingTest {
|
|||||||
|
|
||||||
/** Render [frames], paced (about 10x real time) so the recorder's writer thread
|
/** 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. */
|
* 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)
|
val out = FloatArray(block * 2)
|
||||||
repeat(frames / block) { i -> fillBlock(out, block); if (i % 25 == 24) Thread.sleep(10) }
|
repeat(frames / block) { i -> fillBlock(out, block); if (i % 25 == 24) Thread.sleep(10) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,11 +27,11 @@ import kotlin.math.roundToInt
|
|||||||
import kotlin.math.sin
|
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
|
* reproduce. Runs only when SIZZLE_GOLDEN_DIR is set (`make -C ios golden`), so the
|
||||||
* normal `make check` skips it. Writes:
|
* 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;
|
* 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
|
* - into SIZZLE_GOLDEN_DIR: `input.f32` (a fixed test signal) and, per audio
|
||||||
* effect and scenario, `<TYPE>__<scenario>.scn` (its parameters) and
|
* effect and scenario, `<TYPE>__<scenario>.scn` (its parameters) and
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ class IosGoldenSongs {
|
|||||||
if (seconds > 0) {
|
if (seconds > 0) {
|
||||||
meta.append("clock ${java.lang.Double.toString(FrasilClock.seconds)}\n")
|
meta.append("clock ${java.lang.Double.toString(FrasilClock.seconds)}\n")
|
||||||
meta.append("seeds ${counter(FrasilVoice::class.java)} ${counter(GrainCloud::class.java)}\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()
|
engine.play()
|
||||||
val frames = (seconds * SR).toInt() / BLOCK * BLOCK
|
val frames = (seconds * SR).toInt() / BLOCK * BLOCK
|
||||||
val buf = FloatArray(BLOCK * 2)
|
val buf = FloatArray(BLOCK * 2)
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,287 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
#include "host/EngineHost.hpp"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#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<sampler::SampleStore *> gStore{nullptr};
|
||||||
|
|
||||||
|
bool storeSource(const char *id, std::vector<float> &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<sampler::SampleStore>()),
|
||||||
|
project_(std::make_unique<model::Project>()),
|
||||||
|
shadow_(std::make_unique<model::Project>()),
|
||||||
|
recorder_(std::make_unique<MasterRecorder>(sampleRate)) {
|
||||||
|
wavetable::WaveTables::prewarm();
|
||||||
|
echofield::GrainSources::prewarm();
|
||||||
|
gStore.store(store_.get());
|
||||||
|
wavetable::WaveTables::setSampleSource(&storeSource);
|
||||||
|
engine_ = std::make_unique<engine::Engine>(sampleRate, store_.get());
|
||||||
|
engine_->setProject(project_.get());
|
||||||
|
engine_->setMasterSink(recorder_.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
EngineHost::~EngineHost() {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> 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<model::Project>();
|
||||||
|
io::ProjectIo::loadInto(*fresh, text);
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> 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<model::Project>();
|
||||||
|
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<size_t> 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<size_t> 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<std::mutex> 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<std::mutex> g(lock_);
|
||||||
|
return io::ProjectIo::save(*project_);
|
||||||
|
}
|
||||||
|
|
||||||
|
void EngineHost::rebuildFxChains() { std::lock_guard<std::mutex> g(lock_); engine_->rebuildFxChains(); }
|
||||||
|
void EngineHost::rebuildArrangement() { std::lock_guard<std::mutex> g(lock_); engine_->rebuildArrangement(); }
|
||||||
|
void EngineHost::refreshLoopPlaylist() { std::lock_guard<std::mutex> g(lock_); engine_->refreshLoopPlaylist(); }
|
||||||
|
|
||||||
|
void EngineHost::play(int startBeat) { std::lock_guard<std::mutex> g(lock_); engine_->play(startBeat); }
|
||||||
|
void EngineHost::pause() { std::lock_guard<std::mutex> g(lock_); engine_->pause(); }
|
||||||
|
void EngineHost::stop() { std::lock_guard<std::mutex> g(lock_); engine_->stop(); }
|
||||||
|
void EngineHost::panic() { std::lock_guard<std::mutex> 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<std::mutex> g(lock_);
|
||||||
|
return engine_->describeBusTargets(midiChannel, midi);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- notes
|
||||||
|
|
||||||
|
void EngineHost::push(NoteEvent e) {
|
||||||
|
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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
|
||||||
@@ -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 <atomic>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
#include <array>
|
||||||
|
|
||||||
|
#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<sampler::SampleStore> store_;
|
||||||
|
std::unique_ptr<model::Project> project_; // the engine's song (under lock_)
|
||||||
|
std::unique_ptr<model::Project> shadow_; // the last synced text, parsed (main thread)
|
||||||
|
std::string lastText_;
|
||||||
|
std::unique_ptr<engine::Engine> engine_;
|
||||||
|
std::unique_ptr<MasterRecorder> recorder_;
|
||||||
|
std::mutex lock_;
|
||||||
|
|
||||||
|
// Live notes: producers serialised by pushLock_, the audio thread drains.
|
||||||
|
std::array<NoteEvent, 1024> ring_{};
|
||||||
|
std::atomic<uint32_t> head_{0}, tail_{0};
|
||||||
|
std::mutex pushLock_;
|
||||||
|
|
||||||
|
std::thread builder_;
|
||||||
|
std::atomic<bool> building_{false};
|
||||||
|
std::mutex builderLock_; // scheduleTables runs on the main thread and wherever samples arrive
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace sizzle::host
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
#include "host/MasterRecorder.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdio>
|
||||||
|
|
||||||
|
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::milliseconds>(
|
||||||
|
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<uint64_t>(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
|
||||||
@@ -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 <atomic>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <functional>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#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<void()> 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<void(const std::string &path, int64_t startMillis)> 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<float> ring_;
|
||||||
|
std::string path_;
|
||||||
|
std::atomic<uint64_t> writePos_{0}, readPos_{0};
|
||||||
|
std::atomic<bool> capturing_{false}, active_{false};
|
||||||
|
std::thread writer_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace sizzle::host
|
||||||
@@ -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 <cmath>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <fstream>
|
||||||
|
#include <sstream>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
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 <songs dir>\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<float> 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<float> 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<float> 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;
|
||||||
|
}
|
||||||
+41
-14
@@ -77,16 +77,20 @@ when it names the published APK. One source means the artifact name and the
|
|||||||
manifest can never disagree.
|
manifest can never disagree.
|
||||||
|
|
||||||
```properties
|
```properties
|
||||||
android.versionName = 0.22.0
|
versionName = 0.37.0
|
||||||
android.versionCode = 49
|
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 `-`
|
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
|
until such a port exists, so a port starts from a tracked version instead of
|
||||||
inventing one.
|
inventing one.
|
||||||
|
|
||||||
Semantic versioning, applied on every change: **minor** for a feature, **patch**
|
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,
|
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
|
and a skipped or reused code cannot be taken back once published. `make
|
||||||
bump-minor` / `bump-patch` / `bump-major` does both halves correctly; editing
|
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
|
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).
|
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
|
- **`core/`** — the C++ engine both apps play through: model and file formats,
|
||||||
in an iPadOS 15+ app installed with TrollStore (0.1.0 ships the eight audio
|
sequencer and mixer (`engine/`), every instrument and effect, the sample store,
|
||||||
effects). The DSP is a C++ port of the Kotlin code in `ios/core`, verified
|
MIDI parsing, ZIP, and `host/` (EngineHost: the song, the engine, live-note
|
||||||
against audio the Kotlin code renders: `app/src/test/.../audio/IosGoldenExport.kt`
|
queues, the master recorder and custom wavetable builds behind one lock the
|
||||||
writes the reference files and `ios/core/include/sizzle/DeviceSpecs.gen.hpp` when
|
audio thread only try-locks). Tests: `make -C ios core-test` (on the Mac).
|
||||||
`SIZZLE_GOLDEN_DIR` is set (`make -C ios golden`); without it the test is skipped.
|
- **`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
|
How the Kotlin model reaches the engine: after every edit (`AppViewModel.touched`
|
||||||
parameters makes the iOS reference stale. Run `make -C ios golden core-test`
|
→ `AudioEngine.requestSync`, coalesced to one per main-loop turn), before every
|
||||||
afterwards and port the change, or note it in `ios/README.md`. See that file for
|
transport or routing call, and every 500 ms as a safety net, `AudioEngine` sends
|
||||||
the design, the porting rules and the test steps.
|
`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
|
### 5.5 Sizzle as a background MIDI sound module
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user