translate: read camera frames straight into the OCR engine
- Commit
2c2a3785e801f628e6a2d8e0c696db75cee66c3e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 22:13 UTC (14 days ago)
- Parents
e760d88
Live camera translation copied each frame ~4 times (proxy->Bitmap, crop copy, getPixels, JNI array copy - ~20MB per pass, ~50MB/s). A plane-direct path now reads the RGBA plane in Rust (strides respected, padding never sampled) and applies the same crop/quarter-turn as exact pixel permutations into the reused pixel buffer, then the identical detector/OCR pipeline - proven equal down to the fp16 detector tensor and recognised text. Non-direct or non-RGBA frames keep the Bitmap path; the frozen frame still captures one Bitmap per pause. CameraBinding split for the file-length lint cap. Verified: cargo modelrunner 871 pass, ocr/ml/translate suites and detekt pass. A pre-existing translate lint failure in library/downloadservice is untouched by this change.
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 2f66f09978..0f93b2c33c 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -90,6 +90,39 @@ internal object MlNative { height: Int, ): String? + /**+ * Recognise every line in a camera plane read in place, in the same+ * packed form as [recognizeText], or null on failure.+ *+ * [buffer] must be a **direct** `ByteBuffer` holding an `RGBA_8888`+ * plane (`pixelStride` 4, rows `rowStride` bytes apart, [width] x+ * [height] pixels) and must stay valid — its `ImageProxy` open — for+ * the whole call, since native reads it at its direct address with no+ * copy crossing JNI. The crop (`cropLeft`/`cropTop`/`cropRight`/+ * `cropBottom`, right/bottom exclusive, in plane pixels) and the+ * quarter-turn [rotationDegrees] are applied natively, so returned+ * coordinates are in upright cropped-frame pixels, exactly as if the+ * caller had cropped and rotated a Bitmap of the plane first.+ *+ * Null covers every refusal (non-direct buffer, non-RGBA stride,+ * non-quarter-turn rotation, undersized plane, native failure):+ * callers fall back to [recognizeText] on a Bitmap rather than+ * treating any of them as "no text". An empty string is no text.+ */+ external fun recognizeTextBuffer(+ handle: Long,+ buffer: java.nio.ByteBuffer,+ width: Int,+ height: Int,+ rowStride: Int,+ pixelStride: Int,+ cropLeft: Int,+ cropTop: Int,+ cropRight: Int,+ cropBottom: Int,+ rotationDegrees: Int,+ ): String?+ /** * Bring up Supertonic 3 from its four `.maml` files, the codepoint table and one voice. * Returns 0 on failure.
library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.ktindex 538c1c74ac..0e82d6f160 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt@@ -112,6 +112,42 @@ class TextRecognizer( } } + /**+ * Recognise every line in an `RGBA_8888` camera plane, reading+ * [buffer] in place natively — no Bitmap, no `getPixels`, no pixel+ * array crossing JNI. The crop (right/bottom exclusive) and quarter-+ * turn [rotationDegrees] are applied natively; returned lines are in+ * upright cropped-frame coordinates, identical to recognising a+ * cropped-and-rotated Bitmap of the same plane.+ *+ * Returns null when this path cannot run — engine unavailable,+ * [buffer] not direct, a plane shape or rotation native refuses, or+ * the native pass failed — so the caller can fall back to [recognize]+ * with a Bitmap. An empty list (not null) means the pass ran and+ * found no text. [buffer] must stay valid for the whole call: keep+ * its `ImageProxy` open until this returns.+ */+ @Suppress("LongParameterList") // mirrors the JNI signature one-to-one+ fun recognizeBuffer(+ buffer: java.nio.ByteBuffer,+ width: Int,+ height: Int,+ rowStride: Int,+ pixelStride: Int,+ cropLeft: Int,+ cropTop: Int,+ cropRight: Int,+ cropBottom: Int,+ rotationDegrees: Int,+ ): List<RecognizedLine>? {+ if (handle == 0L || !buffer.isDirect) return null+ val packed = MlNative.recognizeTextBuffer(+ handle, buffer, width, height, rowStride, pixelStride,+ cropLeft, cropTop, cropRight, cropBottom, rotationDegrees,+ ) ?: return null+ return parse(packed)+ }+ /** Free both networks. Idempotent. */ override fun close() { val live = handle
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex d259209c93..223c3f7737 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -30,7 +30,8 @@ use std::fs::File; use std::os::fd::FromRawFd; use jni::objects::{- JByteArray, JClass, JFloatArray, JIntArray, JLongArray, JObjectArray, JShortArray, JString,+ JByteArray, JByteBuffer, JClass, JFloatArray, JIntArray, JLongArray, JObjectArray, JShortArray,+ JString, }; use jni::sys::{jfloatArray, jint, jintArray, jlong, jstring}; use jni::{Env, EnvUnowned};@@ -438,4 +439,5 @@ include!("bridge_part7.rs"); include!("bridge_part8.rs"); include!("bridge_part9.rs"); include!("bridge_part10.rs");-include!("bridge_part11.rs");\ No newline at end of file+include!("bridge_part11.rs");+include!("bridge_part12.rs");\ No newline at end of file
library/ml/src/main/rust/src/bridge_part12.rs
diff --git a/library/ml/src/main/rust/src/bridge_part12.rs b/library/ml/src/main/rust/src/bridge_part12.rsnew file mode 100644index 0000000000..b3e72334fb--- /dev/null+++ b/library/ml/src/main/rust/src/bridge_part12.rs@@ -0,0 +1,101 @@+/// Recognise every line in an RGBA camera plane read in place, and return+/// them in the same tab-separated form as `recognizeText`.+///+/// The plane arrives as a **direct** `ByteBuffer` (CameraX `ImageProxy`+/// planes are direct), so no pixel copy crosses JNI at all: this reads the+/// buffer at its native address, and [`crate::frame::rgba_to_argb_upright`]+/// does the viewport crop and quarter-turn rotation into the handle's+/// reused pixel `Vec` — the detector letterbox, rotated line crops and+/// recognition then run exactly as the Bitmap path's do, over identical+/// pixels. Coordinates in the result are in upright cropped-frame pixels.+///+/// Returns null on failure, on a `0` handle, on a non-direct buffer, and+/// on any plane this path does not convert (non-RGBA stride, non-quarter+/// rotation, undersized buffer) — every one of those is the caller's cue+/// to fall back to the Bitmap path, never a wrong answer. An empty string+/// means no text, as in `recognizeText`.+///+/// # Safety+///+/// `handle` must be `0` or a value returned by+/// [`Java_com_vayunmathur_library_ml_MlNative_createPpocr`] and not yet+/// destroyed, serialised against `destroyOcr` by the caller. The caller+/// must keep the image the buffer belongs to open for the whole call+/// (closing the `ImageProxy` first would let the camera reuse the plane).+#[no_mangle]+#[allow(clippy::too_many_arguments)]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_recognizeTextBuffer<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ handle: jlong,+ buffer: JByteBuffer<'l>,+ width: jint,+ height: jint,+ row_stride: jint,+ pixel_stride: jint,+ crop_left: jint,+ crop_top: jint,+ crop_right: jint,+ crop_bottom: jint,+ rotation_degrees: jint,+) -> jstring {+ env.with_env(|env| -> jni::errors::Result<jstring> {+ let null = std::ptr::null_mut();+ if handle == 0 || width <= 0 || height <= 0 || row_stride <= 0 || pixel_stride <= 0 {+ return Ok(null);+ }+ // SAFETY: as `recognizeText` — the caller guarantees the handle is+ // live and serialises this against `destroyOcr`.+ let state = unsafe { &mut *(handle as *mut OcrHandle) };+ let address = match env.get_direct_buffer_address(&buffer) {+ Ok(a) if !a.is_null() => a,+ _ => return Ok(null),+ };+ let capacity = match env.get_direct_buffer_capacity(&buffer) {+ Ok(c) => c,+ Err(_) => return Ok(null),+ };+ // SAFETY: the buffer is a live local reference for the whole call+ // and the caller keeps its ImageProxy open, so the address stays+ // valid while the slice is read; nothing is retained past return.+ let bytes = unsafe { std::slice::from_raw_parts(address, capacity) };+ let crop = crate::frame::Crop {+ left: crop_left,+ top: crop_top,+ right: crop_right,+ bottom: crop_bottom,+ };+ let (upright_w, upright_h) = match crate::frame::rgba_to_argb_upright(+ bytes,+ width as u32,+ height as u32,+ row_stride as u32,+ pixel_stride as u32,+ crop,+ rotation_degrees,+ &mut state.pixels,+ ) {+ Ok(size) => size,+ Err(e) => {+ log(&format!("buffer OCR frame refused: {e}"));+ return Ok(null);+ }+ };+ let lines = match read_text(state, upright_w, upright_h) {+ Ok(lines) => lines,+ Err(e) => {+ log(&format!("OCR failed: {e}"));+ return Ok(null);+ }+ };+ Ok(match env.new_string(encode(&lines)) {+ Ok(text) => text.into_raw(),+ Err(e) => {+ log(&format!("cannot return the text: {e}"));+ null+ }+ })+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}+
library/ml/src/main/rust/src/frame.rs
diff --git a/library/ml/src/main/rust/src/frame.rs b/library/ml/src/main/rust/src/frame.rsnew file mode 100644index 0000000000..f6f47ac1d5--- /dev/null+++ b/library/ml/src/main/rust/src/frame.rs@@ -0,0 +1,338 @@+//! Plane-direct camera frame to upright `ARGB_8888`, on the CPU.+//!+//! The Bitmap path this replaces was, per live camera-OCR pass:+//! `ImageProxy.toBitmap()` (RGBA plane -> Bitmap copy), `cropAndRotate`+//! (a second full Bitmap copy), a conditional `ARGB_8888` copy plus+//! `getPixels` into a Kotlin `IntArray`, a JNI `IntArray` copy into a Rust+//! `Vec<i32>`, and only then the detector letterbox. This module is the+//! first step of the replacement: it reads the RGBA plane's bytes in place+//! (stride included, padding never sampled), crops to the preview's+//! viewport rect and rotates to upright, writing the one `Vec<i32>` the+//! existing OCR pipeline (`post::ocr::Source`, `preprocess`) already+//! consumes. Crop and rotation are exact pixel permutations for the+//! quarter turns CameraX reports, which is also what+//! `Bitmap.createBitmap(..., Matrix.postRotate(90*k), filter=true)`+//! produces at pixel centres — so both paths feed byte-identical pixels,+//! and therefore identical letterboxed detector tensors, for the same+//! frame. Non-quarter-turn rotations are refused so the caller falls back+//! to the Bitmap path rather than approximating Skia's resampling.+//!+//! The crop clamp mirrors `translate`'s Kotlin `cropAndRotate` exactly:+//! left/top clamped into the frame, the crop's own width/height clamped+//! to what remains, and an empty result falling back to the whole frame.++/// A crop rectangle in source pixels, `right`/`bottom` exclusive — the+/// same convention as `android.graphics.Rect`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Crop {+ pub left: i32,+ pub top: i32,+ pub right: i32,+ pub bottom: i32,+}++/// Bytes per pixel of `RGBA_8888`, the only format this path converts.+/// CameraX also reports it as the plane's pixel stride; anything else is+/// refused so the caller falls back instead of misreading the plane.+pub const RGBA_PIXEL_STRIDE: u32 = 4;++/// The upright `(width, height)` of a `crop_w` x `crop_h` crop rotated by+/// `rotation_degrees`. Quarter turns only; anything else is an error.+pub fn upright_size(crop_w: u32, crop_h: u32, rotation_degrees: i32) -> Result<(u32, u32), String> {+ match rotation_degrees.rem_euclid(360) {+ 0 | 180 => Ok((crop_w, crop_h)),+ 90 | 270 => Ok((crop_h, crop_w)),+ other => Err(format!("rotation {other} is not a quarter turn")),+ }+}++/// Clamp `crop` exactly as the Kotlin Bitmap path does, returning+/// `(left, top, width, height)` in source pixels.+fn clamped_crop(width: u32, height: u32, crop: Crop) -> (u32, u32, u32, u32) {+ let (src_w, src_h) = (width as i64, height as i64);+ let left = (crop.left as i64).clamp(0, src_w);+ let top = (crop.top as i64).clamp(0, src_h);+ let mut w = (crop.right as i64 - crop.left as i64).clamp(0, src_w - left);+ let mut h = (crop.bottom as i64 - crop.top as i64).clamp(0, src_h - top);+ let (mut left, mut top) = (left, top);+ if w <= 0 || h <= 0 {+ left = 0;+ top = 0;+ w = src_w;+ h = src_h;+ }+ (left as u32, top as u32, w as u32, h as u32)+}++/// Convert an RGBA plane into the upright cropped `ARGB_8888` image in+/// `out` (reused, so steady-state passes allocate nothing new here), and+/// return the upright `(width, height)`.+///+/// `bytes` is the plane exactly as the direct `ByteBuffer` exposes it:+/// `height` rows of `row_stride` bytes, each pixel `pixel_stride` bytes+/// in `R, G, B, A` order. Row padding and any bytes past a pixel's alpha+/// are never read as pixels. Errors name the reason; every error is a+/// "fall back to the Bitmap path" signal, never a wrong image.+#[allow(clippy::too_many_arguments)]+pub fn rgba_to_argb_upright(+ bytes: &[u8],+ width: u32,+ height: u32,+ row_stride: u32,+ pixel_stride: u32,+ crop: Crop,+ rotation_degrees: i32,+ out: &mut Vec<i32>,+) -> Result<(u32, u32), String> {+ if width == 0 || height == 0 {+ return Err(format!("a {width}x{height} frame"));+ }+ if pixel_stride != RGBA_PIXEL_STRIDE {+ return Err(format!("pixel stride {pixel_stride}, not RGBA_8888's {RGBA_PIXEL_STRIDE}"));+ }+ let min_row = (width as u64)+ .checked_mul(pixel_stride as u64)+ .ok_or("frame dimensions overflow")?;+ if (row_stride as u64) < min_row {+ return Err(format!("row stride {row_stride} for {width} RGBA pixels"));+ }+ // The last byte actually read: final row, final pixel, alpha channel.+ let last = (height as u64 - 1)+ .checked_mul(row_stride as u64)+ .and_then(|v| v.checked_add((width as u64 - 1) * pixel_stride as u64))+ .and_then(|v| v.checked_add(3))+ .ok_or("frame dimensions overflow")?;+ if last >= bytes.len() as u64 {+ return Err(format!("{} plane bytes for a {width}x{height} frame", bytes.len()));+ }+ let (left, top, crop_w, crop_h) = clamped_crop(width, height, crop);+ let (out_w, out_h) = upright_size(crop_w, crop_h, rotation_degrees)?;+ let count = (out_w as usize)+ .checked_mul(out_h as usize)+ .ok_or("upright dimensions overflow")?;+ out.clear();+ out.resize(count, 0);+ let rotation = rotation_degrees.rem_euclid(360);+ for out_y in 0..out_h {+ for out_x in 0..out_w {+ // Inverse of the clockwise rotation, in cropped coordinates:+ // 90 CW sends source (x, y) to (crop_h-1-y, x), etc. Exact+ // permutations, so no interpolation is involved at all.+ let (crop_x, crop_y) = match rotation {+ 0 => (out_x, out_y),+ 90 => (out_y, crop_h - 1 - out_x),+ 180 => (crop_w - 1 - out_x, crop_h - 1 - out_y),+ _ => (crop_w - 1 - out_y, out_x), // 270, checked above+ };+ let src_x = left + crop_x;+ let src_y = top + crop_y;+ let offset = (src_y as usize) * (row_stride as usize)+ + (src_x as usize) * (pixel_stride as usize);+ let (r, g, b, a) = (+ bytes[offset] as u32,+ bytes[offset + 1] as u32,+ bytes[offset + 2] as u32,+ bytes[offset + 3] as u32,+ );+ out[(out_y * out_w + out_x) as usize] =+ ((a << 24) | (r << 16) | (g << 8) | b) as i32;+ }+ }+ Ok((out_w, out_h))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::preprocess::{to_letterboxed_f16, Letterbox, PPOCR_DET};++ /// A synthetic RGBA plane: pixel (x, y) is a distinct colour derived+ /// from its coordinates, padding poisoned with 0xEE.+ fn plane(w: u32, h: u32, row_pad: u32) -> Vec<u8> {+ let row_stride = w * RGBA_PIXEL_STRIDE + row_pad;+ let mut bytes = vec![0xEEu8; (row_stride * h) as usize];+ for y in 0..h {+ for x in 0..w {+ let o = (y * row_stride + x * RGBA_PIXEL_STRIDE) as usize;+ bytes[o] = (x * 37 + y * 3) as u8;+ bytes[o + 1] = (x * 5 + y * 41) as u8;+ bytes[o + 2] = (x * 11 + y * 17) as u8;+ bytes[o + 3] = 0xFF;+ }+ }+ bytes+ }++ /// The Bitmap-path reference: the same pixels as tight `ARGB_8888`+ /// `i32`s (what `Bitmap.getPixels` hands the old JNI), cropped and+ /// rotated by forward-mapping every source pixel — independent math+ /// from the inverse mapping under test.+ fn reference(bytes: &[u8], w: u32, h: u32, row_stride: u32, crop: Crop, rot: i32) -> (Vec<i32>, u32, u32) {+ let (left, top, cw, ch) = clamped_crop(w, h, crop);+ let (ow, oh) = upright_size(cw, ch, rot).expect("quarter turn");+ let mut out = vec![0i32; (ow * oh) as usize];+ for cy in 0..ch {+ for cx in 0..cw {+ let o = ((top + cy) * row_stride + (left + cx) * RGBA_PIXEL_STRIDE) as usize;+ let argb = ((bytes[o + 3] as u32) << 24+ | (bytes[o] as u32) << 16+ | (bytes[o + 1] as u32) << 8+ | bytes[o + 2] as u32) as i32;+ let (ox, oy) = match rot.rem_euclid(360) {+ 0 => (cx, cy),+ 90 => (ch - 1 - cy, cx),+ 180 => (cw - 1 - cx, ch - 1 - cy),+ _ => (cy, cw - 1 - cx),+ };+ out[(oy * ow + ox) as usize] = argb;+ }+ }+ (out, ow, oh)+ }++ fn argb_at(bytes: &[u8], w: u32, row_stride: u32, x: u32, y: u32) -> i32 {+ let _ = w;+ let o = (y * row_stride + x * RGBA_PIXEL_STRIDE) as usize;+ ((bytes[o + 3] as u32) << 24+ | (bytes[o] as u32) << 16+ | (bytes[o + 1] as u32) << 8+ | bytes[o + 2] as u32) as i32+ }++ #[test]+ fn padded_stride_padding_is_never_sampled() {+ let (w, h, pad) = (37u32, 23u32, 12u32);+ let bytes = plane(w, h, pad);+ let mut out = Vec::new();+ let size = rgba_to_argb_upright(+ &bytes, w, h, w * 4 + pad, 4, Crop { left: 0, top: 0, right: w as i32, bottom: h as i32 }, 0, &mut out,+ )+ .expect("converts");+ assert_eq!(size, (w, h));+ for y in 0..h {+ for x in 0..w {+ assert_eq!(out[(y * w + x) as usize], argb_at(&bytes, w, w * 4 + pad, x, y), "({x},{y})");+ }+ }+ }++ #[test]+ fn stride_crop_and_every_quarter_turn_match_the_bitmap_reference() {+ let (w, h, pad) = (40u32, 30u32, 8u32);+ let bytes = plane(w, h, pad);+ let row_stride = w * 4 + pad;+ for crop in [+ Crop { left: 0, top: 0, right: 40, bottom: 30 },+ Crop { left: 5, top: 4, right: 33, bottom: 21 },+ Crop { left: -10, top: -3, right: 500, bottom: 500 }, // clamped, like Kotlin+ Crop { left: 0, top: 0, right: 0, bottom: 0 }, // empty -> whole frame+ ] {+ for rot in [0, 90, 180, 270, 360, -90] {+ let (want, ww, wh) = reference(&bytes, w, h, row_stride, crop, rot);+ let mut got = Vec::new();+ let size = rgba_to_argb_upright(&bytes, w, h, row_stride, 4, crop, rot, &mut got)+ .expect("converts");+ assert_eq!(size, (ww, wh), "crop {crop:?} rot {rot}");+ assert_eq!(got, want, "crop {crop:?} rot {rot}");+ }+ }+ }++ #[test]+ fn both_paths_produce_identical_detector_tensors() {+ // Equality at the OCR input: the buffer path's upright pixels and+ // the Bitmap path's reference pixels letterbox to the exact same+ // fp16 detector tensor (values and summary stats).+ let (w, h, pad) = (64u32, 48u32, 16u32);+ let bytes = plane(w, h, pad);+ let row_stride = w * 4 + pad;+ let crop = Crop { left: 4, top: 2, right: 60, bottom: 46 };+ let (reference_pixels, rw, rh) = reference(&bytes, w, h, row_stride, crop, 90);+ let mut buffer_pixels = Vec::new();+ let (bw, bh) = rgba_to_argb_upright(&bytes, w, h, row_stride, 4, crop, 90, &mut buffer_pixels)+ .expect("converts");+ assert_eq!((bw, bh), (rw, rh));+ let fit = Letterbox::square(bw, bh, 96).expect("fits");+ let shape = fit.shape();+ let (mut a, mut b) = (vec![0u16; shape.len() as usize], vec![0u16; shape.len() as usize]);+ to_letterboxed_f16(&buffer_pixels, bw, bh, &fit, &PPOCR_DET, &mut a).expect("buffer tensor");+ to_letterboxed_f16(&reference_pixels, rw, rh, &fit, &PPOCR_DET, &mut b).expect("bitmap tensor");+ assert_eq!(a, b, "detector tensors differ");+ let stats = |t: &[u16]| (t.len(), t.iter().map(|&v| v as u64).sum::<u64>(), t.iter().min().copied(), t.iter().max().copied());+ assert_eq!(stats(&a), stats(&b));+ }++ #[test]+ fn both_paths_recognise_the_same_text_through_the_pipeline() {+ // Pipeline-level equality: the buffer path's pixels and the Bitmap+ // reference pixels, run through detection-crop-recognition with a+ // stub recogniser, yield identical lines (text and geometry).+ use crate::post::ctc::{self, Dictionary};+ use crate::post::ocr;+ let mut dict_text = String::new();+ for index in 0..ctc::DICTIONARY_ENTRIES {+ dict_text.push((b'a' + (index % 26) as u8) as char);+ dict_text.push('\n');+ }+ let dictionary = Dictionary::parse(&dict_text).expect("fixture dictionary");+ let map = 64u32;+ let mut probability = vec![0.0f32; (map * map) as usize];+ for y in 24..36 {+ for x in 8..56 {+ probability[(y * map + x) as usize] = 1.0;+ }+ }+ let fit = Letterbox::square(map, map, map).expect("1:1 letterbox");+ let steps = (ocr::REC_WIDTH / crate::nets::ppocr_rec::WIDTH_MULTIPLE) as usize;+ let recognise = |_: &[i32], _: u32, _: u32| {+ let mut logits = vec![0.0f32; ctc::LOGITS * steps];+ for (step, label) in [1usize, 2, 3].iter().enumerate() {+ logits[label * steps + step] = 20.0;+ }+ Ok(logits)+ };+ let (w, h, pad) = (64u32, 64u32, 8u32);+ let bytes = plane(w, h, pad);+ let (reference_pixels, rw, rh) =+ reference(&bytes, w, h, w * 4 + pad, Crop { left: 0, top: 0, right: 64, bottom: 64 }, 0);+ let mut buffer_pixels = Vec::new();+ let (bw, bh) = rgba_to_argb_upright(+ &bytes, w, h, w * 4 + pad, 4, Crop { left: 0, top: 0, right: 64, bottom: 64 }, 0, &mut buffer_pixels,+ )+ .expect("converts");+ let run = |pixels: &[i32], pw: u32, ph: u32| {+ ocr::lines(+ &ocr::Detection { probability: &probability, width: map, height: map, fit: &fit },+ &ocr::Source { pixels, width: pw, height: ph },+ &dictionary,+ recognise,+ )+ .expect("pipeline runs")+ };+ let (from_buffer, from_bitmap) = (run(&buffer_pixels, bw, bh), run(&reference_pixels, rw, rh));+ assert_eq!(from_buffer, from_bitmap);+ assert_eq!(from_buffer.len(), 1);+ assert_eq!(from_buffer[0].text, "abc");+ }++ #[test]+ fn unreadable_planes_are_refused_for_fallback() {+ let mut out = Vec::new();+ let crop = Crop { left: 0, top: 0, right: 4, bottom: 4 };+ assert!(rgba_to_argb_upright(&[0u8; 64], 0, 4, 16, 4, crop, 0, &mut out).is_err(), "zero width");+ assert!(rgba_to_argb_upright(&[0u8; 64], 4, 4, 16, 1, crop, 0, &mut out).is_err(), "pixel stride 1 (a Y plane is not RGBA)");+ assert!(rgba_to_argb_upright(&[0u8; 64], 4, 4, 8, 4, crop, 0, &mut out).is_err(), "row stride too small");+ assert!(rgba_to_argb_upright(&[0u8; 10], 4, 4, 16, 4, crop, 0, &mut out).is_err(), "undersized buffer");+ assert!(rgba_to_argb_upright(&[0u8; 256], 4, 4, 16, 4, crop, 45, &mut out).is_err(), "non-quarter-turn");+ }++ #[test]+ fn upright_size_swaps_only_for_quarter_turns_sideways() {+ assert_eq!(upright_size(40, 30, 0).expect("0"), (40, 30));+ assert_eq!(upright_size(40, 30, 90).expect("90"), (30, 40));+ assert_eq!(upright_size(40, 30, 180).expect("180"), (40, 30));+ assert_eq!(upright_size(40, 30, 270).expect("270"), (30, 40));+ assert_eq!(upright_size(40, 30, -90).expect("-90"), (30, 40));+ assert!(upright_size(40, 30, 45).is_err());+ }+}
library/ml/src/main/rust/src/lib.rs
diff --git a/library/ml/src/main/rust/src/lib.rs b/library/ml/src/main/rust/src/lib.rsindex fcfa5af017..f38d1cb4e0 100644--- a/library/ml/src/main/rust/src/lib.rs+++ b/library/ml/src/main/rust/src/lib.rs@@ -44,6 +44,7 @@ //! Vulkan still passes `cargo test`. On an `x86_64-pc-windows-gnu` host, `libloading` //! needs a `dlltool` on `PATH` to build; the NDK's `llvm-dlltool` works under that name. +pub mod frame; pub mod gate; pub mod knobs; pub mod logmel;
library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt
diff --git a/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt b/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.ktindex 02cdfbdd54..68edd07560 100644--- a/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt+++ b/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt@@ -95,6 +95,43 @@ class OcrEngine(private val context: Context) { linesToResult(engine.recognize(bitmap)) } }+ /**+ * Like [recognizeDetailed] but over an `RGBA_8888` camera plane read+ * in place natively: no Bitmap is materialised and no pixels cross+ * JNI as an array. The crop (right/bottom exclusive, plane pixels)+ * and quarter-turn [rotationDegrees] are applied natively, so boxes+ * are in upright cropped-frame coordinates.+ *+ * Returns null when the buffer path cannot run (engine unavailable,+ * [buffer] not direct, or native refusal/failure) so a caller holding+ * the source frame can fall back to [recognizeDetailed] on a Bitmap;+ * a non-null empty result means the pass ran and found no text.+ * [buffer] must stay valid for the whole call — keep its `ImageProxy`+ * open until this returns.+ */+ @Suppress("LongParameterList") // mirrors the native plane contract one-to-one+ suspend fun recognizeDetailedBuffer(+ buffer: java.nio.ByteBuffer,+ width: Int,+ height: Int,+ rowStride: Int,+ pixelStride: Int,+ cropLeft: Int,+ cropTop: Int,+ cropRight: Int,+ cropBottom: Int,+ rotationDegrees: Int,+ ): OcrResult? = withContext(Dispatchers.Default) {+ lock.withLock {+ if (!ensureInit()) return@withContext null+ val engine = recognizer ?: return@withContext null+ val lines = engine.recognizeBuffer(+ buffer, width, height, rowStride, pixelStride,+ cropLeft, cropTop, cropRight, cropBottom, rotationDegrees,+ ) ?: return@withContext null+ linesToResult(lines)+ }+ } /** Release the models. */ fun close() { try { recognizer?.close() } catch (_: Exception) {}
library/ocr/src/test/java/com/vayunmathur/library/ocr/OcrEngineTest.kt
diff --git a/library/ocr/src/test/java/com/vayunmathur/library/ocr/OcrEngineTest.kt b/library/ocr/src/test/java/com/vayunmathur/library/ocr/OcrEngineTest.ktindex 3167e744bb..55fa621fb0 100644--- a/library/ocr/src/test/java/com/vayunmathur/library/ocr/OcrEngineTest.kt+++ b/library/ocr/src/test/java/com/vayunmathur/library/ocr/OcrEngineTest.kt@@ -98,6 +98,23 @@ class OcrEngineTest { engine.close() } + @Test+ fun bufferRecognitionIsNullWhileInertSoCallersFallBack() = runBlocking<Unit> {+ val engine = OcrEngine(context)+ val direct = java.nio.ByteBuffer.allocateDirect(64 * 32 * 4)+ // Null (not an empty result) is the fallback signal: the engine is+ // unavailable, so a caller holding the frame may retry via Bitmap.+ kotlin.test.assertNull(+ engine.recognizeDetailedBuffer(direct, 64, 32, 64 * 4, 4, 0, 0, 64, 32, 0),+ )+ kotlin.test.assertNull(+ engine.recognizeDetailedBuffer(+ java.nio.ByteBuffer.wrap(ByteArray(64 * 32 * 4)), 64, 32, 64 * 4, 4, 0, 0, 64, 32, 0,+ ),+ )+ engine.close()+ }+ @Test fun closeIsIdempotentAndEngineStaysInertAfterClose() = runBlocking<Unit> { val engine = OcrEngine(context)
translate/src/main/java/com/vayunmathur/translate/ui/CameraBinding.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/CameraBinding.kt b/translate/src/main/java/com/vayunmathur/translate/ui/CameraBinding.ktindex e85e0af901..0a6463e36c 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/CameraBinding.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/CameraBinding.kt@@ -24,9 +24,7 @@ import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.IntSize import androidx.lifecycle.LifecycleOwner import com.vayunmathur.translate.platform.TranslateViewModel@@ -35,8 +33,6 @@ import kotlin.concurrent.atomics.AtomicLong import kotlin.concurrent.atomics.ExperimentalAtomicApi import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.delay-import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.concurrent.ExecutorService@@ -107,6 +103,9 @@ internal fun CameraBinding( } } + // One frozen-frame Bitmap capture per pause episode (see the analyser).+ val pauseFrozen = remember { AtomicBoolean(false) }+ LaunchedEffect(viewSize, boundRotation) { if (viewSize.width <= 0 || viewSize.height <= 0) return@LaunchedEffect val cameraProvider = ProcessCameraProvider.awaitInstance(context)@@ -122,21 +121,108 @@ internal fun CameraBinding( analysis.setAnalyzer(analysisExecutor) { proxy -> val now = System.currentTimeMillis()- if (pausedValue() || inFlight.load() || now - lastMs.load() < ANALYSIS_INTERVAL_MS) {+ if (pausedValue()) {+ // Frozen-frame capture keeps the Bitmap path: the paused UI+ // displays a Bitmap, so one is materialised once per pause+ // episode (not per live pass). Frames arriving while an OCR+ // pass or this capture is in flight are simply dropped.+ if (pauseFrozen.load() || inFlight.load()) {+ proxy.close()+ return@setAnalyzer+ }+ pauseFrozen.store(true)+ inFlight.store(true)+ val frozenBmp = try {+ proxy.toBitmap()+ } catch (e: Exception) {+ Log.error(TAG, "toBitmap failed", e)+ null+ }+ val frozenRotation = proxy.imageInfo.rotationDegrees+ val frozenCrop = Rect(proxy.cropRect)+ proxy.close()+ if (frozenBmp == null) {+ inFlight.store(false)+ return@setAnalyzer+ }+ scope.launch {+ try {+ frozenFrame.value = withContext(Dispatchers.Default) {+ cropAndRotate(frozenBmp, frozenCrop, frozenRotation)+ .also { if (it !== frozenBmp) frozenBmp.recycle() }+ }+ } catch (e: Exception) {+ Log.error(TAG, "Frozen frame capture failed", e)+ } finally {+ inFlight.store(false)+ }+ }+ return@setAnalyzer+ }+ pauseFrozen.store(false)+ if (inFlight.load() || now - lastMs.load() < ANALYSIS_INTERVAL_MS) { proxy.close() return@setAnalyzer } inFlight.store(true)+ val rotation = proxy.imageInfo.rotationDegrees+ // The ViewPort's share of this buffer: exactly what the preview is showing.+ // Copied because the proxy's own Rect is recycled with it.+ val crop = Rect(proxy.cropRect)+ val plane = proxy.planes.firstOrNull()+ val buffer = plane?.buffer?.takeIf {+ bufferPathEligible(it.isDirect, plane.pixelStride, rotation)+ }+ if (buffer != null) {+ // Plane-direct live pass: native reads the RGBA plane in+ // place and does the crop/rotate, so no Bitmap, getPixels+ // IntArray or JNI pixel-array copy happens at all. The+ // proxy must stay open until native has read the plane —+ // closing it here would let CameraX reuse the buffer+ // under the read — so it is closed in the finally below.+ val frameWidth = proxy.width+ val frameHeight = proxy.height+ val rowStride = plane.rowStride+ val pixelStride = plane.pixelStride+ scope.launch {+ try {+ val result = viewModel.ocr.recognizeDetailedBuffer(+ buffer, frameWidth, frameHeight, rowStride, pixelStride,+ crop.left, crop.top, crop.right, crop.bottom, rotation,+ )+ if (result == null) {+ Log.error(TAG, "Buffer OCR failed; frame dropped")+ } else {+ val size = uprightFrameSize(frameWidth, frameHeight, crop, rotation)+ frameW.value = size.width+ frameH.value = size.height+ overlays.value = result.boxes.map { box ->+ OverlayBox(box.corners.map { Offset(it.x, it.y) }, box.text)+ }+ // frozenFrame is deliberately not updated: no+ // Bitmap exists on this path. It is captured+ // once when the user pauses (above).+ }+ } catch (e: Exception) {+ Log.error(TAG, "Frame analysis failed", e)+ } finally {+ proxy.close()+ // Measure the gap from the *end* of the pass, so a slow OCR run+ // doesn't immediately trigger the next one.+ lastMs.store(System.currentTimeMillis())+ inFlight.store(false)+ }+ }+ return@setAnalyzer+ }+ // Bitmap fallback (non-direct plane, non-RGBA stride, or a+ // non-quarter-turn rotation): the frozen-frame path, unchanged. val bmp = try { proxy.toBitmap() } catch (e: Exception) { Log.error(TAG, "toBitmap failed", e) null }- val rotation = proxy.imageInfo.rotationDegrees- // The ViewPort's share of this buffer: exactly what the preview is showing.- // Copied because the proxy's own Rect is recycled with it.- val crop = Rect(proxy.cropRect) proxy.close() if (bmp == null) { inFlight.store(false)@@ -201,77 +287,3 @@ internal fun CameraBinding( } } }--/** Builds the shared ImageAnalysis use case. */-@Composable-internal fun rememberCameraAnalysis(): ImageAnalysis {- val context = LocalContext.current- return remember {- // Built once so the display-rotation listener and the dispose block can reach it.- // Target rotation is pinned to ROTATION_0 here purely so [ANALYSIS_SIZE] is read in- // sensor coords; the real rotation is applied after binding (see below).- ImageAnalysis.Builder()- .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)- .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)- .setTargetRotation(Surface.ROTATION_0)- .setResolutionSelector(- ResolutionSelector.Builder()- .setAspectRatioStrategy(AspectRatioStrategy.RATIO_4_3_FALLBACK_AUTO_STRATEGY)- .setResolutionStrategy(- ResolutionStrategy(- ANALYSIS_SIZE,- ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,- )- )- .build()- )- .build()- }-}--/** One background translator, decoupled from the OCR loop. */-@Composable-internal fun TranslationLoop(- viewModel: TranslateViewModel,- sourceLang: String,- targetLang: String,- translationAvailable: Boolean,- overlays: List<OverlayBox>,- onTranslations: (Map<String, String>) -> Unit,-) {- // NLLB takes on the order of a second per line, so translating every line of every- // frame inline (as this screen used to) meant the overlay updated once every several- // seconds, always against a frame the camera had long since moved off. Instead we- // memo per source line: repeat lines are free, and OCR keeps redrawing boxes at full- // rate. Keyed on the source too: switching it must drop the memo, or lines keep- // showing translations made from the previous source language.- // The overlay list arrives new on every OCR pass, but this loop must not- // restart for that (it would drop the memo and re-translate everything).- // rememberUpdatedState keeps the polling loop reading the latest snapshot.- val latestOverlays = rememberUpdatedState(overlays)- LaunchedEffect(sourceLang, targetLang, translationAvailable) {- onTranslations(emptyMap())- if (!translationAvailable) return@LaunchedEffect- var memo = emptyMap<String, String>()- while (isActive) {- val next = latestOverlays.value.firstOrNull { it.text !in memo }- if (next == null) {- delay(TRANSLATE_IDLE_POLL_MS)- continue- }- // Memo failures as the source text so a line that can't be translated- // isn't retried on every frame forever.- val translated = viewModel.translate(next.text) ?: next.text- memo = (memo + (next.text to translated)).let { updated ->- if (updated.size <= TRANSLATION_CACHE_MAX) {- updated- } else {- updated.entries.drop(updated.size - TRANSLATION_CACHE_MAX)- .associate { it.key to it.value }- }- }- onTranslations(memo)- }- }-}-
translate/src/main/java/com/vayunmathur/translate/ui/CameraFrameUtils.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/CameraFrameUtils.kt b/translate/src/main/java/com/vayunmathur/translate/ui/CameraFrameUtils.ktindex 9a4fe60153..370ed87f2f 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/CameraFrameUtils.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/CameraFrameUtils.kt@@ -41,18 +41,56 @@ internal data class OverlayBox( * just the region the preview is showing. May return [src] itself when there is nothing * to do, so callers must compare identities before recycling. */-internal fun cropAndRotate(src: Bitmap, crop: Rect, degrees: Int): Bitmap {- var left = crop.left.coerceIn(0, src.width)- var top = crop.top.coerceIn(0, src.height)- var width = crop.width().coerceIn(0, src.width - left)- var height = crop.height().coerceIn(0, src.height - top)+/**+ * Clamp [crop] to a `srcWidth` x `srcHeight` frame exactly as+ * [cropAndRotate] always has: left/top into the frame, the crop's own+ * size to what remains, and an empty result falling back to the whole+ * frame. Shared by the Bitmap path and [uprightFrameSize] so the buffer+ * path's native clamp (which mirrors this in Rust) and both Kotlin paths+ * cannot drift. Right/bottom are exclusive in the result, as in [Rect].+ */+internal fun clampedCrop(srcWidth: Int, srcHeight: Int, crop: Rect): Rect {+ val left = crop.left.coerceIn(0, srcWidth)+ val top = crop.top.coerceIn(0, srcHeight)+ var width = crop.width().coerceIn(0, srcWidth - left)+ var height = crop.height().coerceIn(0, srcHeight - top) // An unresolved viewport gives an empty rect; fall back to the whole frame. if (width <= 0 || height <= 0) {- left = 0- top = 0- width = src.width- height = src.height+ width = srcWidth+ height = srcHeight+ return Rect(0, 0, width, height) }+ return Rect(left, top, left + width, top + height)+}++/**+ * The size of the upright frame [cropAndRotate] would produce from a+ * `srcWidth` x `srcHeight` frame — quarter turns swap the axes, other+ * rotations keep them guarded by callers to quarter turns only. This is+ * what the plane-direct path reports as the analysed frame's size,+ * since native does the crop and rotation and no Bitmap exists to ask.+ */+internal fun uprightFrameSize(srcWidth: Int, srcHeight: Int, crop: Rect, degrees: Int): Size {+ val clamped = clampedCrop(srcWidth, srcHeight, crop)+ return when ((degrees % 360 + 360) % 360) {+ 90, 270 -> Size(clamped.height(), clamped.width())+ else -> Size(clamped.width(), clamped.height())+ }+}++/** Whether a camera plane may take the direct-buffer OCR path at all. */+internal fun bufferPathEligible(isDirect: Boolean, pixelStride: Int, rotationDegrees: Int): Boolean =+ isDirect && pixelStride == RGBA_PIXEL_STRIDE && (rotationDegrees % 360 + 360) % 90 == 0++/** Bytes per pixel (and the required pixel stride) of RGBA_8888 planes. */+internal const val RGBA_PIXEL_STRIDE = 4++internal fun cropAndRotate(src: Bitmap, crop: Rect, degrees: Int): Bitmap {+ val clamped = clampedCrop(src.width, src.height, crop)+ val left = clamped.left+ val top = clamped.top+ val width = clamped.width()+ val height = clamped.height() if (width <= 0 || height <= 0) return src val matrix = if (degrees % 360 == 0) null else Matrix().apply { postRotate(degrees.toFloat()) } val whole = left == 0 && top == 0 && width == src.width && height == src.height
translate/src/main/java/com/vayunmathur/translate/ui/CameraLoops.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/CameraLoops.kt b/translate/src/main/java/com/vayunmathur/translate/ui/CameraLoops.ktnew file mode 100644index 0000000000..f9b5f5c780--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/ui/CameraLoops.kt@@ -0,0 +1,91 @@+@file:OptIn(kotlin.concurrent.atomics.ExperimentalAtomicApi::class)++package com.vayunmathur.translate.ui++import android.view.Surface+import androidx.camera.core.ImageAnalysis+import androidx.camera.core.resolutionselector.AspectRatioStrategy+import androidx.camera.core.resolutionselector.ResolutionSelector+import androidx.camera.core.resolutionselector.ResolutionStrategy+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.translate.platform.TranslateViewModel+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive++/** Builds the shared ImageAnalysis use case. */+@Composable+internal fun rememberCameraAnalysis(): ImageAnalysis {+ val context = LocalContext.current+ return remember {+ // Built once so the display-rotation listener and the dispose block can reach it.+ // Target rotation is pinned to ROTATION_0 here purely so [ANALYSIS_SIZE] is read in+ // sensor coords; the real rotation is applied after binding (see below).+ ImageAnalysis.Builder()+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+ .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)+ .setTargetRotation(Surface.ROTATION_0)+ .setResolutionSelector(+ ResolutionSelector.Builder()+ .setAspectRatioStrategy(AspectRatioStrategy.RATIO_4_3_FALLBACK_AUTO_STRATEGY)+ .setResolutionStrategy(+ ResolutionStrategy(+ ANALYSIS_SIZE,+ ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,+ )+ )+ .build()+ )+ .build()+ }+}++/** One background translator, decoupled from the OCR loop. */+@Composable+internal fun TranslationLoop(+ viewModel: TranslateViewModel,+ sourceLang: String,+ targetLang: String,+ translationAvailable: Boolean,+ overlays: List<OverlayBox>,+ onTranslations: (Map<String, String>) -> Unit,+) {+ // NLLB takes on the order of a second per line, so translating every line of every+ // frame inline (as this screen used to) meant the overlay updated once every several+ // seconds, always against a frame the camera had long since moved off. Instead we+ // memo per source line: repeat lines are free, and OCR keeps redrawing boxes at full+ // rate. Keyed on the source too: switching it must drop the memo, or lines keep+ // showing translations made from the previous source language.+ // The overlay list arrives new on every OCR pass, but this loop must not+ // restart for that (it would drop the memo and re-translate everything).+ // rememberUpdatedState keeps the polling loop reading the latest snapshot.+ val latestOverlays = rememberUpdatedState(overlays)+ LaunchedEffect(sourceLang, targetLang, translationAvailable) {+ onTranslations(emptyMap())+ if (!translationAvailable) return@LaunchedEffect+ var memo = emptyMap<String, String>()+ while (isActive) {+ val next = latestOverlays.value.firstOrNull { it.text !in memo }+ if (next == null) {+ delay(TRANSLATE_IDLE_POLL_MS)+ continue+ }+ // Memo failures as the source text so a line that can't be translated+ // isn't retried on every frame forever.+ val translated = viewModel.translate(next.text) ?: next.text+ memo = (memo + (next.text to translated)).let { updated ->+ if (updated.size <= TRANSLATION_CACHE_MAX) {+ updated+ } else {+ updated.entries.drop(updated.size - TRANSLATION_CACHE_MAX)+ .associate { it.key to it.value }+ }+ }+ onTranslations(memo)+ }+ }+}+
translate/src/test/java/com/vayunmathur/translate/ui/CameraAndUtilsTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/ui/CameraAndUtilsTest.kt b/translate/src/test/java/com/vayunmathur/translate/ui/CameraAndUtilsTest.ktindex 905de41ff5..054b7816b9 100644--- a/translate/src/test/java/com/vayunmathur/translate/ui/CameraAndUtilsTest.kt+++ b/translate/src/test/java/com/vayunmathur/translate/ui/CameraAndUtilsTest.kt@@ -182,6 +182,34 @@ class CameraAndUtilsTest { assertSame(src, fullTurn) } + @Test+ fun `upright frame size matches crop and rotate bitmap dimensions`() {+ // The buffer path has no Bitmap to measure, so its reported frame+ // size must agree with the Bitmap path it replaces, per rotation.+ val src = bitmap(40, 30)+ for ((crop, degrees) in listOf(+ Rect(0, 0, 40, 30) to 0, Rect(0, 0, 40, 30) to 90,+ Rect(5, 5, 25, 20) to 180, Rect(0, 0, 20, 10) to 270,+ Rect(0, 0, 0, 0) to 90, Rect(-10, -10, 500, 500) to 270,+ )) {+ val viaBitmap = cropAndRotate(src, crop, degrees)+ val viaBuffer = uprightFrameSize(40, 30, crop, degrees)+ assertEquals(viaBitmap.width, viaBuffer.width, "crop=$crop rot=$degrees")+ assertEquals(viaBitmap.height, viaBuffer.height, "crop=$crop rot=$degrees")+ if (viaBitmap !== src) viaBitmap.recycle()+ }+ src.recycle()+ }++ @Test+ fun `buffer path eligibility requires direct rgba quarter turn planes`() {+ assertTrue(bufferPathEligible(isDirect = true, pixelStride = 4, rotationDegrees = 90))+ assertTrue(bufferPathEligible(isDirect = true, pixelStride = 4, rotationDegrees = -90))+ assertTrue(!bufferPathEligible(isDirect = false, pixelStride = 4, rotationDegrees = 0))+ assertTrue(!bufferPathEligible(isDirect = true, pixelStride = 1, rotationDegrees = 0))+ assertTrue(!bufferPathEligible(isDirect = true, pixelStride = 4, rotationDegrees = 45))+ }+ @Test fun `frame constants and overlay box data`() { assertEquals(1280, ANALYSIS_SIZE.width)