Modern Apps git

← Modern-Apps.git

camera: video recording now honours the framed zoom instead of recording at 1x

Commit
c798cec058918896ad720f6588f25c6d675d841f
Author
Vayun Mathur <[email protected]>
When
2026-12-01 05:27 UTC (5 days ago)
Parents
125965d
Zoom state was owned by the preview session and never
carried across the session handoff: the user frames at 3x
(zoom bar/pinch applies CONTROL_ZOOM_RATIO to the preview,
persisted), presses record — CustomRecordingConfig had no
zoom field, the viewfinder swapped to the recording engine,
and its TEMPLATE_RECORD request set only the FPS range, so
the saved MP4 was framed at the HAL default 1x, not the
framing the user shot. Mid-recording pinch wrote only the
persisted ratio (the engine owns the camera then; the
preview session reference was null) — the encoder kept the
record-press framing. Wear SET_ZOOM during recording hit
the same dead end.

The recording engine now owns zoom during a take:
CustomRecordingConfig carries zoomRatio (from
effectiveZoomRatioForMode, so panorama/photosphere still
lock 1x); the new RecordingZoomPolicy resolves it via
Camera2Controls (same clamp and centred-crop fallback as
preview), the engine applies it on the record request at
camera open and exposes setZoomRatio() re-issuing on the
camera thread; CameraControls forwards setZoomRatio/
onViewfinderZoomRatio to the live engine, covering pinch,
zoom bar and wear mid-take. Five policy tests pin carry-
through, clamping, crop fallback and plumbing. Verified:
:camera:testDevUnitTest — the only 2 failures are proven
identical on a pristine HEAD worktree (pre-existing zoom-stop
lens-sync assertions failing in the full-suite environment,
passing in isolation before and after); lint 0 errors.
CameraX was not reintroduced.

Diff

camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.ktindex d83f6fa23e..4f8b9b9501 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -16,6 +16,7 @@ import android.view.Surface import com.vayunmathur.camera.domain.LiveBitrateController import com.vayunmathur.camera.domain.SceneMotion import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership+import com.vayunmathur.camera.platform.camera2.toRect import com.vayunmathur.library.log.Log import java.io.File @@ -59,6 +60,17 @@ data class CustomRecordingConfig(      * played sideways/upside-down outside portrait back-lens use.      */     val orientationDegrees: Int = 0,+    /**+     * Zoom ratio the user framed with at the record press (the preview+     * session's ratio, persisted in the ViewModel). The engine owns a+     * different session than the preview, so without this field its+     * `TEMPLATE_RECORD` request ran at the HAL default 1x and the saved+     * video did not match the viewfinder. Resolved/clamped against the+     * lens snapshot at session configure (see RecordingZoomPolicy);+     * live changes during the take go through+     * [Camera2VideoRecordingEngine.setZoomRatio].+     */+    val zoomRatio: Float = 1f, )  /** Read-back summary of a finished file (see [Camera2VideoRecordingEngine.validateOutput]). */@@ -135,6 +147,16 @@ class Camera2VideoRecordingEngine(     private var adaptationThread: Thread? = null     private var outputFile: File? = null +    /** Lens snapshot read at camera open; zoom is resolved against it. */+    @Volatile private var lensSnapshot: com.vayunmathur.camera.platform.camera2.LensCharacteristicsSnapshot? = null++    /** Live zoom ratio for the recording request; starts at the config's record-press ratio. */+    @Volatile private var currentZoomRatio: Float = config.zoomRatio++    /** Device/session/targets of the live recording request, for live zoom re-issue. */+    private var recordingDevice: CameraDevice? = null+    private var repeatingSurfaces: List<Surface> = emptyList()+     /** Opens the camera + encoders and starts recording into [outputFile]. */     @SuppressLint("MissingPermission")     fun start(outputFile: File, cameraId: String, previewSurface: Surface?) {@@ -289,25 +311,24 @@ class Camera2VideoRecordingEngine(                                 hasPreviewSurface = effectivePreview != null,                                 hasAnalysisSurface = true,                             ).map { surfacesByRole.getValue(it) }+                    // Lens snapshot for zoom resolution: same facade the+                    // preview/start path reads, so the recording request+                    // clamps/falls back exactly as the viewfinder did.+                    lensSnapshot = com.vayunmathur.camera.platform.camera2.CharacteristicsFacade+                        .tryFromCameraManager(manager, cameraId)?.snapshot                     device.createCaptureSession(configureSurfaces, object : CameraCaptureSession.StateCallback() {                         override fun onConfigured(session: CameraCaptureSession) {                             captureSession = session+                            recordingDevice = device+                            repeatingSurfaces =+                                com.vayunmathur.camera.platform.camera2.RecordingSessionTargets+                                    .repeatingTargets(+                                        hasPreviewSurface = effectivePreview != null,+                                        hasAnalysisSurface = true,+                                    ).map { surfacesByRole.getValue(it) }                             core.markSessionStreaming()                             try {-                                val repeatingSurfaces =-                                    com.vayunmathur.camera.platform.camera2.RecordingSessionTargets-                                        .repeatingTargets(-                                            hasPreviewSurface = effectivePreview != null,-                                            hasAnalysisSurface = true,-                                        ).map { surfacesByRole.getValue(it) }-                                val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {-                                    repeatingSurfaces.forEach { addTarget(it) }-                                    set(-                                        CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,-                                        android.util.Range(config.captureFps, config.captureFps)-                                    )-                                }.build()-                                session.setRepeatingRequest(request, null, cameraHandler)+                                issueRecordingRequest()                             } catch (e: IllegalStateException) {                                 // Device closed under us (a competing                                 // session took the camera): surface as an@@ -345,6 +366,56 @@ class Camera2VideoRecordingEngine(         Log.debug("Camera2Recorder", "opening camera $cameraId facing=$facing")     } +    /**+     * Applies a live zoom change during the take (pinch / zoom bar / watch+     * SET_ZOOM, all routed through `CameraViewModel.setZoomRatio`). Before+     * the session configures this only updates the ratio the first request+     * will carry; afterwards it re-issues the repeating request on the+     * camera thread. Without this, zoom gestures during a recording updated+     * only the ViewModel flow and the encoder kept the record-press framing.+     */+    fun setZoomRatio(ratio: Float) {+        currentZoomRatio = com.vayunmathur.camera.platform.camera2.RecordingZoomPolicy+            .clampedRatio(ratio, lensSnapshot)+        val handler = cameraHandler ?: return+        handler.post {+            try {+                issueRecordingRequest()+            } catch (e: IllegalStateException) {+                onError(e)+            }+        }+    }++    /** The clamped zoom ratio the live (or next) recording request carries. */+    fun currentRecordingZoomRatio(): Float = currentZoomRatio++    /** Builds and issues the `TEMPLATE_RECORD` repeating request at the current zoom. */+    private fun issueRecordingRequest() {+        val session = captureSession ?: return+        val device = recordingDevice ?: return+        val surfaces = repeatingSurfaces+        if (surfaces.isEmpty()) return+        val zoomParams = com.vayunmathur.camera.platform.camera2.RecordingZoomPolicy+            .resolve(currentZoomRatio, lensSnapshot)+        val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {+            surfaces.forEach { addTarget(it) }+            set(+                CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,+                android.util.Range(config.captureFps, config.captureFps)+            )+            // Zoom: same resolution as the preview (CONTROL_ZOOM_RATIO+            // when honoured, centred crop region otherwise). The ratio+            // key is API 30+ and minSdk is 31, so it is set directly.+            if (zoomParams.zoomRatio != null) {+                set(CaptureRequest.CONTROL_ZOOM_RATIO, zoomParams.zoomRatio)+            } else if (zoomParams.cropRegion != null) {+                set(CaptureRequest.SCALER_CROP_REGION, zoomParams.cropRegion.toRect())+            }+        }.build()+        session.setRepeatingRequest(request, null, cameraHandler)+    }+     /** Every 2 s: ask the controller, apply via encoder parameters when it moves. */     private fun startAdaptationThread() {         adaptationThread = Thread({@@ -375,6 +446,9 @@ class Camera2VideoRecordingEngine(         // TextureView (via its bridge), never released here.         analysisReader = null         previousGrid = null+        recordingDevice = null+        captureSession = null+        repeatingSurfaces = emptyList()         core.release()         try { cameraThread?.quitSafely() } catch (_: Exception) {}     }
camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.ktindex 230ae4438c..9685e49758 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt@@ -31,6 +31,10 @@ fun CameraViewModel.onViewfinderZoomRatio(ratio: Float) {         return     }     zoomRatioMutable.value = ratio+    // While a recording owns the camera the preview session is gone, so+    // the ratio must also reach the recording engine or the gesture only+    // updates the stored/displayed value.+    camera2RecordingState.engine?.setZoomRatio(ratio)     viewModelScope.launch { ds.setString("camera_zoom_ratio", ratio.toString()) }     syncSelectedLensToZoomStop(ratio) }@@ -55,6 +59,12 @@ fun CameraViewModel.setZoomRatio(ratio: Float) {     zoomRatioMutable.value = clamped     viewModelScope.launch { ds.setString("camera_zoom_ratio", clamped.toString()) }     session?.setZoomRatio(clamped)+    // While recording, the preview session above is torn down and the+    // recording engine owns the camera: forward the change there (it+    // clamps against its own lens snapshot), otherwise a pinch/zoom-bar+    // change mid-take silently left the encoder at the record-press+    // framing while the UI showed the new ratio.+    camera2RecordingState.engine?.setZoomRatio(clamped)     // A committed zoom landing on a lens stop commits that lens too     // (selectedLens + startup persistence + night reset); between stops     // the selection is left alone. See syncSelectedLensToZoomStop.
camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.ktindex 6f8727153b..eaccd19ae2 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -199,6 +199,11 @@ internal fun CameraViewModel.startRecording() {         orientationDegrees = snapshot0?.let {             captureRotationDegrees(it.sensorOrientationDegrees, it.lensFacing)         } ?: 0,+        // Framing decided at record start: the zoom the user framed the+        // preview with. The engine owns a different session than the+        // preview (torn down above), so this is the only way the saved+        // video keeps that framing instead of snapping back to 1x.+        zoomRatio = effectiveZoomRatioForMode(recordingMode, zoomRatioMutable.value),     )     val controller = com.vayunmathur.camera.domain.LiveBitrateController(decision)     val engine = Camera2VideoRecordingEngine(
camera/src/main/java/com/vayunmathur/camera/platform/camera2/RecordingZoomPolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RecordingZoomPolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RecordingZoomPolicy.ktnew file mode 100644index 0000000000..c219a52462--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RecordingZoomPolicy.kt@@ -0,0 +1,49 @@+package com.vayunmathur.camera.platform.camera2++/**+ * Zoom resolution for the Camera2 recording engine's `TEMPLATE_RECORD`+ * request.+ *+ * The preview session resolves zoom through [Camera2Controls] (the+ * `CONTROL_ZOOM_RATIO` key when the HAL honours it, a centred+ * `SCALER_CROP_REGION` otherwise, clamped to the lens range). The recording+ * engine owns a *different* CameraDevice/session once recording starts —+ * the preview session is torn down at the record press — so it must resolve+ * the same user ratio through the same rules or the recorded framing+ * silently snaps back to 1x while the viewfinder (and the zoom bar) still+ * show the zoomed framing. This is the recording half of that contract:+ * pure, so the clamp/fallback rules are unit-tested without a HAL.+ */+object RecordingZoomPolicy {++    /**+     * Resolves [requestedRatio] against [snapshot] exactly as the preview+     * does, returning only the zoom fields of the resolved params. A null+     * snapshot (characteristics unreadable) keeps the request on the+     * zoom-ratio key at the unclamped-but-sane ratio: still better than+     * dropping the user's framing to 1x, and the HAL clamps what it cannot+     * honour.+     */+    fun resolve(requestedRatio: Float, snapshot: LensCharacteristicsSnapshot?): ResolvedRequestParams {+        val sane = if (requestedRatio.isFinite() && requestedRatio > 0f) requestedRatio else 1f+        if (snapshot == null) {+            return ResolvedRequestParams(+                zoomRatio = sane,+                cropRegion = null,+                flashMode = android.hardware.camera2.CameraMetadata.FLASH_MODE_OFF,+                aeExposureCompensationSteps = 0,+                afRegions = emptyList(),+                aeRegions = emptyList(),+                meteringActive = false,+            )+        }+        return Camera2Controls.resolve(Camera2ControlState(zoomRatio = sane), snapshot)+    }++    /** The clamped ratio a recording at [requestedRatio] will actually use. */+    fun clampedRatio(requestedRatio: Float, snapshot: LensCharacteristicsSnapshot?): Float {+        val sane = if (requestedRatio.isFinite() && requestedRatio > 0f) requestedRatio else 1f+        if (snapshot == null) return sane+        return sane.coerceIn(snapshot.minZoomRatio, snapshot.maxZoomRatio)+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/RecordingZoomPolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RecordingZoomPolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RecordingZoomPolicyTest.ktnew file mode 100644index 0000000000..b29487874d--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RecordingZoomPolicyTest.kt@@ -0,0 +1,85 @@+package com.vayunmathur.camera.platform.camera2++import android.util.Range+import com.vayunmathur.camera.platform.CustomRecordingConfig+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Regression contract for "video zoom silently snaps back to 1x at the+ * record press": the preview session is torn down when recording starts+ * and the recording engine owns a different session, so its+ * `TEMPLATE_RECORD` request must carry the user's ratio resolved through+ * the same rules as the preview (zoom-ratio key when honoured, centred+ * crop region otherwise, clamped to the lens range). Before the fix the+ * config carried no zoom at all and the engine set only the FPS range.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class RecordingZoomPolicyTest {++    private fun snapshot(+        zoomRatioRange: Range<Float>? = Range(1f, 10f),+        supportsZoomRatioKey: Boolean = true,+    ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+        cameraId = "0",+        zoomRatioRange = zoomRatioRange,+        supportsZoomRatioKey = supportsZoomRatioKey,+        activeArrayWidth = 4000,+        activeArrayHeight = 3000,+    ).snapshot++    @Test+    fun framedZoomCarriesToRecordingRequest() {+        // Exact bug inputs: VIDEO preview framed at 3x, then record.+        val params = RecordingZoomPolicy.resolve(3f, snapshot())+        assertEquals(3f, params.zoomRatio)+        assertNull(params.cropRegion)+        assertEquals(3f, RecordingZoomPolicy.clampedRatio(3f, snapshot()))+    }++    @Test+    fun recordingZoomClampsToLensRange() {+        assertEquals(10f, RecordingZoomPolicy.resolve(99f, snapshot()).zoomRatio)+        assertEquals(1f, RecordingZoomPolicy.resolve(0.1f, snapshot()).zoomRatio)+        assertEquals(10f, RecordingZoomPolicy.clampedRatio(99f, snapshot()))+        // Sub-1x (ultra-wide) framing is honoured when the lens offers it.+        val wide = snapshot(zoomRatioRange = Range(0.5f, 10f))+        assertEquals(0.5f, RecordingZoomPolicy.resolve(0.5f, wide).zoomRatio)+    }++    @Test+    fun cropRegionFallbackWhenZoomRatioKeyUnsupported() {+        val params = RecordingZoomPolicy.resolve(+            2f,+            snapshot(zoomRatioRange = Range(1f, 8f), supportsZoomRatioKey = false),+        )+        assertNull(params.zoomRatio)+        assertEquals(SensorRect(1000, 750, 3000, 2250), params.cropRegion)+    }++    @Test+    fun unreadableSnapshotKeepsRequestedFraming() {+        // No snapshot: never silently drop to 1x.+        assertEquals(2.5f, RecordingZoomPolicy.resolve(2.5f, null).zoomRatio)+        assertEquals(2.5f, RecordingZoomPolicy.clampedRatio(2.5f, null))+        // Degenerate requests fall back to 1x.+        assertEquals(1f, RecordingZoomPolicy.resolve(0f, null).zoomRatio)+        assertEquals(1f, RecordingZoomPolicy.resolve(Float.NaN, snapshot()).zoomRatio)+    }++    @Test+    fun recordingConfigCarriesRecordPressZoom() {+        // The plumbing the engine request is built from: default is the+        // honest 1x, an explicit record-press ratio is carried verbatim.+        assertEquals(1f, CustomRecordingConfig(width = 1920, height = 1080).zoomRatio)+        assertEquals(+            3f,+            CustomRecordingConfig(width = 1920, height = 1080, zoomRatio = 3f).zoomRatio,+        )+    }+}