From c769a476a225fab7deaed2a704f4f2e205d6465b Mon Sep 17 00:00:00 2001 From: Siavash Sameni Date: Thu, 9 Apr 2026 18:12:01 +0400 Subject: [PATCH] phase 2(android): port Oboe C++ bridge + audio FFI into wzp-native MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Now that Phase 1 proved the split-cdylib pipeline (build #37 launched cleanly with 'wzp-native dlopen OK: version=42 msg=...' in logcat), this commit brings the real audio code into wzp-native without ever touching the Tauri crate: - cpp/oboe_bridge.{h,cpp}, oboe_stub.cpp, getauxval_fix.c copied verbatim from crates/wzp-android/cpp/ (same files that work in the legacy wzp-android .so on this phone) - build.rs near-identical to crates/wzp-android/build.rs: clones google/oboe@1.8.1 into OUT_DIR, compiles oboe_bridge.cpp + all oboe source files as a single static lib with c++_shared linkage, emits -llog + -lOpenSLES. On non-android hosts it compiles just oboe_stub.cpp so `cargo check` works locally without an NDK. - Cargo.toml gets cc = "1" in [build-dependencies]. This is SAFE because wzp-native is a single-cdylib crate — crate-type is only ["cdylib"], no staticlib, so rust-lang/rust#104707 does not apply. - src/lib.rs extends the FFI surface with the real audio API: wzp_native_audio_start() -> i32 wzp_native_audio_stop() wzp_native_audio_read_capture(*mut i16, usize) -> usize wzp_native_audio_write_playout(*const i16, usize) -> usize wzp_native_audio_capture_latency_ms() -> f32 wzp_native_audio_playout_latency_ms() -> f32 wzp_native_audio_is_running() -> i32 Plus a static AudioBackend singleton holding the two SPSC ring buffers (capture + playout) that are shared with the C++ Oboe callbacks via AtomicI32 cursors. The wzp_native_version() and wzp_native_hello() smoke tests from Phase 1 are preserved. Compiles cleanly on macOS host with the stub oboe .cpp. Next build will exercise the full cargo-ndk path inside docker to verify the whole Oboe compile still works standalone. Phase 3 (next commit): wzp-desktop engine.rs on Android calls wzp-native's audio FFI via the already-wired libloading handle, and the real CallEngine::start() is implemented for Android using the same codec/handshake/send/recv pipeline as desktop but with Oboe rings instead of CPAL rings. Co-Authored-By: Claude Opus 4.6 (1M context) --- crates/wzp-native/Cargo.toml | 15 +- crates/wzp-native/build.rs | 119 +++++++++++ crates/wzp-native/cpp/getauxval_fix.c | 21 ++ crates/wzp-native/cpp/oboe_bridge.cpp | 278 +++++++++++++++++++++++++ crates/wzp-native/cpp/oboe_bridge.h | 43 ++++ crates/wzp-native/cpp/oboe_stub.cpp | 27 +++ crates/wzp-native/src/lib.rs | 281 ++++++++++++++++++++++++-- 7 files changed, 758 insertions(+), 26 deletions(-) create mode 100644 crates/wzp-native/build.rs create mode 100644 crates/wzp-native/cpp/getauxval_fix.c create mode 100644 crates/wzp-native/cpp/oboe_bridge.cpp create mode 100644 crates/wzp-native/cpp/oboe_bridge.h create mode 100644 crates/wzp-native/cpp/oboe_stub.cpp diff --git a/crates/wzp-native/Cargo.toml b/crates/wzp-native/Cargo.toml index 893d3ea..18d917f 100644 --- a/crates/wzp-native/Cargo.toml +++ b/crates/wzp-native/Cargo.toml @@ -15,8 +15,15 @@ description = "WarzonePhone native audio library — standalone Android cdylib t name = "wzp_native" crate-type = ["cdylib"] +[build-dependencies] +# cc is SAFE to use here because this crate is a single-cdylib: no +# staticlib in crate-type → no rust-lang/rust#104707 symbol leak. The +# legacy wzp-android crate uses the same setup and works. +cc = "1" + [dependencies] -# Phase 1 scaffold: no dependencies at all. Pure Rust FFI smoke test so we -# can validate the standalone-cdylib + libloading runtime pipeline before -# bringing Oboe / wzp-codec / etc. back in. Phase 2 will add the Oboe cc -# build and the actual audio pipeline. +# Phase 2: Oboe C++ audio bridge. Still no Rust deps — we do the whole +# audio pipeline via extern "C" into the bundled C++ and expose our own +# narrow extern "C" API for wzp-desktop to dlopen via libloading. +# Phase 3 can add wzp-proto/wzp-codec if we want to share codec logic +# instead of calling back into wzp-desktop via callbacks. diff --git a/crates/wzp-native/build.rs b/crates/wzp-native/build.rs new file mode 100644 index 0000000..bbdd3d6 --- /dev/null +++ b/crates/wzp-native/build.rs @@ -0,0 +1,119 @@ +//! wzp-native build.rs — Oboe C++ bridge compile on Android. +//! +//! Near-verbatim copy of crates/wzp-android/build.rs (which is known to +//! work). The crucial distinction: this crate is a single-cdylib (no +//! staticlib, no rlib in crate-type) so rust-lang/rust#104707 doesn't +//! apply — bionic's internal pthread_create / __init_tcb symbols stay +//! UND and resolve against libc.so at runtime, as they should. +//! +//! On non-Android hosts we compile `cpp/oboe_stub.cpp` (empty stubs) so +//! `cargo check --target ` still works for IDEs and CI. + +use std::path::PathBuf; + +fn main() { + let target = std::env::var("TARGET").unwrap_or_default(); + + if target.contains("android") { + // getauxval_fix: override compiler-rt's broken static getauxval + // stub that SIGSEGVs in shared libraries. + cc::Build::new() + .file("cpp/getauxval_fix.c") + .compile("wzp_native_getauxval_fix"); + + let oboe_dir = fetch_oboe(); + match oboe_dir { + Some(oboe_path) => { + println!("cargo:warning=wzp-native: building with Oboe from {:?}", oboe_path); + let mut build = cc::Build::new(); + build + .cpp(true) + .std("c++17") + // Shared libc++ — matches legacy wzp-android setup. + .cpp_link_stdlib(Some("c++_shared")) + .include("cpp") + .include(oboe_path.join("include")) + .include(oboe_path.join("src")) + .define("WZP_HAS_OBOE", None) + .file("cpp/oboe_bridge.cpp"); + add_cpp_files_recursive(&mut build, &oboe_path.join("src")); + build.compile("wzp_native_oboe_bridge"); + } + None => { + println!("cargo:warning=wzp-native: Oboe not found, building stub"); + cc::Build::new() + .cpp(true) + .std("c++17") + .cpp_link_stdlib(Some("c++_shared")) + .file("cpp/oboe_stub.cpp") + .include("cpp") + .compile("wzp_native_oboe_bridge"); + } + } + + // Oboe needs log + OpenSLES backends at runtime. + println!("cargo:rustc-link-lib=log"); + println!("cargo:rustc-link-lib=OpenSLES"); + + // Re-run if any cpp file changes + println!("cargo:rerun-if-changed=cpp/oboe_bridge.cpp"); + println!("cargo:rerun-if-changed=cpp/oboe_bridge.h"); + println!("cargo:rerun-if-changed=cpp/oboe_stub.cpp"); + println!("cargo:rerun-if-changed=cpp/getauxval_fix.c"); + } else { + // Non-Android hosts: compile the empty stub so lib.rs's extern + // declarations resolve when someone runs `cargo check` on macOS + // or Linux without an NDK. + cc::Build::new() + .cpp(true) + .std("c++17") + .file("cpp/oboe_stub.cpp") + .include("cpp") + .compile("wzp_native_oboe_bridge"); + println!("cargo:rerun-if-changed=cpp/oboe_stub.cpp"); + } +} + +/// Recursively add all `.cpp` files from a directory to a cc::Build. +fn add_cpp_files_recursive(build: &mut cc::Build, dir: &std::path::Path) { + if !dir.is_dir() { + return; + } + for entry in std::fs::read_dir(dir).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if path.is_dir() { + add_cpp_files_recursive(build, &path); + } else if path.extension().map_or(false, |e| e == "cpp") { + build.file(&path); + } + } +} + +/// Fetch or find Oboe headers + sources (v1.8.1). Same logic as the +/// legacy wzp-android crate's build.rs. +fn fetch_oboe() -> Option { + let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap()); + let oboe_dir = out_dir.join("oboe"); + + if oboe_dir.join("include").join("oboe").join("Oboe.h").exists() { + return Some(oboe_dir); + } + + let status = std::process::Command::new("git") + .args([ + "clone", + "--depth=1", + "--branch=1.8.1", + "https://github.com/google/oboe.git", + oboe_dir.to_str().unwrap(), + ]) + .status(); + + match status { + Ok(s) if s.success() && oboe_dir.join("include").join("oboe").join("Oboe.h").exists() => { + Some(oboe_dir) + } + _ => None, + } +} diff --git a/crates/wzp-native/cpp/getauxval_fix.c b/crates/wzp-native/cpp/getauxval_fix.c new file mode 100644 index 0000000..2f287cb --- /dev/null +++ b/crates/wzp-native/cpp/getauxval_fix.c @@ -0,0 +1,21 @@ +// Override the broken static getauxval from compiler-rt/CRT. +// The static version reads from __libc_auxv which is NULL in shared libs +// loaded via dlopen, causing SIGSEGV in init_have_lse_atomics at load time. +// This version calls the real bionic getauxval via dlsym. +#ifdef __ANDROID__ +#include +#include + +typedef unsigned long (*getauxval_fn)(unsigned long); + +unsigned long getauxval(unsigned long type) { + static getauxval_fn real_getauxval = (getauxval_fn)0; + if (!real_getauxval) { + real_getauxval = (getauxval_fn)dlsym((void*)-1L /* RTLD_DEFAULT */, "getauxval"); + if (!real_getauxval) { + return 0; + } + } + return real_getauxval(type); +} +#endif diff --git a/crates/wzp-native/cpp/oboe_bridge.cpp b/crates/wzp-native/cpp/oboe_bridge.cpp new file mode 100644 index 0000000..066bb61 --- /dev/null +++ b/crates/wzp-native/cpp/oboe_bridge.cpp @@ -0,0 +1,278 @@ +// Full Oboe implementation for Android +// This file is compiled only when targeting Android + +#include "oboe_bridge.h" + +#ifdef __ANDROID__ +#include +#include +#include +#include + +#define LOG_TAG "wzp-oboe" +#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) +#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) +#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) + +// --------------------------------------------------------------------------- +// Ring buffer helpers (SPSC, lock-free) +// --------------------------------------------------------------------------- + +static inline int32_t ring_available_read(const wzp_atomic_int* write_idx, + const wzp_atomic_int* read_idx, + int32_t capacity) { + int32_t w = std::atomic_load_explicit(write_idx, std::memory_order_acquire); + int32_t r = std::atomic_load_explicit(read_idx, std::memory_order_relaxed); + int32_t avail = w - r; + if (avail < 0) avail += capacity; + return avail; +} + +static inline int32_t ring_available_write(const wzp_atomic_int* write_idx, + const wzp_atomic_int* read_idx, + int32_t capacity) { + return capacity - 1 - ring_available_read(write_idx, read_idx, capacity); +} + +static inline void ring_write(int16_t* buf, int32_t capacity, + wzp_atomic_int* write_idx, const wzp_atomic_int* read_idx, + const int16_t* src, int32_t count) { + int32_t w = std::atomic_load_explicit(write_idx, std::memory_order_relaxed); + for (int32_t i = 0; i < count; i++) { + buf[w] = src[i]; + w++; + if (w >= capacity) w = 0; + } + std::atomic_store_explicit(write_idx, w, std::memory_order_release); +} + +static inline void ring_read(int16_t* buf, int32_t capacity, + const wzp_atomic_int* write_idx, wzp_atomic_int* read_idx, + int16_t* dst, int32_t count) { + int32_t r = std::atomic_load_explicit(read_idx, std::memory_order_relaxed); + for (int32_t i = 0; i < count; i++) { + dst[i] = buf[r]; + r++; + if (r >= capacity) r = 0; + } + std::atomic_store_explicit(read_idx, r, std::memory_order_release); +} + +// --------------------------------------------------------------------------- +// Global state +// --------------------------------------------------------------------------- + +static std::shared_ptr g_capture_stream; +static std::shared_ptr g_playout_stream; +static const WzpOboeRings* g_rings = nullptr; +static std::atomic g_running{false}; +static std::atomic g_capture_latency_ms{0.0f}; +static std::atomic g_playout_latency_ms{0.0f}; + +// --------------------------------------------------------------------------- +// Capture callback +// --------------------------------------------------------------------------- + +class CaptureCallback : public oboe::AudioStreamDataCallback { +public: + oboe::DataCallbackResult onAudioReady( + oboe::AudioStream* stream, + void* audioData, + int32_t numFrames) override { + if (!g_running.load(std::memory_order_relaxed) || !g_rings) { + return oboe::DataCallbackResult::Stop; + } + + const int16_t* src = static_cast(audioData); + int32_t avail = ring_available_write(g_rings->capture_write_idx, + g_rings->capture_read_idx, + g_rings->capture_capacity); + int32_t to_write = (numFrames < avail) ? numFrames : avail; + if (to_write > 0) { + ring_write(g_rings->capture_buf, g_rings->capture_capacity, + g_rings->capture_write_idx, g_rings->capture_read_idx, + src, to_write); + } + + // Update latency estimate + auto result = stream->calculateLatencyMillis(); + if (result) { + g_capture_latency_ms.store(static_cast(result.value()), + std::memory_order_relaxed); + } + + return oboe::DataCallbackResult::Continue; + } +}; + +// --------------------------------------------------------------------------- +// Playout callback +// --------------------------------------------------------------------------- + +class PlayoutCallback : public oboe::AudioStreamDataCallback { +public: + oboe::DataCallbackResult onAudioReady( + oboe::AudioStream* stream, + void* audioData, + int32_t numFrames) override { + if (!g_running.load(std::memory_order_relaxed) || !g_rings) { + memset(audioData, 0, numFrames * sizeof(int16_t)); + return oboe::DataCallbackResult::Stop; + } + + int16_t* dst = static_cast(audioData); + int32_t avail = ring_available_read(g_rings->playout_write_idx, + g_rings->playout_read_idx, + g_rings->playout_capacity); + int32_t to_read = (numFrames < avail) ? numFrames : avail; + + if (to_read > 0) { + ring_read(g_rings->playout_buf, g_rings->playout_capacity, + g_rings->playout_write_idx, g_rings->playout_read_idx, + dst, to_read); + } + // Fill remainder with silence on underrun + if (to_read < numFrames) { + memset(dst + to_read, 0, (numFrames - to_read) * sizeof(int16_t)); + } + + // Update latency estimate + auto result = stream->calculateLatencyMillis(); + if (result) { + g_playout_latency_ms.store(static_cast(result.value()), + std::memory_order_relaxed); + } + + return oboe::DataCallbackResult::Continue; + } +}; + +static CaptureCallback g_capture_cb; +static PlayoutCallback g_playout_cb; + +// --------------------------------------------------------------------------- +// Public C API +// --------------------------------------------------------------------------- + +int wzp_oboe_start(const WzpOboeConfig* config, const WzpOboeRings* rings) { + if (g_running.load(std::memory_order_relaxed)) { + LOGW("wzp_oboe_start: already running"); + return -1; + } + + g_rings = rings; + + // Build capture stream + oboe::AudioStreamBuilder captureBuilder; + captureBuilder.setDirection(oboe::Direction::Input) + ->setPerformanceMode(oboe::PerformanceMode::LowLatency) + ->setSharingMode(oboe::SharingMode::Exclusive) + ->setFormat(oboe::AudioFormat::I16) + ->setChannelCount(config->channel_count) + ->setSampleRate(config->sample_rate) + ->setFramesPerDataCallback(config->frames_per_burst) + ->setInputPreset(oboe::InputPreset::VoiceCommunication) + ->setDataCallback(&g_capture_cb); + + oboe::Result result = captureBuilder.openStream(g_capture_stream); + if (result != oboe::Result::OK) { + LOGE("Failed to open capture stream: %s", oboe::convertToText(result)); + return -2; + } + + // Build playout stream + oboe::AudioStreamBuilder playoutBuilder; + playoutBuilder.setDirection(oboe::Direction::Output) + ->setPerformanceMode(oboe::PerformanceMode::LowLatency) + ->setSharingMode(oboe::SharingMode::Exclusive) + ->setFormat(oboe::AudioFormat::I16) + ->setChannelCount(config->channel_count) + ->setSampleRate(config->sample_rate) + ->setFramesPerDataCallback(config->frames_per_burst) + ->setUsage(oboe::Usage::VoiceCommunication) + ->setDataCallback(&g_playout_cb); + + result = playoutBuilder.openStream(g_playout_stream); + if (result != oboe::Result::OK) { + LOGE("Failed to open playout stream: %s", oboe::convertToText(result)); + g_capture_stream->close(); + g_capture_stream.reset(); + return -3; + } + + g_running.store(true, std::memory_order_release); + + // Start both streams + result = g_capture_stream->requestStart(); + if (result != oboe::Result::OK) { + LOGE("Failed to start capture: %s", oboe::convertToText(result)); + g_running.store(false, std::memory_order_release); + g_capture_stream->close(); + g_playout_stream->close(); + g_capture_stream.reset(); + g_playout_stream.reset(); + return -4; + } + + result = g_playout_stream->requestStart(); + if (result != oboe::Result::OK) { + LOGE("Failed to start playout: %s", oboe::convertToText(result)); + g_running.store(false, std::memory_order_release); + g_capture_stream->requestStop(); + g_capture_stream->close(); + g_playout_stream->close(); + g_capture_stream.reset(); + g_playout_stream.reset(); + return -5; + } + + LOGI("Oboe started: sr=%d burst=%d ch=%d", + config->sample_rate, config->frames_per_burst, config->channel_count); + return 0; +} + +void wzp_oboe_stop(void) { + g_running.store(false, std::memory_order_release); + + if (g_capture_stream) { + g_capture_stream->requestStop(); + g_capture_stream->close(); + g_capture_stream.reset(); + } + if (g_playout_stream) { + g_playout_stream->requestStop(); + g_playout_stream->close(); + g_playout_stream.reset(); + } + + g_rings = nullptr; + LOGI("Oboe stopped"); +} + +float wzp_oboe_capture_latency_ms(void) { + return g_capture_latency_ms.load(std::memory_order_relaxed); +} + +float wzp_oboe_playout_latency_ms(void) { + return g_playout_latency_ms.load(std::memory_order_relaxed); +} + +int wzp_oboe_is_running(void) { + return g_running.load(std::memory_order_relaxed) ? 1 : 0; +} + +#else +// Non-Android fallback — should not be reached; oboe_stub.cpp is used instead. +// Provide empty implementations just in case. + +int wzp_oboe_start(const WzpOboeConfig* config, const WzpOboeRings* rings) { + (void)config; (void)rings; + return -99; +} + +void wzp_oboe_stop(void) {} +float wzp_oboe_capture_latency_ms(void) { return 0.0f; } +float wzp_oboe_playout_latency_ms(void) { return 0.0f; } +int wzp_oboe_is_running(void) { return 0; } + +#endif // __ANDROID__ diff --git a/crates/wzp-native/cpp/oboe_bridge.h b/crates/wzp-native/cpp/oboe_bridge.h new file mode 100644 index 0000000..8c2f143 --- /dev/null +++ b/crates/wzp-native/cpp/oboe_bridge.h @@ -0,0 +1,43 @@ +#ifndef WZP_OBOE_BRIDGE_H +#define WZP_OBOE_BRIDGE_H + +#include + +#ifdef __cplusplus +#include +typedef std::atomic wzp_atomic_int; +extern "C" { +#else +#include +typedef atomic_int wzp_atomic_int; +#endif + +typedef struct { + int32_t sample_rate; + int32_t frames_per_burst; + int32_t channel_count; +} WzpOboeConfig; + +typedef struct { + int16_t* capture_buf; + int32_t capture_capacity; + wzp_atomic_int* capture_write_idx; + wzp_atomic_int* capture_read_idx; + + int16_t* playout_buf; + int32_t playout_capacity; + wzp_atomic_int* playout_write_idx; + wzp_atomic_int* playout_read_idx; +} WzpOboeRings; + +int wzp_oboe_start(const WzpOboeConfig* config, const WzpOboeRings* rings); +void wzp_oboe_stop(void); +float wzp_oboe_capture_latency_ms(void); +float wzp_oboe_playout_latency_ms(void); +int wzp_oboe_is_running(void); + +#ifdef __cplusplus +} +#endif + +#endif // WZP_OBOE_BRIDGE_H diff --git a/crates/wzp-native/cpp/oboe_stub.cpp b/crates/wzp-native/cpp/oboe_stub.cpp new file mode 100644 index 0000000..6792259 --- /dev/null +++ b/crates/wzp-native/cpp/oboe_stub.cpp @@ -0,0 +1,27 @@ +// Stub implementation for non-Android host builds (testing, cargo check, etc.) + +#include "oboe_bridge.h" +#include + +int wzp_oboe_start(const WzpOboeConfig* config, const WzpOboeRings* rings) { + (void)config; + (void)rings; + fprintf(stderr, "wzp_oboe_start: stub (not on Android)\n"); + return 0; +} + +void wzp_oboe_stop(void) { + fprintf(stderr, "wzp_oboe_stop: stub (not on Android)\n"); +} + +float wzp_oboe_capture_latency_ms(void) { + return 0.0f; +} + +float wzp_oboe_playout_latency_ms(void) { + return 0.0f; +} + +int wzp_oboe_is_running(void) { + return 0; +} diff --git a/crates/wzp-native/src/lib.rs b/crates/wzp-native/src/lib.rs index 8d65790..0d85cc9 100644 --- a/crates/wzp-native/src/lib.rs +++ b/crates/wzp-native/src/lib.rs @@ -1,32 +1,31 @@ //! wzp-native — standalone Android cdylib for all the C++ audio code. //! -//! This crate is built with `cargo ndk`, NOT `cargo tauri android build`, -//! because the latter mispipes link flags in a way that causes bionic's -//! private `pthread_create` / `__init_tcb` symbols to land LOCALLY inside -//! any cdylib that also has a `cc::Build::new().cpp(true)` step. See -//! `docs/incident-tauri-android-init-tcb.md` for the full post-mortem. +//! Built with `cargo ndk`, NOT `cargo tauri android build`. Loaded at +//! runtime by the Tauri desktop cdylib (`wzp-desktop`) via libloading. +//! See `docs/incident-tauri-android-init-tcb.md` for why the split exists. //! -//! The Tauri desktop crate (`wzp-desktop`) has **no C++ at all**. At -//! runtime on Android, it `libloading::Library::new("libwzp_native.so")`'s -//! this crate's .so and calls the `wzp_native_*` functions below. +//! Phase 2: real Oboe audio backend. //! -//! Phase 1 (this file): a tiny smoke-test FFI surface so we can validate -//! that (a) cargo-ndk happily builds this crate standalone, (b) gradle -//! picks up the resulting .so from jniLibs, (c) the Tauri cdylib can -//! dlopen us at runtime and call exported functions. No C++, no Oboe, no -//! external deps. Phase 2 will add the Oboe cc::Build + audio FFI. +//! Architecture: Oboe runs capture + playout streams on its own high- +//! priority AAudio callback threads inside the C++ bridge. Two SPSC ring +//! buffers (capture and playout) are shared between the C++ callbacks +//! and the Rust side via atomic indices — no locks on the hot path. +//! `wzp-desktop` drains the capture ring into its Opus encoder and fills +//! the playout ring with decoded PCM. -/// Smoke-test export #1 — returns a fixed magic number so the Tauri cdylib -/// can assert that `dlopen + dlsym` worked end-to-end. Always returns 42. +use std::sync::atomic::{AtomicI32, Ordering}; + +// ─── Phase 1 smoke-test exports (kept for sanity checks) ───────────────── + +/// Returns 42. Used by wzp-desktop's setup() to verify dlopen + dlsym +/// work before any audio code runs. #[unsafe(no_mangle)] pub extern "C" fn wzp_native_version() -> i32 { 42 } -/// Smoke-test export #2 — writes a fixed message into the caller's buffer -/// (NUL-terminated, capped at `cap`) and returns the number of bytes -/// written (not counting the NUL). Lets us verify we can move non-trivial -/// data across the FFI boundary without fighting ownership. +/// Writes a NUL-terminated string into `out` (capped at `cap`) and +/// returns bytes written excluding the NUL. #[unsafe(no_mangle)] pub unsafe extern "C" fn wzp_native_hello(out: *mut u8, cap: usize) -> usize { const MSG: &[u8] = b"hello from wzp-native\0"; @@ -34,11 +33,249 @@ pub unsafe extern "C" fn wzp_native_hello(out: *mut u8, cap: usize) -> usize { return 0; } let n = MSG.len().min(cap); - // SAFETY: caller provided a writable buffer of at least `cap` bytes. unsafe { core::ptr::copy_nonoverlapping(MSG.as_ptr(), out, n); - // ensure last byte is a NUL even if we had to truncate *out.add(n - 1) = 0; } - n - 1 // bytes written excluding the NUL + n - 1 +} + +// ─── C++ Oboe bridge FFI ───────────────────────────────────────────────── + +#[repr(C)] +struct WzpOboeConfig { + sample_rate: i32, + frames_per_burst: i32, + channel_count: i32, +} + +#[repr(C)] +struct WzpOboeRings { + capture_buf: *mut i16, + capture_capacity: i32, + capture_write_idx: *mut AtomicI32, + capture_read_idx: *mut AtomicI32, + playout_buf: *mut i16, + playout_capacity: i32, + playout_write_idx: *mut AtomicI32, + playout_read_idx: *mut AtomicI32, +} + +// SAFETY: atomics synchronise producer/consumer; raw pointers are owned +// by the AudioBackend singleton below whose lifetime covers all calls. +unsafe impl Send for WzpOboeRings {} +unsafe impl Sync for WzpOboeRings {} + +unsafe extern "C" { + fn wzp_oboe_start(config: *const WzpOboeConfig, rings: *const WzpOboeRings) -> i32; + fn wzp_oboe_stop(); + fn wzp_oboe_capture_latency_ms() -> f32; + fn wzp_oboe_playout_latency_ms() -> f32; + fn wzp_oboe_is_running() -> i32; +} + +// ─── SPSC ring buffer (shared with C++ via AtomicI32) ──────────────────── + +/// 20 ms @ 48 kHz mono = 960 samples. +const FRAME_SAMPLES: usize = 960; +/// ~160 ms headroom at 48 kHz. +const RING_CAPACITY: usize = 7680; + +struct RingBuffer { + buf: Vec, + capacity: usize, + write_idx: AtomicI32, + read_idx: AtomicI32, +} + +// SAFETY: SPSC with atomic read/write cursors; producer and consumer +// are always on different threads. +unsafe impl Send for RingBuffer {} +unsafe impl Sync for RingBuffer {} + +impl RingBuffer { + fn new(capacity: usize) -> Self { + Self { + buf: vec![0i16; capacity], + capacity, + write_idx: AtomicI32::new(0), + read_idx: AtomicI32::new(0), + } + } + + fn available_read(&self) -> usize { + let w = self.write_idx.load(Ordering::Acquire); + let r = self.read_idx.load(Ordering::Relaxed); + let avail = w - r; + if avail < 0 { (avail + self.capacity as i32) as usize } else { avail as usize } + } + + fn available_write(&self) -> usize { + self.capacity - 1 - self.available_read() + } + + fn write(&self, data: &[i16]) -> usize { + let count = data.len().min(self.available_write()); + if count == 0 { + return 0; + } + let mut w = self.write_idx.load(Ordering::Relaxed) as usize; + let cap = self.capacity; + let buf_ptr = self.buf.as_ptr() as *mut i16; + for sample in &data[..count] { + unsafe { *buf_ptr.add(w) = *sample; } + w += 1; + if w >= cap { w = 0; } + } + self.write_idx.store(w as i32, Ordering::Release); + count + } + + fn read(&self, out: &mut [i16]) -> usize { + let count = out.len().min(self.available_read()); + if count == 0 { + return 0; + } + let mut r = self.read_idx.load(Ordering::Relaxed) as usize; + let cap = self.capacity; + let buf_ptr = self.buf.as_ptr(); + for slot in &mut out[..count] { + unsafe { *slot = *buf_ptr.add(r); } + r += 1; + if r >= cap { r = 0; } + } + self.read_idx.store(r as i32, Ordering::Release); + count + } + + fn buf_ptr(&self) -> *mut i16 { + self.buf.as_ptr() as *mut i16 + } + fn write_idx_ptr(&self) -> *mut AtomicI32 { + &self.write_idx as *const AtomicI32 as *mut AtomicI32 + } + fn read_idx_ptr(&self) -> *mut AtomicI32 { + &self.read_idx as *const AtomicI32 as *mut AtomicI32 + } +} + +// ─── AudioBackend singleton ────────────────────────────────────────────── +// +// There is one global AudioBackend instance because Oboe's C++ side +// holds its own singleton of the streams. The `Box::leak`'d statics own +// the ring buffers for the lifetime of the process — dropping them while +// Oboe is still running would cause use-after-free in the audio callback. + +use std::sync::OnceLock; + +struct AudioBackend { + capture: RingBuffer, + playout: RingBuffer, + started: std::sync::Mutex, +} + +static BACKEND: OnceLock<&'static AudioBackend> = OnceLock::new(); + +fn backend() -> &'static AudioBackend { + BACKEND.get_or_init(|| { + Box::leak(Box::new(AudioBackend { + capture: RingBuffer::new(RING_CAPACITY), + playout: RingBuffer::new(RING_CAPACITY), + started: std::sync::Mutex::new(false), + })) + }) +} + +// ─── C FFI for wzp-desktop ─────────────────────────────────────────────── + +/// Start the Oboe audio streams. Returns 0 on success, non-zero on error. +/// Idempotent — calling while already running is a no-op that returns 0. +#[unsafe(no_mangle)] +pub extern "C" fn wzp_native_audio_start() -> i32 { + let b = backend(); + let mut started = match b.started.lock() { + Ok(g) => g, + Err(_) => return -1, + }; + if *started { + return 0; + } + + let config = WzpOboeConfig { + sample_rate: 48_000, + frames_per_burst: FRAME_SAMPLES as i32, + channel_count: 1, + }; + let rings = WzpOboeRings { + capture_buf: b.capture.buf_ptr(), + capture_capacity: b.capture.capacity as i32, + capture_write_idx: b.capture.write_idx_ptr(), + capture_read_idx: b.capture.read_idx_ptr(), + playout_buf: b.playout.buf_ptr(), + playout_capacity: b.playout.capacity as i32, + playout_write_idx: b.playout.write_idx_ptr(), + playout_read_idx: b.playout.read_idx_ptr(), + }; + let ret = unsafe { wzp_oboe_start(&config, &rings) }; + if ret != 0 { + return ret; + } + *started = true; + 0 +} + +/// Stop Oboe. Idempotent. Safe to call from any thread. +#[unsafe(no_mangle)] +pub extern "C" fn wzp_native_audio_stop() { + let b = backend(); + if let Ok(mut started) = b.started.lock() { + if *started { + unsafe { wzp_oboe_stop() }; + *started = false; + } + } +} + +/// Read captured PCM samples from the capture ring. Returns the number +/// of `i16` samples actually copied into `out` (may be less than +/// `out_len` if the ring is empty). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn wzp_native_audio_read_capture(out: *mut i16, out_len: usize) -> usize { + if out.is_null() || out_len == 0 { + return 0; + } + let slice = unsafe { std::slice::from_raw_parts_mut(out, out_len) }; + backend().capture.read(slice) +} + +/// Write PCM samples into the playout ring. Returns the number of +/// samples actually enqueued (may be less than `in_len` if the ring +/// is nearly full — in practice the caller should pace to 20 ms +/// frames and spin briefly if the ring is full). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn wzp_native_audio_write_playout(input: *const i16, in_len: usize) -> usize { + if input.is_null() || in_len == 0 { + return 0; + } + let slice = unsafe { std::slice::from_raw_parts(input, in_len) }; + backend().playout.write(slice) +} + +/// Current capture latency reported by Oboe, in milliseconds. Returns +/// NaN / 0.0 if the stream isn't running. +#[unsafe(no_mangle)] +pub extern "C" fn wzp_native_audio_capture_latency_ms() -> f32 { + unsafe { wzp_oboe_capture_latency_ms() } +} + +/// Current playout latency reported by Oboe, in milliseconds. +#[unsafe(no_mangle)] +pub extern "C" fn wzp_native_audio_playout_latency_ms() -> f32 { + unsafe { wzp_oboe_playout_latency_ms() } +} + +/// Non-zero if both Oboe streams are currently running. +#[unsafe(no_mangle)] +pub extern "C" fn wzp_native_audio_is_running() -> i32 { + unsafe { wzp_oboe_is_running() } }