camera: orient captures by physical display rotation (#932)
- Commit
087677cdb9d99a70fd8194221a0b06c54d22308f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 19:06 UTC (5 days ago)
- Parents
9dd3fa5
Front camera photos (and in fact every non-portrait capture) were
sometimes rotated because capture rotation never followed the phone:
the activity is portrait-locked, so the window display rotation is
always 0 and every path effectively stamped the sensor orientation.
Only portrait holdings were right — for both facings and both sensor
orientations, the other three physical quadrants were wrong, and
video carried a muxer hint of 0 everywhere.
Capture rotation is now one decision in domain/CaptureRotation
(sensor orientation from characteristics, physical display rotation
from the OrientationEventListener, facing-aware, same formula as
AnalysisRotation) pushed to live Camera2 sessions and consumed by
stills (StillCapturePlanner + JPEG_ORIENTATION), analysis frames
(so QR/portrait/pano/Motion Photo agree with the still), night
(baked into the merge, RAW night included), and video/slo-mo/Motion
Photo (muxer orientation hint computed at record start).
Metadata convention, never double-applied: JPEG/JPEG_R keep sensor
pixels plus a correct EXIF Orientation (flip-carrying tags for
mirrored raw front pixels; writeRawCaptureExif for raw re-encodes);
AVIF bakes rotation+mirror into pixels with EXIF Normal and no irot
box; MP4 carries only the muxer hint; thumbnails and RGB mode
outputs bake upright. No DNG writer exists to tag (DngMetadata only
assembles requirements), noted in AGENTS.md.
New CaptureRotationTest pins the full 4-rotation x 2-facing x
{90,270}-sensor table plus EXIF conventions per pixel state, and
CaptureRotationBakedTest the baked rotate/mirror math. Verified:
:camera:testDevUnitTest and :camera:lint pass against a clean tree
(634+ tests); the shared tree's only lint error is the pre-existing
RouteScreenshotCoverage finding on Route.kt. On-device check still
owed: all four holdings, both lenses, dumb-viewer uprightness.Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex 2d0e51723f..854f78d368 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -25,6 +25,7 @@ _Install: ./install camera (dev by default)._ - 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. 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. 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@@ -36,6 +37,8 @@ _Install: ./install camera (dev by default)._ - com/vayunmathur/camera/domain/ArgbToI420Converter.kt — bulk ARGB→YUV 4:2:0 for the Motion Photo clip - com/vayunmathur/camera/domain/MotionSaveQueue.kt — bound on Motion Photos still saving after the shutter - com/vayunmathur/camera/domain/StillCaptureModePolicy.kt — ZSL vs MINIMIZE_LATENCY choice+- com/vayunmathur/camera/domain/CaptureRotation.kt — the one capture-rotation decision (sensor + physical display + facing) and EXIF convention+- com/vayunmathur/camera/domain/AnalysisRotation.kt — analysis-frame rotation (same formula as CaptureRotation) - com/vayunmathur/camera/domain/PanoXmp.kt - com/vayunmathur/camera/domain/MotionPhotoWriter.kt ### platform/ — capability queries@@ -70,6 +73,7 @@ _Install: ./install camera (dev by default)._ - com/vayunmathur/camera/platform/CameraViewModelTypes.kt - com/vayunmathur/camera/platform/CameraStartup.kt - com/vayunmathur/camera/platform/CameraSessions.kt+- com/vayunmathur/camera/platform/CaptureOrientation.kt — pushes the physical display rotation to live sessions - com/vayunmathur/camera/platform/CameraSingleCapture.kt - com/vayunmathur/camera/platform/CameraPhotoCapture.kt - com/vayunmathur/camera/platform/CameraCaptureProcessing.kt
camera/src/main/AndroidManifest.xml
diff --git a/camera/src/main/AndroidManifest.xml b/camera/src/main/AndroidManifest.xmlindex 529144b0c2..907835d070 100644--- a/camera/src/main/AndroidManifest.xml+++ b/camera/src/main/AndroidManifest.xml@@ -33,8 +33,9 @@ android:theme="@style/Theme.General"> <!-- Portrait-locked on purpose: the viewfinder layout never rotates, so capture controls stay in the same place in portrait and landscape;- only the control icons rotate in place (OrientationEventListener in- CameraScreenEffects) and CameraX auto-rotation orients captures. -->+ only the control icons rotate in place, and capture orientation is+ derived from the same physical quadrant (OrientationEventListener+ in CameraScreenEffects, via domain.CaptureRotation). --> <activity android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:name=".MainActivity"
camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.ktindex 9c384cabf4..db7dffb43e 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt@@ -52,7 +52,12 @@ internal fun CameraViewModel.saveStillBytes(displayName: String, bytes: ByteArra } /** A saved processed still: where it landed and the container actually used. */-internal data class SavedStill(val uri: Uri, val format: StillFormat)+internal data class SavedStill(+ val uri: Uri,+ val format: StillFormat,+ /** True when the encoder baked rotation/mirror into the pixels. */+ val orientationBaked: Boolean = false,+) /** * Encodes a processed [bitmap] in the user's still format and saves it.@@ -72,6 +77,12 @@ internal fun CameraViewModel.saveProcessedStill( rotationDegrees: Int, sourceJpeg: ByteArray? = null, fileStem: String? = null,+ /**+ * True when [bitmap]'s pixels are not yet mirrored and a mirrored+ * front capture must be flipped. Only the AVIF (baked) path can+ * honour it; callers whose bitmap is already mirrored pass false.+ */+ mirrored: Boolean = false, ): SavedStill? { val started = android.os.SystemClock.elapsedRealtime() val exifTiff = if (photoFormatMutable.value == com.vayunmathur.camera.platform.PhotoFormat.AVIF) {@@ -85,7 +96,7 @@ internal fun CameraViewModel.saveProcessedStill( } val exifMs = android.os.SystemClock.elapsedRealtime() - started val encodeStarted = android.os.SystemClock.elapsedRealtime()- val encoded: EncodedStill = encode(bitmap, rotationDegrees, exifTiff)+ val encoded: EncodedStill = encode(bitmap, rotationDegrees, exifTiff, mirrored) // StillSave breadcrumb: the two segments a processed still spends // before MediaStore — EXIF TIFF build (full-res JPEG carrier encode // + tag copy) and the container encode itself (ravif segment is@@ -103,7 +114,7 @@ internal fun CameraViewModel.saveProcessedStill( } val uri = saveStillBytes(name, encoded.bytes, StillFormatRouting.mimeType(encoded.format)) ?: return null- return SavedStill(uri, encoded.format)+ return SavedStill(uri, encoded.format, encoded.orientationBaked) } /** Same as [saveStillBytes] for a [bitmap]. */
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.ktindex 335608bea9..2356008873 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt@@ -47,16 +47,12 @@ data class AnalysisSourceInput( * still blocks feeding `segment(Bitmap)`/`offerFrame` from Camera2, in * order: *- * 1. No rotation/crop metadata on the Camera2 frame. `AnalysisFrame`- * carries planes + timestamp only; CameraX consumers read- * `imageInfo.rotationDegrees` (BokehAnalyzer's orient-to-display,- * PanoramaEngine's per-frame upright, MotionPhotoEncoder's clip- * rotation) and, on the night path, `ImageProxy.cropRect`. Deriving- * the Camera2 equivalent needs sensor orientation + display rotation- * + facing at the analysis source (the still path's- * `StillCapturePlanner.jpegRotationDegrees` is the back-lens half of- * that formula; the front-lens analysis formula is unproven), and no- * crop is ever applied to the Camera2 analysis stream.+ * 1. Rotation/crop metadata on the Camera2 frame. `AnalysisFrame`+ * carries planes + timestamp plus the rotation from+ * [CaptureRotation] (sensor orientation + physical display+ * rotation + facing at the analysis source, the same decision the+ * still path consumes); no crop is applied to the Camera2 analysis+ * stream, so frames carry a full-frame [FrameCrop]. * 2. The bitmap sessions never compose a Camera2 session. Portrait, * panorama and Motion-Photo (PHOTO with its excluded still routes) * bind CameraX sessions; under `PreviewEnginePolicy` a Camera2
camera/src/main/java/com/vayunmathur/camera/domain/CaptureRotation.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/CaptureRotation.kt b/camera/src/main/java/com/vayunmathur/camera/domain/CaptureRotation.ktnew file mode 100644index 0000000000..288a1cbee5--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/CaptureRotation.kt@@ -0,0 +1,120 @@+package com.vayunmathur.camera.domain++/**+ * The single rotation decision for every capture artefact.+ *+ * The activity is portrait-locked, so the window display rotation+ * (`Surface.ROTATION_*`) is always 0 and cannot describe how the user is+ * holding the phone. Capture rotation must instead be derived from the+ * physical device orientation (the quadrant the+ * `OrientationEventListener` reports, the same source CameraX+ * auto-rotation used) combined with the lens's `SENSOR_ORIENTATION`+ * from its characteristics:+ *+ * - BACK: `(sensor - display + 360) % 360`+ * - FRONT: `(sensor + display) % 360` (mirroring is a separate flag)+ *+ * This is exactly [AnalysisRotation]'s formula; stills, analysis,+ * Motion Photo and video all consume this one decision so they can+ * never disagree. Preview/metering are a different space (the locked+ * window) and keep using the window rotation — see `PreviewTransform`.+ *+ * Metadata convention (one per format, never double-applied):+ * - JPEG / JPEG_R: pixels stay sensor-oriented, EXIF Orientation+ * carries the rotation (plus the flip for a mirrored front still).+ * - AVIF: pixels are baked upright (rotated, and mirrored when the+ * source pixels were not yet), EXIF Orientation reads Normal and+ * no `irot` box is written.+ * - MP4 (video / slo-mo / Motion Photo clip): pixels stay+ * sensor-oriented, the muxer orientation hint carries the rotation.+ * - Processed RGB outputs (night merge, panorama): pixels are baked+ * upright before encoding, so they carry no rotation tag.+ */+object CaptureRotation {++ /** Normalises any degree value into `0..359`. */+ fun normalize(degrees: Int): Int = ((degrees % 360) + 360) % 360++ /**+ * Clockwise degrees a sensor-oriented frame must be rotated to sit+ * upright for [displayRotationDegrees] (the physical display+ * rotation, `Surface.ROTATION_* * 90` in an unlocked window).+ */+ fun rotationDegrees(+ sensorOrientationDegrees: Int,+ displayRotationDegrees: Int,+ facing: LensFacing?,+ ): Int = AnalysisRotation.rotationDegrees(+ sensorOrientationDegrees, displayRotationDegrees, facing,+ )++ /**+ * Physical display rotation for the icon rotation the portrait-+ * locked UI maintains: icons rotate by `Modifier.rotate(icon)`+ * (clockwise) to stay upright for the user, which is the inverse+ * of the display rotation an unlocked window would report. E.g.+ * holding the phone 90° clockwise gives icon rotation 270 and+ * display rotation 90.+ */+ fun displayRotationDegrees(iconRotationDegrees: Int): Int =+ (360 - normalize(iconRotationDegrees)) % 360++ /**+ * Physical display rotation quadrant for an+ * `OrientationEventListener` angle (0..359, -1 = unknown), or null+ * when unknown so the caller keeps the last rotation. The angle+ * grows clockwise from the natural orientation, which is exactly+ * the display-rotation convention above.+ */+ fun displayRotationForOrientationAngle(orientation: Int): Int? = when {+ orientation < 0 -> null+ orientation in 45..134 -> 90+ orientation in 135..224 -> 180+ orientation in 225..314 -> 270+ else -> 0+ }++ // EXIF Orientation values (mirroring androidx.exifinterface constants,+ // kept as plain ints so this file stays Android-free).+ const val EXIF_NORMAL = 1+ const val EXIF_FLIP_HORIZONTAL = 2+ const val EXIF_ROTATE_180 = 3+ const val EXIF_FLIP_VERTICAL = 4+ const val EXIF_TRANSPOSE = 5+ const val EXIF_ROTATE_90 = 6+ const val EXIF_TRANSVERSE = 7+ const val EXIF_ROTATE_270 = 8++ /**+ * EXIF Orientation for a still whose display rotation is+ * [rotationDegrees]. When [pixelsAlreadyMirrored] is true the+ * bitmap was already flipped in sensor space, and flip ∘ rotate+ * does not commute: the tag must carry rotate(-θ) alone. When the+ * pixels are still raw sensor pixels and [mirrored] is set, the+ * tag itself must carry the rotate-then-flip combination.+ */+ fun exifOrientation(+ rotationDegrees: Int,+ mirrored: Boolean,+ pixelsAlreadyMirrored: Boolean,+ ): Int {+ val rotation = normalize(rotationDegrees)+ if (pixelsAlreadyMirrored) {+ return pureRotationExif((360 - rotation) % 360)+ }+ if (!mirrored) return pureRotationExif(rotation)+ return when (rotation) {+ 90 -> EXIF_TRANSPOSE+ 180 -> EXIF_FLIP_VERTICAL+ 270 -> EXIF_TRANSVERSE+ else -> EXIF_FLIP_HORIZONTAL+ }+ }++ private fun pureRotationExif(rotation: Int): Int = when (rotation) {+ 90 -> EXIF_ROTATE_90+ 180 -> EXIF_ROTATE_180+ 270 -> EXIF_ROTATE_270+ else -> EXIF_NORMAL+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.ktindex 1019be5f8b..9671ae2b28 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt@@ -46,6 +46,7 @@ internal fun CameraViewModel.registerCamera2ExtensionSession(session: Camera2Ext activeCamera2ExtensionSession = session camera2NightSessionActiveMutable.value = session != null if (session != null) {+ session.setCaptureDisplayRotationDegrees(captureDisplayRotationDegrees) // No Camera2 strength flow: never carry a CameraX strength value over. extensionStrengthMutable.value = null }
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.ktindex c23fcff958..2ec7291a5a 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt@@ -67,11 +67,21 @@ internal fun CameraViewModel.tryCaptureCamera2RawNight(): Boolean { if (merged == null) { null } else {+ // RAW frames merge in sensor orientation+ // (unlike the YUV night path, whose frames+ // are uprighted before merging): bake the+ // capture rotation/mirror in, then save as+ // already-upright pixels.+ val rotation = captureRotationDegrees(+ snapshot.sensorOrientationDegrees, snapshot.lensFacing,+ )+ val upright = uprightCopy(merged, rotation, 0, mirrorCaptures) try { withContext(Dispatchers.IO) {- saveProcessedStill(merged, 0)?.uri+ saveProcessedStill(upright, 0)?.uri } } finally {+ if (upright !== merged) upright.recycle() merged.recycle() } }
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.ktindex 8ad8718ecf..4f21af8423 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt@@ -141,7 +141,10 @@ class Camera2RecordingCore( * codec is created at all and the recording proceeds video-only with * a logged reason — never an AAC fallback. */- fun setupMuxerAndAudio(outputFile: File) {+ fun setupMuxerAndAudio(+ outputFile: File,+ orientationDegrees: Int = config.orientationDegrees,+ ) { if (videoCodec == null) configureVideoCodec() audioTrackExpected = false audioMuxerRejected = false@@ -181,6 +184,12 @@ class Camera2RecordingCore( } } muxer = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)+ // Encoder frames stay sensor-oriented; the hint is the only+ // rotation a dumb player will ever apply, so it must be set+ // before the muxer starts (and before any track is added).+ muxer?.setOrientationHint(+ com.vayunmathur.camera.domain.CaptureRotation.normalize(orientationDegrees)+ ) } fun startVideoCodec() {
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.ktindex f272b3be0f..6a6c80ba3c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt@@ -65,4 +65,6 @@ internal class Camera2RecordingState { internal class SloMoRecordingControl( val start: (java.io.File, (java.io.File, Boolean) -> Unit) -> Unit, val stop: () -> Unit,+ /** Sets the muxer orientation hint for the next recording. */+ val setOrientationDegrees: (Int) -> Unit = {}, )
camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.ktindex 334a7efa4b..1f1183ea71 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt@@ -226,6 +226,13 @@ internal fun CameraViewModel.startCamera2SloMoRecording() { null } val selection = facade?.let { HighSpeedPlanner.select(it.snapshot) }+ // Rotation for this recording, from the probed lens + the+ // physical display rotation at the record press.+ facade?.snapshot?.let { snapshot ->+ control.setOrientationDegrees(+ captureRotationDegrees(snapshot.sensorOrientationDegrees, snapshot.lensFacing)+ )+ } if (selection == null || !encoderSupportsSloMoCaptureRate(selection)) { Log.error("SloMo", "No encoder supports the slo-mo capture rate; recording not started") com.vayunmathur.library.util.AppMessages.show(
camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.ktindex 7aad737a63..b0cc06ec33 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -48,6 +48,9 @@ import kotlinx.coroutines.withContext internal fun CameraViewModel.registerCamera2Session(session: Camera2Session?) { activeCamera2Session = session if (session != null) {+ // A session bound after the user already rotated the phone+ // must not start from the portrait default.+ session.setCaptureDisplayRotationDegrees(captureDisplayRotationDegrees) // Zoom-locked modes (PANORAMA/PHOTOSPHERE) bind at 1x in the // session itself — the strongest guarantee, applied before the // capability refresh below re-asserts it — regardless of the@@ -188,12 +191,21 @@ internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? { try { val saved = saveProcessedStill( cropped, still.metadata.rotationDegrees, still.jpegBytes,+ mirrored = still.metadata.mirrored, ) ?: return null if (saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG) {- writeCaptureExif(- saved.uri, still.jpegBytes,- still.metadata.rotationDegrees, mirrored = still.metadata.mirrored,- )+ // Baked output carries upright pixels: only the copied+ // tags/GPS with a Normal orientation may be stamped.+ // Otherwise the cropped pixels are still raw sensor+ // pixels, so the tag must carry the flip itself.+ if (saved.orientationBaked) {+ writeCaptureExif(saved.uri, still.jpegBytes, 0)+ } else {+ writeRawCaptureExif(+ saved.uri, still.jpegBytes,+ still.metadata.rotationDegrees, mirrored = still.metadata.mirrored,+ )+ } } return saved.uri } finally {@@ -266,13 +278,20 @@ private fun CameraViewModel.saveCamera2EncodedStill(still: CapturedStill): Uri? val bitmap = BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size) ?: return saveJpegStill(still) try {- val saved = saveProcessedStill(bitmap, rotation, still.jpegBytes) ?: return null+ val saved = saveProcessedStill(+ bitmap, rotation, still.jpegBytes, mirrored = still.metadata.mirrored,+ ) ?: return null if (saved.format == StillFormat.JPEG) { // The JPEG re-encode dropped the HAL EXIF; restore it from- // the original frame, exactly as the processed CameraX path.- writeCaptureExif(- saved.uri, still.jpegBytes, rotation, mirrored = still.metadata.mirrored,- )+ // the original frame. Baked (AVIF-fallback) pixels are already+ // upright/mirrored, so they take only a Normal orientation.+ if (saved.orientationBaked) {+ writeCaptureExif(saved.uri, still.jpegBytes, 0)+ } else {+ writeCaptureExif(+ saved.uri, still.jpegBytes, rotation, mirrored = still.metadata.mirrored,+ )+ } } return saved.uri } finally {
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 15e9f9f54c..d83f6fa23e 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -52,6 +52,13 @@ data class CustomRecordingConfig( */ val audioInputDevice: com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection = com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO,+ /**+ * Muxer orientation hint for the sensor-oriented encoder frames:+ * the [com.vayunmathur.camera.domain.CaptureRotation] decision at+ * record start. Without it every recording saved with a 0 hint and+ * played sideways/upside-down outside portrait back-lens use.+ */+ val orientationDegrees: Int = 0, ) /** Read-back summary of a finished file (see [Camera2VideoRecordingEngine.validateOutput]). */
camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.ktindex 12b3085f07..e48eeca98d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt@@ -16,12 +16,6 @@ import java.io.ByteArrayInputStream import kotlin.math.roundToInt import com.vayunmathur.camera.data.updateLocation -/** EXIF orientation buckets (degrees clockwise). */-private const val EXIF_DEGREES_90 = 90-private const val EXIF_DEGREES_180 = 180-private const val EXIF_DEGREES_270 = 270-private const val EXIF_FULL_CIRCLE_DEGREES = 360- /** Center-crop [src] to [rect] (the ImageProxy cropRect), returning [src] unchanged for a * full-frame/empty rect. Recycles the pre-crop bitmap when a new one is produced. */ internal fun CameraViewModel.cropToRect(src: Bitmap, rect: Rect): Bitmap {@@ -74,12 +68,20 @@ private fun isFullFrame(src: Bitmap, left: Int, top: Int, w: Int, h: Int): Boole * [downscaledThumbnail] it does not mirror — the processed bitmap already is. Always returns a * bitmap distinct from [src] so the caller can recycle it. */-internal fun uprightCopy(src: Bitmap, rotationDegrees: Int, maxSide: Int): Bitmap {+internal fun uprightCopy(+ src: Bitmap,+ rotationDegrees: Int,+ maxSide: Int,+ mirrored: Boolean = false,+): Bitmap { val scale = if (maxSide > 0) { (maxSide.toFloat() / maxOf(src.width, src.height)).coerceAtMost(1f) } else 1f val matrix = Matrix().apply { postRotate(rotationDegrees.toFloat())+ // Rotate-then-flip, the same order downscaledThumbnail and the+ // raw-still EXIF flip tags describe for unmirrored sensor pixels.+ if (mirrored) postScale(-1f, 1f) if (scale < 1f) postScale(scale, scale) } val out = Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, true)@@ -143,7 +145,7 @@ internal fun CameraViewModel.writeCaptureExif( // and getLastKnownLocation is a cheap cached lookup, so no main-thread concern. updateLocation() try {- writeExifAttributes(uri, sourceJpeg, rotationDegrees, mirrored)+ writeExifAttributes(uri, sourceJpeg, orientationString(rotationDegrees, mirrored)) } catch (e: java.io.IOException) { Log.status("CameraViewModel", "Failed to write EXIF for adjusted capture", e) } catch (e: SecurityException) {@@ -151,6 +153,27 @@ internal fun CameraViewModel.writeCaptureExif( } } +/**+ * Same restore as [writeCaptureExif] for pixels that are still raw+ * sensor pixels (not yet mirrored): the orientation tag itself must+ * carry the rotate-then-flip for a mirrored front capture.+ */+internal fun CameraViewModel.writeRawCaptureExif(+ uri: Uri,+ sourceJpeg: ByteArray?,+ rotationDegrees: Int,+ mirrored: Boolean = false+) {+ updateLocation()+ try {+ writeExifAttributes(uri, sourceJpeg, rawStillOrientationString(rotationDegrees, mirrored))+ } catch (e: java.io.IOException) {+ Log.status("CameraViewModel", "Failed to write EXIF for raw capture", e)+ } catch (e: SecurityException) {+ Log.status("CameraViewModel", "Failed to write EXIF for raw capture", e)+ }+}+ /** * Builds the TIFF payload for an AVIF Exif item from the same tag set * the JPEG path stamps: [CameraViewModel.EXIF_TAGS_TO_COPY] copied from@@ -189,18 +212,17 @@ internal fun CameraViewModel.buildAvifExifTiff(sourceJpeg: ByteArray?, carrierJp } } -/** Opens [uri] for EXIF read/write and stamps orientation (+GPS +copied tags). */+/** Opens [uri] for EXIF read/write and stamps [orientation] (+GPS +copied tags). */ private fun CameraViewModel.writeExifAttributes( uri: Uri, sourceJpeg: ByteArray?,- rotationDegrees: Int,- mirrored: Boolean+ orientation: String ) { val source = sourceJpeg?.let { ExifInterface(ByteArrayInputStream(it)) } app.contentResolver.openFileDescriptor(uri, "rw")?.use { pfd -> val dest = ExifInterface(pfd.fileDescriptor) copyExifTags(source, dest)- dest.setAttribute(ExifInterface.TAG_ORIENTATION, orientationString(rotationDegrees, mirrored))+ dest.setAttribute(ExifInterface.TAG_ORIENTATION, orientation) if (locationEnabledMutable.value) lastLocation?.let { dest.setGpsInfo(it) } dest.saveAttributes() }@@ -216,22 +238,15 @@ private fun copyExifTags(source: ExifInterface?, dest: ExifInterface) { } /**- * EXIF orientation tag for [rotationDegrees], inverted when the pixels were already- * mirrored (front camera): flip and rotate don't commute, and FLIP∘ROTATE(θ)∘FLIP =- * ROTATE(−θ). Without this, portrait selfies (θ=90/270) save upside down; landscape- * (θ=0/180) commutes and is unaffected.+ * EXIF orientation tag for [rotationDegrees] over pixels that were+ * already mirrored as a bitmap when [mirrored] is set: flip and rotate+ * don't commute, and FLIP∘ROTATE(θ)∘FLIP = ROTATE(−θ). Delegates to+ * the pure [com.vayunmathur.camera.domain.CaptureRotation] decision. */-private fun orientationString(rotationDegrees: Int, mirrored: Boolean): String {- val effectiveDegrees =- if (mirrored) (EXIF_FULL_CIRCLE_DEGREES - rotationDegrees) % EXIF_FULL_CIRCLE_DEGREES- else rotationDegrees- return when (effectiveDegrees) {- EXIF_DEGREES_90 -> ExifInterface.ORIENTATION_ROTATE_90- EXIF_DEGREES_180 -> ExifInterface.ORIENTATION_ROTATE_180- EXIF_DEGREES_270 -> ExifInterface.ORIENTATION_ROTATE_270- else -> ExifInterface.ORIENTATION_NORMAL- }.toString()-}+private fun orientationString(rotationDegrees: Int, mirrored: Boolean): String =+ com.vayunmathur.camera.domain.CaptureRotation.exifOrientation(+ rotationDegrees, mirrored = false, pixelsAlreadyMirrored = mirrored,+ ).toString() /** * EXIF orientation for a still whose pixels are still in sensor orientation (the raw@@ -244,18 +259,10 @@ private fun orientationString(rotationDegrees: Int, mirrored: Boolean): String { * displays portrait selfies (θ=90/270) upside down, while landscape (θ=0/180) still * reads the right way up (issue #932). */-internal fun rawStillOrientationString(rotationDegrees: Int, mirrored: Boolean): String {- if (!mirrored) return orientationString(rotationDegrees, mirrored = false)- val normalized =- ((rotationDegrees % EXIF_FULL_CIRCLE_DEGREES) + EXIF_FULL_CIRCLE_DEGREES) %- EXIF_FULL_CIRCLE_DEGREES- return when (normalized) {- EXIF_DEGREES_90 -> ExifInterface.ORIENTATION_TRANSPOSE- EXIF_DEGREES_180 -> ExifInterface.ORIENTATION_FLIP_VERTICAL- EXIF_DEGREES_270 -> ExifInterface.ORIENTATION_TRANSVERSE- else -> ExifInterface.ORIENTATION_FLIP_HORIZONTAL- }.toString()-}+internal fun rawStillOrientationString(rotationDegrees: Int, mirrored: Boolean): String =+ com.vayunmathur.camera.domain.CaptureRotation.exifOrientation(+ rotationDegrees, mirrored = mirrored, pixelsAlreadyMirrored = false,+ ).toString() /** * Stamps orientation + GPS into an in-memory still's JPEG [jpeg] and returns the updated
camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.ktindex cd843dba6f..8a7c990a7d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -407,8 +407,11 @@ internal fun CameraViewModel.assembleAndSaveMotionPhoto(request: MotionSaveReque val tmp = java.io.File(app.cacheDir, "motion_${System.currentTimeMillis()}.mp4") val spanNs = (sized.last().timestampNanos - sized.first().timestampNanos).coerceAtLeast(1) val fps = (sized.size * 1_000_000_000.0 / spanNs).roundToInt().coerceIn(5, 30)+ // The clip's hint must agree with the still it trails: use the+ // still's capture rotation, not an analysis frame's (the two+ // are the same decision now, but the still is the authority). val ok = MotionPhotoEncoder.encode(- sized.map { it.bitmap }, tmp, sized.last().rotationDegrees, fps+ sized.map { it.bitmap }, tmp, request.rotationDegrees, fps ) if (ok && tmp.exists()) { val mp4 = tmp.readBytes()
camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.ktindex e8bbad05d8..1abe007a57 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt@@ -180,7 +180,14 @@ private fun CameraViewModel.processSingleFrame( adjusted.recycle() if (saved == null) return null if (saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG) {- writeCaptureExif(saved.uri, sourceJpeg, degrees, mirrored = plan.mirror)+ // Baked (AVIF-fallback) pixels are already upright; the plain+ // JPEG re-encode keeps sensor pixels whose bitmap was mirrored+ // by the colour/bokeh pass, so it takes the inverted tag.+ if (saved.orientationBaked) {+ writeCaptureExif(saved.uri, sourceJpeg, 0)+ } else {+ writeCaptureExif(saved.uri, sourceJpeg, degrees, mirrored = plan.mirror)+ } } return saved.uri }
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 faeab7a012..0b3086f721 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -194,6 +194,11 @@ internal fun CameraViewModel.startRecording() { audioEnabled = audioEnabled, // Physical mic from the bind-time snapshot (held during a take). audioInputDevice = bindTimeSettings.value.audioInputDevice,+ // Rotation decided at record start from this lens's sensor+ // orientation + the physical display rotation.+ orientationDegrees = snapshot0?.let {+ captureRotationDegrees(it.sensorOrientationDegrees, it.lensFacing)+ } ?: 0, ) val controller = com.vayunmathur.camera.domain.LiveBitrateController(decision) val engine = Camera2VideoRecordingEngine(
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.ktindex 0bb1272a01..8ce6d61fde 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -171,6 +171,17 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal var activeCamera2Session: com.vayunmathur.camera.platform.camera2.Camera2Session? = null + /**+ * Physical display rotation (0/90/180/270) at this moment, fed from+ * the screen's `OrientationEventListener` (see+ * `domain.CaptureRotation`). The portrait-locked window rotation is+ * always 0, so this is the only rotation capture orientation may+ * be computed from. Sessions are pushed the same value, so a still,+ * its analysis frames and a video started now all agree.+ */+ @Volatile+ internal var captureDisplayRotationDegrees: Int = 0+ internal val cameraModeMutable = MutableStateFlow(CameraMode.PHOTO) val cameraMode = cameraModeMutable.asStateFlow()
camera/src/main/java/com/vayunmathur/camera/platform/CaptureOrientation.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CaptureOrientation.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CaptureOrientation.ktnew file mode 100644index 0000000000..ae9894813a--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CaptureOrientation.kt@@ -0,0 +1,38 @@+package com.vayunmathur.camera.platform++import com.vayunmathur.camera.domain.CaptureRotation+import com.vayunmathur.camera.domain.LensFacing++/**+ * Capture-orientation plumbing: the ViewModel's single physical+ * display rotation, pushed to every live capture session so stills,+ * analysis frames and recordings taken at the same moment orient+ * identically. See [CaptureRotation] for the decision itself.+ */++/**+ * Records the physical display rotation (degrees, any value — it is+ * normalised here) and forwards it to the live still/extension+ * sessions. No-op when the quadrant has not changed, so the+ * orientation listener may call this on every sensor event.+ */+internal fun CameraViewModel.setCaptureDisplayRotationDegrees(degrees: Int) {+ val normalized = CaptureRotation.normalize(degrees)+ if (captureDisplayRotationDegrees == normalized) return+ captureDisplayRotationDegrees = normalized+ activeCamera2Session?.setCaptureDisplayRotationDegrees(normalized)+ activeCamera2ExtensionSession?.setCaptureDisplayRotationDegrees(normalized)+}++/**+ * The capture rotation for a lens with [sensorOrientationDegrees] and+ * [facing] at the current physical display rotation — the value a+ * muxer orientation hint (video/slo-mo) must carry, since recordings+ * compute it at record start rather than through a session still.+ */+internal fun CameraViewModel.captureRotationDegrees(+ sensorOrientationDegrees: Int,+ facing: LensFacing?,+): Int = CaptureRotation.rotationDegrees(+ sensorOrientationDegrees, captureDisplayRotationDegrees, facing,+)
camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt b/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.ktindex f7440082da..6ac708431d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt@@ -7,7 +7,16 @@ import com.vayunmathur.library.log.Log import java.io.ByteArrayOutputStream /** One encoded still plus the container it actually landed in. */-internal data class EncodedStill(val bytes: ByteArray, val format: StillFormat) {+internal data class EncodedStill(+ val bytes: ByteArray,+ val format: StillFormat,+ /**+ * True when rotation (and any requested mirror) was baked into+ * the pixels: the caller must not stamp a rotation EXIF on top,+ * only the copied tags/GPS with a Normal orientation.+ */+ val orientationBaked: Boolean = false,+) { override fun equals(other: Any?): Boolean = other is EncodedStill && format == other.format && bytes.contentEquals(other.bytes) @@ -35,14 +44,18 @@ internal object StillEncoder { /** * Encoded container for [bitmap] under the current settings.- * [rotationDegrees] is baked into the pixels on the AVIF path; the- * JPEG path leaves pixels untouched and the caller stamps- * orientation via EXIF as before.+ * [rotationDegrees] (and [mirrored], when the source pixels are not+ * yet mirrored) is baked into the pixels on the AVIF path; a JPEG+ * fallback for an attempted AVIF encodes those same upright pixels+ * and reports [EncodedStill.orientationBaked] so the caller stamps+ * no second rotation. The plain JPEG path leaves pixels untouched+ * and the caller stamps orientation via EXIF as before. */ fun CameraViewModel.encode( bitmap: Bitmap, rotationDegrees: Int = 0, exifTiff: ByteArray? = null,+ mirrored: Boolean = false, ): EncodedStill { val requested = requestedStillFormat() val effective = StillFormatRouting.effectiveFormat(@@ -54,7 +67,7 @@ internal object StillEncoder { if (exifTiff == null || exifTiff.isEmpty()) { Log.status("StillEncoder", "AVIF without EXIF payload; falling back to JPEG") } else {- val upright = uprightCopy(bitmap, rotationDegrees, 0)+ val upright = uprightCopy(bitmap, rotationDegrees, 0, mirrored) try { // Hardware still encoder first when the device ships // one (cached MediaCodecList probe, warmed at startup);@@ -67,12 +80,22 @@ internal object StillEncoder { } else { null }- hw?.let { return EncodedStill(it, StillFormat.AVIF) }- encodeAvif(upright, exifTiff)?.let { return EncodedStill(it, StillFormat.AVIF) }+ hw?.let {+ return EncodedStill(it, StillFormat.AVIF, orientationBaked = true)+ }+ encodeAvif(upright, exifTiff)?.let {+ return EncodedStill(it, StillFormat.AVIF, orientationBaked = true)+ }+ Log.status("StillEncoder", "AVIF encode failed; falling back to JPEG")+ // Same upright pixels as JPEG, never a sensor-oriented+ // JPEG under an AVIF decision: the caller writes only+ // a Normal orientation for baked output.+ return EncodedStill(+ encodeJpeg(upright), StillFormat.JPEG, orientationBaked = true,+ ) } finally { if (upright !== bitmap) upright.recycle() }- Log.status("StillEncoder", "AVIF encode failed; falling back to JPEG") } } return EncodedStill(encodeJpeg(bitmap), StillFormat.JPEG)
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 7ee12442a6..be47a5f738 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@@ -75,6 +75,10 @@ class Camera2ExtensionSession( val requestedSize: FrameSize, ) private var displayRotationDegrees: Int = 0++ /** Physical display rotation for still orientation; see [Camera2Session]. */+ @Volatile+ internal var captureDisplayRotationDegrees: Int = 0 private var controls: Camera2ControlState = Camera2ControlState.DEFAULT private class PendingStill(@@ -103,11 +107,17 @@ class Camera2ExtensionSession( } } - /** Records the display rotation still orientations are computed from. */+ /** Records the window display rotation preview sizing is computed from. */ fun setDisplayRotationDegrees(degrees: Int) { executor.execute { displayRotationDegrees = degrees } } + /** Records the physical display rotation still orientation uses. */+ fun setCaptureDisplayRotationDegrees(degrees: Int) {+ captureDisplayRotationDegrees =+ com.vayunmathur.camera.domain.CaptureRotation.normalize(degrees)+ }+ /** * Opens [cameraId] as a NIGHT extension session on [surface]. The probe * runs first; an unusable lens reports [Listener.onError] and never@@ -184,7 +194,7 @@ class Camera2ExtensionSession( state = controls, snapshot = snapshot, displayRotationDegrees = displayRotationDegrees- ?: [email protected],+ ?: [email protected], mirrored = mirrored, ) val pending = PendingStill(params, callback)
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 55b16115cd..ee9c42570c 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,6 +138,19 @@ class Camera2Session( private var latestPreviewMeta: RawStillMetadata? = null internal var pendingStill: PendingStill? = null internal var displayRotationDegrees: Int = 0++ /**+ * Physical display rotation (0/90/180/270) captures and analysis+ * frames are oriented by. The window rotation in+ * [displayRotationDegrees] is always 0 in the portrait-locked+ * activity and only describes the preview surface; this separate+ * value tracks how the user holds the phone (fed from the+ * `OrientationEventListener` via the ViewModel, see+ * `CaptureRotation`). Written from the main thread, read on the+ * executor and the analysis thread, hence volatile.+ */+ @Volatile+ internal var captureDisplayRotationDegrees: Int = 0 internal var controls: Camera2ControlState = Camera2ControlState.DEFAULT /** In-flight still: JPEG bytes and result metadata pair up by arrival. */@@ -312,11 +325,17 @@ class Camera2Session( } } - /** Records the display rotation still orientations are computed from. */+ /** Records the window display rotation preview sizing is computed from. */ fun setDisplayRotationDegrees(degrees: Int) { executor.execute { displayRotationDegrees = degrees } } + /** Records the physical display rotation still/analysis orientation uses. */+ fun setCaptureDisplayRotationDegrees(degrees: Int) {+ captureDisplayRotationDegrees =+ com.vayunmathur.camera.domain.CaptureRotation.normalize(degrees)+ }+ /** The JPEG still size configured at [open], or null when unavailable. */ fun currentStillSize(): FrameSize? = stillSize @@ -429,7 +448,7 @@ class Camera2Session( state = controls, snapshot = snapshot, displayRotationDegrees = displayRotationDegrees- ?: [email protected],+ ?: [email protected], mirrored = mirrored, ) val pending = PendingStill(params, callback, tag)
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.ktindex ab83e87406..d625fe7a45 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt@@ -101,7 +101,10 @@ internal fun Camera2Session.configureSession(opened: DeviceHandle, gen: Long, re AnalysisFrameMetadata( sensorOrientationDegrees = snapshot.sensorOrientationDegrees, lensFacing = snapshot.lensFacing,- displayRotationDegrees = { displayRotationDegrees },+ // Physical rotation, not the locked window's: analysis+ // frames (QR, bokeh, pano, Motion Photo) must orient+ // like the still taken at the same moment.+ displayRotationDegrees = { captureDisplayRotationDegrees }, ), ) }.getOrNull()
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.ktindex cd5f6bd3d3..c571bfcc0e 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt@@ -51,7 +51,7 @@ fun Camera2Session.captureFromRing( state = controls, snapshot = snapshot, displayRotationDegrees = displayRotationDegrees- ?: [email protected],+ ?: [email protected], mirrored = mirrored, ) val output = stillOutput
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.ktindex 9cf589f7a2..e8973b0be8 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt@@ -142,20 +142,32 @@ data class ResolvedStillParams( object StillCapturePlanner { /**- * Rotation (clockwise, EXIF sense) for a JPEG from this lens at- * [displayRotationDegrees]. Uses the same relative rotation as- * [MeteringTransform] (`sensor - display`, normalised): e.g. the usual- * back lens (sensor 90°) in portrait (display 0°) yields 90, exactly- * the `rotationDegrees` CameraX reports for that frame, which is what- * `stampStillBytes`/`rawStillOrientationString` expect.+ * Rotation (clockwise, EXIF sense) for a JPEG from a back lens at+ * [displayRotationDegrees]; kept for the back-lens callers/tests.+ * The facing-aware overload is the capture decision (see+ * [com.vayunmathur.camera.domain.CaptureRotation]). */ fun jpegRotationDegrees( sensorOrientationDegrees: Int, displayRotationDegrees: Int,- ): Int {- val relative = (sensorOrientationDegrees - displayRotationDegrees) % 360- return (relative + 360) % 360- }+ ): Int = jpegRotationDegrees(+ sensorOrientationDegrees, displayRotationDegrees, LensFacing.BACK,+ )++ /**+ * The one still rotation decision: [CaptureRotation] over the+ * lens's sensor orientation, physical display rotation and facing.+ * The old back-only formula (`sensor - display`) was wrong for the+ * front lens at display 90/270 by 180° — landscape selfies saved+ * upside down (issue #932's front-camera half).+ */+ fun jpegRotationDegrees(+ sensorOrientationDegrees: Int,+ displayRotationDegrees: Int,+ facing: LensFacing?,+ ): Int = com.vayunmathur.camera.domain.CaptureRotation.rotationDegrees(+ sensorOrientationDegrees, displayRotationDegrees, facing,+ ) /** * Resolves the still request for the session's current [state].@@ -203,7 +215,7 @@ object StillCapturePlanner { flashResolution = resolution, requiresScreenFlash = resolution == FlashResolution.SCREEN, jpegOrientationDegrees = jpegRotationDegrees(- snapshot.sensorOrientationDegrees, displayRotationDegrees,+ snapshot.sensorOrientationDegrees, displayRotationDegrees, facing, ), mirrored = mirrored, manualExposureTimeNs = preview.manualExposureTimeNs,
camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreviewSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreviewSession.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreviewSession.ktindex 45b2f50f69..8e3c33bb89 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreviewSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreviewSession.kt@@ -40,6 +40,10 @@ internal class Camera2SloMoPreviewSession( @Volatile private var selection: com.vayunmathur.camera.platform.camera2.HighSpeedSelection? = null + /** Muxer orientation hint for the next recording, set at record press. */+ @Volatile+ private var orientationDegrees: Int = 0+ @Volatile private var lastPreviewSurface: android.view.Surface? = null @@ -167,6 +171,7 @@ internal class Camera2SloMoPreviewSession( com.vayunmathur.camera.platform.SloMoRecordingControl( start = { file, callback -> startRecording(file, callback) }, stop = { stopRecording() },+ setOrientationDegrees = { orientationDegrees = it }, ) private fun startRecording(@@ -183,7 +188,7 @@ internal class Camera2SloMoPreviewSession( recordCallback = callback recordStartedAtMs = android.os.SystemClock.elapsedRealtime() try {- liveCore.setupMuxerAndAudio(file)+ liveCore.setupMuxerAndAudio(file, orientationDegrees) liveCore.startVideoCodec() liveCore.markSessionStreaming() liveCore.startDrain()
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 0acdd40b80..590fa7232a 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -28,6 +28,7 @@ import com.vayunmathur.camera.platform.onLuminance import com.vayunmathur.camera.platform.onSessionBound import com.vayunmathur.camera.platform.refreshNightExtensionUsable import com.vayunmathur.camera.platform.runSessionBindWithRetry+import com.vayunmathur.camera.platform.setCaptureDisplayRotationDegrees import com.vayunmathur.camera.platform.setQrResult import com.vayunmathur.camera.platform.setAnalysisSink import com.vayunmathur.camera.platform.onSceneMotionSample@@ -58,13 +59,20 @@ internal fun CameraScreenEffects( val useCamera2NightPreview = state.useCamera2NightPreview val useCamera2SloMoPreview = state.useCamera2SloMoPreview - // Tracks physical orientation purely to rotate the on-screen control icons. Capture output- // rotation is handled by CameraX via SessionConfig.setAutoRotationEnabled(true).+ // Tracks physical orientation to rotate the on-screen control icons, and+ // feeds the same quadrant to capture orientation: the activity is+ // portrait-locked, so this listener is the only live source of how the+ // user holds the phone (the window display rotation is always 0). DisposableEffect(Unit) { val listener = object : OrientationEventListener(context) { override fun onOrientationChanged(orientation: Int) { // Unknown angle keeps the last rotation (helper returns null).- state.deviceRotation = deviceRotationForOrientation(orientation) ?: return+ val iconRotation = deviceRotationForOrientation(orientation) ?: return+ state.deviceRotation = iconRotation+ viewModel.setCaptureDisplayRotationDegrees(+ com.vayunmathur.camera.domain.CaptureRotation+ .displayRotationDegrees(iconRotation)+ ) } } listener.enable()
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 d5bf706717..ed1f50f395 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/DeviceRotation.kt@@ -8,8 +8,9 @@ package com.vayunmathur.camera.ui * portrait and landscape. What changes with the physical device is only the * glyph orientation: [deviceRotationForOrientation] maps the sensor angle from * `OrientationEventListener` onto the quadrant the on-screen icons must rotate- * to (via `Modifier.rotate`), while capture output rotation is handled by- * CameraX (`SessionConfig.setAutoRotationEnabled(true)` in the session binder).+ * 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). */ /**
camera/src/test/java/com/vayunmathur/camera/domain/CaptureRotationTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/CaptureRotationTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/CaptureRotationTest.ktnew file mode 100644index 0000000000..eb5b7449da--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/CaptureRotationTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.camera.domain++import com.vayunmathur.camera.platform.camera2.StillCapturePlanner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * The full capture-rotation table: 4 physical display rotations × 2+ * facings × the two sensor orientations phones ship (90/270), plus+ * the portrait-locked icon/angle conversions and the per-format EXIF+ * convention. Expected values follow the Camera2 contract+ * (BACK: sensor − display; FRONT: sensor + display).+ */+class CaptureRotationTest {++ private val displays = listOf(0, 90, 180, 270)++ @Test fun backSensor90FullTable() {+ assertEquals(+ listOf(90, 0, 270, 180),+ displays.map { CaptureRotation.rotationDegrees(90, it, LensFacing.BACK) },+ )+ }++ @Test fun backSensor270FullTable() {+ assertEquals(+ listOf(270, 180, 90, 0),+ displays.map { CaptureRotation.rotationDegrees(270, it, LensFacing.BACK) },+ )+ }++ @Test fun frontSensor270FullTable() {+ assertEquals(+ listOf(270, 0, 90, 180),+ displays.map { CaptureRotation.rotationDegrees(270, it, LensFacing.FRONT) },+ )+ }++ @Test fun frontSensor90FullTable() {+ assertEquals(+ listOf(90, 180, 270, 0),+ displays.map { CaptureRotation.rotationDegrees(90, it, LensFacing.FRONT) },+ )+ }++ @Test fun stillPlannerAgreesForBothFacings() {+ // The still planner is the capture path's entry to the same+ // decision: it must agree with AnalysisRotation/CaptureRotation+ // for every cell, front included (the old back-only planner+ // disagreed at front display 90/270 by 180 degrees).+ for (sensor in listOf(90, 270)) {+ for (display in displays) {+ for (facing in LensFacing.entries) {+ assertEquals(+ CaptureRotation.rotationDegrees(sensor, display, facing),+ StillCapturePlanner.jpegRotationDegrees(sensor, display, facing),+ "sensor=$sensor display=$display facing=$facing",+ )+ assertEquals(+ CaptureRotation.rotationDegrees(sensor, display, facing),+ AnalysisRotation.rotationDegrees(sensor, display, facing),+ "analysis sensor=$sensor display=$display facing=$facing",+ )+ }+ }+ }+ }++ @Test fun iconRotationInvertsToDisplayRotation() {+ // Portrait-locked icons rotate clockwise to stay upright for+ // the user; the capture display rotation is the inverse.+ assertEquals(0, CaptureRotation.displayRotationDegrees(0))+ assertEquals(90, CaptureRotation.displayRotationDegrees(270))+ assertEquals(180, CaptureRotation.displayRotationDegrees(180))+ assertEquals(270, CaptureRotation.displayRotationDegrees(90))+ assertEquals(90, CaptureRotation.displayRotationDegrees(-90))+ }++ @Test fun orientationAngleQuadrantsMatchIconConversion() {+ // For every quadrant, the listener angle must land on the same+ // display rotation the icon state converts to.+ val cases = mapOf(0 to 0, 90 to 90, 180 to 180, 270 to 270, 359 to 0, 44 to 0, 45 to 90)+ for ((angle, expected) in cases) {+ assertEquals(expected, CaptureRotation.displayRotationForOrientationAngle(angle), "angle=$angle")+ }+ assertNull(CaptureRotation.displayRotationForOrientationAngle(-1))+ }++ // -- Per-format metadata convention ------------------------------------++ @Test fun jpegExifCarriesPureRotationForUnmirroredPixels() {+ assertEquals(CaptureRotation.EXIF_NORMAL, CaptureRotation.exifOrientation(0, false, false))+ assertEquals(CaptureRotation.EXIF_ROTATE_90, CaptureRotation.exifOrientation(90, false, false))+ assertEquals(CaptureRotation.EXIF_ROTATE_180, CaptureRotation.exifOrientation(180, false, false))+ assertEquals(CaptureRotation.EXIF_ROTATE_270, CaptureRotation.exifOrientation(270, false, false))+ }++ @Test fun jpegExifCarriesFlipForMirroredRawPixels() {+ // Rotate-then-flip is a single combined EXIF orientation.+ assertEquals(CaptureRotation.EXIF_FLIP_HORIZONTAL, CaptureRotation.exifOrientation(0, true, false))+ assertEquals(CaptureRotation.EXIF_TRANSPOSE, CaptureRotation.exifOrientation(90, true, false))+ assertEquals(CaptureRotation.EXIF_FLIP_VERTICAL, CaptureRotation.exifOrientation(180, true, false))+ assertEquals(CaptureRotation.EXIF_TRANSVERSE, CaptureRotation.exifOrientation(270, true, false))+ }++ @Test fun jpegExifInvertsRotationForAlreadyMirroredPixels() {+ // Processed (portrait/colour) bitmaps were flipped in sensor+ // space already: the tag carries rotate(-theta) and no flip.+ assertEquals(CaptureRotation.EXIF_NORMAL, CaptureRotation.exifOrientation(0, true, true))+ assertEquals(CaptureRotation.EXIF_ROTATE_270, CaptureRotation.exifOrientation(90, true, true))+ assertEquals(CaptureRotation.EXIF_ROTATE_180, CaptureRotation.exifOrientation(180, true, true))+ assertEquals(CaptureRotation.EXIF_ROTATE_90, CaptureRotation.exifOrientation(270, true, true))+ }++ @Test fun bakedFormatsCarryNoRotation() {+ // AVIF / night / pano pixels are baked upright: their+ // orientation is Normal, exactly what buildAvifExifTiff stamps.+ assertEquals(+ CaptureRotation.EXIF_NORMAL,+ CaptureRotation.exifOrientation(0, mirrored = false, pixelsAlreadyMirrored = false),+ )+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/CaptureRotationBakedTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/CaptureRotationBakedTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/CaptureRotationBakedTest.ktnew file mode 100644index 0000000000..66f56ff058--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/CaptureRotationBakedTest.kt@@ -0,0 +1,47 @@+package com.vayunmathur.camera.platform++import android.graphics.Bitmap+import android.graphics.Color+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * The baked-pixel convention (AVIF, night/pano RGB outputs): the+ * upright copy the AVIF encoder consumes must rotate sensor pixels+ * upright and, for an unmirrored front frame, flip them after the+ * rotation — the pixel equivalent of the raw EXIF flip tags.+ */[email protected](org.robolectric.annotation.GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CaptureRotationBakedTest {++ /** 2x1 bitmap: left pixel red, right pixel blue. */+ private fun twoPixelBitmap(): Bitmap {+ val bitmap = Bitmap.createBitmap(2, 1, Bitmap.Config.ARGB_8888)+ bitmap.setPixel(0, 0, Color.RED)+ bitmap.setPixel(1, 0, Color.BLUE)+ return bitmap+ }++ @Test fun quarterTurnSwapsDimensions() {+ val out = uprightCopy(twoPixelBitmap(), 90, 0)+ assertEquals(1, out.width)+ assertEquals(2, out.height)+ }++ @Test fun mirrorFlipsHorizontallyWithoutRotation() {+ val out = uprightCopy(twoPixelBitmap(), 0, 0, mirrored = true)+ assertEquals(Color.BLUE, out.getPixel(0, 0))+ assertEquals(Color.RED, out.getPixel(1, 0))+ }++ @Test fun unmirroredCopyKeepsPixelOrder() {+ val out = uprightCopy(twoPixelBitmap(), 0, 0)+ assertEquals(Color.RED, out.getPixel(0, 0))+ assertEquals(Color.BLUE, out.getPixel(1, 0))+ }+}