Modern Apps git

← Modern-Apps.git

camera: cap photo analyzer cadence to fix pinch-zoom lag (#881)

Commit
789c5771aa2de47ea040dfe4c0becb9a8763de96
Author
Vayun Mathur <[email protected]>
When
2026-11-06 04:50 UTC (1 month ago)
Parents
3ac8469
Pinch zoom lagged in photo mode (hard to settle on a zoom level) while
video mode stayed smooth, on all devices. Photo is the only mode that
binds an ImageAnalysis stream, and PhotoAnalyzer ran its two expensive
ops on every frame: a full YUV->RGB toBitmap() for the Motion-Photo ring
buffer plus a full-frame ZXing decode, back to back on a single analysis
thread under KEEP_ONLY_LATEST. That kept one core saturated and churned
~5MB bitmaps plus megabit Y-plane copies at frame rate; the resulting
CPU/GC contention stalled the UI thread mid-gesture (overshoot), while
video binds no analyzer at all.

The consumers never needed frame-rate work: the ring buffer is sized for
8 fps (MOTION_FRAMES_PER_SECOND, hard cap 24) and recycled everything
above it, and a held QR code resolves fine at a few attempts per second.
So the analyzer now samples instead of grinding: luminance stays
per-frame (cheap strided sum, and the night-mode debounce counts
frames), while motion-frame copies run at most every 125ms (~8fps) and
QR decodes at most every 400ms. Frame close semantics are unchanged
(decode path still closes in its finally; skipped ticks close inline).

Ruled out by reading code: night-preview rebind flapping needs a dark
scene to flip nightModeActive mid-pinch (steady light never rebinds),
and the per-tick zoom StateFlow/DataStore write is shared verbatim with
video mode so it cannot explain a photo-only lag. No zoom/pipeline diff
exists between v2.6.10 and v2.6.11b (CameraX pinned at 1.7.0-alpha03
since April); this is a latent photo-only bottleneck.

Verified with ./gradlew :camera:compileDevKotlin (BUILD SUCCESSFUL).
On device, check: pinch in PHOTO at default 4:3 tracks fingers without
overshoot; QR still decodes when held steady; Motion Photo still records
its clip; night auto-engage timing unchanged.

Diff

camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.ktindex 24aafbfbea..f2f4256137 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt@@ -1,6 +1,7 @@ package com.vayunmathur.camera.util  import android.graphics.Bitmap+import android.os.SystemClock import com.vayunmathur.library.log.Log import androidx.annotation.OptIn import androidx.camera.core.ExperimentalGetImage@@ -30,6 +31,21 @@ import com.google.zxing.common.HybridBinarizer 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+ * re-binarizing megapixel frames dozens of times per second.+ */+internal const val QR_DECODE_INTERVAL_MS = 400L++/**+ * Minimum gap between Motion-Photo RGB frame copies (ms). The ring buffer is+ * sized for [CameraViewModel.MOTION_FRAMES_PER_SECOND] (8 fps) and recycles+ * anything above it, so converting faster only churns bitmaps that are+ * immediately thrown away.+ */+internal const val MOTION_FRAME_INTERVAL_MS = 125L+ class PhotoAnalyzer(     private val onLuminance: (Float) -> Unit,     private val onQrDetected: (String) -> Unit,@@ -47,14 +63,39 @@ class PhotoAnalyzer(         )     } +    // Last-run timestamps for the cadence-capped ops below. analyze() runs on+    // the single analysis executor, so plain fields are sufficient.+    private var lastDecodeAtMs = 0L+    private var lastMotionAtMs = 0L+     @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)-            emitMotionFrame(imageProxy)-            decodeQr(frame, 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+            // saturate this single analysis thread (photo-only; video binds no+            // analyzer) and the allocation churn stalls the UI thread during+            // pinch zoom (#881). Luminance above keeps night detection live.+            val nowMs = SystemClock.elapsedRealtime()+            if (nowMs - lastMotionAtMs >= MOTION_FRAME_INTERVAL_MS) {+                lastMotionAtMs = nowMs+                emitMotionFrame(imageProxy)+            }+            if (nowMs - lastDecodeAtMs >= QR_DECODE_INTERVAL_MS) {+                lastDecodeAtMs = nowMs+                decodeQr(frame, imageProxy, startMs)+            } else {+                // decodeQr() closes the frame in its finally; on a skipped+                // tick close here so the pipeline never stalls.+                closeQuietly(imageProxy, "decode skipped by cadence cap")+            }         } catch (e: IllegalStateException) {             Log.error(                 "NightPreview",