diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs index 84f2694..b689677 100644 --- a/desktop/src-tauri/build.rs +++ b/desktop/src-tauri/build.rs @@ -1,3 +1,4 @@ +use std::path::PathBuf; use std::process::Command; fn main() { @@ -15,24 +16,154 @@ fn main() { println!("cargo:rerun-if-changed=../../.git/HEAD"); println!("cargo:rerun-if-changed=../../.git/refs/heads"); - // ─── Step A: single trivial cpp/hello.c compiled via cc::Build ───────── - // ─── Step D: also compile getauxval_fix.c (legacy wzp-android shim) ──── - // getauxval_fix.c overrides the broken static getauxval stub that - // compiler-rt pulls in for Android targets. It's been shipping in the - // legacy wzp-android .so for months without issue, so including it here - // is low-risk — but it's an incremental variable we want to isolate. let target = std::env::var("TARGET").unwrap_or_default(); if target.contains("android") { - println!("cargo:rerun-if-changed=cpp/hello.c"); - cc::Build::new() - .file("cpp/hello.c") - .compile("wzp_hello"); - - println!("cargo:rerun-if-changed=cpp/getauxval_fix.c"); - cc::Build::new() - .file("cpp/getauxval_fix.c") - .compile("getauxval_fix"); + build_android_native(); } tauri_build::build() } + +fn build_android_native() { + // ─── Step A: cpp/hello.c sanity static lib ───────────────────────────── + println!("cargo:rerun-if-changed=cpp/hello.c"); + cc::Build::new() + .file("cpp/hello.c") + .compile("wzp_hello"); + + // ─── Step D: getauxval_fix shim ──────────────────────────────────────── + println!("cargo:rerun-if-changed=cpp/getauxval_fix.c"); + cc::Build::new() + .file("cpp/getauxval_fix.c") + .compile("getauxval_fix"); + + // ─── Step E: full Oboe C++ bridge ────────────────────────────────────── + // Clones google/oboe@1.8.1 into OUT_DIR and compiles the bridge + all + // Oboe source files as a single static library. NOT yet called from + // Rust — this step only verifies that the C++ compile + link path + // doesn't regress the known-good build. Same approach as the legacy + // crates/wzp-android/build.rs, copied verbatim below. + 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"); + + match fetch_oboe() { + Some(oboe_path) => { + println!("cargo:warning=Building with Oboe from {:?}", oboe_path); + + let mut build = cc::Build::new(); + build + .cpp(true) + .std("c++17") + // Shared libc++ — static pulls broken libc stubs that crash + // in .so libraries (getauxval, __init_tcb, pthread_create). + // Google's official NDK guidance. + .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("oboe_bridge"); + } + None => { + println!("cargo:warning=Oboe not found, building with stub"); + cc::Build::new() + .cpp(true) + .std("c++17") + .cpp_link_stdlib(Some("c++_shared")) + .file("cpp/oboe_stub.cpp") + .include("cpp") + .compile("oboe_bridge"); + } + } + + // Copy libc++_shared.so next to libwzp_desktop_lib.so in the Tauri + // jniLibs directory so the dynamic linker can resolve it at runtime. + if let Ok(ndk) = std::env::var("ANDROID_NDK_HOME") + .or_else(|_| std::env::var("NDK_HOME")) + { + let (triple, abi) = match target_os_abi() { + Some(v) => v, + None => ("aarch64-linux-android", "arm64-v8a"), + }; + let lib_dir = format!( + "{ndk}/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/{triple}" + ); + println!("cargo:rustc-link-search=native={lib_dir}"); + + let shared_so = format!("{lib_dir}/libc++_shared.so"); + if std::path::Path::new(&shared_so).exists() { + let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default(); + let jni_dir = format!("{manifest}/gen/android/app/src/main/jniLibs/{abi}"); + if std::fs::create_dir_all(&jni_dir).is_ok() { + let _ = std::fs::copy(&shared_so, format!("{jni_dir}/libc++_shared.so")); + println!("cargo:warning=Copied libc++_shared.so to {jni_dir}"); + } + } + } + + // Oboe requires Android log + OpenSLES backends + println!("cargo:rustc-link-lib=log"); + println!("cargo:rustc-link-lib=OpenSLES"); +} + +fn target_os_abi() -> Option<(&'static str, &'static str)> { + let target = std::env::var("TARGET").ok()?; + if target.contains("aarch64") { + Some(("aarch64-linux-android", "arm64-v8a")) + } else if target.contains("armv7") { + Some(("arm-linux-androideabi", "armeabi-v7a")) + } else if target.contains("x86_64") { + Some(("x86_64-linux-android", "x86_64")) + } else if target.contains("i686") { + Some(("i686-linux-android", "x86")) + } else { + None + } +} + +/// 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); + } + } +} + +/// Try to find or fetch Oboe headers + source (v1.8.1). +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 = 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/desktop/src-tauri/cpp/oboe_bridge.cpp b/desktop/src-tauri/cpp/oboe_bridge.cpp new file mode 100644 index 0000000..066bb61 --- /dev/null +++ b/desktop/src-tauri/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/desktop/src-tauri/cpp/oboe_bridge.h b/desktop/src-tauri/cpp/oboe_bridge.h new file mode 100644 index 0000000..8c2f143 --- /dev/null +++ b/desktop/src-tauri/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/desktop/src-tauri/cpp/oboe_stub.cpp b/desktop/src-tauri/cpp/oboe_stub.cpp new file mode 100644 index 0000000..6792259 --- /dev/null +++ b/desktop/src-tauri/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; +}