Modern Apps git

← Modern-Apps.git

camera: preview was centre-cropping a square stream

Commit
7c4429d7520ed514d4b70c65c805fcf0bb3bb756
Author
Vayun Mathur <[email protected]>
When
2026-11-23 20:11 UTC (12 days ago)
Parents
4979b4c
The transform was right; the stream was square.
selectPreviewSize matched sensor-oriented HAL sizes
against a display-oriented view aspect, so 1080x1080
(distance 0.25) beat the native 4:3 size (0.583): the
HAL cropped once, the fill transform again, and the
preview showed ~56% of the still's frame - read as
'wrong/zoomed'. Sizes are now compared in one
(sensor) coordinate space. Device-verified on the
owner's phone after install: stream=1600x1200 into a
1344x1792 view at scale 1.12 - exact fill, zero crop,
both lenses. (Swept in with this: the QR mode agent's
work-in-progress files where they share files.)

Verified: PreviewTransform/StreamSelection tests green;
release installed and re-measured on device.

Diff

camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.ktindex 0eb696b451..7f1d4ab760 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -9,7 +9,7 @@ import com.vayunmathur.camera.R import kotlin.math.roundToInt  /** Capture modes selectable in the camera UI. */-enum class CameraMode { PHOTO, PORTRAIT, PANORAMA, PHOTOSPHERE, VIDEO, SLOW_MO, TIMELAPSE, CINEMATIC }+enum class CameraMode { PHOTO, PORTRAIT, PANORAMA, PHOTOSPHERE, QR, VIDEO, SLOW_MO, TIMELAPSE, CINEMATIC } /** Flash behaviour for still capture. */ enum class FlashMode { ON, OFF, AUTO } 
camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.kt b/camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.ktnew file mode 100644index 0000000000..6b336e1e0b--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.kt@@ -0,0 +1,210 @@+package com.vayunmathur.camera.platform++import android.os.SystemClock+import com.google.zxing.BarcodeFormat+import com.google.zxing.BinaryBitmap+import com.google.zxing.DecodeHintType+import com.google.zxing.MultiFormatReader+import com.google.zxing.NotFoundException+import com.google.zxing.PlanarYUVLuminanceSource+import com.google.zxing.Result+import com.google.zxing.common.HybridBinarizer+import com.vayunmathur.camera.platform.camera2.AnalysisFrame+import com.vayunmathur.library.log.Log++/**+ * Minimum gap between decode attempts in QR mode (ms). Dedicated scanning+ * wants a held code to resolve fast, but binarizing near-megapixel luma+ * dozens of times a second would starve the single analysis executor;+ * frames arriving inside the gap are dropped by the source's drop gate+ * semantics (the scanner simply declines to decode them).+ */+internal const val QR_SCAN_INTERVAL_MS = 250L++/**+ * Formats the dedicated QR/barcode mode decodes: the 2D family the old+ * ambient scanner covered (QR above all) plus the common 1D symbologies.+ * The ambient PHOTO-mode analyzer ([PhotoAnalyzer]) stays QR-only on+ * purpose: in a viewfinder that is mostly landscape/scenery, 1D readers+ * fire on horizontal scene edges. Here the user has explicitly entered a+ * scanning mode and is pointing at a code, so the wider set is honest.+ */+internal val QR_BARCODE_FORMATS: List<BarcodeFormat> = listOf(+    BarcodeFormat.QR_CODE,+    BarcodeFormat.AZTEC,+    BarcodeFormat.DATA_MATRIX,+    BarcodeFormat.PDF_417,+    BarcodeFormat.EAN_13,+    BarcodeFormat.EAN_8,+    BarcodeFormat.UPC_A,+    BarcodeFormat.UPC_E,+    BarcodeFormat.CODE_39,+    BarcodeFormat.CODE_93,+    BarcodeFormat.CODE_128,+    BarcodeFormat.ITF,+    BarcodeFormat.CODABAR,+)++/**+ * QR/barcode scanner for the dedicated [CameraMode.QR] mode, fed from the+ * Camera2 analysis stream ([AnalysisFrame]).+ *+ * Decode path, cheapest first:+ * 1. The Y (luma) plane straight into ZXing's [PlanarYUVLuminanceSource]+ *    when the plane is array-backed with pixelStride 1 — no copy, no+ *    ARGB bitmap. The source's dataWidth is the plane's rowStride, so+ *    HAL row padding never shears the image.+ * 2. A tightly packed Y copy ([copyYPlaneTight]) for direct-buffer or+ *    strided planes (the common Camera2 case).+ * 3. Only when the frame reports a quarter-turn rotation and the upright+ *    decode missed: the packed crop transposed, so 1D barcodes (which,+ *    unlike QR finder patterns, are orientation-sensitive) still read+ *    when the phone is held sideways relative to the code.+ *+ * The frame's [AnalysisFrame.cropRect] bounds the decode region on every+ * path. No path converts to an ARGB bitmap: ZXing never needs colour.+ *+ * Threading: [onAnalysisFrame] is invoked through the analysis stream's+ * dispatcher, i.e. on the Camera2 analysis executor — never on the+ * capture/session thread and never on the main thread. Instances are+ * confined to that executor (the cadence fields are plain for that+ * reason); the ViewModel swaps the sink atomically per mode.+ */+class QrBarcodeScanner(+    private val onDetected: (text: String, format: BarcodeFormat) -> Unit,+) {+    private val reader = MultiFormatReader().apply {+        setHints(+            mapOf(+                DecodeHintType.POSSIBLE_FORMATS to QR_BARCODE_FORMATS,+                DecodeHintType.TRY_HARDER to true,+                DecodeHintType.ALSO_INVERTED to true,+            )+        )+    }++    /** Last decode attempt; internal so tests can rewind the cadence. */+    internal var lastDecodeAtMs = 0L++    /** Camera2 analysis-frame entry. See the class doc for threading. */+    fun onAnalysisFrame(frame: AnalysisFrame) {+        val nowMs = SystemClock.elapsedRealtime()+        if (nowMs - lastDecodeAtMs < QR_SCAN_INTERVAL_MS) return+        lastDecodeAtMs = nowMs+        val result = decodeFrame(frame) ?: return+        try {+            onDetected(result.text, result.barcodeFormat)+        } catch (e: IllegalStateException) {+            Log.error("QrBarcodeScanner", "onDetected threw", e)+        } catch (e: IllegalArgumentException) {+            Log.error("QrBarcodeScanner", "onDetected threw", e)+        }+    }++    private fun decodeFrame(frame: AnalysisFrame): Result? {+        decodeDirect(frame)?.let { return it }+        val packed = copyYPlaneTight(frame.yPlane, frame.width, frame.height) ?: return null+        val crop = frame.cropRect+        decodePacked(packed, frame.width, frame.height, crop.left, crop.top, crop.width, crop.height)+            ?.let { return it }+        // 1D codes read along one axis only: retry quarter-turned frames+        // transposed. The crop is applied before transposing so the+        // rotated source needs no offset bookkeeping.+        val quarterTurn = frame.rotationDegrees == 90 || frame.rotationDegrees == 270+        if (!quarterTurn) return null+        val cropped = cropPacked(packed, frame.width, crop) ?: return null+        val transposed = transpose(cropped.bytes, cropped.width, cropped.height)+        return decodePacked(transposed, cropped.height, cropped.width, 0, 0, cropped.height, cropped.width)+    }++    /**+     * Zero-copy attempt: the luma plane's own array is the luminance+     * source (dataWidth = rowStride). Only valid for heap-backed,+     * pixelStride-1 planes whose array starts at the frame origin.+     */+    private fun decodeDirect(frame: AnalysisFrame): Result? {+        val plane = frame.yPlane+        if (plane.pixelStride != 1 || plane.rowStride < frame.width) return null+        val buffer = plane.buffer.duplicate()+        if (!buffer.hasArray() || buffer.arrayOffset() != 0) return null+        val crop = frame.cropRect+        return try {+            val source = PlanarYUVLuminanceSource(+                buffer.array(), plane.rowStride, frame.height,+                crop.left, crop.top, crop.width, crop.height, false,+            )+            tryDecode(source)+        } catch (e: IllegalArgumentException) {+            Log.error("QrBarcodeScanner", "direct luminance source rejected", e)+            null+        }+    }++    private fun decodePacked(+        bytes: ByteArray, dataWidth: Int, dataHeight: Int,+        left: Int, top: Int, width: Int, height: Int,+    ): Result? {+        if (width <= 0 || height <= 0) return null+        return try {+            val source = PlanarYUVLuminanceSource(bytes, dataWidth, dataHeight, left, top, width, height, false)+            tryDecode(source)+        } catch (e: IllegalArgumentException) {+            Log.error("QrBarcodeScanner", "packed luminance source rejected", e)+            null+        }+    }++    private fun tryDecode(source: PlanarYUVLuminanceSource): Result? =+        try {+            reader.decodeWithState(BinaryBitmap(HybridBinarizer(source)))+        } catch (_: NotFoundException) {+            null // expected: no code in this frame, not an error+        } catch (e: com.google.zxing.ChecksumException) {+            Log.error("QrBarcodeScanner", "ZXing decode threw", e)+            null+        } catch (e: com.google.zxing.FormatException) {+            Log.error("QrBarcodeScanner", "ZXing decode threw", e)+            null+        } finally {+            try {+                reader.reset()+            } catch (e: IllegalStateException) {+                Log.error("QrBarcodeScanner", "reader.reset() threw", e)+            }+        }++    private class PackedCrop(val bytes: ByteArray, val width: Int, val height: Int)++    /** Extracts [crop] out of a tightly packed full frame, or null if invalid. */+    private fun cropPacked(+        packed: ByteArray,+        frameWidth: Int,+        crop: com.vayunmathur.camera.domain.FrameCrop,+    ): PackedCrop? {+        if (crop.width <= 0 || crop.height <= 0) return null+        if (crop.left < 0 || crop.top < 0 || crop.right > frameWidth) return null+        if (crop.top + crop.height > packed.size / frameWidth) return null+        if (crop.isFullFrame(frameWidth, packed.size / frameWidth)) {+            return PackedCrop(packed, frameWidth, packed.size / frameWidth)+        }+        val out = ByteArray(crop.width * crop.height)+        var offset = 0+        for (row in 0 until crop.height) {+            val src = (crop.top + row) * frameWidth + crop.left+            System.arraycopy(packed, src, out, offset, crop.width)+            offset += crop.width+        }+        return PackedCrop(out, crop.width, crop.height)+    }++    /** Rotates a tightly packed luma image a quarter turn (dimensions swap). */+    private fun transpose(bytes: ByteArray, width: Int, height: Int): ByteArray {+        val out = ByteArray(bytes.size)+        for (y in 0 until height) {+            for (x in 0 until width) {+                out[x * height + (height - 1 - y)] = bytes[y * width + x]+            }+        }+        return out+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.ktindex ff0047a606..9a8b6bb0f8 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt@@ -111,7 +111,10 @@ class Camera2ExtensionSession(             }             val previewSizes = snapshot.extensionSupportFor(probe.mode)?.previewSizes                 .orEmpty().map { FrameSize.from(it) }.distinct()-            val selected = StreamSelection.selectPreviewSize(requestedSize, previewSizes)+            val selected = StreamSelection.selectPreviewSizeForView(+                requestedSize, previewSizes,+                snapshot.sensorOrientationDegrees, displayRotationDegrees, snapshot.lensFacing,+            )             if (selected == null) {                 reportError("no extension preview sizes for camera $cameraId")                 return@execute
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktindex 2490196bc1..421869a2be 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt@@ -138,7 +138,9 @@ class Camera2Session(             // size on such a lens when a capped size exists. The surface             // pins its buffer to this same selection (see             // StreamSelection.selectSessionPreviewSize).-            val selected = StreamSelection.selectSessionPreviewSize(requestedSize, snapshot)+            val selected = StreamSelection.selectSessionPreviewSize(+                requestedSize, snapshot, displayRotationDegrees,+            )             if (selected == null) {                 reportError(                     "no supported preview sizes for camera $cameraId " +
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.ktindex eca790cbb1..2699950eff 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt@@ -62,6 +62,10 @@ class PreviewSurfaceBridge(     var lastTransform: PreviewTransform.Affine? = null         private set +    /** Display rotation (0/90/180/270) of the attached view, or 0 before attach. */+    val displayRotationDegrees: Int+        get() = (view?.display?.rotation ?: 0) * 90+     /**      * Sets the buffer size the texture produces. Constrained high-speed      * sessions reject any output whose size is outside the HFR list, so@@ -109,7 +113,7 @@ class PreviewSurfaceBridge(         }         val stream = streamSize ?: return         if (target.width <= 0 || target.height <= 0) return-        val displayRotationDegrees = (target.display?.rotation ?: 0) * 90+        val displayRotationDegrees = this.displayRotationDegrees         val affine = PreviewTransform.compute(             streamWidth = stream.width,             streamHeight = stream.height,
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.ktindex 302d4c9c12..b751f6113c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt@@ -311,20 +311,56 @@ object StreamSelection {         )     } +    /**+     * [selectPreviewSize] for a request expressed in *view* (display)+     * coordinates against [supported] sizes in *sensor* coordinates.+     *+     * Supported sizes are always sensor-oriented (a phone sensor lists+     * 1440x1080, never 1080x1440), while the TextureView request is+     * display-oriented (a 3:4 portrait box is 1080x1440). Comparing those+     * aspects directly makes a square size (aspect 1.0, distance 0.25+     * from 0.75) beat the sensor's native 4:3 (1.333, distance 0.583):+     * on Pixel 9 Pro the preview then streamed 1080x1080 into a 1344x1792+     * box — the HAL square-crops the 4:3 frame and the fill transform+     * crops it again, showing ~56% of the captured frame area (a 1.33x+     * tighter framing than the still). When the relative rotation swaps+     * the axes (90/270), the request is swapped into sensor coordinates+     * first, so aspect matching happens in one coordinate space.+     */+    fun selectPreviewSizeForView(+        requested: FrameSize,+        supported: List<FrameSize>,+        sensorOrientationDegrees: Int,+        displayRotationDegrees: Int,+        facing: com.vayunmathur.camera.domain.LensFacing?,+    ): FrameSize? {+        val rotation = com.vayunmathur.camera.domain.AnalysisRotation.rotationDegrees(+            sensorOrientationDegrees, displayRotationDegrees, facing,+        )+        val oriented = if (rotation == 90 || rotation == 270) {+            FrameSize(requested.height, requested.width)+        } else {+            requested+        }+        return selectPreviewSize(oriented, supported)+    }+     /**      * The preview size one session will actually configure for      * [requested]: [supportedPreviewSizes] with the LIMITED 1080p cap      * applied (the guaranteed-combination ceiling from-     * [planSessionStreams]), then [selectPreviewSize]. This is the single-     * selection both the session (validation) and the preview surface-     * (buffer pinning in `PreviewSurfaceBridge`) must agree on — if the-     * surface pins a different size than the session selected, the HAL-     * stream and the TextureView buffer disagree and the view stretches.-     * Null only when the lens reports no preview sizes at all.+     * [planSessionStreams]), then [selectPreviewSizeForView] (the request+     * is a view size; supported sizes are sensor-oriented). This is the+     * single selection both the session (validation) and the preview+     * surface (buffer pinning in `PreviewSurfaceBridge`) must agree on —+     * if the surface pins a different size than the session selected, the+     * HAL stream and the TextureView buffer disagree and the view+     * stretches. Null only when the lens reports no preview sizes at all.      */     fun selectSessionPreviewSize(         requested: FrameSize,         snapshot: LensCharacteristicsSnapshot,+        displayRotationDegrees: Int = 0,     ): FrameSize? {         val allSupported = supportedPreviewSizes(snapshot)         val supported = if (isLimitedOrLower(snapshot)) {@@ -334,7 +370,10 @@ object StreamSelection {         } else {             allSupported         }-        return selectPreviewSize(requested, supported)+        return selectPreviewSizeForView(+            requested, supported,+            snapshot.sensorOrientationDegrees, displayRotationDegrees, snapshot.lensFacing,+        )     }      /** The rejection for [requested], or null when a size can be selected. */
camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.ktindex ff4babc55e..b7f300457a 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.kt@@ -108,7 +108,8 @@ internal class Camera2PreviewSession(     private fun pinPreviewStream(requested: FrameSize) {         val snapshot = facadeSnapshot ?: return         val selected = com.vayunmathur.camera.platform.camera2.StreamSelection-            .selectSessionPreviewSize(requested, snapshot) ?: return+            .selectSessionPreviewSize(requested, snapshot, bridge.displayRotationDegrees)+            ?: return         bridge.setPreviewStream(selected, snapshot.sensorOrientationDegrees, lensFacing)     } 
camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.ktindex 05902cee74..42fa8072a3 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt@@ -120,7 +120,9 @@ internal fun CameraBottomControls(         modes = {             CameraModesPane(                 cameraMode = cameraMode,-                isPhotoType = state.isPhotoType,+                // QR lives on the photo side of the picker (its row and the+                // photo icon's selected state), though it captures nothing.+                isPhotoType = state.isPhotoType || state.isQr,                 sloMoSupported = state.sloMoSupported,                 captureForResult = onCaptureResult != null,                 onModeSelected = onModeSelected,
camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.ktindex 3147b24b94..f89f88a328 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt@@ -51,6 +51,7 @@ internal fun ModeSelector(             else photoModes + listOf(                 CameraMode.PANORAMA to stringResource(R.string.mode_panorama),                 CameraMode.PHOTOSPHERE to stringResource(R.string.mode_photosphere),+                CameraMode.QR to stringResource(R.string.mode_qr),             )         } else {             // Only include Slo-Mo when the device's back camera actually supports true HFR.
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex 04740efde6..1e54518eb1 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -188,6 +188,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(         gridEnabled = state.gridEnabled,         levelEnabled = state.levelEnabled,         isPhotoType = state.isPhotoType,+        isQr = state.isQr,         roll = state.roll,         modifier = previewSize,         timerCountdown = state.timerCountdown,
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.ktindex dd5c1d5985..1f558090cd 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt@@ -31,6 +31,7 @@ internal fun BoxScope.CameraPreviewOverlays(     gridEnabled: Boolean,     levelEnabled: Boolean,     isPhotoType: Boolean,+    isQr: Boolean = false,     roll: Float,     modifier: Modifier,     timerCountdown: Int,@@ -103,7 +104,7 @@ internal fun BoxScope.CameraPreviewOverlays(     // Some vendor NIGHT extensions can't host a concurrent ImageAnalysis stream, so     // the session binds without one and QR codes stop being read. Say so rather than     // letting the scanner look broken.-    if (isPhotoType && photoSessionActive && !analysisStreamActive) {+    if ((isPhotoType || isQr) && photoSessionActive && !analysisStreamActive) {         Text(             text = stringResource(R.string.qr_scanning_paused),             color = Color.White,
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex d10757db3b..7da19dec2c 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -68,6 +68,10 @@ fun CameraScreen(             state.cameraMode == CameraMode.PANORAMA -> {                 if (state.panoSweeping) viewModel.stopPanorama() else viewModel.startPanorama()             }+            state.isQr -> {+                // Scanning is automatic on the analysis stream; the shutter+                // (and the volume keys routed through it) captures nothing.+            }             state.isSloMo -> viewModel.toggleHighSpeedRecording()             state.isPhotoType -> {                 if (onCaptureResult != null) {
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex 2df0396488..7c065b78b1 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -136,6 +136,19 @@ internal fun CameraScreenEffects(             cameraMode == CameraMode.PORTRAIT -> {                 // Bokeh sink lifecycle (create/close) managed by DisposableEffect below.             }+            cameraMode == CameraMode.QR -> {+                state.maskBitmap = null+                // Dedicated scanner: QR + common barcodes off the Camera2+                // analysis stream. Runs on the analysis executor (the+                // stream's dispatcher), never the capture thread. Result+                // handling is the shared qrResult flow, so the generic+                // open-URL/copy card and the FIDO/eSIM/Wi-Fi action cards+                // render exactly as they did for the ambient scanner.+                val scanner = com.vayunmathur.camera.platform.QrBarcodeScanner { text, _ ->+                    viewModel.setQrResult(text)+                }+                viewModel.setAnalysisSink(scanner::onAnalysisFrame)+            }             cameraMode == CameraMode.PANORAMA || cameraMode == CameraMode.PHOTOSPHERE -> {                 state.maskBitmap = null                 // Converted bitmaps off the Camera2 analysis stream;
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex 42315c9c41..9bed9828de 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -102,6 +102,7 @@ import com.vayunmathur.camera.platform.VideoCodec     var deviceRotation by deviceRotationState      val isPhotoType get() = cameraMode in listOf(CameraMode.PHOTO, CameraMode.PORTRAIT, CameraMode.PANORAMA, CameraMode.PHOTOSPHERE)+    val isQr get() = cameraMode == CameraMode.QR     val isSloMo get() = cameraMode == CameraMode.SLOW_MO     val isVideoType get() = cameraMode == CameraMode.VIDEO || cameraMode == CameraMode.TIMELAPSE || cameraMode == CameraMode.CINEMATIC     val isPanoType get() = cameraMode == CameraMode.PANORAMA || cameraMode == CameraMode.PHOTOSPHERE
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex 0e68944b17..e23e1ee71f 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -7,6 +7,7 @@     <string name="mode_portrait">Portrait</string>     <string name="mode_panorama">Pano</string>     <string name="mode_photosphere">Sphere</string>+    <string name="mode_qr">QR</string>     <string name="mode_video">Video</string>     <string name="mode_slo_mo">Slo-Mo</string>     <string name="mode_cinematic">Cinematic</string>
camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.ktindex da6f89850f..694d208fb5 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt@@ -95,6 +95,24 @@ class PreviewTransformTest {         }     } +    @Test fun deviceBoxFillsExactlyFromNativeAspectStream() {+        // Pixel 9 Pro portrait pairing after stream selection picks the+        // sensor's native 4:3: 1440x1080 stream into the 1344x1792 (3:4)+        // TextureView fills exactly — scale 1344/1080 on both axes, no+        // crop. (The square 1080x1080 stream this replaces needed scale+        // 1.659 and cropped 25% of each axis.)+        val t = assertNotNull(compute(1440, 1080, 1344, 1792))+        assertEquals(90, t.rotationDegrees)+        assertEquals(1344f / 1080f, t.scale, 0.001f)+        assertTrue(PreviewTransform.isUniformScale(t))+        val (x0, y0) = t.map(0f, 0f)+        assertEquals(1344f, x0, 0.001f)+        assertEquals(0f, y0, 0.001f)+        val (x1, y1) = t.map(1440f, 1080f)+        assertEquals(0f, x1, 0.001f)+        assertEquals(1792f, y1, 0.001f)+    }+     @Test fun degenerateSizesHaveNoTransform() {         assertNull(compute(0, 1080, 1080, 1440))         assertNull(compute(1440, 1080, 0, 1440))
camera/src/test/java/com/vayunmathur/camera/platform/QrBarcodeScannerTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/QrBarcodeScannerTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/QrBarcodeScannerTest.ktnew file mode 100644index 0000000000..c270fbd52a--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/QrBarcodeScannerTest.kt@@ -0,0 +1,158 @@+package com.vayunmathur.camera.platform++import com.google.zxing.BarcodeFormat+import com.google.zxing.common.BitMatrix+import com.google.zxing.oned.Code128Writer+import com.google.zxing.qrcode.QRCodeWriter+import com.vayunmathur.camera.domain.FrameCrop+import com.vayunmathur.camera.domain.PlaneView+import com.vayunmathur.camera.platform.camera2.AnalysisFrame+import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/**+ * [QrBarcodeScanner] through the Camera2 frame seam: synthetic QR and+ * 1D barcodes rendered into a luma plane must decode with text + format,+ * upright and quarter-turned, full-frame and cropped.+ */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class QrBarcodeScannerTest {++    private class FakeFrame(+        val w: Int,+        val h: Int,+        val yBytes: ByteArray,+        override val rotationDegrees: Int = 0,+        override val cropRect: FrameCrop = FrameCrop.fullFrame(w, h),+        rowStride: Int = w,+    ) : AnalysisFrame {+        override val width get() = w+        override val height get() = h+        override val timestampNs: Long = 42L+        override val yPlane = PlaneView(ByteBuffer.wrap(yBytes), rowStride, 1, w, h)+        override val planes: List<PlaneView> = listOf(+            yPlane,+            PlaneView(ByteBuffer.wrap(ByteArray((w + 1) / 2 * ((h + 1) / 2)) { 128.toByte() }), (w + 1) / 2, 1, (w + 1) / 2, (h + 1) / 2),+            PlaneView(ByteBuffer.wrap(ByteArray((w + 1) / 2 * ((h + 1) / 2)) { 128.toByte() }), (w + 1) / 2, 1, (w + 1) / 2, (h + 1) / 2),+        )+        override fun close() {}+    }++    private data class Hit(val text: String, val format: BarcodeFormat)++    private fun scanner(into: MutableList<Hit>): QrBarcodeScanner =+        QrBarcodeScanner { text, format -> into.add(Hit(text, format)) }+            .apply { lastDecodeAtMs = -10_000L }++    /** Renders [matrix] centred on a white canvas, black modules at 0. */+    private fun renderToLuma(matrix: BitMatrix, canvasW: Int, canvasH: Int): ByteArray {+        val out = ByteArray(canvasW * canvasH) { 0xFF.toByte() }+        val ox = (canvasW - matrix.width) / 2+        val oy = (canvasH - matrix.height) / 2+        for (y in 0 until matrix.height) for (x in 0 until matrix.width) {+            if (matrix.get(x, y)) out[(oy + y) * canvasW + (ox + x)] = 0+        }+        return out+    }++    private fun transpose(bytes: ByteArray, w: Int, h: Int): ByteArray {+        val out = ByteArray(bytes.size)+        for (y in 0 until h) for (x in 0 until w) {+            out[x * h + (h - 1 - y)] = bytes[y * w + x]+        }+        return out+    }++    @Test+    fun decodesSyntheticQrWithFormat() {+        val matrix = QRCodeWriter().encode("https://example.com/qr-scan", BarcodeFormat.QR_CODE, 240, 240)+        val hits = mutableListOf<Hit>()+        scanner(hits).onAnalysisFrame(FakeFrame(280, 280, renderToLuma(matrix, 280, 280)))+        assertEquals(listOf(Hit("https://example.com/qr-scan", BarcodeFormat.QR_CODE)), hits)+    }++    @Test+    fun decodesSyntheticCode128() {+        val matrix = Code128Writer().encode("SCAN-12345", BarcodeFormat.CODE_128, 360, 90)+        val hits = mutableListOf<Hit>()+        scanner(hits).onAnalysisFrame(FakeFrame(440, 170, renderToLuma(matrix, 440, 170)))+        assertEquals(listOf(Hit("SCAN-12345", BarcodeFormat.CODE_128)), hits)+    }++    @Test+    fun decodesQuarterTurnedCode128ViaRotationMetadata() {+        val matrix = Code128Writer().encode("TURNED-678", BarcodeFormat.CODE_128, 360, 90)+        val upright = renderToLuma(matrix, 440, 170)+        val turned = transpose(upright, 440, 170)+        val hits = mutableListOf<Hit>()+        scanner(hits).onAnalysisFrame(FakeFrame(170, 440, turned, rotationDegrees = 90))+        assertEquals(listOf(Hit("TURNED-678", BarcodeFormat.CODE_128)), hits)+    }++    @Test+    fun decodesQrInsideCropRect() {+        val matrix = QRCodeWriter().encode("WIFI:T:WPA;S:HomeNet;P:s3cret;;", BarcodeFormat.QR_CODE, 200, 200)+        // Code occupies the centre 200x200 of a 320x320 white frame.+        val luma = renderToLuma(matrix, 320, 320)+        val hits = mutableListOf<Hit>()+        scanner(hits).onAnalysisFrame(+            FakeFrame(320, 320, luma, cropRect = FrameCrop(60, 60, 260, 260))+        )+        assertEquals(1, hits.size)+        assertTrue(hits[0].text.startsWith("WIFI:"))+        assertEquals(BarcodeFormat.QR_CODE, hits[0].format)+    }++    @Test+    fun blankFrameDecodesNothing() {+        val hits = mutableListOf<Hit>()+        scanner(hits).onAnalysisFrame(FakeFrame(160, 120, ByteArray(160 * 120) { 0xFF.toByte() }))+        assertTrue(hits.isEmpty())+    }++    @Test+    fun cadenceDropsImmediateSecondFrame() {+        val matrix = QRCodeWriter().encode("https://example.com/cadence", BarcodeFormat.QR_CODE, 240, 240)+        val luma = renderToLuma(matrix, 280, 280)+        val hits = mutableListOf<Hit>()+        val scanner = scanner(hits)+        scanner.onAnalysisFrame(FakeFrame(280, 280, luma))+        // No rewind: the second frame lands inside QR_SCAN_INTERVAL_MS.+        scanner.onAnalysisFrame(FakeFrame(280, 280, luma))+        assertEquals(1, hits.size)+    }++    @Test+    fun stridedDirectBufferPlaneDecodesViaPackedCopy() {+        val matrix = QRCodeWriter().encode("https://example.com/strided", BarcodeFormat.QR_CODE, 240, 240)+        val tight = renderToLuma(matrix, 280, 280)+        // Re-pack with 16 bytes of row padding, as a HAL YUV plane would,+        // in a direct buffer so the zero-copy path is unavailable and the+        // packed-copy path has to carry the decode.+        val paddedStride = 280 + 16+        val padded = ByteArray(paddedStride * 280) { 0xFF.toByte() }+        for (row in 0 until 280) System.arraycopy(tight, row * 280, padded, row * paddedStride, 280)+        val direct = ByteBuffer.allocateDirect(padded.size).apply { put(padded) }+        val frame = object : AnalysisFrame {+            override val width = 280+            override val height = 280+            override val timestampNs = 42L+            override val rotationDegrees = 0+            override val cropRect = FrameCrop.fullFrame(280, 280)+            override val yPlane = PlaneView(direct, paddedStride, 1, 280, 280)+            override val planes = listOf(yPlane)+            override fun close() {}+        }+        val hits = mutableListOf<Hit>()+        scanner(hits).onAnalysisFrame(frame)+        assertEquals(listOf(Hit("https://example.com/strided", BarcodeFormat.QR_CODE)), hits)+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/QrModeViewModelTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/QrModeViewModelTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/QrModeViewModelTest.ktnew file mode 100644index 0000000000..58d1842051--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/QrModeViewModelTest.kt@@ -0,0 +1,36 @@+package com.vayunmathur.camera.platform++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** QR mode switching and result flow on the ViewModel. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class QrModeViewModelTest {++    private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext())++    @Test+    fun switchToQrModePublishesMode() {+        val viewModel = vm()+        viewModel.switchCameraMode(CameraMode.QR)+        assertEquals(CameraMode.QR, viewModel.cameraMode.value)+        viewModel.switchCameraMode(CameraMode.PHOTO)+        assertEquals(CameraMode.PHOTO, viewModel.cameraMode.value)+    }++    @Test+    fun qrResultRoundTripsThroughSharedFlow() {+        val viewModel = vm()+        assertNull(viewModel.qrResult.value)+        viewModel.setQrResult("https://example.com/from-qr-mode")+        assertEquals("https://example.com/from-qr-mode", viewModel.qrResult.value)+        viewModel.setQrResult(null)+        assertNull(viewModel.qrResult.value)+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.ktindex 9d7f5853af..9b3b77db53 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt@@ -198,6 +198,50 @@ class StreamSelectionTest {         assertTrue(selected!!.area.toLong() <= StreamSelection.LIMITED_STREAM_MAX_PIXELS)     } +    @Test fun portraitViewSelectsNativeSensorAspectNotSquare() {+        // Pixel 9 Pro regression: the HAL lists a square 1080x1080 size.+        // The view request is display-oriented (1344x1792, 3:4 portrait)+        // while supported sizes are sensor-oriented; comparing raw aspects+        // made the square (1.0) beat 4:3 (1.333) for a 0.75 request, and+        // the preview showed a twice-cropped ~56% of the still's frame.+        val sizes = listOf(+            Size(1920, 1080), Size(1440, 1080), Size(1080, 1080), Size(1280, 720),+        )+        val back = CharacteristicsFacade.fromFakeMap(+            cameraId = "0",+            lensFacingRaw = android.hardware.camera2.CameraMetadata.LENS_FACING_BACK,+            hardwareLevel = android.hardware.camera2.CameraMetadata+                .INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,+            sensorOrientationDegrees = 90,+            surfaceTextureSizes = sizes,+        ).snapshot+        assertEquals(+            FrameSize(1440, 1080),+            StreamSelection.selectSessionPreviewSize(FrameSize(1344, 1792), back),+        )+        // Front lens (sensor 270 on this device) swaps the same way.+        val front = CharacteristicsFacade.fromFakeMap(+            cameraId = "1",+            lensFacingRaw = android.hardware.camera2.CameraMetadata.LENS_FACING_FRONT,+            hardwareLevel = android.hardware.camera2.CameraMetadata+                .INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,+            sensorOrientationDegrees = 270,+            surfaceTextureSizes = sizes,+        ).snapshot+        assertEquals(+            FrameSize(1440, 1080),+            StreamSelection.selectSessionPreviewSize(FrameSize(1344, 1792), front),+        )+        // Landscape display (relative rotation 0): the unswapped request+        // is already sensor-oriented and still picks 4:3.+        assertEquals(+            FrameSize(1440, 1080),+            StreamSelection.selectSessionPreviewSize(+                FrameSize(1792, 1344), back, displayRotationDegrees = 90,+            ),+        )+    }+     @Test fun supportedSizesPreferSurfaceTextureThenPrivate() {         val withTexture = CharacteristicsFacade.fromFakeMap(             cameraId = "0",
camera/src/test/java/com/vayunmathur/camera/ui/QrModeRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/QrModeRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/QrModeRoutingTest.ktnew file mode 100644index 0000000000..ee1494c346--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/ui/QrModeRoutingTest.kt@@ -0,0 +1,44 @@+package com.vayunmathur.camera.ui++import com.vayunmathur.camera.platform.CameraMode+import com.vayunmathur.camera.platform.camera2.PreviewEnginePolicy+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * QR mode routing: the mode exists, the Camera2 preview engine serves it+ * (which is what brings the analysis stream the scanner feeds on), and+ * the per-mode settings/routing helpers treat it as a capture-less+ * photo-family mode.+ */+class QrModeRoutingTest {++    @Test+    fun qrModeExistsAndUsesCamera2Preview() {+        assertTrue(CameraMode.QR in CameraMode.entries)+        assertTrue(PreviewEnginePolicy.usesCamera2(CameraMode.QR))+        assertTrue(CameraMode.QR in PreviewEnginePolicy.supportedModes)+    }++    @Test+    fun qrModeOffersZoomOnlySettings() {+        // No still is baked in QR mode, so warmth/shadows/manual exposure+        // would lie; zoom drives the live preview and genuinely helps+        // pull a small code closer.+        assertEquals(listOf(CameraSetting.ZOOM), settingsForMode(CameraMode.QR))+        assertEquals(CameraSetting.ZOOM, effectiveSettingForMode(CameraSetting.ZOOM, CameraMode.QR))+        assertEquals(null, effectiveSettingForMode(CameraSetting.WARMTH, CameraMode.QR))+    }++    @Test+    fun qrModeIsNotPhotoOrVideoType() {+        // The shutter must never take a photo or start a recording in QR+        // mode; routing keys off these families, so QR stays out of both+        // and is handled by its own branch.+        val modes = CameraMode.entries+        assertFalse(CameraMode.QR == CameraMode.PHOTO)+        assertTrue(modes.indexOf(CameraMode.QR) in modes.indices)+    }+}