Modern Apps git

← Modern-Apps.git

photos, measure: cut the two biggest frame copies

Commit
1e647f1d34cabb10d680bf7acb134885988f99ad
Author
Vayun Mathur <[email protected]>
When
2026-11-21 17:55 UTC (14 days ago)
Parents
b61409a
Photos' subject segmentation computed a 512px cap and then
passed the full-size bitmap anyway - the model downscales to
320 internally, so each auto-select burned ~25MB of copies.
The capped bitmap is now created before segment() and recycled
after. Measure copied the Y plane ByteBuffer->ByteArray every
frame (~28MB/s at 30fps) plus another Rust-side copy: a new
direct-ByteBuffer JNI overload de-strides straight into a
retained gray buffer that ping-pongs with the previous frame -
no per-frame allocation for incoming frames after warm-up,
ByteArray path kept for other callers, equality between the
two paths proven in Rust and Kotlin tests.

Verified: cargo measure_cv 88 pass, measure and photos tests
pass.

Diff

measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt b/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.ktindex 8b5f186911..75418248ab 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt@@ -4,6 +4,7 @@ import com.vayunmathur.library.log.NativeLoader  import com.vayunmathur.measure.domain.Pose3 import com.vayunmathur.measure.domain.Vec3+import java.nio.ByteBuffer  /** One tracked correspondence, in pixels: previous -> current. [id] is stable for the feature's life. */ data class CvPair(@@ -66,7 +67,34 @@ object MeasureCvNative {         rowStride: Int,     ): CvFrameFlow? {         if (!available || handle == 0L) return null-        val raw = nativeProcessFrame(handle, yPlane, width, height, rowStride)+        return parseFlow(nativeProcessFrame(handle, yPlane, width, height, rowStride))+    }++    /**+     * Direct-buffer twin of the [ByteArray] overload: a direct [yPlane] (the+     * CameraX Y plane) is de-strided natively from its own address, with no+     * Kotlin copy. A heap buffer, or one whose position is not the plane+     * start, falls back to the [ByteArray] path so correctness does not+     * depend on buffer provenance. The buffer is only read during this+     * synchronous call, so the caller may close its frame afterwards.+     */+    fun processFrame(+        handle: Long,+        yPlane: ByteBuffer,+        width: Int,+        height: Int,+        rowStride: Int,+    ): CvFrameFlow? {+        if (!available || handle == 0L) return null+        if (!yPlane.isDirect || yPlane.position() != 0) {+            val copy = ByteArray(yPlane.remaining())+            yPlane.duplicate().get(copy)+            return processFrame(handle, copy, width, height, rowStride)+        }+        return parseFlow(nativeProcessFrameDirect(handle, yPlane, width, height, rowStride))+    }++    private fun parseFlow(raw: DoubleArray): CvFrameFlow? {         if (raw.size < HEADER_SIZE) return null         val pairCount = raw[0].toInt()         val pose = if (raw[1] != 0.0) {@@ -122,4 +150,12 @@ object MeasureCvNative {         height: Int,         rowStride: Int,     ): DoubleArray++    private external fun nativeProcessFrameDirect(+        handle: Long,+        yPlane: ByteBuffer,+        width: Int,+        height: Int,+        rowStride: Int,+    ): DoubleArray }
measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt b/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.ktindex c1ceb564fc..78407bbca1 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt@@ -19,6 +19,7 @@ import com.vayunmathur.measure.domain.solveCameraCentre import com.vayunmathur.measure.domain.triangulate import com.vayunmathur.measure.platform.Intrinsics import com.vayunmathur.library.log.Log+import java.nio.ByteBuffer import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.sqrt@@ -206,6 +207,33 @@ class VioEngine(     ): VioFrameResult {         framesSeen++         val flow = MeasureCvNative.processFrame(nativeHandle, yPlane, width, height, rowStride)+        return processFlow(flow, width, height, rowStride, timestampNs)+    }++    /**+     * Direct-buffer overload: the CameraX Y plane is de-strided natively+     * from its own address, with no per-frame Kotlin copy of the plane.+     */+    fun processFrame(+        yPlane: ByteBuffer,+        width: Int,+        height: Int,+        rowStride: Int,+        timestampNs: Long,+    ): VioFrameResult {+        framesSeen+++        val flow = MeasureCvNative.processFrame(nativeHandle, yPlane, width, height, rowStride)+        return processFlow(flow, width, height, rowStride, timestampNs)+    }++    private fun processFlow(+        flowOrNull: CvFrameFlow?,+        width: Int,+        height: Int,+        rowStride: Int,+        timestampNs: Long,+    ): VioFrameResult {+        val flow = flowOrNull             ?: run {                 if (framesSeen % 30 == 1) Log.dev(TAG, "frame=$framesSeen native=null handle=$nativeHandle avail=$available")                 return trackingFailure(0)
measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt b/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.ktindex 70eaa53d50..20232bda6f 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt@@ -171,7 +171,6 @@ internal class VioFrameAnalyzer(     private var engine: VioEngine? = engine     private var engineCreationTried = false -    private var buffer: ByteArray? = null     private var lastFrameNs = 0L     private var frameIntervalNs = 0L     private var frameCount = 0L@@ -204,14 +203,14 @@ internal class VioFrameAnalyzer(             if (imu.isNotEmpty()) eng.pushImu(imu)              val plane = image.planes[0]-            val src = plane.buffer-            val needed = src.remaining()-            val dst = buffer?.takeIf { it.size >= needed } ?: ByteArray(needed).also { buffer = it }-            src.get(dst, 0, needed)              val tNs = image.imageInfo.timestamp+            // Hand the Y plane's direct buffer straight to the engine: it is+            // de-strided natively, with no per-frame Kotlin copy of the plane.+            // The image is only closed in the finally block, after this+            // synchronous call has returned.             val result = eng.processFrame(-                yPlane = dst,+                yPlane = plane.buffer,                 width = image.width,                 height = image.height,                 rowStride = plane.rowStride,
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.rsnew file mode 100644index 0000000000..9e6944067d--- /dev/null+++ b/measure/src/main/rust/src/jni_bindings.rs@@ -0,0 +1,204 @@+//! JNI bindings for `measure_cv` (split from `lib.rs` for the file-length gate).+//! Not cfg-gated to Android: the host build must export the same JNI symbols+//! or the Kotlin bridge's availability check lies in JVM tests.++use crate::{destride_into, CvSession, FrameFlow};+use jni::objects::{JByteArray, JByteBuffer, JClass};+use jni::sys::{jdouble, jdoubleArray, jlong};+use jni::{Env, EnvUnowned};+use std::collections::HashMap;+use std::sync::{Mutex, OnceLock};+use vision_core::imgbuf::Gray;++/// Sessions are held behind a handle rather than a raw pointer so a stale+/// handle from Kotlin is a lookup miss instead of a use-after-free.+fn sessions() -> &'static Mutex<HashMap<i64, CvSession>> {+    static S: OnceLock<Mutex<HashMap<i64, CvSession>>> = OnceLock::new();+    S.get_or_init(|| Mutex::new(HashMap::new()))+}++fn next_handle() -> i64 {+    static N: OnceLock<Mutex<i64>> = OnceLock::new();+    let m = N.get_or_init(|| Mutex::new(0));+    let mut g = m.lock().unwrap();+    *g += 1;+    *g+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeCreateSession(+    _env: EnvUnowned,+    _class: JClass,+    fx: jdouble,+    fy: jdouble,+    cx: jdouble,+    cy: jdouble,+) -> jlong {+    if !(fx.is_finite() && fy.is_finite() && fx > 1.0 && fy > 1.0) {+        return 0;+    }+    let h = next_handle();+    sessions().lock().unwrap().insert(h, CvSession::new(fx, fy, cx, cy));+    h+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeDestroySession(+    _env: EnvUnowned,+    _class: JClass,+    handle: jlong,+) {+    sessions().lock().unwrap().remove(&handle);+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeReset(+    _env: EnvUnowned,+    _class: JClass,+    handle: jlong,+) {+    if let Some(s) = sessions().lock().unwrap().get_mut(&handle) {+        s.reset();+    }+}++/// 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>()+}++/// 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(),+            },+            None => Vec::new(),+        };+        Ok(make_double_array(env, &vals))+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}++fn encode_flow(flow: &FrameFlow) -> Vec<f64> {+    let mut v = Vec::with_capacity(20 + flow.pairs.len() * 5);+    v.push(flow.pairs.len() as f64);+    v.push(if flow.pose.is_some() { 1.0 } else { 0.0 });+    v.push(if flow.first_frame { 1.0 } else { 0.0 });+    v.push(flow.point_count as f64);+    match &flow.pose {+        Some(p) => {+            for row in 0..3 {+                for col in 0..3 {+                    v.push(p.r[(row, col)]);+                }+            }+            v.push(p.t[0]);+            v.push(p.t[1]);+            v.push(p.t[2]);+        }+        None => v.extend(std::iter::repeat_n(0.0, 12)),+    }+    v.push(flow.seeded as f64);+    v.push(flow.forward_ok as f64);+    v.push(flow.fb_survivors as f64);+    v.push(flow.ransac_inliers as f64);+    for pair in &flow.pairs {+        v.push(pair.id as f64);+        v.push(pair.prev.0);+        v.push(pair.prev.1);+        v.push(pair.curr.0);+        v.push(pair.curr.1);+    }+    v+}++fn make_double_array(env: &mut Env, vals: &[f64]) -> jdoubleArray {+    let arr = match env.new_double_array(vals.len()) {+        Ok(a) => a,+        Err(_) => return std::ptr::null_mut(),+    };+    if !vals.is_empty() && arr.set_region(env, 0, vals).is_err() {+        return std::ptr::null_mut();+    }+    arr.into_raw()+}
measure/src/main/rust/src/lib.rs
diff --git a/measure/src/main/rust/src/lib.rs b/measure/src/main/rust/src/lib.rsindex 990911a70e..4484cfb2b4 100644--- a/measure/src/main/rust/src/lib.rs+++ b/measure/src/main/rust/src/lib.rs@@ -76,6 +76,10 @@ struct Intrinsics { pub struct CvSession {     intr: Intrinsics,     prev_gray: Option<Gray>,+    /// Retained scratch for the strided/direct path: refilled in place each+    /// frame, then swapped with `prev_gray` (the old previous frame becomes+    /// the next scratch), so the incoming frame needs no per-frame allocation.+    incoming_gray: Option<Gray>,     prev_points: Vec<(u64, f32, f32)>,     next_id: u64, }@@ -85,6 +89,7 @@ impl CvSession {         CvSession {             intr: Intrinsics { fx, fy, cx, cy },             prev_gray: None,+            incoming_gray: None,             prev_points: Vec::new(),             next_id: 1,         }@@ -92,6 +97,7 @@ impl CvSession {      pub fn reset(&mut self) {         self.prev_gray = None;+        self.incoming_gray = None;         self.prev_points = Vec::new();         self.next_id = 1;     }@@ -103,10 +109,42 @@ impl CvSession {     }      pub fn process_frame(&mut self, gray: &Gray) -> FrameFlow {+        self.process_frame_owned(gray.clone())+    }++    /// Process one frame handed over as a strided luminance plane (e.g. a+    /// direct `ByteBuffer` from CameraX): de-stride straight into the retained+    /// incoming buffer, with no per-frame `Vec` for the incoming frame.+    /// `None` when the plane is too short or the stride cannot hold a row.+    pub fn process_frame_strided(+        &mut self,+        src: &[u8],+        width: usize,+        height: usize,+        row_stride: usize,+    ) -> Option<FrameFlow> {+        if width == 0 || height == 0 || row_stride < width {+            return None;+        }+        if src.len() < row_stride * (height - 1) + width {+            return None;+        }+        let mut gray = self+            .incoming_gray+            .take()+            .unwrap_or_else(|| Gray::new(width, height));+        destride_into(src, width, height, row_stride, &mut gray);+        Some(self.process_frame_owned(gray))+    }++    fn process_frame_owned(&mut self, gray: Gray) -> FrameFlow {         let prev_gray = match self.prev_gray.take() {             Some(p) if p.w == gray.w && p.h == gray.h => p,-            _ => {-                let pts = corners::detect(gray);+            other => {+                if let Some(old) = other {+                    self.incoming_gray = Some(old);+                }+                let pts = corners::detect(&gray);                 let count = pts.len();                 self.prev_points = pts                     .into_iter()@@ -116,7 +154,7 @@ impl CvSession {                         (id, x, y)                     })                     .collect();-                self.prev_gray = Some(gray.clone());+                self.prev_gray = Some(gray);                 return FrameFlow {                     first_frame: true,                     pairs: Vec::new(),@@ -131,7 +169,7 @@ impl CvSession {         };          let prev_pyr = Pyramid::build(&prev_gray, PYRAMID_LEVELS);-        let curr_pyr = Pyramid::build(gray, PYRAMID_LEVELS);+        let curr_pyr = Pyramid::build(&gray, PYRAMID_LEVELS);         let prev_xy: Vec<(f32, f32)> =             self.prev_points.iter().map(|&(_, x, y)| (x, y)).collect();         let forward = klt::track(&prev_pyr, &curr_pyr, &prev_xy);@@ -197,7 +235,7 @@ impl CvSession {             .map(|p| (p.id, p.curr.0 as f32, p.curr.1 as f32))             .collect();         if next_points.len() < corners::MAX_CORNERS / 2 {-            for pt in corners::detect(gray) {+            for pt in corners::detect(&gray) {                 if next_points                     .iter()                     .all(|&(_, x, y)| (x - pt.0).powi(2) + (y - pt.1).powi(2) >= 100.0)@@ -212,7 +250,10 @@ impl CvSession {         }         let point_count = next_points.len();         self.prev_points = next_points;-        self.prev_gray = Some(gray.clone());+        // The current frame becomes the previous frame with no copy; the old+        // previous buffer is retained as the next incoming scratch.+        self.incoming_gray = Some(prev_gray);+        self.prev_gray = Some(gray);         FrameFlow {             first_frame: false,             pairs,@@ -233,159 +274,24 @@ impl CvSession {     } } -// Not cfg-gated to Android: the host build must export the same JNI symbols-// or the Kotlin bridge's availability check lies in JVM tests.-mod jni_bindings {-    use crate::CvSession;-    use jni::objects::{JByteArray, JClass};-    use jni::sys::{jdouble, jdoubleArray, jlong};-    use jni::{Env, EnvUnowned};-    use std::collections::HashMap;-    use std::sync::{Mutex, OnceLock};-    use vision_core::imgbuf::Gray;--    /// Sessions are held behind a handle rather than a raw pointer so a stale-    /// handle from Kotlin is a lookup miss instead of a use-after-free.-    fn sessions() -> &'static Mutex<HashMap<i64, CvSession>> {-        static S: OnceLock<Mutex<HashMap<i64, CvSession>>> = OnceLock::new();-        S.get_or_init(|| Mutex::new(HashMap::new()))+/// Copy a strided luminance plane into [dst], dropping row padding.+/// [dst] keeps its allocation when the size is unchanged. Callers validate+/// `stride >= width` and that [src] holds `stride * (height - 1) + width` bytes.+pub fn destride_into(src: &[u8], width: usize, height: usize, row_stride: usize, dst: &mut Gray) {+    if dst.w != width || dst.h != height {+        dst.w = width;+        dst.h = height;+        dst.px.resize(width * height, 0);     }--    fn next_handle() -> i64 {-        static N: OnceLock<Mutex<i64>> = OnceLock::new();-        let m = N.get_or_init(|| Mutex::new(0));-        let mut g = m.lock().unwrap();-        *g += 1;-        *g-    }--    #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeCreateSession(-        _env: EnvUnowned,-        _class: JClass,-        fx: jdouble,-        fy: jdouble,-        cx: jdouble,-        cy: jdouble,-    ) -> jlong {-        if !(fx.is_finite() && fy.is_finite() && fx > 1.0 && fy > 1.0) {-            return 0;-        }-        let h = next_handle();-        sessions().lock().unwrap().insert(h, CvSession::new(fx, fy, cx, cy));-        h+    if row_stride == width {+        dst.px.copy_from_slice(&src[..width * height]);+        return;     }--    #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeDestroySession(-        _env: EnvUnowned,-        _class: JClass,-        handle: jlong,-    ) {-        sessions().lock().unwrap().remove(&handle);-    }--    #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeReset(-        _env: EnvUnowned,-        _class: JClass,-        handle: jlong,-    ) {-        if let Some(s) = sessions().lock().unwrap().get_mut(&handle) {-            s.reset();-        }-    }--    /// 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, &[]));-            }-            let mut gray = Gray::new(w, h);-            for row in 0..h {-                let src = row * stride;-                let dst = row * w;-                for col in 0..w {-                    gray.px[dst + col] = buf[src + col] as u8;-                }-            }-            let mut guard = sessions().lock().unwrap();-            let vals: Vec<f64> = match guard.get_mut(&handle) {-                Some(s) => {-                    let flow = s.process_frame(&gray);-                    let mut v = Vec::with_capacity(16 + flow.pairs.len() * 4);-                    v.push(flow.pairs.len() as f64);-                    v.push(if flow.pose.is_some() { 1.0 } else { 0.0 });-                    v.push(if flow.first_frame { 1.0 } else { 0.0 });-                    v.push(flow.point_count as f64);-                    match &flow.pose {-                        Some(p) => {-                            for row in 0..3 {-                                for col in 0..3 {-                                    v.push(p.r[(row, col)]);-                                }-                            }-                            v.push(p.t[0]);-                            v.push(p.t[1]);-                            v.push(p.t[2]);-                        }-                        None => v.extend(std::iter::repeat_n(0.0, 12)),-                    }-                    v.push(flow.seeded as f64);-                    v.push(flow.forward_ok as f64);-                    v.push(flow.fb_survivors as f64);-                    v.push(flow.ransac_inliers as f64);-                    for pair in &flow.pairs {-                        v.push(pair.id as f64);-                        v.push(pair.prev.0);-                        v.push(pair.prev.1);-                        v.push(pair.curr.0);-                        v.push(pair.curr.1);-                    }-                    v-                }-                None => Vec::new(),-            };-            Ok(make_double_array(env, &vals))-        })-        .resolve::<jni::errors::LogErrorAndDefault>()-    }--    fn make_double_array(env: &mut Env, vals: &[f64]) -> jdoubleArray {-        let arr = match env.new_double_array(vals.len()) {-            Ok(a) => a,-            Err(_) => return std::ptr::null_mut(),-        };-        if !vals.is_empty() && arr.set_region(env, 0, vals).is_err() {-            return std::ptr::null_mut();-        }-        arr.into_raw()+    for row in 0..height {+        let src_off = row * row_stride;+        let dst_off = row * width;+        dst.px[dst_off..dst_off + width].copy_from_slice(&src[src_off..src_off + width]);     } }++mod jni_bindings;
measure/src/main/rust/src/lib_tests.rs
diff --git a/measure/src/main/rust/src/lib_tests.rs b/measure/src/main/rust/src/lib_tests.rsindex 1b3f832156..a600f723b8 100644--- a/measure/src/main/rust/src/lib_tests.rs+++ b/measure/src/main/rust/src/lib_tests.rs@@ -181,6 +181,92 @@ fn tiny_frames_never_track_and_never_panic() {     assert!(f2.pose.is_none()); } +// --- Strided / direct-buffer path -------------------------------------------------++/// Pack [gray] into a padded plane: `pad` junk bytes after every row.+fn padded(gray: &Gray, pad: usize) -> (Vec<u8>, usize) {+    let stride = gray.w + pad;+    let mut out = vec![0xEEu8; stride * gray.h];+    for y in 0..gray.h {+        out[y * stride..y * stride + gray.w]+            .copy_from_slice(&gray.px[y * gray.w..(y + 1) * gray.w]);+    }+    (out, stride)+}++#[test]+fn destride_drops_row_padding_and_ignores_the_junk_bytes() {+    // Hand-computed: 4x3 image, stride 7, padding filled with 0xEE.+    let mut src = Vec::new();+    for row in 0..3u8 {+        src.extend_from_slice(&[row * 10 + 1, row * 10 + 2, row * 10 + 3, row * 10 + 4]);+        src.extend_from_slice(&[0xEE, 0xEE, 0xEE]);+    }+    let mut dst = Gray::new(1, 1);+    destride_into(&src, 4, 3, 7, &mut dst);+    assert_eq!((dst.w, dst.h), (4, 3));+    assert_eq!(dst.px, vec![1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24]);+    // A tight plane (stride == width) round-trips too, reusing the buffer.+    let tight: Vec<u8> = (0..12).collect();+    destride_into(&tight, 4, 3, 4, &mut dst);+    assert_eq!(dst.px, tight);+}++#[test]+fn strided_path_matches_the_byte_array_path_frame_for_frame() {+    let f1 = aperiodic(320, 240, 0, 0);+    let f2 = aperiodic(320, 240, 3, 1);+    let (p1, stride1) = padded(&f1, 17);+    let (p2, stride2) = padded(&f2, 17);+    assert_eq!(stride1, 337);++    let mut via_array = CvSession::new(300.0, 300.0, 160.0, 120.0);+    let a1 = via_array.process_frame(&f1);+    let a2 = via_array.process_frame(&f2);++    let mut via_strided = CvSession::new(300.0, 300.0, 160.0, 120.0);+    let b1 = via_strided+        .process_frame_strided(&p1, f1.w, f1.h, stride1)+        .expect("padded first frame");+    let b2 = via_strided+        .process_frame_strided(&p2, f2.w, f2.h, stride2)+        .expect("padded second frame");++    assert_eq!(b1.first_frame, a1.first_frame);+    assert_eq!(b1.point_count, a1.point_count);+    assert_eq!(b2.first_frame, a2.first_frame);+    assert_eq!(b2.point_count, a2.point_count);+    assert_eq!(b2.seeded, a2.seeded);+    assert_eq!(b2.forward_ok, a2.forward_ok);+    assert_eq!(b2.fb_survivors, a2.fb_survivors);+    assert_eq!(b2.ransac_inliers, a2.ransac_inliers);+    assert_eq!(b2.pairs, a2.pairs, "tracked pairs must be identical");+    assert_eq!(b2.pose.is_some(), a2.pose.is_some());+    if let (Some(pa), Some(pb)) = (&a2.pose, &b2.pose) {+        for i in 0..3 {+            assert_eq!(pa.t[i], pb.t[i]);+            for j in 0..3 {+                assert_eq!(pa.r[(i, j)], pb.r[(i, j)]);+            }+        }+    }+    assert!(b2.pairs.len() >= 15, "strided path tracked {}", b2.pairs.len());+}++#[test]+fn strided_path_rejects_short_or_malformed_planes() {+    let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+    assert!(s.process_frame_strided(&[0u8; 10], 320, 240, 320).is_none());+    assert!(s.process_frame_strided(&[0u8; 4096], 320, 240, 100).is_none(), "stride < width");+    assert!(s.process_frame_strided(&[0u8; 4096], 0, 240, 320).is_none());+    // Rejection must not poison the session: a valid frame still seeds.+    let f = aperiodic(320, 240, 0, 0);+    let (p, stride) = padded(&f, 5);+    let flow = s.process_frame_strided(&p, f.w, f.h, stride).unwrap();+    assert!(flow.first_frame);+    assert!(flow.point_count > 50);+}+ #[test] fn reset_clears_points_so_the_next_frame_reseeds_from_scratch() {     let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);
measure/src/test/java/com/vayunmathur/measure/platform/DirectByteBufferVioTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/platform/DirectByteBufferVioTest.kt b/measure/src/test/java/com/vayunmathur/measure/platform/DirectByteBufferVioTest.ktnew file mode 100644index 0000000000..32a05d2d60--- /dev/null+++ b/measure/src/test/java/com/vayunmathur/measure/platform/DirectByteBufferVioTest.kt@@ -0,0 +1,128 @@+package com.vayunmathur.measure.platform++import com.vayunmathur.measure.platform.vio.MeasureCvNative+import com.vayunmathur.measure.platform.vio.VioEngine+import java.nio.ByteBuffer+import kotlin.math.cos+import kotlin.math.sin+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * The direct-ByteBuffer frame path (CameraX Y plane -> JNI+ * GetDirectBufferAddress -> retained Rust Gray buffer) must produce exactly+ * the ByteArray path's output on padded planes, and fall back safely for+ * heap buffers. Host-side: skipped when the native library is unavailable.+ */+class DirectByteBufferVioTest {++    private val w = 320+    private val h = 240+    private val pad = 17+    private val stride = w + pad++    private fun frame(shiftX: Int, shiftY: Int): ByteArray {+        val out = ByteArray(w * h)+        for (y in 0 until h) {+            for (x in 0 until w) {+                val sx = x - shiftX+                val sy = y - shiftY+                val v = (sin(sx * 0.31) * cos(sy * 0.23) + sin((sx + sy) * 0.13) ++                    cos(sx * 0.07 - sy * 0.09)) * 55.0 + 128.0+                out[y * w + x] = v.coerceIn(0.0, 255.0).toInt().toByte()+            }+        }+        return out+    }++    /** [tight] re-laid at [stride] with junk padding after every row. */+    private fun padded(tight: ByteArray): ByteArray {+        val out = ByteArray(stride * h) { 0xEE.toByte() }+        for (y in 0 until h) {+            System.arraycopy(tight, y * w, out, y * stride, w)+        }+        return out+    }++    private fun direct(bytes: ByteArray): ByteBuffer =+        ByteBuffer.allocateDirect(bytes.size).apply {+            put(bytes)+            rewind()+        }++    @Test+    fun directBufferMatchesByteArrayPathOnPaddedFrames() {+        if (!MeasureCvNative.available) return+        val f1 = padded(frame(0, 0))+        val f2 = padded(frame(4, 2))++        val arrayHandle = MeasureCvNative.createSession(300.0, 300.0, 160.0, 120.0)+        val directHandle = MeasureCvNative.createSession(300.0, 300.0, 160.0, 120.0)+        try {+            assertTrue(arrayHandle != 0L && directHandle != 0L)+            val a1 = assertNotNull(MeasureCvNative.processFrame(arrayHandle, f1, w, h, stride))+            val b1 = assertNotNull(MeasureCvNative.processFrame(directHandle, direct(f1), w, h, stride))+            assertEquals(a1.firstFrame, b1.firstFrame)+            assertEquals(a1.pointCount, b1.pointCount)+            assertTrue(b1.pointCount >= 20, "seeded ${b1.pointCount}")++            val a2 = assertNotNull(MeasureCvNative.processFrame(arrayHandle, f2, w, h, stride))+            val b2 = assertNotNull(MeasureCvNative.processFrame(directHandle, direct(f2), w, h, stride))+            assertEquals(a2.pairs, b2.pairs)+            assertEquals(a2.pointCount, b2.pointCount)+            assertEquals(a2.seeded, b2.seeded)+            assertEquals(a2.forwardOk, b2.forwardOk)+            assertEquals(a2.fbSurvivors, b2.fbSurvivors)+            assertEquals(a2.ransacInliers, b2.ransacInliers)+            assertEquals(a2.pose == null, b2.pose == null)+            val aPose = a2.pose+            val bPose = b2.pose+            if (aPose != null && bPose != null) {+                assertTrue(aPose.r.contentEquals(bPose.r))+                assertEquals(aPose.t, bPose.t)+            }+            assertTrue(b2.pairs.size >= 15, "direct path tracked ${b2.pairs.size}")+        } finally {+            MeasureCvNative.destroySession(arrayHandle)+            MeasureCvNative.destroySession(directHandle)+        }+    }++    @Test+    fun heapBufferFallsBackAndStillTracks() {+        if (!MeasureCvNative.available) return+        val handle = MeasureCvNative.createSession(300.0, 300.0, 160.0, 120.0)+        try {+            val heap = ByteBuffer.wrap(padded(frame(0, 0)))+            val first = assertNotNull(MeasureCvNative.processFrame(handle, heap, w, h, stride))+            assertTrue(first.firstFrame)+            assertTrue(first.pointCount >= 20)+        } finally {+            MeasureCvNative.destroySession(handle)+        }+    }++    @Test+    fun vioEngineByteBufferOverloadMatchesByteArrayOverload() {+        if (!MeasureCvNative.available) return+        val intrinsics = Intrinsics(300.0, 300.0, 160.0, 120.0, true)+        val viaArray = VioEngine(intrinsics, w, h)+        val viaBuffer = VioEngine(intrinsics, w, h)+        try {+            val f1 = padded(frame(0, 0))+            val f2 = padded(frame(4, 2))+            val a1 = viaArray.processFrame(f1, w, h, stride, 1_000_000L)+            val b1 = viaBuffer.processFrame(direct(f1), w, h, stride, 1_000_000L)+            assertEquals(a1, b1)+            val a2 = viaArray.processFrame(f2, w, h, stride, 34_000_000L)+            val b2 = viaBuffer.processFrame(direct(f2), w, h, stride, 34_000_000L)+            assertEquals(a2, b2)+            assertTrue(b2.trackedFeatures >= 15, "engine tracked ${b2.trackedFeatures}")+        } finally {+            viaArray.close()+            viaBuffer.close()+        }+    }+}
photos/src/main/java/com/vayunmathur/photos/platform/MlSegmentation.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/MlSegmentation.kt b/photos/src/main/java/com/vayunmathur/photos/platform/MlSegmentation.ktindex 1beb90c416..d33211b9ea 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/MlSegmentation.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/MlSegmentation.kt@@ -5,6 +5,7 @@ import android.graphics.Bitmap import android.os.Handler import android.os.Looper import com.vayunmathur.library.log.Log+import com.vayunmathur.library.ml.SegmentationMask import com.vayunmathur.library.ml.SubjectSegmenter import com.vayunmathur.photos.data.Selection @@ -50,24 +51,39 @@ private const val FEATHER_RADIUS = 1.5f  */ private val segLock = Any() -private fun runSegmenter(context: Context, bitmap: Bitmap): Selection? {-    // Cap the returned mask resolution for speed/memory; the model runs at its-    // fixed input size and we upsample the saliency map to this.-    val maxDim = 512-    val scale = minOf(1f, maxDim.toFloat() / maxOf(bitmap.width, bitmap.height))-    val w = (bitmap.width * scale).toInt().coerceAtLeast(1)-    val h = (bitmap.height * scale).toInt().coerceAtLeast(1)+/** Longest side handed to the segmenter, and of the returned mask. */+internal const val SEGMENTATION_MAX_DIM = 512 -    val result = synchronized(segLock) {-        SubjectSegmenter(context.applicationContext).use { seg ->-            if (!seg.isAvailable) {-                Log.error("MlSegmentation", "U\u00b2-Net unavailable; see the ModelRunner log tag")-                return null-            }-            // HARDWARE and unknown bitmap configs are handled inside SubjectSegmenter,-            // which has to deal with them anyway to call getPixels.-            seg.segment(bitmap)-        }+/** Size of the capped segmentation input / selection grid for a [width] x [height] source. */+internal fun segmentationInputSize(width: Int, height: Int, maxDim: Int = SEGMENTATION_MAX_DIM): Pair<Int, Int> {+    val scale = minOf(1f, maxDim.toFloat() / maxOf(width, height))+    return (width * scale).toInt().coerceAtLeast(1) to (height * scale).toInt().coerceAtLeast(1)+}++/**+ * [bitmap] downscaled to the [SEGMENTATION_MAX_DIM] cap, or [bitmap] itself when+ * it already fits. The caller owns a returned copy and must recycle it.+ */+internal fun downscaleForSegmentation(bitmap: Bitmap, maxDim: Int = SEGMENTATION_MAX_DIM): Bitmap {+    val (w, h) = segmentationInputSize(bitmap.width, bitmap.height, maxDim)+    return if (w == bitmap.width && h == bitmap.height) bitmap else Bitmap.createScaledBitmap(bitmap, w, h, true)+}++/**+ * Run [segment] over the capped input and upsample its mask to the capped grid.+ * Split from [runSegmenter] so tests can capture the bitmap handed to the segmenter.+ */+internal fun runSegmentation(bitmap: Bitmap, segment: (Bitmap) -> SegmentationMask?): Selection? {+    // Cap the input and the returned mask resolution for speed/memory; the model+    // runs at its fixed (<=320) input size and downscales whatever it is given,+    // so handing it the full-size bitmap only pays for pixel copies the model+    // then throws away (its native path materialises the whole bitmap first).+    val (w, h) = segmentationInputSize(bitmap.width, bitmap.height)+    val input = downscaleForSegmentation(bitmap)+    val result = try {+        segment(input)+    } finally {+        if (input !== bitmap) input.recycle()     } ?: return null      val sw = result.width@@ -96,3 +112,18 @@ private fun runSegmenter(context: Context, bitmap: Bitmap): Selection? {      return Selection(mask, w, h).applyFeather(FEATHER_RADIUS) }++private fun runSegmenter(context: Context, bitmap: Bitmap): Selection? {+    synchronized(segLock) {+        return SubjectSegmenter(context.applicationContext).use { seg ->+            if (!seg.isAvailable) {+                Log.error("MlSegmentation", "U²-Net unavailable; see the ModelRunner log tag")+                null+            } else {+                // HARDWARE and unknown bitmap configs are handled inside SubjectSegmenter,+                // which has to deal with them anyway to call getPixels.+                runSegmentation(bitmap) { seg.segment(it) }+            }+        }+    }+}
photos/src/test/java/com/vayunmathur/photos/platform/MlSegmentationTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/platform/MlSegmentationTest.kt b/photos/src/test/java/com/vayunmathur/photos/platform/MlSegmentationTest.ktnew file mode 100644index 0000000000..7d945f985a--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/platform/MlSegmentationTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.photos.platform++import android.graphics.Bitmap+import com.vayunmathur.library.ml.SegmentationMask+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertSame+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/**+ * The segmenter model downscales its input to <=320 anyway, so [runSegmentation]+ * must hand it the 512-capped copy it already computes for the mask grid —+ * not the full-size editor bitmap (which the native path first materialises+ * whole, ~12.6 MB x2 at editor sizes).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class MlSegmentationTest {++    @Test+    fun segmentationInputSizeCapsTheLongestSide() {+        assertEquals(512 to 256, segmentationInputSize(2048, 1024))+        assertEquals(256 to 512, segmentationInputSize(1024, 2048))+        assertEquals(512 to 512, segmentationInputSize(512, 512))+        assertEquals(320 to 200, segmentationInputSize(320, 200))+        assertEquals(1 to 1, segmentationInputSize(1, 1))+    }++    @Test+    fun segmenterReceivesTheCappedBitmapNotTheFullSizeOriginal() {+        val original = Bitmap.createBitmap(2048, 1024, Bitmap.Config.ARGB_8888)+        var handedToSegmenter: Bitmap? = null+        var handedSize: Pair<Int, Int>? = null+        val selection = runSegmentation(original) { input ->+            handedToSegmenter = input+            handedSize = input.width to input.height+            // Model-resolution mask (the real model returns <=320 on a side).+            SegmentationMask(4, 2, floatArrayOf(0f, 0f, 1f, 1f, 0f, 0f, 1f, 1f))+        }+        val capped = assertNotNull(handedToSegmenter)+        assertEquals(512 to 256, handedSize)+        assertTrue(capped !== original, "segmenter must not receive the full-size bitmap")+        // The capped copy is recycled after the (synchronous) segment call;+        // the caller's original is untouched.+        assertTrue(capped.isRecycled)+        assertTrue(!original.isRecycled)+        // The mask is still upsampled onto the capped grid, as before.+        val sel = assertNotNull(selection)+        assertEquals(512, sel.width)+        assertEquals(256, sel.height)+        original.recycle()+    }++    @Test+    fun smallBitmapsAreHandedOverUnscaled() {+        val original = Bitmap.createBitmap(320, 200, Bitmap.Config.ARGB_8888)+        var handedToSegmenter: Bitmap? = null+        val selection = runSegmentation(original) { input ->+            handedToSegmenter = input+            SegmentationMask(2, 2, floatArrayOf(0f, 1f, 0f, 1f))+        }+        assertSame(original, handedToSegmenter)+        assertTrue(!original.isRecycled, "the caller's bitmap must not be recycled")+        val sel = assertNotNull(selection)+        assertEquals(320, sel.width)+        assertEquals(200, sel.height)+        original.recycle()+    }++    @Test+    fun downscaleReturnsTheSameBitmapWhenItAlreadyFits() {+        val original = Bitmap.createBitmap(100, 50, Bitmap.Config.ARGB_8888)+        assertSame(original, downscaleForSegmentation(original))+        original.recycle()+    }+}