Modern Apps git

← Modern-Apps.git

camera: stop double-rotating the viewfinder on phone rotation

Commit
f2038879b64167b30524370e70adcd40645a38cd
Author
Vayun Mathur <[email protected]>
When
2026-12-05 15:07 UTC (18 hours ago)
Parents
e2c0b09
Owner report (2026-12-05): when the phone rotates, the viewfinder rotated again, ending up in the wrong orientation.

Root cause: CameraPreviewSurface applied a Compose graphicsLayer rotationZ (plus a cover scale) fed from the physical device quadrant via CameraPreviewBox previewRotation = animatedRotation and DeviceRotation.previewRotationForOrientation. The Camera2 TextureView stream already carries the single preview rotation: PreviewTransform.computeTextureAffine derives the displayed size from CaptureRotation's sensor-vs-window relative rotation and deliberately applies rotation 0 in view space, because the SurfaceTexture transform already turned the frame. The view-layer turn was a second application of the same holding on top of that, double-rotating every preview engine (regular, night, slo-mo and recording previews all share CameraPreviewSurface).

Fix: remove the graphicsLayer rotation and its cover scale from CameraPreviewSurface, remove the previewRotation argument from CameraPreviewBox, and delete the now-dead previewRotationForOrientation and previewCoverScale helpers. Single-source rule now: preview applied rotation in view space is always 0; the stream texture transform is the only preview rotation. Chrome glyphs (ZoomBar numbers, config-row icons) still rotate with the device, and capture/output rotation is untouched: CaptureRotation still decides EXIF orientation, muxer hints and analysis rotation exactly as before, so saved photos and videos do not regress.

Tests: added PreviewTransformTest.previewAppliedRotationIsZeroForEveryDisplayAndSensor pinning display R x sensor S x facing to applied rotation 0 while the geometry form still reports CaptureRotation.rotationDegrees(S, R, facing), and rewrote the OrientationLayoutGuardTest preview cases to the same rule at the physical-angle level. Verified with ./gradlew :camera:lint :camera:lintVitalRelease :camera:testDevUnitTest (all green; ktlintCheck failures are pre-existing across untouched camera test files).

Diff

camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex 7748ea06f0..a8c9039f07 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -62,7 +62,7 @@ for a direct open-on-phone broadcast. - Listing screenshots are preview-rendered (`:camera:metadata`): Layoutlib can't open a camera, so `src/screenshotTest` draws the deterministic `FakeCameraPreview` scene behind the real top bar/grid/shutter/mode controls. `Route.Settings` is captured from the stateless `CameraSettingsContent` slice in `ui/SettingsPage.kt` with literal fixtures. The `screenshotFakePreview` parameter on `CameraScreen`/`CameraPreviewSurface` is the same seam in `main` — production-default null, never passed by `MainActivity`, so no fake frame can appear on device - Volume keys act as the shutter, gated on the camera route being foreground; Esc/space covers desktop keyboards - `.maml` model assets ship uncompressed (`noCompress`) — never compress them-- Capture rotation is one decision in `domain/CaptureRotation.kt` (sensor orientation from characteristics + physical display rotation + facing), consumed by stills (`StillCapturePlanner`), analysis frames, and video/slo-mo/Motion-Photo muxer hints. The activity is portrait-locked, so the window display rotation is always 0 and must never orient captures: the physical quadrant comes from the `OrientationEventListener` (fed to sessions via `CameraViewModel.setCaptureDisplayRotationDegrees`); preview sizing/metering keep the window rotation. The live preview's *display* rotates in its view layer with that same physical quadrant (`ui/DeviceRotation.previewRotationForOrientation` + `previewCoverScale`, applied in `CameraPreviewSurface`), as do the ZoomBar numbers and the config-row icons — glyph/display rotation only, never a second capture rotation. Metadata convention: JPEG/JPEG_R keep sensor pixels + EXIF orientation (flip-carrying for mirrored raw front pixels), AVIF bakes rotation/mirror into pixels with EXIF Normal and no `irot`, MP4 carries only the muxer orientation hint, night/pano RGB outputs bake pixels upright. No DNG writer is wired (`DngMetadata` only assembles requirements)+- Capture rotation is one decision in `domain/CaptureRotation.kt` (sensor orientation from characteristics + physical display rotation + facing), consumed by stills (`StillCapturePlanner`), analysis frames, and video/slo-mo/Motion-Photo muxer hints. The activity is portrait-locked, so the window display rotation is always 0 and must never orient captures: the physical quadrant comes from the `OrientationEventListener` (fed to sessions via `CameraViewModel.setCaptureDisplayRotationDegrees`); preview sizing/metering keep the window rotation. The live preview adds no rotation in its view layer: its stream texture transform (`domain/PreviewTransform.computeTextureAffine`) is the single preview rotation, so `ui/CameraPreviewSurface` never rotates the surface with the physical quadrant. Only the ZoomBar numbers and the config-row icons rotate with that quadrant — glyph rotation only, never a second capture or preview rotation. Metadata convention: JPEG/JPEG_R keep sensor pixels + EXIF orientation (flip-carrying for mirrored raw front pixels), AVIF bakes rotation/mirror into pixels with EXIF Normal and no `irot`, MP4 carries only the muxer orientation hint, night/pano RGB outputs bake pixels upright. No DNG writer is wired (`DngMetadata` only assembles requirements)  ## Key files ### Root — entry + navigation
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 e248927cd6..ef19e02d9e 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -176,16 +176,15 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(                 )             ) +    // The viewfinder surface itself is never rotated in the view layer:+    // its stream transform is the single preview rotation. The animated+    // rotation below only turns the chrome glyphs stacked over it, and+    // CaptureRotation still decides EXIF/muxer output on its own.     CameraPreviewSurface(         state = state,         viewModel = viewModel,         previewModifier = previewModifier,         screenshotFakePreview = screenshotFakePreview,-        // Display-only preview rotation (physical orientation, same-        // animated icon-rotation value the chrome uses): the live image-        // turns with the device while the session/capture rotation is-        // untouched (CaptureRotation still decides EXIF/muxer output).-        previewRotation = animatedRotation,     )      CaptureFlashOverlay(viewModel.shutterFeedback, previewSize.clip(RoundedCornerShape(12.dp)))
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.ktindex 87cacd2b50..7e1ef8b55a 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -8,7 +8,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import com.vayunmathur.camera.R@@ -46,25 +45,17 @@ internal fun CameraPreviewSurface(     viewModel: CameraViewModel,     previewModifier: Modifier,     screenshotFakePreview: (@Composable (Modifier) -> Unit)? = null,-    // Display-only rotation of the live image (clockwise degrees, the-    // animated physical-orientation value the chrome icons use). The-    // session and its CaptureRotation decision are untouched, so stills/-    // video never get this rotation double-applied.-    previewRotation: Float = 0f, ) {-    // Rotate the rendered preview in place, scaled to keep covering its-    // box at quarter turns. Applied only to the surface below, never to-    // the gesture layer or overlays the caller stacks over it.-    val rotatedModifier = previewModifier.then(-        Modifier.graphicsLayer {-            rotationZ = previewRotation-            val cover = previewCoverScale(previewRotation, size.width, size.height)-            scaleX *= cover-            scaleY *= cover-        }-    )+    // No view-layer rotation: the preview stream's own texture transform+    // (PreviewTransform.computeTextureAffine, rotation 0 in view space)+    // is the single preview rotation, derived once from sensor vs window+    // display rotation. Rotating this surface again with the physical+    // device quadrant double-rotates the viewfinder — the phone's+    // holding already changed what the sensor sees, and the stream+    // already accounts for the window. Only the chrome glyphs rotate+    // with the device; captures keep their CaptureRotation decision.     if (screenshotFakePreview != null) {-        screenshotFakePreview(rotatedModifier)+        screenshotFakePreview(previewModifier)         return     }     val useCamera2Preview = state.useCamera2Preview@@ -78,7 +69,7 @@ internal fun CameraPreviewSurface(     ) {         // The recording engine owns the camera; the recording preview's         // own TextureView surface is the engine's preview target.-        Camera2RecordingPreview(viewModel = viewModel, modifier = rotatedModifier)+        Camera2RecordingPreview(viewModel = viewModel, modifier = previewModifier)         return     } @@ -97,10 +88,10 @@ internal fun CameraPreviewSurface(                     viewModel.registerCamera2SloMoControl(control)                 },                 onError = { viewModel.onCamera2SloMoFailed(sloMoCamera2Id) },-                modifier = rotatedModifier,+                modifier = previewModifier,             )         } else {-            Box(modifier = rotatedModifier.background(Color.Black))+            Box(modifier = previewModifier.background(Color.Black))         }     } @@ -118,10 +109,10 @@ internal fun CameraPreviewSurface(                     viewModel.registerCamera2ExtensionSession(session)                 },                 onError = { viewModel.onCamera2NightPreviewFailed(nightCamera2Id) },-                modifier = rotatedModifier,+                modifier = previewModifier,             )         } else {-            Box(modifier = rotatedModifier.background(Color.Black))+            Box(modifier = previewModifier.background(Color.Black))         }     }     if (useCamera2Preview && !useCamera2NightPreview && !useCamera2SloMoPreview) {@@ -154,17 +145,17 @@ internal fun CameraPreviewSurface(                 analysisConsumer = viewModel.camera2AnalysisConsumer(),                 onError = { viewModel.onCamera2PreviewFailed(camera2Id) },                 onBindRequested = { viewModel.noteCamera2BindRequested() },-                modifier = rotatedModifier,+                modifier = previewModifier,             )         } else {-            Box(modifier = rotatedModifier.background(Color.Black))+            Box(modifier = previewModifier.background(Color.Black))         }     }     if (!useCamera2Preview && !useCamera2NightPreview && !useCamera2SloMoPreview) {         if (state.sessionBindFailed) {             // Bind exhausted its retries: a visible, retryable error instead             // of parking on a black preview until the next mode/lens change.-            Box(modifier = rotatedModifier.background(Color.Black), contentAlignment = Alignment.Center) {+            Box(modifier = previewModifier.background(Color.Black), contentAlignment = Alignment.Center) {                 ErrorState(                     title = stringResource(R.string.camera_bind_failed_title),                     message = stringResource(R.string.camera_bind_failed_message),@@ -175,7 +166,7 @@ internal fun CameraPreviewSurface(         } else {             // Brief gap between a mode's teardown and the next session's first frame.             // Show a plain black fill (no debug text) so the switch reads as instant.-            Box(modifier = rotatedModifier.background(Color.Black))+            Box(modifier = previewModifier.background(Color.Black))         }     } }
camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt b/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.ktindex 662efd8db2..d43fca2379 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt@@ -10,7 +10,11 @@ package com.vayunmathur.camera.ui  * `OrientationEventListener` onto the quadrant the on-screen icons must rotate  * to (via `Modifier.rotate`). Capture output rotation derives from the same  * physical quadrant via `domain.CaptureRotation` (the locked window's- * display rotation is always 0 and cannot describe the holding).+ * display rotation is always 0 and cannot describe the holding). The live+ * preview adds no view-layer rotation at any holding: its stream texture+ * transform (`PreviewTransform.computeTextureAffine`) already carries the+ * one sensor-vs-window rotation, so a second turn with the physical+ * quadrant double-rotates the viewfinder.  */  /**@@ -27,38 +31,6 @@ internal fun deviceRotationForOrientation(orientation: Int): Int? = when {     else -> 0 } -/**- * Clockwise degrees the live preview *display* rotates for an- * `OrientationEventListener` angle, or null when unknown (keep the last- * rotation). This is the same physical-orientation source and quadrant- * as the icon rotation ([deviceRotationForOrientation]) and as capture- * rotation (`CaptureRotation.displayRotationForOrientationAngle` — the- * two are exact inverses via `CaptureRotation.displayRotationDegrees`),- * NOT the window display rotation, which is always 0 in this- * portrait-locked activity. Display-only: rotating the preview view- * never touches the session, so captures keep their single- * `CaptureRotation` decision (EXIF/muxer) with no double application.- */-internal fun previewRotationForOrientation(orientation: Int): Int? =-    deviceRotationForOrientation(orientation)--/**- * Uniform scale that keeps a [width]x[height] preview covering its box- * while the display rotates it by [rotationDegrees] (clockwise) in- * place: the rotated content's bounding box must still cover the- * unrotated box on both axes. 1 at 0/180 for a square box; for a- * 90/270 turn it is `max(w/h, h/w)`. Pure so the mapping is testable.- */-internal fun previewCoverScale(rotationDegrees: Float, width: Float, height: Float): Float {-    if (width <= 0f || height <= 0f || !rotationDegrees.isFinite()) return 1f-    val rad = Math.toRadians(rotationDegrees.toDouble())-    val cos = kotlin.math.abs(kotlin.math.cos(rad)).toFloat()-    val sin = kotlin.math.abs(kotlin.math.sin(rad)).toFloat()-    val boundW = width * cos + height * sin-    val boundH = width * sin + height * cos-    return maxOf(boundW / width, boundH / height).coerceAtLeast(1f)-}- /**  * Whether the capture controls (shutter row + mode/bottom rows) rearrange  * side-by-side for [deviceRotation]. Always false: rotating the phone must
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 34f49b04c8..a6604e9c5c 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt@@ -224,6 +224,46 @@ class PreviewTransformTest {         assertEquals(back.toMatrixValues().toList(), texture.toMatrixValues().toList())     } +    @Test fun previewAppliedRotationIsZeroForEveryDisplayAndSensor() {+        // Single-source rule (owner report 2026-12-05): for every display+        // rotation R and sensor orientation S, the rotation actually+        // applied to the preview surface is 0 — the stream's texture+        // transform already applied the one relative rotation+        // CaptureRotation.rotationDegrees(S, R, facing), and any extra+        // view-layer rotation (the removed graphicsLayer rotationZ fed+        // from the physical quadrant) double-counts it. The geometry+        // form still reports that single relative rotation, and only+        // uses it to decide the displayed (swapped) size.+        for (display in listOf(0, 90, 180, 270)) {+            for (sensor in listOf(90, 270)) {+                for (facing in LensFacing.entries) {+                    val relative = CaptureRotation.rotationDegrees(sensor, display, facing)+                    val placement = assertNotNull(+                        compute(1600, 1200, 1200, 1600, sensor = sensor, display = display, facing = facing),+                        "placement sensor=$sensor display=$display facing=$facing",+                    )+                    assertEquals(+                        relative, placement.rotationDegrees,+                        "geometry sensor=$sensor display=$display facing=$facing",+                    )+                    val applied = assertNotNull(+                        texture(1600, 1200, 1200, 1600, sensor = sensor, display = display, facing = facing),+                        "texture sensor=$sensor display=$display facing=$facing",+                    )+                    assertEquals(+                        0, applied.rotationDegrees,+                        "applied preview rotation must not double-count " ++                            "sensor=$sensor display=$display facing=$facing relative=$relative",+                    )+                    // No rotation in the applied matrix at all: the+                    // linear part is a pure per-axis cover scale.+                    assertEquals(0f, applied.b, 0.001f)+                    assertEquals(0f, applied.c, 0.001f)+                }+            }+        }+    }+     @Test fun textureFormCentreCropsForSixteenNineBox() {         // 1440x1080 stream (displayed 1080x1440, 4:3) into a 9:16 box         // (1080x1920): cover scales the base content by 4/3 in x about
camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.ktindex fa4a8f7157..bbae8523cb 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/OrientationLayoutGuardTest.kt@@ -62,33 +62,32 @@ class OrientationLayoutGuardTest {     }      @Test-    fun previewDisplayRotationFollowsTheSamePhysicalQuadrant() {-        // The live preview image rotates with the same OrientationEventListener-        // quadrant as the icons (not the always-0 window rotation), and that-        // quadrant is the exact inverse of CaptureRotation's physical display-        // rotation, so preview and capture can never disagree about the holding-        // and the display rotation is never applied twice to a capture.+    fun viewfinderAddsNoRotationOnTopOfTheStreamTransform() {+        // Owner report 2026-12-05: rotating the phone must not rotate+        // the viewfinder again. The icons still follow the physical+        // quadrant (and its inverse is the capture display rotation),+        // but the preview applied rotation — the TextureView transform+        // for the display rotation that physical quadrant implies — is+        // 0 at every holding: the stream already carries the single+        // sensor-vs-display rotation, so a view-layer turn would+        // double-count it.         for ((angle, icon) in listOf(0 to 0, 90 to 270, 180 to 180, 270 to 90)) {-            assertEquals(icon, previewRotationForOrientation(angle), "preview rotation for angle $angle")             assertEquals(                 com.vayunmathur.camera.domain.CaptureRotation.displayRotationForOrientationAngle(angle),                 com.vayunmathur.camera.domain.CaptureRotation.displayRotationDegrees(icon),-                "capture display rotation must be the inverse of the preview/icon rotation at $angle",+                "capture display rotation must be the inverse of the icon rotation at $angle",             )+            val display = com.vayunmathur.camera.domain.CaptureRotation+                .displayRotationForOrientationAngle(angle)!!+            for (facing in com.vayunmathur.camera.domain.LensFacing.entries) {+                val applied = com.vayunmathur.camera.domain.PreviewTransform+                    .computeTextureAffine(1600, 1200, 1200, 1600, 90, display, facing)+                assertEquals(+                    0, applied?.rotationDegrees,+                    "viewfinder applied rotation at angle=$angle facing=$facing",+                )+            }         }-        assertNull(previewRotationForOrientation(-1))-    }--    @Test-    fun previewCoverScaleKeepsRotatedPreviewCoveringItsBox() {-        // Upright / upside-down in a portrait box: no scale needed at 180,-        // and a quarter turn needs max(w/h, h/w) to keep covering.-        assertEquals(1f, previewCoverScale(0f, 300f, 400f), 0.001f)-        assertEquals(1f, previewCoverScale(180f, 300f, 400f), 0.001f)-        assertEquals(400f / 300f, previewCoverScale(90f, 300f, 400f), 0.001f)-        assertEquals(400f / 300f, previewCoverScale(270f, 300f, 400f), 0.001f)-        assertEquals(1f, previewCoverScale(90f, 400f, 400f), 0.001f)-        assertEquals(1f, previewCoverScale(45f, 0f, 400f), 0.001f)     }      @Test