measure: convert JNI surface to shared jni_fn! macro
- Commit
c420d1b1daf79ead702b20fa11c362a0518d790b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 19:52 UTC (4 days ago)
- Parents
6cb3277
LOC Phase 5 rollout. Two of the five measure_cv JNI functions repeated the EnvUnowned / with_env / LogErrorAndDefault scaffold and convert to jni_bridge::jni_fn!; the other three take an unused _env and operate on the session handle directly, so they stay hand-written. Bodies are verbatim (verified token-for-token); handles and null checks stay in the bodies. Lines: jni_bindings.rs 209 -> 180 (-29, -13.9%); structure_check measure module counted after (structure: OK). Cargo.lock gains only the jni_bridge edge for measure_cv. Verified: nm -D on libmeasure_cv.so before/after - exported symbol set identical (5/5 Java_ MeasureCvNative symbols); cargo test -p measure_cv: 88 passed; JVM bridge tests :measure:testDevUnitTestNative DirectByteBufferVioTest: 3/3 passed (run excludes the pre-existing rustFileLength ratchet); cargo fmt --check -p measure_cv clean.
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex ad7f9bc73d..6d7621e136 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3605,6 +3605,7 @@ name = "measure_cv" version = "0.1.0" dependencies = [ "jni",+ "jni_bridge", "vision_core", ]
measure/src/main/rust/Cargo.toml
diff --git a/measure/src/main/rust/Cargo.toml b/measure/src/main/rust/Cargo.tomlindex 233e04517e..97de1445fe 100644--- a/measure/src/main/rust/Cargo.toml+++ b/measure/src/main/rust/Cargo.toml@@ -11,6 +11,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] jni.workspace = true+jni_bridge = { path = "../../../../library/jni-bridge/src/main/rust" } # Shared CV primitives. Default features only: no JPEG codec, since frames arrive # as raw camera luminance planes. vision_core = { path = "../../../../library/vision/src/main/rust" }
measure/src/main/rust/src/jni_bindings.rs
diff --git a/measure/src/main/rust/src/jni_bindings.rs b/measure/src/main/rust/src/jni_bindings.rsindex bf22cff86e..b4470cc0ff 100644--- a/measure/src/main/rust/src/jni_bindings.rs+++ b/measure/src/main/rust/src/jni_bindings.rs@@ -6,6 +6,7 @@ use crate::{destride_into, CvSession, FrameFlow}; use jni::objects::{JByteArray, JByteBuffer, JClass}; use jni::sys::{jdouble, jdoubleArray, jlong}; use jni::{Env, EnvUnowned};+use jni_bridge::jni_fn; use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; use vision_core::imgbuf::Gray;@@ -62,107 +63,77 @@ pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative } } -/// Feed one luminance plane; `row_stride` is honoured so the caller can-/// pass the CameraX Y plane straight through without repacking it.-///-/// Returns `[pairCount, poseFlag, firstFlag, pointCount, R(9), t(3),-/// then prevX, prevY, currX, currY per pair]`; empty for a bad handle.-#[no_mangle]-#[allow(clippy::too_many_arguments)]-pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeProcessFrame<- 'l,->(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- handle: jlong,- y_plane: JByteArray<'l>,- width: jni::sys::jint,- height: jni::sys::jint,- row_stride: jni::sys::jint,-) -> jdoubleArray {- env.with_env(|env| -> jni::errors::Result<jdoubleArray> {- let (w, h, stride) = (width as usize, height as usize, row_stride as usize);- if w == 0 || h == 0 || stride < w {- return Ok(make_double_array(env, &[]));- }- let len = match y_plane.len(env) {- Ok(l) => l,- Err(_) => return Ok(make_double_array(env, &[])),- };- if len < stride * (h - 1) + w {- return Ok(make_double_array(env, &[]));- }- let mut buf = vec![0i8; len];- if y_plane.get_region(env, 0, &mut buf).is_err() {- return Ok(make_double_array(env, &[]));- }- // Byte-wise reinterpretation of the copied plane; the values are- // luminance bytes, so the i8/u8 bit pattern is what matters.- let bytes: &[u8] =- unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, buf.len()) };- let mut gray = Gray::new(w, h);- destride_into(bytes, w, h, stride, &mut gray);- let mut guard = sessions().lock().unwrap();- let vals: Vec<f64> = match guard.get_mut(&handle) {- Some(s) => encode_flow(&s.process_frame(&gray)),- None => Vec::new(),- };- Ok(make_double_array(env, &vals))- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+// Feed one luminance plane; `row_stride` is honoured so the caller can+// pass the CameraX Y plane straight through without repacking it.+//+// Returns `[pairCount, poseFlag, firstFlag, pointCount, R(9), t(3),+// then prevX, prevY, currX, currY per pair]`; empty for a bad handle.+jni_fn! { #[allow(clippy::too_many_arguments)] Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeProcessFrame -> jdoubleArray; (_class: JClass<'l>, handle: jlong, y_plane: JByteArray<'l>, width: jni::sys::jint, height: jni::sys::jint, row_stride: jni::sys::jint) |env| {+ let (w, h, stride) = (width as usize, height as usize, row_stride as usize);+ if w == 0 || h == 0 || stride < w {+ return Ok(make_double_array(env, &[]));+ }+ let len = match y_plane.len(env) {+ Ok(l) => l,+ Err(_) => return Ok(make_double_array(env, &[])),+ };+ if len < stride * (h - 1) + w {+ return Ok(make_double_array(env, &[]));+ }+ let mut buf = vec![0i8; len];+ if y_plane.get_region(env, 0, &mut buf).is_err() {+ return Ok(make_double_array(env, &[]));+ }+ // Byte-wise reinterpretation of the copied plane; the values are+ // luminance bytes, so the i8/u8 bit pattern is what matters.+ let bytes: &[u8] =+ unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, buf.len()) };+ let mut gray = Gray::new(w, h);+ destride_into(bytes, w, h, stride, &mut gray);+ let mut guard = sessions().lock().unwrap();+ let vals: Vec<f64> = match guard.get_mut(&handle) {+ Some(s) => encode_flow(&s.process_frame(&gray)),+ None => Vec::new(),+ };+ Ok(make_double_array(env, &vals))+} } -/// Direct-`ByteBuffer` twin of `nativeProcessFrame`: the caller hands over-/// the CameraX Y plane's (direct) buffer, and the plane is de-strided-/// straight from its native address into the session's retained Gray-/// buffer — no Kotlin `ByteArray` copy and no Rust `Vec` for the frame.-/// The buffer must outlive this call, which the synchronous JNI call-/// guarantees for the caller's `ImageProxy` (closed after it returns).-/// Empty for a bad handle, a non-direct buffer, or a short plane.-#[no_mangle]-#[allow(clippy::too_many_arguments)]-pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeProcessFrameDirect<- 'l,->(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- handle: jlong,- y_plane: JByteBuffer<'l>,- width: jni::sys::jint,- height: jni::sys::jint,- row_stride: jni::sys::jint,-) -> jdoubleArray {- env.with_env(|env| -> jni::errors::Result<jdoubleArray> {- let (w, h, stride) = (width as usize, height as usize, row_stride as usize);- if w == 0 || h == 0 || stride < w {- return Ok(make_double_array(env, &[]));- }- let addr = match env.get_direct_buffer_address(&y_plane) {- Ok(a) if !a.is_null() => a,- _ => return Ok(make_double_array(env, &[])),- };- let capacity = match env.get_direct_buffer_capacity(&y_plane) {- Ok(c) => c,- Err(_) => return Ok(make_double_array(env, &[])),- };- if capacity < stride * (h - 1) + w {- return Ok(make_double_array(env, &[]));- }- // Safety: `addr`/`capacity` describe the direct buffer, which the- // JVM keeps alive while this JNI call (and its local ref) runs.- let src: &[u8] = unsafe { std::slice::from_raw_parts(addr as *const u8, capacity) };- let mut guard = sessions().lock().unwrap();- let vals: Vec<f64> = match guard.get_mut(&handle) {- Some(s) => match s.process_frame_strided(src, w, h, stride) {- Some(flow) => encode_flow(&flow),- None => Vec::new(),- },+// Direct-`ByteBuffer` twin of `nativeProcessFrame`: the caller hands over+// the CameraX Y plane's (direct) buffer, and the plane is de-strided+// straight from its native address into the session's retained Gray+// buffer — no Kotlin `ByteArray` copy and no Rust `Vec` for the frame.+// The buffer must outlive this call, which the synchronous JNI call+// guarantees for the caller's `ImageProxy` (closed after it returns).+// Empty for a bad handle, a non-direct buffer, or a short plane.+jni_fn! { #[allow(clippy::too_many_arguments)] Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeProcessFrameDirect -> jdoubleArray; (_class: JClass<'l>, handle: jlong, y_plane: JByteBuffer<'l>, width: jni::sys::jint, height: jni::sys::jint, row_stride: jni::sys::jint) |env| {+ let (w, h, stride) = (width as usize, height as usize, row_stride as usize);+ if w == 0 || h == 0 || stride < w {+ return Ok(make_double_array(env, &[]));+ }+ let addr = match env.get_direct_buffer_address(&y_plane) {+ Ok(a) if !a.is_null() => a,+ _ => return Ok(make_double_array(env, &[])),+ };+ let capacity = match env.get_direct_buffer_capacity(&y_plane) {+ Ok(c) => c,+ Err(_) => return Ok(make_double_array(env, &[])),+ };+ if capacity < stride * (h - 1) + w {+ return Ok(make_double_array(env, &[]));+ }+ // Safety: `addr`/`capacity` describe the direct buffer, which the+ // JVM keeps alive while this JNI call (and its local ref) runs.+ let src: &[u8] = unsafe { std::slice::from_raw_parts(addr as *const u8, capacity) };+ let mut guard = sessions().lock().unwrap();+ let vals: Vec<f64> = match guard.get_mut(&handle) {+ Some(s) => match s.process_frame_strided(src, w, h, stride) {+ Some(flow) => encode_flow(&flow), None => Vec::new(),- };- Ok(make_double_array(env, &vals))- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ },+ None => Vec::new(),+ };+ Ok(make_double_array(env, &vals))+} } fn encode_flow(flow: &FrameFlow) -> Vec<f64> { let mut v = Vec::with_capacity(20 + flow.pairs.len() * 5);