// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later

package space.rcmd.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.
 */
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

    fun stop() {
        if (LIB_LOADED) nativeStop()
    }

    private external fun nativeStart(callback: NativeAudioBridge, sampleRate: Int, framesPerCallback: 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
    }
}
