camera: plane-based analysis path with native luma stats
- Commit
eb1dbe4e587ec3e12fc2a7d5c42c517ea3f41f8a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 17:37 UTC (14 days ago)
- Parents
1b933be
Phase 3 of the Camera2 migration: an ImageReader YUV_420_888 analysis source that hands consumers plane views (direct buffers + strides) with a strict drop policy (one frame in flight, drops counted, images closed on every path) instead of ImageProxy.toBitmap() copies. PhotoAnalyzer's luma and VideoMotionAnalyzer's grid now share one plane-math contract used by both CameraX and Camera2 paths (the CameraX copy survives only on QR decode ticks - ZXing needs contiguous bytes, so QR stays CameraX this phase, as do the bitmap-eating Bokeh/Pano consumers). A Rust luma-stats JNI entry computes identical stats from direct buffers (integer-sum parity proven against Kotlin in tests, poisoned-padding cases included), on-ramp for moving the math native. Gated off by policy until a Camera2 session owns the reader. Verified: targeted suites pass, cargo 152 pass.
Diff
camera/src/main/java/com/vayunmathur/camera/domain/AnalysisPlaneMath.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisPlaneMath.kt b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisPlaneMath.ktnew file mode 100644index 0000000000..ae8f24adae--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisPlaneMath.kt@@ -0,0 +1,172 @@+package com.vayunmathur.camera.domain++import java.nio.ByteBuffer++/**+ * A non-owning view of one image plane: the (usually direct) [buffer] plus the+ * strides needed to address pixels in it. No copy is made to create or read a+ * view — that is the whole point of the Camera2 analysis path: the CameraX+ * path copies plane 0 into a fresh [ByteArray] per frame, and `toBitmap()`+ * converts the whole frame, before any math runs.+ *+ * Lifetime: the view is only valid while the owning frame is open. Consumers+ * must finish reading before the frame is closed and must never retain the+ * buffer beyond that call.+ */+class PlaneView(+ val buffer: ByteBuffer,+ val rowStride: Int,+ val pixelStride: Int,+ val width: Int,+ val height: Int,+) {+ /** Byte offset of pixel ([x], [y]) inside [buffer]. */+ fun offsetOf(x: Int, y: Int): Int = y * rowStride + x * pixelStride+}++/**+ * Luma statistics over a Y plane: a strided [mean] plus a downsampled grid.+ *+ * @property mean mean of the strided luma samples (see [LumaPlaneMath]), on+ * the 0–255 scale. Computed from an integer sum, so the Kotlin and native+ * implementations agree exactly before the final division.+ * @property grid row-major downsampled luma grid, [gridWidth] samples per row.+ */+class LumaStats(+ val mean: Double,+ val grid: FloatArray,+ val gridWidth: Int,+ val gridHeight: Int,+) {+ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is LumaStats) return false+ return mean == other.mean && gridWidth == other.gridWidth &&+ gridHeight == other.gridHeight && grid.contentEquals(other.grid)+ }++ override fun hashCode(): Int {+ var result = mean.hashCode()+ result = 31 * result + grid.contentHashCode()+ result = 31 * result + gridWidth+ result = 31 * result + gridHeight+ return result+ }+}++/**+ * The one definition of the cheap Y-plane math, shared by the CameraX+ * analyzers, the Camera2 [PlaneView] consumers, the Kotlin fallback and (by+ * contract, proven by tests) the Rust native implementation.+ *+ * Mean: samples are taken every [LUMA_SAMPLE_STEP] pixels in raster order+ * (pixel index `n = y * width + x`, `n % 16 == 0`), each read through the+ * plane strides, so row padding is never mistaken for pixels.+ *+ * Grid: at most [GRID_MAX_SIDE] samples per side, taking every+ * `strideX`/`strideY`-th pixel, exactly as the video motion diff has always+ * sampled plane 0.+ */+object LumaPlaneMath {+ const val LUMA_SAMPLE_STEP: Int = 16+ const val GRID_MAX_SIDE: Int = 96++ /** Strided mean luma, or null when the plane cannot be read. */+ fun mean(+ buffer: ByteBuffer,+ rowStride: Int,+ pixelStride: Int,+ width: Int,+ height: Int,+ ): Double? = stats(buffer, rowStride, pixelStride, width, height)?.mean++ fun mean(plane: PlaneView): Double? =+ mean(plane.buffer, plane.rowStride, plane.pixelStride, plane.width, plane.height)++ /**+ * Downsampled luma grid and its width, or null when unreadable. The+ * buffer is read by absolute index, so the caller's buffer position is+ * untouched; a duplicate is not required.+ */+ fun grid(+ buffer: ByteBuffer,+ rowStride: Int,+ pixelStride: Int,+ width: Int,+ height: Int,+ ): Pair<FloatArray, Int>? {+ val stats = gridOnly(buffer, rowStride, pixelStride, width, height) ?: return null+ return stats.first to stats.second+ }++ fun grid(plane: PlaneView): Pair<FloatArray, Int>? =+ grid(plane.buffer, plane.rowStride, plane.pixelStride, plane.width, plane.height)++ /** Both statistics in one contract; the grid is computed as in [grid]. */+ fun stats(+ buffer: ByteBuffer,+ rowStride: Int,+ pixelStride: Int,+ width: Int,+ height: Int,+ ): LumaStats? {+ if (!isReadable(buffer, rowStride, pixelStride, width, height)) return null+ val (grid, gridWidth, gridHeight) =+ gridOnly(buffer, rowStride, pixelStride, width, height) ?: return null+ var sum = 0L+ var count = 0L+ var n = 0L+ val total = width.toLong() * height.toLong()+ while (n < total) {+ val x = (n % width).toInt()+ val y = (n / width).toInt()+ sum += (buffer.get(y * rowStride + x * pixelStride).toInt() and 0xFF).toLong()+ count+++ n += LUMA_SAMPLE_STEP+ }+ if (count == 0L) return null+ return LumaStats(sum.toDouble() / count.toDouble(), grid, gridWidth, gridHeight)+ }++ fun stats(plane: PlaneView): LumaStats? =+ stats(plane.buffer, plane.rowStride, plane.pixelStride, plane.width, plane.height)++ private fun gridOnly(+ buffer: ByteBuffer,+ rowStride: Int,+ pixelStride: Int,+ width: Int,+ height: Int,+ ): Triple<FloatArray, Int, Int>? {+ if (!isReadable(buffer, rowStride, pixelStride, width, height)) return null+ val strideX = maxOf(1, width / GRID_MAX_SIDE)+ val strideY = maxOf(1, height / GRID_MAX_SIDE)+ val gridWidth = (width + strideX - 1) / strideX+ val gridHeight = (height + strideY - 1) / strideY+ val grid = FloatArray(gridWidth * gridHeight)+ var out = 0+ var y = 0+ while (y < height) {+ val rowStart = y * rowStride+ var x = 0+ while (x < width) {+ grid[out++] = (buffer.get(rowStart + x * pixelStride).toInt() and 0xFF).toFloat()+ x += strideX+ }+ y += strideY+ }+ return Triple(grid, gridWidth, gridHeight)+ }++ private fun isReadable(+ buffer: ByteBuffer,+ rowStride: Int,+ pixelStride: Int,+ width: Int,+ height: Int,+ ): Boolean {+ if (width <= 0 || height <= 0 || rowStride <= 0 || pixelStride <= 0) return false+ val last = (height - 1).toLong() * rowStride + (width - 1).toLong() * pixelStride+ return last < buffer.limit()+ }+}
camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.ktnew file mode 100644index 0000000000..b41fe47f0f--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt@@ -0,0 +1,54 @@+package com.vayunmathur.camera.domain++/** Which pipeline feeds the per-frame analysis consumers for one session. */+enum class AnalysisSource { CAMERAX, CAMERA2_IMAGE_READER }++/**+ * What one session asks its analysis stream to do.+ *+ * @property camera2Enabled the policy flag for the Camera2/ImageReader path.+ * Default off ([AnalysisSourcePolicy.CAMERA2_ENABLED]): every session stays+ * on CameraX until the ImageReader path is device-verified per mode.+ * @property needsQr the session decodes QR/barcodes from the analysis stream.+ * @property needsBitmapFrame a consumer needs a converted `Bitmap` frame+ * (portrait segmentation, panorama/motion-photo frame copies).+ * @property cheapPlaneConsumersOnly every consumer of this session can run+ * from Y-plane views alone (luma sampling, Y-grid motion diff).+ */+data class AnalysisSourceInput(+ val camera2Enabled: Boolean = AnalysisSourcePolicy.CAMERA2_ENABLED,+ val needsQr: Boolean,+ val needsBitmapFrame: Boolean,+ val cheapPlaneConsumersOnly: Boolean,+)++/**+ * Per-session analysis-source selection (Camera2 migration Phase 3).+ *+ * The ImageReader path delivers plane views with no bitmap conversion, so it+ * may only serve sessions whose consumers are all cheap plane consumers:+ *+ * - QR stays on CameraX: ZXing's `PlanarYUVLuminanceSource` consumes a+ * contiguous `ByteArray`, so feeding it from a plane means copying the+ * whole Y plane per decode — the copy this phase exists to remove — and+ * the decode path's rotation/crop handling is written against `ImageProxy`.+ * - Portrait bokeh and panorama stay on CameraX: the segmenters+ * (`SelfieSegmenter.segment(Bitmap)`) and `PanoramaEngine.offerFrame(Bitmap)`+ * take converted bitmaps today; neither has a plane entry point.+ * - Motion-Photo frame copies likewise need a bitmap per frame.+ *+ * Everything else (night-hysteresis luma, video motion grid) is plane-only+ * and may move once the flag is enabled for that session.+ */+object AnalysisSourcePolicy {+ /** Master policy flag: default CameraX everywhere. */+ const val CAMERA2_ENABLED: Boolean = false++ fun select(input: AnalysisSourceInput): AnalysisSource = when {+ !input.camera2Enabled -> AnalysisSource.CAMERAX+ input.needsQr -> AnalysisSource.CAMERAX+ input.needsBitmapFrame -> AnalysisSource.CAMERAX+ !input.cheapPlaneConsumersOnly -> AnalysisSource.CAMERAX+ else -> AnalysisSource.CAMERA2_IMAGE_READER+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.ktindex d4bcf486bd..7b6c7ccdb5 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt@@ -14,6 +14,8 @@ import com.google.zxing.MultiFormatReader import com.google.zxing.NotFoundException import com.google.zxing.PlanarYUVLuminanceSource import com.google.zxing.common.HybridBinarizer+import com.vayunmathur.camera.domain.LumaPlaneMath+import com.vayunmathur.camera.domain.PlaneView /** * Combined PHOTO-stream analyzer. The ImageAnalysis use case can only host one analyzer, so this@@ -27,10 +29,6 @@ import com.google.zxing.common.HybridBinarizer * When [onMotionFrame] is supplied it also emits a copy of each frame (bitmap + timestamp + * rotation) so the ViewModel can maintain a Motion-Photo ring buffer off this same stream. */-/** Y-plane subsample stride (px) and unsigned-byte mask for luminance sampling. */-private const val LUMA_STRIDE_PX = 16-private const val CHANNEL_MASK = 0xFF- /** * Minimum gap between full ZXing decode attempts (ms). A held QR code still * resolves within a fraction of a second, while the analysis thread stops@@ -69,15 +67,35 @@ class PhotoAnalyzer( private var lastDecodeAtMs = 0L private var lastMotionAtMs = 0L + /**+ * Plane-based entry point shared by the CameraX analyzer below and the+ * Camera2 ImageReader analysis source: luma sampling only, read straight+ * from the plane buffer with no byte copy and no bitmap conversion. QR+ * and Motion-Photo copies deliberately have no plane entry point this+ * phase (see AnalysisSourcePolicy) and stay on the CameraX path.+ */+ fun onYPlane(plane: PlaneView) {+ val avg = LumaPlaneMath.mean(plane) ?: return+ try {+ onLuminance(avg.toFloat())+ } catch (e: IllegalStateException) {+ Log.error("NightPreview", "PhotoAnalyzer onLuminance callback threw (was hidden)", e)+ } catch (e: IllegalArgumentException) {+ Log.error("NightPreview", "PhotoAnalyzer onLuminance callback threw (was hidden)", e)+ }+ }+ @OptIn(ExperimentalGetImage::class) override fun analyze(imageProxy: ImageProxy) { val startMs = System.currentTimeMillis() try {- val frame = readYPlane(imageProxy) ?: return // Luminance stays per-frame: it is a cheap strided sum and the // night-mode debounce counts frames, so skipping here would- // silently retune its engage/disengage timing.- sampleLuminance(frame, imageProxy, startMs)+ // silently retune its engage/disengage timing. It now reads the+ // plane buffer in place (no ByteArray copy); only the cadence-+ // gated QR decode below still copies, because ZXing needs a+ // contiguous byte array.+ sampleLuminance(imageProxy, startMs) // The two expensive ops — the YUV->RGB conversion for the // Motion-Photo ring buffer and the full-frame ZXing decode — run // at a capped cadence instead of on every frame. Unthrottled they@@ -91,6 +109,13 @@ class PhotoAnalyzer( } if (nowMs - lastDecodeAtMs >= QR_DECODE_INTERVAL_MS) { lastDecodeAtMs = nowMs+ // ZXing needs a contiguous byte array, so this copy stays —+ // but only on a decode tick, not on every frame.+ val frame = readYPlane(imageProxy)+ if (frame == null) {+ closeQuietly(imageProxy, "Y plane unreadable")+ return+ } decodeQr(frame, imageProxy, startMs) } else { // decodeQr() closes the frame in its finally; on a skipped@@ -124,7 +149,7 @@ class PhotoAnalyzer( private fun readYPlane(imageProxy: ImageProxy): YFrame? { val plane = imageProxy.planes[0] val rowStride = plane.rowStride- val buffer = plane.buffer+ val buffer = plane.buffer.duplicate() val bytes = ByteArray(buffer.remaining()) try { buffer.get(bytes)@@ -142,43 +167,31 @@ class PhotoAnalyzer( /** Samples average luminance over a strided subsample and forwards it. */ @OptIn(ExperimentalGetImage::class)- private fun sampleLuminance(frame: YFrame, imageProxy: ImageProxy, startMs: Long) {- // Average luminance over a strided subsample of the Y plane (kept cheap).- var sum = 0L- var count = 0- var i = 0- try {- while (i < frame.bytes.size) {- sum += (frame.bytes[i].toInt() and CHANNEL_MASK)- count++- i += LUMA_STRIDE_PX- }- } catch (e: ArithmeticException) {- Log.error("NightPreview", "PhotoAnalyzer luma loop threw (hidden)", e)+ private fun sampleLuminance(imageProxy: ImageProxy, startMs: Long) {+ val plane = imageProxy.planes.firstOrNull()+ if (plane == null) {+ Log.status("NightPreview", "PhotoAnalyzer no Y plane – preview may be black?")+ return }- if (count > 0) {- val avg = sum.toFloat() / count+ val view = PlaneView(+ buffer = plane.buffer.duplicate(),+ rowStride = plane.rowStride,+ pixelStride = plane.pixelStride,+ width = imageProxy.width,+ height = imageProxy.height,+ )+ val avg = LumaPlaneMath.mean(view)+ if (avg != null) { Log.dev( "NightPreview",- "PhotoAnalyzer luma avg=$avg sum=$sum count=$count bytesSize=${frame.bytes.size} " +- "width=${imageProxy.width} height=${imageProxy.height} rowStride=${frame.rowStride} " +- "timestamp=${imageProxy.imageInfo.timestamp} " ++ "PhotoAnalyzer luma avg=$avg width=${imageProxy.width} height=${imageProxy.height} " ++ "rowStride=${plane.rowStride} timestamp=${imageProxy.imageInfo.timestamp} " + "rot=${imageProxy.imageInfo.rotationDegrees} " + "took=${System.currentTimeMillis() - startMs}ms" )- try {- onLuminance(avg)- } catch (e: IllegalStateException) {- Log.error("NightPreview", "PhotoAnalyzer onLuminance callback threw (was hidden)", e)- } catch (e: IllegalArgumentException) {- Log.error("NightPreview", "PhotoAnalyzer onLuminance callback threw (was hidden)", e)- }+ onYPlane(view) } else {- Log.status(- "NightPreview",- "PhotoAnalyzer count=0, no luma callback – preview may be black? " +- "bytesSize=${frame.bytes.size}"- )+ Log.status("NightPreview", "PhotoAnalyzer no luma samples – preview may be black?") } }
camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.ktindex 3b4604d0f5..ccfe3b5867 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt@@ -1,6 +1,10 @@ package com.vayunmathur.camera.platform +import com.vayunmathur.camera.domain.LumaPlaneMath+import com.vayunmathur.camera.domain.LumaStats+import com.vayunmathur.camera.domain.PlaneView import com.vayunmathur.library.log.NativeLoader+import java.nio.ByteBuffer /**@@ -55,4 +59,58 @@ object StitchNative { * Callers must check [isAvailable] first and fall back to JPEG on null. */ external fun encodeAvif(rgba: ByteArray, width: Int, height: Int, quality: Float, speed: Int): ByteArray?++ // --- Zero-copy luma on-ramp (Camera2 migration Phase 3) ---++ /**+ * Luma statistics from a *direct* Y-plane [buffer], read in place by+ * Rust — no bytes cross JNI. Returns+ * `[mean, gridWidth, gridHeight, grid...]`, or null for a non-direct /+ * unreadable buffer, in which case [lumaStats] falls back to the+ * identical Kotlin computation in [LumaPlaneMath]. This is the on-ramp+ * for moving the night-hysteresis / motion math native later; today+ * callers consume the same [LumaStats] either way.+ */+ external fun lumaStatsFromYPlane(+ buffer: ByteBuffer,+ width: Int,+ height: Int,+ rowStride: Int,+ pixelStride: Int,+ ): FloatArray?++ /**+ * [LumaStats] for [plane]: native when the buffer is direct and the+ * library is loaded, the Kotlin fallback otherwise. Both implement the+ * one contract in [LumaPlaneMath]; parity is proven on synthetic+ * buffers in `LumaStatsNativeTest`.+ */+ fun lumaStats(plane: PlaneView): LumaStats? {+ if (isAvailable && plane.buffer.isDirect) {+ val encoded = try {+ lumaStatsFromYPlane(+ plane.buffer, plane.width, plane.height, plane.rowStride, plane.pixelStride,+ )+ } catch (e: UnsatisfiedLinkError) {+ null+ }+ decodeLumaStats(encoded)?.let { return it }+ }+ return LumaPlaneMath.stats(plane)+ }+}++/** Decodes the `[mean, gridWidth, gridHeight, grid...]` native encoding. */+internal fun decodeLumaStats(encoded: FloatArray?): LumaStats? {+ if (encoded == null || encoded.size < 3) return null+ val gridWidth = encoded[1].toInt()+ val gridHeight = encoded[2].toInt()+ if (gridWidth <= 0 || gridHeight <= 0) return null+ if (encoded.size != 3 + gridWidth * gridHeight) return null+ return LumaStats(+ mean = encoded[0].toDouble(),+ grid = encoded.copyOfRange(3, encoded.size),+ gridWidth = gridWidth,+ gridHeight = gridHeight,+ ) }
camera/src/main/java/com/vayunmathur/camera/platform/VideoMotionAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/VideoMotionAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/platform/VideoMotionAnalyzer.ktindex 8751ad5524..23e6f7ea3c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/VideoMotionAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/VideoMotionAnalyzer.kt@@ -6,6 +6,8 @@ import androidx.camera.core.ExperimentalGetImage import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.vayunmathur.camera.domain.FrameDiffSample+import com.vayunmathur.camera.domain.LumaPlaneMath+import com.vayunmathur.camera.domain.PlaneView import com.vayunmathur.camera.domain.SceneMotionMath import com.vayunmathur.library.log.Log @@ -36,29 +38,47 @@ class VideoMotionAnalyzer( private var previousGrid: FloatArray? = null private var previousGridWidth = 0 + /**+ * Plane-based entry point shared by the CameraX analyzer below and the+ * Camera2 ImageReader analysis source: same cadence, same grid, same+ * diff — the logic is not forked per pipeline.+ */+ fun onYPlane(plane: PlaneView) {+ val nowMs = SystemClock.elapsedRealtime()+ if (nowMs - lastSampleAtMs < VIDEO_MOTION_SAMPLE_INTERVAL_MS) return+ lastSampleAtMs = nowMs+ val (grid, gridWidth) = LumaPlaneMath.grid(plane) ?: return+ val previous = previousGrid+ previousGrid = grid+ if (previous == null || previous.size != grid.size || previousGridWidth != gridWidth) {+ previousGridWidth = gridWidth+ return // first frame of a (re)bind: no diff to take yet+ }+ previousGridWidth = gridWidth+ SceneMotionMath.sample(previous, grid, gridWidth)?.let { sample ->+ try {+ onSample(sample)+ } catch (e: IllegalStateException) {+ Log.error("VideoMotion", "onSample callback threw", e)+ } catch (e: IllegalArgumentException) {+ Log.error("VideoMotion", "onSample callback threw", e)+ }+ }+ }+ @OptIn(ExperimentalGetImage::class) override fun analyze(imageProxy: ImageProxy) { try {- val nowMs = SystemClock.elapsedRealtime()- if (nowMs - lastSampleAtMs < VIDEO_MOTION_SAMPLE_INTERVAL_MS) return- lastSampleAtMs = nowMs- val (grid, gridWidth) = readLuminanceGrid(imageProxy) ?: return- val previous = previousGrid- previousGrid = grid- if (previous == null || previous.size != grid.size || previousGridWidth != gridWidth) {- previousGridWidth = gridWidth- return // first frame of a (re)bind: no diff to take yet- }- previousGridWidth = gridWidth- SceneMotionMath.sample(previous, grid, gridWidth)?.let { sample ->- try {- onSample(sample)- } catch (e: IllegalStateException) {- Log.error("VideoMotion", "onSample callback threw", e)- } catch (e: IllegalArgumentException) {- Log.error("VideoMotion", "onSample callback threw", e)- }- }+ val plane = imageProxy.planes.firstOrNull() ?: return+ onYPlane(+ PlaneView(+ buffer = plane.buffer.duplicate(),+ rowStride = plane.rowStride,+ pixelStride = plane.pixelStride,+ width = imageProxy.width,+ height = imageProxy.height,+ )+ ) } catch (e: IllegalStateException) { Log.error("VideoMotion", "VideoMotionAnalyzer analyze() threw", e) } catch (e: IllegalArgumentException) {@@ -72,18 +92,6 @@ class VideoMotionAnalyzer( } } - /**- * Downsamples plane 0 (Y) to a grid of at most [VIDEO_MOTION_GRID_MAX_SIDE]- * samples per side. Returns the grid and its width, or null when unreadable.- */- @OptIn(ExperimentalGetImage::class)- private fun readLuminanceGrid(imageProxy: ImageProxy): Pair<FloatArray, Int>? {- val plane = imageProxy.planes.firstOrNull() ?: return null- return sampleYPlaneGrid(- plane.buffer.duplicate(), plane.rowStride, plane.pixelStride,- imageProxy.width, imageProxy.height,- )- } } /**@@ -91,6 +99,10 @@ class VideoMotionAnalyzer( * per side. Shared by the CameraX [VideoMotionAnalyzer] and the Camera2 custom * path's ImageReader analysis surface, so both pipelines feed the estimator the * same signal. Returns the grid and its width, or null when unreadable.+ *+ * Delegates to [LumaPlaneMath] — the single definition of this sampling —+ * so the Camera2 [com.vayunmathur.camera.domain.PlaneView] entry point and+ * this buffer entry point can never drift apart. */ internal fun sampleYPlaneGrid( buffer: java.nio.ByteBuffer,@@ -98,25 +110,4 @@ internal fun sampleYPlaneGrid( pixelStride: Int, width: Int, height: Int,-): Pair<FloatArray, Int>? {- if (width <= 0 || height <= 0) return null- val strideX = maxOf(1, width / VIDEO_MOTION_GRID_MAX_SIDE)- val strideY = maxOf(1, height / VIDEO_MOTION_GRID_MAX_SIDE)- val gridWidth = (width + strideX - 1) / strideX- val gridHeight = (height + strideY - 1) / strideY- val grid = FloatArray(gridWidth * gridHeight)- var out = 0- var y = 0- while (y < height) {- val rowStart = y * rowStride- var x = 0- while (x < width) {- val index = rowStart + x * pixelStride- if (index >= buffer.limit()) return null- grid[out++] = (buffer.get(index).toInt() and 0xFF).toFloat()- x += strideX- }- y += strideY- }- return grid to gridWidth-}+): Pair<FloatArray, Int>? = LumaPlaneMath.grid(buffer, rowStride, pixelStride, width, height)
camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.ktnew file mode 100644index 0000000000..e70bbea02f--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt@@ -0,0 +1,203 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.media.Image+import android.media.ImageReader+import android.os.Handler+import android.view.Surface+import com.vayunmathur.camera.domain.PlaneView+import com.vayunmathur.library.log.Log+import java.util.concurrent.Executor+import java.util.concurrent.RejectedExecutionException+import java.util.concurrent.atomic.AtomicBoolean+import java.util.concurrent.atomic.AtomicLong++/**+ * One analysis frame as plane views. The buffers are borrowed: they are only+ * valid until [close], consumers must read them synchronously during the+ * delivery call and retain nothing. There is deliberately no bitmap accessor+ * on this path — no `ImageProxy.toBitmap()` equivalent exists here.+ */+interface AnalysisFrame : AutoCloseable {+ val width: Int+ val height: Int+ val timestampNs: Long++ /** Plane 0 (Y in YUV_420_888), the only plane the cheap consumers read. */+ val yPlane: PlaneView++ /** All planes, in format order. */+ val planes: List<PlaneView>+}++/** Synchronous plane consumer; see the lifetime contract on [AnalysisFrame]. */+fun interface AnalysisConsumer {+ fun onFrame(frame: AnalysisFrame)+}++/**+ * The drop policy, isolated from Android so it is unit-testable: at most one+ * frame is in flight to the consumer. A frame that arrives while the consumer+ * is busy is dropped (and counted) instead of queued — analysis consumers+ * want the latest frame, never a backlog of stale ones. This mirrors+ * `acquireLatestImage()` semantics one level up, where the count is visible.+ */+class FrameDropGate {+ private val busy = AtomicBoolean(false)+ private val dropped = AtomicLong(0)+ private val delivered = AtomicLong(0)++ val droppedFrames: Long get() = dropped.get()+ val deliveredFrames: Long get() = delivered.get()+ val isBusy: Boolean get() = busy.get()++ /** Claims the single in-flight slot; false means this frame must drop. */+ fun tryBeginDelivery(): Boolean {+ if (!busy.compareAndSet(false, true)) {+ dropped.incrementAndGet()+ return false+ }+ delivered.incrementAndGet()+ return true+ }++ fun endDelivery() {+ busy.set(false)+ }++ /** Counts a frame dropped before delivery was even attempted. */+ fun recordDrop() {+ dropped.incrementAndGet()+ }+}++/**+ * Hands frames to [consumer] on [executor] under [gate]'s drop policy. The+ * frame stays open while the consumer runs and is closed on every path —+ * an unclosed ImageReader image exhausts the reader's image pool and stalls+ * the stream, the same failure mode as an unclosed CameraX proxy.+ */+class AnalysisFrameDispatcher(+ private val consumer: AnalysisConsumer,+ private val executor: Executor,+ val gate: FrameDropGate = FrameDropGate(),+) {+ /** Returns true when the frame was accepted for delivery. */+ fun dispatch(frame: AnalysisFrame): Boolean {+ if (!gate.tryBeginDelivery()) {+ closeQuietly(frame)+ return false+ }+ return try {+ executor.execute {+ try {+ consumer.onFrame(frame)+ } catch (e: IllegalStateException) {+ Log.error("AnalysisImageSource", "consumer threw", e)+ } catch (e: IllegalArgumentException) {+ Log.error("AnalysisImageSource", "consumer threw", e)+ } finally {+ closeQuietly(frame)+ gate.endDelivery()+ }+ }+ true+ } catch (e: RejectedExecutionException) {+ gate.endDelivery()+ gate.recordDrop()+ closeQuietly(frame)+ false+ }+ }++ private fun closeQuietly(frame: AnalysisFrame) {+ try {+ frame.close()+ } catch (e: IllegalStateException) {+ Log.error("AnalysisImageSource", "frame close threw", e)+ }+ }+}++/** [AnalysisFrame] over a Camera2 [Image]; duplicates buffers so position state is private. */+private class ImageAnalysisFrame(private val image: Image) : AnalysisFrame {+ override val width: Int get() = image.width+ override val height: Int get() = image.height+ override val timestampNs: Long get() = image.timestamp++ override val planes: List<PlaneView> = image.planes.map { plane ->+ PlaneView(+ buffer = plane.buffer.duplicate(),+ rowStride = plane.rowStride,+ pixelStride = plane.pixelStride,+ width = image.width,+ height = image.height,+ )+ }++ override val yPlane: PlaneView get() = planes[0]++ override fun close() {+ image.close()+ }+}++/**+ * Camera2 migration Phase 3: an `ImageReader` (YUV_420_888) analysis source.+ *+ * The listener uses `acquireLatestImage()`: when the HAL delivers faster+ * than the consumer drains, intermediate images are discarded by the reader+ * itself, and any image that still arrives while [FrameDropGate] reports the+ * consumer busy is closed immediately and counted in [droppedFrames]. Frames+ * are never queued — a stale analysis frame has no value to luma or motion+ * consumers, and queueing would only add latency to the latest one.+ *+ * Ownership: whoever constructs this owns it and must call [close] when the+ * session ends. The reader's [surface] is the capture-session target.+ */+class AnalysisImageSource(+ width: Int,+ height: Int,+ maxImages: Int = DEFAULT_MAX_IMAGES,+ handler: Handler,+ executor: Executor,+ consumer: AnalysisConsumer,+) : AutoCloseable {++ private val reader: ImageReader =+ ImageReader.newInstance(width, height, ImageFormat.YUV_420_888, maxImages)+ private val dispatcher = AnalysisFrameDispatcher(consumer, executor)++ val surface: Surface get() = reader.surface++ /** Frames dropped because the consumer was busy (see [FrameDropGate]). */+ val droppedFrames: Long get() = dispatcher.gate.droppedFrames+ val deliveredFrames: Long get() = dispatcher.gate.deliveredFrames++ init {+ reader.setOnImageAvailableListener({ r -> onImageAvailable(r) }, handler)+ }++ private fun onImageAvailable(reader: ImageReader) {+ val image = try {+ reader.acquireLatestImage()+ } catch (e: IllegalStateException) {+ Log.error("AnalysisImageSource", "acquireLatestImage threw", e)+ null+ } ?: return+ dispatcher.dispatch(ImageAnalysisFrame(image))+ }++ override fun close() {+ try {+ reader.setOnImageAvailableListener(null, null)+ } catch (e: IllegalStateException) {+ Log.error("AnalysisImageSource", "clearing listener threw", e)+ }+ reader.close()+ }++ companion object {+ const val DEFAULT_MAX_IMAGES: Int = 3+ }+}
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex c148c5f62a..206e54f857 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -20,6 +20,7 @@ mod blend; mod stitch; mod night; mod avif;+mod luma; use imgbuf::Rgba; use std::collections::HashMap;
camera/src/main/rust/src/luma.rs
diff --git a/camera/src/main/rust/src/luma.rs b/camera/src/main/rust/src/luma.rsnew file mode 100644index 0000000000..28bf450254--- /dev/null+++ b/camera/src/main/rust/src/luma.rs@@ -0,0 +1,190 @@+//! Zero-copy Y-plane luma statistics: the native half of the contract in+//! Kotlin's `LumaPlaneMath`. The JNI entry takes a *direct* `ByteBuffer`+//! (as delivered by `Image` planes / `ImageReader`) and reads it in place —+//! no byte-array copy crosses JNI. The Kotlin fallback computes the same+//! statistics from any buffer; tests prove the two agree on synthetic+//! planes, padded strides included.+//!+//! Mean: samples every 16th pixel in raster order, summed as integers, so+//! both sides agree exactly before the final division. Grid: at most 96+//! samples per side, every `strideX`/`strideY`-th pixel.++/// Pixels between mean samples, in raster order.+pub const LUMA_SAMPLE_STEP: usize = 16;+/// Longest side of the downsampled grid.+pub const GRID_MAX_SIDE: usize = 96;++/// Statistics for one Y plane: `(mean, grid, grid_width, grid_height)`.+pub type LumaStats = (f64, Vec<f32>, usize, usize);++fn readable(len: usize, row_stride: usize, pixel_stride: usize, w: usize, h: usize) -> bool {+ if w == 0 || h == 0 || row_stride == 0 || pixel_stride == 0 {+ return false;+ }+ match (h - 1)+ .checked_mul(row_stride)+ .and_then(|v| v.checked_add((w - 1) * pixel_stride))+ {+ Some(last) => last < len,+ None => false,+ }+}++/// Computes the shared statistics over `data`, or `None` when unreadable.+pub fn luma_stats(+ data: &[u8],+ width: usize,+ height: usize,+ row_stride: usize,+ pixel_stride: usize,+) -> Option<LumaStats> {+ if !readable(data.len(), row_stride, pixel_stride, width, height) {+ return None;+ }+ let stride_x = (width / GRID_MAX_SIDE).max(1);+ let stride_y = (height / GRID_MAX_SIDE).max(1);+ let grid_width = width.div_ceil(stride_x);+ let grid_height = height.div_ceil(stride_y);+ let mut grid = vec![0f32; grid_width * grid_height];+ let mut out = 0usize;+ let mut y = 0usize;+ while y < height {+ let row_start = y * row_stride;+ let mut x = 0usize;+ while x < width {+ grid[out] = data[row_start + x * pixel_stride] as f32;+ out += 1;+ x += stride_x;+ }+ y += stride_y;+ }+ let mut sum: u64 = 0;+ let mut count: u64 = 0;+ let mut n: usize = 0;+ let total = width * height;+ while n < total {+ let x = n % width;+ let yy = n / width;+ sum += data[yy * row_stride + x * pixel_stride] as u64;+ count += 1;+ n += LUMA_SAMPLE_STEP;+ }+ if count == 0 {+ return None;+ }+ Some((sum as f64 / count as f64, grid, grid_width, grid_height))+}++#[cfg(test)]+mod luma_tests {+ use super::luma_stats;++ fn plane(w: usize, h: usize, row_stride: usize, pixel_stride: usize) -> Vec<u8> {+ // Padding bytes are poisoned with 0xEE: stats must never read them+ // as pixels, so a stride bug changes the result and fails the test.+ let mut data = vec![0xEEu8; row_stride * h];+ for y in 0..h {+ for x in 0..w {+ data[y * row_stride + x * pixel_stride] = ((x * 7 + y * 13) % 251) as u8;+ }+ }+ data+ }++ #[test]+ fn flat_plane_mean_and_grid() {+ let data = vec![100u8; 64 * 48];+ let (mean, grid, gw, gh) = luma_stats(&data, 64, 48, 64, 1).expect("stats");+ assert_eq!(mean, 100.0);+ assert_eq!((gw, gh), (64, 48));+ assert!(grid.iter().all(|v| *v == 100.0));+ }++ #[test]+ fn padded_strides_ignore_padding() {+ let data = plane(37, 23, 48, 1);+ let (mean, grid, gw, _) = luma_stats(&data, 37, 23, 48, 1).expect("stats");+ // Independent recomputation straight from pixel coordinates.+ let mut sum = 0u64;+ let mut count = 0u64;+ let mut n = 0usize;+ while n < 37 * 23 {+ sum += ((n % 37 * 7 + n / 37 * 13) % 251) as u64;+ count += 1;+ n += 16;+ }+ assert_eq!(mean, sum as f64 / count as f64);+ assert_eq!(gw, 37);+ assert_eq!(grid[0], 0.0);+ }++ #[test]+ fn rejects_unreadable_planes() {+ assert!(luma_stats(&[], 0, 0, 0, 1).is_none());+ assert!(luma_stats(&[0u8; 10], 64, 48, 64, 1).is_none());+ assert!(luma_stats(&[0u8; 64 * 48], 64, 48, 0, 1).is_none());+ }+}++/// JNI entry for `StitchNative.lumaStatsFromYPlane`: direct Y-plane buffer+/// in, `[mean, gridWidth, gridHeight, grid...]` float array out, null on any+/// failure (non-direct buffer, bad strides, undersized buffer) so Kotlin+/// falls back to its own identical computation.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_lumaStatsFromYPlane<'l>(+ mut env: jni::EnvUnowned<'l>,+ _class: jni::objects::JClass<'l>,+ buffer: jni::objects::JByteBuffer<'l>,+ width: jni::sys::jint,+ height: jni::sys::jint,+ row_stride: jni::sys::jint,+ pixel_stride: jni::sys::jint,+) -> jni::sys::jfloatArray {+ env.with_env(|env| -> jni::errors::Result<jni::sys::jfloatArray> {+ let null = std::ptr::null_mut();+ if width <= 0 || height <= 0 || row_stride <= 0 || pixel_stride <= 0 {+ return Ok(null);+ }+ let address = match env.get_direct_buffer_address(&buffer) {+ Ok(a) => a,+ Err(_) => return Ok(null),+ };+ if address.is_null() {+ return Ok(null);+ }+ let capacity = match env.get_direct_buffer_capacity(&buffer) {+ Ok(c) => c,+ Err(_) => return Ok(null),+ };+ // The buffer is a live local reference for the whole call, so the+ // address stays valid while the slice is read; nothing is retained.+ let data = unsafe { std::slice::from_raw_parts(address, capacity) };+ let stats = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ luma_stats(+ data,+ width as usize,+ height as usize,+ row_stride as usize,+ pixel_stride as usize,+ )+ }))+ .unwrap_or(None);+ let Some((mean, grid, grid_width, grid_height)) = stats else {+ return Ok(null);+ };+ let mut out = Vec::with_capacity(3 + grid.len());+ out.push(mean as f32);+ out.push(grid_width as f32);+ out.push(grid_height as f32);+ out.extend_from_slice(&grid);+ let arr = match env.new_float_array(out.len()) {+ Ok(a) => a,+ Err(_) => return Ok(null),+ };+ match arr.set_region(env, 0, &out) {+ Ok(()) => Ok(arr.into_raw()),+ Err(_) => Ok(null),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}