- 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>
206 lines
8.8 KiB
C++
206 lines
8.8 KiB
C++
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// Native Oboe (AAudio) output backend for Sizzletracker.
|
|
//
|
|
// 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 <jni.h>
|
|
#include <android/log.h>
|
|
#include <oboe/Oboe.h>
|
|
#include <atomic>
|
|
#include <memory>
|
|
#include <time.h>
|
|
|
|
// Optional profiling of the real-time render callback (render time, xruns, buffer
|
|
// size), logged ~once/second under tag SizzleNative. Off by default; set to 1 to
|
|
// diagnose audio glitches.
|
|
#define SIZZLE_PROFILE 0
|
|
|
|
#define LOG_TAG "SizzleNative"
|
|
#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 {
|
|
|
|
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<bool> g_wantRunning{false}; // false once nativeStop is called, so a
|
|
// concurrent disconnect doesn't reopen a stream
|
|
// 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. (Sized when
|
|
// the render went through the JVM and its GC pauses; kept, the cost is latency only.)
|
|
constexpr int32_t kInitialBursts = 8;
|
|
|
|
class SizzleCallback : public oboe::AudioStreamDataCallback {
|
|
public:
|
|
oboe::DataCallbackResult onAudioReady(oboe::AudioStream *stream, void *audioData,
|
|
int32_t numFrames) override {
|
|
auto *out = static_cast<float *>(audioData);
|
|
|
|
// Always time the render — the adaptive buffer sizing below relies on it
|
|
// (this device reports getXRunCount()==0, so an xrun-only heuristic never
|
|
// fires even under real underruns).
|
|
struct timespec ts0;
|
|
clock_gettime(CLOCK_MONOTONIC, &ts0);
|
|
|
|
// Adaptive buffer sizing (xrun path): if AAudio reports an underrun, grow the
|
|
// buffer by one burst (up to capacity). Kept for devices where it works.
|
|
auto xr = stream->getXRunCount();
|
|
if (xr && xr.value() > g_prevXRuns) {
|
|
g_prevXRuns = xr.value();
|
|
stream->setBufferSizeInFrames(
|
|
stream->getBufferSizeInFrames() + stream->getFramesPerBurst());
|
|
}
|
|
|
|
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
|
|
// (or did) underrun, so grow the buffer a burst up to capacity. This is what
|
|
// actually absorbs the crackle here, since getXRunCount() stays 0.
|
|
{
|
|
struct timespec ts1;
|
|
clock_gettime(CLOCK_MONOTONIC, &ts1);
|
|
const double renderMs =
|
|
(ts1.tv_sec - ts0.tv_sec) * 1e3 + (ts1.tv_nsec - ts0.tv_nsec) / 1e6;
|
|
const double budgetMs = numFrames * 1000.0 / (double) stream->getSampleRate();
|
|
static int sConsecutiveOver = 0;
|
|
if (renderMs > budgetMs) {
|
|
if (++sConsecutiveOver >= 2) {
|
|
const int32_t cap = stream->getBufferCapacityInFrames();
|
|
const int32_t cur = stream->getBufferSizeInFrames();
|
|
const int32_t burst = stream->getFramesPerBurst();
|
|
if (cur + burst <= cap) stream->setBufferSizeInFrames(cur + burst);
|
|
sConsecutiveOver = 0;
|
|
}
|
|
} else {
|
|
sConsecutiveOver = 0;
|
|
}
|
|
}
|
|
|
|
#if SIZZLE_PROFILE
|
|
{
|
|
struct timespec ts1;
|
|
clock_gettime(CLOCK_MONOTONIC, &ts1);
|
|
double renderMs = (ts1.tv_sec - ts0.tv_sec) * 1e3 + (ts1.tv_nsec - ts0.tv_nsec) / 1e6;
|
|
static double sMaxMs = 0, sSumMs = 0;
|
|
static int sCount = 0, sOver = 0;
|
|
static int32_t sBaseXRuns = -1;
|
|
sSumMs += renderMs;
|
|
if (renderMs > sMaxMs) sMaxMs = renderMs;
|
|
// Budget = one callback's worth of time; count overruns of the callback.
|
|
double budgetMs = numFrames * 1000.0 / (double) stream->getSampleRate();
|
|
if (renderMs > budgetMs) sOver++;
|
|
if (sBaseXRuns < 0 && xr) sBaseXRuns = xr.value();
|
|
if (++sCount >= 500) {
|
|
int32_t xrNow = xr ? xr.value() : -1;
|
|
LOGI("prof: cbSize=%d budget=%.2fms avg=%.2fms max=%.2fms over=%d xruns=%d(+%d) buf=%d",
|
|
numFrames, budgetMs, sSumMs / sCount, sMaxMs, sOver,
|
|
xrNow, (sBaseXRuns >= 0 ? xrNow - sBaseXRuns : -1),
|
|
stream->getBufferSizeInFrames());
|
|
sMaxMs = 0; sSumMs = 0; sCount = 0; sOver = 0; sBaseXRuns = xrNow;
|
|
}
|
|
}
|
|
#endif
|
|
return oboe::DataCallbackResult::Continue;
|
|
}
|
|
};
|
|
|
|
SizzleCallback g_dataCallback;
|
|
std::shared_ptr<oboe::AudioStream> g_stream;
|
|
|
|
bool openAndStartStream(); // fwd
|
|
|
|
// Recovers from a stream disconnect — e.g. a voice assistant or a phone call grabs
|
|
// the audio route, or headphones are (un)plugged. AAudio delivers ErrorDisconnected
|
|
// and closes the stream; without reopening it, the data callback never fires again
|
|
// and playback freezes (the sequencer only advances inside the callback). Oboe calls
|
|
// this on its own error thread AFTER the stream is closed, so it is safe to open a
|
|
// fresh one here (a few retries cover a route that is briefly still busy).
|
|
class SizzleErrorCallback : public oboe::AudioStreamErrorCallback {
|
|
public:
|
|
void onErrorAfterClose(oboe::AudioStream * /*stream*/, oboe::Result error) override {
|
|
LOGE("Oboe stream disconnected (%s) — reopening", oboe::convertToText(error));
|
|
g_prevXRuns = 0;
|
|
for (int attempt = 0; attempt < 10; ++attempt) {
|
|
if (!g_wantRunning) return; // app asked to stop while we were recovering
|
|
if (openAndStartStream()) {
|
|
LOGI("Oboe stream reopened after disconnect (attempt %d)", attempt + 1);
|
|
return;
|
|
}
|
|
struct timespec ts{0, 200 * 1000 * 1000}; // 200 ms
|
|
nanosleep(&ts, nullptr);
|
|
}
|
|
LOGE("Oboe reopen failed after retries; audio will stay silent until restart");
|
|
}
|
|
};
|
|
|
|
SizzleErrorCallback g_errorCallback;
|
|
|
|
// Opens, buffers and starts the low-latency output stream. Used both at initial
|
|
// start and to recover from a disconnect.
|
|
bool openAndStartStream() {
|
|
oboe::AudioStreamBuilder builder;
|
|
builder.setDirection(oboe::Direction::Output)
|
|
->setPerformanceMode(oboe::PerformanceMode::LowLatency)
|
|
->setSharingMode(oboe::SharingMode::Shared)
|
|
->setFormat(oboe::AudioFormat::Float)
|
|
->setChannelCount(oboe::ChannelCount::Stereo)
|
|
->setSampleRate(g_sampleRate)
|
|
->setDataCallback(&g_dataCallback)
|
|
->setErrorCallback(&g_errorCallback);
|
|
|
|
oboe::Result result = builder.openStream(g_stream);
|
|
if (result != oboe::Result::OK) {
|
|
LOGE("Failed to open Oboe stream: %s", oboe::convertToText(result));
|
|
return false;
|
|
}
|
|
const int32_t burst = g_stream->getFramesPerBurst();
|
|
g_stream->setBufferSizeInFrames(burst * kInitialBursts);
|
|
result = g_stream->requestStart();
|
|
if (result != oboe::Result::OK) {
|
|
LOGE("Failed to start Oboe stream: %s", oboe::convertToText(result));
|
|
g_stream->close();
|
|
g_stream.reset();
|
|
return false;
|
|
}
|
|
LOGI("Oboe stream started (%d Hz, burst=%d, bufferSize=%d, capacity=%d)",
|
|
g_sampleRate, burst, g_stream->getBufferSizeInFrames(),
|
|
g_stream->getBufferCapacityInFrames());
|
|
return true;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
extern "C" JNIEXPORT jboolean JNICALL
|
|
Java_cc_tiredsysadmin_android_sizzle_audio_NativeAudioBridge_nativeStart(
|
|
JNIEnv * /*env*/, jobject /*thiz*/, jint sampleRate) {
|
|
g_prevXRuns = 0;
|
|
g_sampleRate = sampleRate;
|
|
g_wantRunning = true;
|
|
return openAndStartStream() ? JNI_TRUE : JNI_FALSE;
|
|
}
|
|
|
|
extern "C" JNIEXPORT void JNICALL
|
|
Java_cc_tiredsysadmin_android_sizzle_audio_NativeAudioBridge_nativeStop(
|
|
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();
|
|
}
|
|
}
|