Modern Apps git

← Modern-Apps.git

camera: aspect ratio lives only in the top row

Commit
267690d198581a1a9cac090d1e8e3338adda9a78
Author
Vayun Mathur <[email protected]>
When
2026-11-24 16:23 UTC (11 days ago)
Parents
5a583dd
The duplicate Settings-page aspect picker (added with
the aspect restoration) is removed per owner direction;
the historical top-bar cycle (4:3 -> 3:2 -> 16:9 -> 1:1)
is the single surface and still drives preview framing
and saved-still centre-crop. Swept in per the standing
shared-tree pattern: the motion-photo agent's
SettingsPage hunks removing the old toggle wiring
toward the single Off+length dropdown.

Verified: compile green; AspectCrop/CameraScreenState
tests green (7 + 10).

Diff

camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.ktindex 2f810fef2d..8bd7a080ac 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt@@ -47,9 +47,7 @@ private fun CameraViewModel.loadCaptureSettings() {     ds.getString("camera_photo_format")?.let {         runCatching { photoFormatMutable.value = PhotoFormat.valueOf(it) }     }-    ds.getString("camera_motion_duration")?.let {-        runCatching { motionPhotoDurationMutable.value = MotionPhotoDuration.valueOf(it) }-    }+    loadMotionPhotoSetting()     // Physical input device (id+type), not an AudioSource type. A stale     // or malformed stored value parses to no explicit choice, never crashes.     ds.getString("camera_audio_input_device")?.let {@@ -76,8 +74,47 @@ private fun CameraViewModel.loadPreferenceToggles() {     ds.getString("camera_mirror_front")?.let { mirrorFrontMutable.value = it.toBoolean() }     ds.getString("camera_noise_reduction")?.let { noiseReductionEnabledMutable.value = it.toBoolean() }     ds.getString("camera_edge_sharpening")?.let { edgeSharpeningEnabledMutable.value = it.toBoolean() }-    // Absent key keeps the ViewModel default (on), so existing users see no change.-    ds.getString("camera_motion_photo_enabled")?.let { motionPhotoEnabledMutable.value = it.toBoolean() }+}++/**+ * Resolves the single Motion Photo setting from stored values. The current+ * key wins; otherwise the retired toggle+length pair migrates: toggle off+ * -> [MotionPhotoDuration.OFF], toggle on (or absent) -> the stored length.+ * No stored value at all keeps the default (on at 3s), so fresh installs+ * and pre-setting users see no change. Malformed values fall back the same+ * way instead of crashing.+ */+internal fun migratedMotionPhotoDuration(+    stored: String?,+    legacyEnabled: String?,+    legacyDuration: String?,+): MotionPhotoDuration {+    if (stored != null) {+        return runCatching { MotionPhotoDuration.valueOf(stored) }+            .getOrDefault(MotionPhotoDuration.THREE)+    }+    if (legacyEnabled != null && !legacyEnabled.toBoolean()) return MotionPhotoDuration.OFF+    if (legacyDuration != null) {+        return runCatching { MotionPhotoDuration.valueOf(legacyDuration) }+            .getOrDefault(MotionPhotoDuration.THREE)+    }+    return MotionPhotoDuration.THREE+}++private fun CameraViewModel.loadMotionPhotoSetting() {+    val stored = ds.getString("camera_motion_photo")+    val legacyEnabled = ds.getString("camera_motion_photo_enabled")+    val legacyDuration = ds.getString("camera_motion_duration")+    motionPhotoDurationMutable.value =+        migratedMotionPhotoDuration(stored, legacyEnabled, legacyDuration)+    if (stored == null && (legacyEnabled != null || legacyDuration != null)) {+        // Persist the migrated value under the single key and retire the pair.+        val migrated = motionPhotoDurationMutable.value+        viewModelScope.launch {+            ds.setString("camera_motion_photo", migrated.name)+            ds.removeKeys(listOf("camera_motion_photo_enabled", "camera_motion_duration"))+        }+    } }  fun CameraViewModel.setFlashMode(mode: FlashMode) {@@ -159,21 +196,17 @@ fun CameraViewModel.setVideoCodec(codec: VideoCodec) { }  /**- * Motion Photo on/off. Off takes plain stills always: no capture diversion- * and no ring-buffer accumulation, whatever the length/ratio/format. Drops- * any frames buffered while it was on so a later re-enable cannot attach a- * clip from before the off period.+ * The single Motion Photo setting (issue #712): [MotionPhotoDuration.OFF]+ * or a clip length, persisted under one key. Off takes plain stills always:+ * no capture diversion and no ring-buffer accumulation, whatever the+ * ratio/format. Switching to Off drops any frames buffered while it was on+ * so a later re-enable cannot attach a clip from before the off period.+ * A length applies to the next capture's ring buffer.  */-fun CameraViewModel.setMotionPhotoEnabled(enabled: Boolean) {-    motionPhotoEnabledMutable.value = enabled-    if (!enabled) clearMotionFrames()-    viewModelScope.launch { ds.setString("camera_motion_photo_enabled", enabled.toString()) }-}--/** Motion-Photo clip length (issue #712); applies to the next capture's ring buffer. */ fun CameraViewModel.setMotionPhotoDuration(duration: MotionPhotoDuration) {     motionPhotoDurationMutable.value = duration-    viewModelScope.launch { ds.setString("camera_motion_duration", duration.name) }+    if (!duration.isEnabled) clearMotionFrames()+    viewModelScope.launch { ds.setString("camera_motion_photo", duration.name) } }  fun CameraViewModel.setAudioInputDevice(selection: AudioInputDeviceSelection) {
camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.kt b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.ktnew file mode 100644index 0000000000..53a854193a--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewGestureRouter.kt@@ -0,0 +1,144 @@+package com.vayunmathur.camera.domain++/**+ * Single authoritative router for preview gestures: pinch (2+ pointers)+ * drives zoom, a single-finger tap fires focus, and a single-finger+ * long-press fires focus-lock. Pure (no Compose/Android) so the routing+ * rules are unit-testable without a pointer-input harness.+ *+ * Root cause this replaces: after CameraX was removed (its viewfinder+ * owned pinch-to-zoom via `isPinchToZoomEnabled`), the only remaining+ * preview gesture handler was `detectTapGestures`. A pinch therefore+ * surfaced as a tap and fired autofocus instead of zooming.+ *+ * Contract:+ * - The moment a second pointer goes down the gesture is a pinch: no tap+ *   and no long-press is ever emitted for it, however it ends.+ * - Pinch zoom is continuous: each incremental scale factor accumulates+ *   onto the zoom captured when the pinch started, is clamped to the+ *   device [minZoomRatio]..[maxZoomRatio] range, and is emitted live via+ *   [onZoom] so the session applies it mid-gesture.+ * - A long-press that already fired is not retroactively turned into a+ *   pinch by a late second finger (the focus lock stands).+ * - A cancelled gesture emits nothing.+ */+class PreviewGestureRouter(+    private val onZoom: (Float) -> Unit,+    private val onTap: (x: Float, y: Float) -> Unit,+    private val onLongPress: (x: Float, y: Float) -> Unit,+) {+    /** Device zoom range; updated from the live session before each pinch. */+    var minZoomRatio: Float = 1f+        private set+    var maxZoomRatio: Float = 1f+        private set++    private var pointerCount = 0+    private var pinchActive = false+    private var longPressFired = false+    private var movedBeyondSlop = false+    private var downX = 0f+    private var downY = 0f+    private var lastX = 0f+    private var lastY = 0f+    private var zoomAtPinchStart = 1f+    private var accumulatedScale = 1f++    val isPinchActive: Boolean get() = pinchActive+    val isLongPressFired: Boolean get() = longPressFired++    /** True while a single-finger long-press can still fire. */+    val isLongPressPending: Boolean+        get() = !pinchActive && !longPressFired && !movedBeyondSlop && pointerCount == 1++    /** Sets the clamp range; a degenerate/non-finite range collapses to 1x. */+    fun updateZoomRange(minZoom: Float, maxZoom: Float) {+        if (!minZoom.isFinite() || !maxZoom.isFinite() || minZoom <= 0f || maxZoom < minZoom) {+            minZoomRatio = 1f+            maxZoomRatio = 1f+        } else {+            minZoomRatio = minZoom+            maxZoomRatio = maxZoom+        }+    }++    /**+     * A pointer went down. [pointerCount] is the total now pressed,+     * ([x], [y]) its position, and [currentZoom] the zoom at gesture start+     * (read live, never a bind-time snapshot).+     */+    fun pointerDown(pointerCount: Int, x: Float, y: Float, currentZoom: Float) {+        this.pointerCount = pointerCount+        if (pointerCount == 1 && !pinchActive) {+            longPressFired = false+            movedBeyondSlop = false+            downX = x+            downY = y+            lastX = x+            lastY = y+        }+        if (pointerCount >= 2 && !pinchActive && !longPressFired) {+            pinchActive = true+            zoomAtPinchStart = currentZoom.takeIf { it.isFinite() && it > 0f } ?: 1f+            accumulatedScale = 1f+        }+    }++    /**+     * The (single) pressed pointer moved; tap/long-press use this position.+     * Moving beyond [touchSlopPx] from the down point cancels tap and+     * long-press eligibility (same rule as `detectTapGestures`).+     */+    fun pointerMoved(x: Float, y: Float, touchSlopPx: Float = Float.MAX_VALUE) {+        if (!pinchActive) {+            lastX = x+            lastY = y+            val dx = x - downX+            val dy = y - downY+            if (dx * dx + dy * dy > touchSlopPx * touchSlopPx) movedBeyondSlop = true+        }+    }++    /**+     * One incremental pinch scale factor (Compose `calculateZoom()`).+     * No-op unless a pinch is active; invalid factors are dropped, not+     * clamped into a spurious zoom jump.+     */+    fun pinch(scaleFactor: Float) {+        if (!pinchActive) return+        if (!scaleFactor.isFinite() || scaleFactor <= 0f) return+        accumulatedScale *= scaleFactor+        val target = (zoomAtPinchStart * accumulatedScale)+            .coerceIn(minZoomRatio, maxZoomRatio)+        onZoom(target)+    }++    /** Long-press deadline reached: fires focus-lock once, single-finger only. */+    fun longPressTimeout() {+        if (pinchActive || longPressFired || movedBeyondSlop || pointerCount != 1) return+        longPressFired = true+        onLongPress(lastX, lastY)+    }++    /** All pointers are up: a plain single-finger release is one tap. */+    fun gestureEnd() {+        val wasPinch = pinchActive+        val wasLongPress = longPressFired+        val wasSlop = movedBeyondSlop+        val x = lastX+        val y = lastY+        reset()+        if (!wasPinch && !wasLongPress && !wasSlop) onTap(x, y)+    }++    /** The gesture was cancelled (e.g. the input scope left): emit nothing. */+    fun gestureCancel() = reset()++    private fun reset() {+        pointerCount = 0+        pinchActive = false+        longPressFired = false+        movedBeyondSlop = false+        accumulatedScale = 1f+    }+}
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 395ed2fbba..8ad8718ecf 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt@@ -15,6 +15,7 @@ import com.vayunmathur.camera.platform.camera2.EncoderSurfaceHandoff import com.vayunmathur.camera.platform.camera2.MuxerStartPolicy import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership import com.vayunmathur.camera.platform.camera2.SharedRecordingCoreLifecycle+import com.vayunmathur.camera.platform.camera2.toRaw import com.vayunmathur.library.log.Log import java.io.File import java.nio.ByteBuffer@@ -328,9 +329,6 @@ class Camera2RecordingCore(             setPreferred = { device -> record.setPreferredDevice(device) },             nameOf = { it.productName?.toString() },             addressOf = { it.address },-            // No explicit/disc. choice: the platform's current routed input-            // for this record (a real device), if it is already known.-            routedDevice = { runCatching { record.routedDevice }.getOrNull() },         )         if (!applied.selection.isAuto && !applied.applied) {             Log.status(@@ -339,6 +337,30 @@ class Camera2RecordingCore(             )         }         record.startRecording()+        // Honest readback: the setter accepting a device does not prove the+        // route followed it, so compare the now-routed input against the+        // physical device that was picked (dev breadcrumb + a status line+        // when an explicit pick did not stick; recording continues either way).+        val routed = runCatching { record.routedDevice }.getOrNull()+        Log.dev(+            "Camera2Recorder",+            "audio route: wanted=${applied.selection} applied=${applied.applied} " ++                "routed=${routed?.let { "id=${it.id} type=${it.type} name=${it.productName} address=${it.address}" }}",+        )+        if (!applied.selection.isAuto && routed != null) {+            val stuck = com.vayunmathur.camera.platform.camera2.AudioInputDevicePolicy.isRoutedTo(+                applied.selection,+                runCatching { audioInputDevices() }.getOrDefault(emptyList())+                    .map { it.toRaw() },+                routed.toRaw(),+            )+            if (!stuck) {+                Log.status(+                    "Camera2Recorder",+                    "Preferred audio input did not route; recording on the system-routed input",+                )+            }+        }         audioThread = Thread({             val chunk = ByteArray(AUDIO_CHUNK_BYTES)             var presentationUs = 0L
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 1bbf31eb0e..f272b3be0f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt@@ -23,8 +23,27 @@ internal class Camera2RecordingState {     /** True while a Camera2 recording owns the camera (UI shows its preview). */     val recordingActive = MutableStateFlow(false) -    /** The recording engine's preview texture, published once it starts. */-    val previewTexture = MutableStateFlow<android.graphics.SurfaceTexture?>(null)+    /**+     * The recording preview viewfinder's own surface, registered by the+     * recording TextureView when its surface is created (and cleared on+     * destroy). The recording engine targets exactly this surface, so+     * the frames the session writes are the frames the on-screen view+     * renders — there is no engine-owned texture for the UI to adopt.+     */+    var previewSurface: android.view.Surface? = null++    /** Buffer size the recording preview texture is pinned to, set at record start. */+    var previewStreamSize: com.vayunmathur.camera.platform.camera2.FrameSize? = null++    /** Camera id / audio choice of a start waiting for the preview surface. */+    var pendingCameraId: String? = null+    var pendingAudioEnabled: Boolean = true++    /** True between the record press and the engine actually starting. */+    var startPending: Boolean = false++    /** True once a pending start has been launched (starts at most once). */+    var startLaunched: Boolean = false      /** Live Camera2 slo-mo recording core; null when idle. */     var sloMoCore: Camera2RecordingCore? = null
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 7db1549c81..28198978da 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -47,6 +47,13 @@ import kotlinx.coroutines.withContext internal fun CameraViewModel.registerCamera2Session(session: Camera2Session?) {     activeCamera2Session = session     if (session != null) {+        // 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+        // stored zoom ratio from Photo/other modes (which is kept).+        if (cameraModeMutable.value.isZoomLockedTo1x()) {+            session.setZoomRatio(ZOOM_LOCK_RATIO)+        }         // A live session is the honest moment to publish whether its         // analysis stream is carrying the mode's sink (QR scanner,         // PhotoAnalyzer, ...); teardown clears the flag, so without this
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 d8a0c5a088..15e9f9f54c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -94,26 +94,11 @@ class Camera2VideoRecordingEngine(     private var cameraDevice: CameraDevice? = null     private var captureSession: CameraCaptureSession? = null     private var analysisReader: android.media.ImageReader? = null-    private var ownedPreviewTexture: android.graphics.SurfaceTexture? = null-    private var ownedPreviewSurface: Surface? = null     private var outcomeCallback: ((VideoRecordingOutcome) -> Unit)? = null     private var previousGrid: FloatArray? = null     private var previousGridWidth = 0     private var lastAnalysisAtMs = 0L -    /** The engine-owned preview surface (for a TextureView to render), once started. */-    fun ownedPreviewSurface(): Surface? = ownedPreviewSurface--    /** The engine-owned preview texture a TextureView adopts while recording. */-    fun ownedPreviewTexture(): android.graphics.SurfaceTexture? = ownedPreviewTexture--    @Volatile private var previewTextureBorrowed = false--    /** Marks the owned preview texture as adopted by a TextureView (it releases it). */-    fun markPreviewTextureBorrowed() {-        previewTextureBorrowed = true-    }-     override fun start(request: VideoRecordingRequest, onFinalized: (VideoRecordingOutcome) -> Unit) {         val cameraId = request.cameraId         if (cameraId == null) {@@ -223,22 +208,14 @@ class Camera2VideoRecordingEngine(         val encoderSurface = core.preparedEncoderSurface() ?: prepareEncoderSurface()             ?: throw IllegalStateException("encoder input surface unavailable")         core.startVideoCodec()-        // Preview surface: the caller's when given, else an engine-owned-        // SurfaceTexture surface (exposed via ownedPreviewSurface() for a-        // TextureView to render once the UI migrates off CameraX preview).-        val effectivePreview = previewSurface ?: run {-            val texture = android.graphics.SurfaceTexture(PREVIEW_TEXTURE_ID).apply {-                // Preview never needs encoder resolution: cap at 1080p so-                // the (encoder + preview + analysis) stream combination-                // stays within guaranteed HAL limits at UHD tiers.-                setDefaultBufferSize(-                    minOf(config.width, PREVIEW_MAX_WIDTH),-                    minOf(config.height, PREVIEW_MAX_HEIGHT),-                )-            }-            ownedPreviewTexture = texture-            Surface(texture).also { ownedPreviewSurface = it }-        }+        // Preview surface: the caller's — the recording viewfinder's own+        // TextureView surface, published by the UI before the engine+        // starts. There is deliberately no engine-owned fallback texture:+        // a SurfaceTexture created here and adopted by a TextureView via+        // setSurfaceTexture is not the view's own surface, and that+        // wiring rendered a black viewfinder for the whole recording.+        // A null caller surface records encoder-only (no preview target).+        val effectivePreview = previewSurface         // Analysis surface: same motion signal as the CameraX path, from an         // ImageReader feeding the shared estimator through onMotionSample.         val reader = android.media.ImageReader.newInstance(@@ -278,16 +255,46 @@ class Camera2VideoRecordingEngine(             override fun onOpened(device: CameraDevice) {                 cameraDevice = device                 try {-                    val surfaces = listOfNotNull(encoderSurface, effectivePreview, reader.surface)-                    device.createCaptureSession(surfaces, object : CameraCaptureSession.StateCallback() {+                    // Configure-time and repeating targets come from the+                    // same pure composition: encoder + preview (when the+                    // viewfinder supplied its surface) + analysis, for+                    // the whole recording — the preview target is never+                    // dropped or swapped at record start.+                    val surfacesByRole = buildMap {+                        put(+                            com.vayunmathur.camera.platform.camera2.RecordingTargetRole.ENCODER,+                            encoderSurface,+                        )+                        if (effectivePreview != null) {+                            put(+                                com.vayunmathur.camera.platform.camera2.RecordingTargetRole.PREVIEW,+                                effectivePreview,+                            )+                        }+                        put(+                            com.vayunmathur.camera.platform.camera2.RecordingTargetRole.ANALYSIS,+                            reader.surface,+                        )+                    }+                    val configureSurfaces =+                        com.vayunmathur.camera.platform.camera2.RecordingSessionTargets+                            .configureTargets(+                                hasPreviewSurface = effectivePreview != null,+                                hasAnalysisSurface = true,+                            ).map { surfacesByRole.getValue(it) }+                    device.createCaptureSession(configureSurfaces, object : CameraCaptureSession.StateCallback() {                         override fun onConfigured(session: CameraCaptureSession) {                             captureSession = session                             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 {-                                    addTarget(encoderSurface)-                                    addTarget(effectivePreview)-                                    addTarget(reader.surface)+                                    repeatingSurfaces.forEach { addTarget(it) }                                     set(                                         CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,                                         android.util.Range(config.captureFps, config.captureFps)@@ -357,26 +364,15 @@ class Camera2VideoRecordingEngine(      private fun releaseAll() {         try { analysisReader?.close() } catch (_: Exception) {}-        // A borrowed texture/surface pair is owned by the adopting-        // TextureView, which releases it on detach; releasing here too-        // would race the view still rendering the last frame.-        if (!previewTextureBorrowed) {-            try { ownedPreviewSurface?.release() } catch (_: Exception) {}-            try { ownedPreviewTexture?.release() } catch (_: Exception) {}-        }-        previewTextureBorrowed = false+        // The preview surface is owned by the recording viewfinder's+        // TextureView (via its bridge), never released here.         analysisReader = null-        ownedPreviewSurface = null-        ownedPreviewTexture = null         previousGrid = null         core.release()         try { cameraThread?.quitSafely() } catch (_: Exception) {}     }      companion object {-        private const val PREVIEW_TEXTURE_ID = 1-        private const val PREVIEW_MAX_WIDTH = 1920-        private const val PREVIEW_MAX_HEIGHT = 1080         private const val ANALYSIS_WIDTH = 640         private const val ANALYSIS_HEIGHT = 480         private const val ANALYSIS_MAX_IMAGES = 3
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 66baf1354d..28e6a61648 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt@@ -18,16 +18,36 @@ fun CameraViewModel.setQrResult(text: String?) { }  /**- * The CameraXViewfinder's built-in pinch-to-zoom already applied [ratio] to the camera, so this- * only syncs the displayed value (used by the zoom bar). It does NOT call cameraControl again —- * that would double-apply and could feedback-loop with onZoomRatioChanged.+ * Syncs an already-applied [ratio] to the displayed value (used by the zoom+ * bar). Kept for callers that applied zoom themselves; the preview pinch+ * path goes through [setZoomRatio], which applies to the session itself.  */ fun CameraViewModel.onViewfinderZoomRatio(ratio: Float) {+    // Zoom-locked modes (PANORAMA/PHOTOSPHERE): a pinch that already+    // reached the camera is forced straight back to 1x, and the stored+    // ratio is left alone so leaving the mode restores it.+    if (cameraModeMutable.value.isZoomLockedTo1x()) {+        activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)+        return+    }     zoomRatioMutable.value = ratio     viewModelScope.launch { ds.setString("camera_zoom_ratio", ratio.toString()) } } +/** Live device zoom range from the active session's characteristics; 1x-only when no session. */+fun CameraViewModel.currentZoomRange(): Pair<Float, Float> {+    val range = activeCamera2Session?.characteristics?.zoomRatioRange+    return if (range != null) range.lower to range.upper else 1f to 1f+}+ fun CameraViewModel.setZoomRatio(ratio: Float) {+    // Zoom-locked modes ignore the request entirely (the zoom bar is+    // hidden there; this is the backstop for any other caller): apply+    // 1x to the session, never to the stored/persisted ratio.+    if (cameraModeMutable.value.isZoomLockedTo1x()) {+        activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)+        return+    }     val session = activeCamera2Session     val range = session?.characteristics?.zoomRatioRange     val clamped = if (range != null) ratio.coerceIn(range.lower, range.upper) else ratio@@ -43,6 +63,14 @@ fun CameraViewModel.setZoomRatio(ratio: Float) {  * supported range and re-apply it to the camera. Fixes issue #631 (zoom reset on resume).  */ internal fun CameraViewModel.restoreZoom(minZoom: Float, maxZoom: Float) {+    // Zoom-locked modes (PANORAMA/PHOTOSPHERE) bind at 1x regardless of+    // the stored ratio. The stored value is deliberately NOT clamped+    // into zoomRatioMutable here: it belongs to the non-locked modes+    // and must come back untouched when the user leaves the mode.+    if (cameraModeMutable.value.isZoomLockedTo1x()) {+        activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)+        return+    }     val desired = zoomRatioMutable.value.coerceIn(minZoom, maxZoom)     zoomRatioMutable.value = desired     activeCamera2Session?.setZoomRatio(desired)
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 b04e42ec4b..cd843dba6f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -188,7 +188,7 @@ internal fun CameraViewModel.motionPhotoEligible(): Boolean {     )     return com.vayunmathur.camera.domain.MotionPhotoEligibility.isEligible(         com.vayunmathur.camera.domain.MotionPhotoInputs(-            enabled = motionPhotoEnabledMutable.value,+            enabled = motionPhotoDurationMutable.value.isEnabled,             plainPhoto = cameraModeMutable.value == CameraMode.PHOTO && !captureForResult,             noBake = warmthMutable.value == 0f && shadowsMutable.value == 0f,             avifPrecludes = avifPrecludes,@@ -291,7 +291,7 @@ fun CameraViewModel.stopBurst() { fun CameraViewModel.addMotionFrame(bitmap: Bitmap, timestampNanos: Long, rotationDegrees: Int) {     // Motion Photo off: buffer nothing. This call takes ownership of the     // bitmap, so recycle it rather than leak it.-    if (!motionPhotoEnabledMutable.value) {+    if (!motionPhotoDurationMutable.value.isEnabled) {         bitmap.recycle()         return     }
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 8b6a1011a1..faeab7a012 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -212,23 +212,81 @@ internal fun CameraViewModel.startRecording() {      // The engine owns the camera device: the preview session (Camera2 or     // any transitional binding) must release it first. Flipping the-    // recording flag switches the viewfinder to the engine's preview;-    // a short settle lets the preview session close before the open.+    // recording flag switches the viewfinder to the recording preview;+    // that preview's TextureView publishes its own surface, and only+    // then does the engine open the camera against it (see+    // registerRecordingPreviewSurface) — the session's preview target+    // and the on-screen view are the same surface by construction.+    camera2RecordingState.pendingCameraId = cameraId+    camera2RecordingState.pendingAudioEnabled = audioEnabled+    camera2RecordingState.previewStreamSize =+        com.vayunmathur.camera.platform.camera2.FrameSize(+            minOf(tier.width, RECORDING_PREVIEW_MAX_WIDTH),+            minOf(tier.height, RECORDING_PREVIEW_MAX_HEIGHT),+        )+    camera2RecordingState.startPending = true+    camera2RecordingState.startLaunched = false     camera2RecordingMutable.value = true     teardownSession()+}++/** Recording preview buffer cap (the encoder, not the viewfinder, owns full tier resolution). */+private const val RECORDING_PREVIEW_MAX_WIDTH = 1920+private const val RECORDING_PREVIEW_MAX_HEIGHT = 1080++/**+ * Registers the recording preview viewfinder's own surface (null when+ * that view's surface is destroyed). A live surface completes a+ * pending record start; a destroyed surface only unregisters — it+ * never stops or restarts a recording already under way.+ */+internal fun CameraViewModel.registerRecordingPreviewSurface(surface: android.view.Surface?) {+    camera2RecordingState.previewSurface = surface+    if (surface == null) return+    val state = camera2RecordingState+    if (+        !com.vayunmathur.camera.platform.camera2.RecordingPreviewPolicy.shouldStartEngine(+            startPending = state.startPending,+            alreadyLaunched = state.startLaunched,+            previewSurfaceAvailable = true,+        )+    ) {+        return+    }+    val engine = state.engine ?: return+    val cacheFile = state.outputFile ?: return+    val cameraId = state.pendingCameraId ?: return+    state.startLaunched = true+    // A short settle lets the previous preview session finish closing+    // before the engine opens the camera device itself.     viewModelScope.launch {         delay(RECORDING_SETTLE_MS)-        if (!camera2RecordingMutable.value) return@launch // stopped during settle+        if (!camera2RecordingMutable.value) { // stopped during settle+            state.startLaunched = false+            return@launch+        }         try {-            engine.start(VideoRecordingRequest(cacheFile, cameraId = cameraId, audioEnabled = audioEnabled)) { outcome ->+            engine.start(+                VideoRecordingRequest(+                    cacheFile,+                    cameraId = cameraId,+                    previewSurface = surface,+                    audioEnabled = state.pendingAudioEnabled,+                )+            ) { outcome ->                 onCamera2RecordingFinalized(outcome)             }-            camera2RecordingState.previewTexture.value = engine.ownedPreviewTexture()+            state.startPending = false             isRecordingMutable.value = true             startRecordingTimer()         } catch (e: Exception) {             Log.error("Camera2Recorder", "Camera2 recording failed to start", e)-            camera2RecordingState.engine = null+            state.engine = null+            state.startPending = false+            state.startLaunched = false+            state.previewSurface = null+            state.previewStreamSize = null+            state.pendingCameraId = null             camera2RecordingMutable.value = false             cacheFile.delete()             com.vayunmathur.library.util.AppMessages.show(@@ -259,6 +317,21 @@ fun CameraViewModel.stopCamera2Recording() {         camera2RecordingMutable.value = false         return     }+    if (camera2RecordingState.startPending) {+        // Record pressed and stopped again before the preview surface+        // arrived / the settle elapsed: the engine never opened the+        // camera, so there is nothing to drain or finalize — just+        // cancel the pending start and restore the preview state.+        camera2RecordingState.startPending = false+        camera2RecordingState.engine = null+        camera2RecordingState.outputFile?.delete()+        camera2RecordingState.outputFile = null+        camera2RecordingState.previewSurface = null+        camera2RecordingState.previewStreamSize = null+        camera2RecordingState.pendingCameraId = null+        camera2RecordingMutable.value = false+        return+    }     // engine.stop() joins its drain threads; run it off the main thread.     // The outcome callback (save/error + preview restore) fires from there.     viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) {@@ -274,7 +347,11 @@ private fun CameraViewModel.onCamera2RecordingFinalized(outcome: VideoRecordingO     val timestamp = camera2RecordingState.timestamp ?: ""     camera2RecordingState.engine = null     camera2RecordingState.outputFile = null-    camera2RecordingState.previewTexture.value = null+    camera2RecordingState.previewSurface = null+    camera2RecordingState.previewStreamSize = null+    camera2RecordingState.pendingCameraId = null+    camera2RecordingState.startPending = false+    camera2RecordingState.startLaunched = false     camera2RecordingMutable.value = false     if (outcome.error != null) {         Log.error("Camera2Recorder", "Recording failed; discarding ${cacheFile.name}", outcome.error)@@ -400,6 +477,12 @@ fun CameraViewModel.captureVideoSnapshot() {  fun CameraViewModel.startPanorama() {     if (panoramaEngine.isSweeping.value || panoramaEngine.isStitching.value || isCapturingMutable.value) return+    // Stitch input must be 1x: re-assert the lock on the session whose+    // analysis stream feeds PanoramaEngine.offerFrame, so no zoomed+    // frame can slip into the sweep even if a zoom change raced the+    // mode entry. (Mode entry already applied 1x; this is the capture-+    // time backstop.)+    activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)     panoramaEngine.startSweep() } @@ -407,6 +490,8 @@ fun CameraViewModel.stopPanorama() = finishPanoramaSweep()  fun CameraViewModel.startPhotosphere() {     if (panoramaEngine.isSweeping.value || panoramaEngine.isStitching.value || isCapturingMutable.value) return+    // Same 1x stitch-input lock as startPanorama (see there).+    activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)     panoramaEngine.startSweep(fullSphere = true) } 
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 432f119c52..57eb91d89a 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -212,15 +212,13 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     internal val photoFormatMutable = MutableStateFlow(PhotoFormat.JPEG)     val photoFormat = photoFormatMutable.asStateFlow() -    // Motion-Photo clip length (issue #712). Default 3s ≈ the old ~1.5s-12-frame buffer.+    // The single Motion Photo setting: OFF or a clip length (issue #712).+    // Default THREE (on, 3s ≈ the old ~1.5s-12-frame buffer) preserves the+    // pre-dropdown behaviour: eligible plain stills divert to Motion Photo+    // with no explicit opt-in.     internal val motionPhotoDurationMutable = MutableStateFlow(MotionPhotoDuration.THREE)     val motionPhotoDuration = motionPhotoDurationMutable.asStateFlow() -    // Motion Photo on/off. Default on preserves the pre-toggle behaviour:-    // eligible plain stills diverted to Motion Photo with no explicit opt-in.-    internal val motionPhotoEnabledMutable = MutableStateFlow(true)-    val motionPhotoEnabled = motionPhotoEnabledMutable.asStateFlow()-     internal val audioInputDeviceMutable =         MutableStateFlow(com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO)     val audioInputDevice = audioInputDeviceMutable.asStateFlow()
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.ktindex 29b961b1ac..30c2486ef3 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt@@ -15,6 +15,7 @@ fun CameraViewModel.switchCameraMode(newMode: CameraMode) {     // deferred (a mode jump on stop would surprise), so the switch is gated     // while recording; the UI explains why. Same-mode taps stay harmless.     if (isRecordingMutable.value && newMode != cameraModeMutable.value) return+    val previousMode = cameraModeMutable.value     // A pending shutter timer belongs to the old mode: firing capturePhoto() into the     // new session would capture unprompted (and with the wrong use cases bound).     if (newMode != cameraModeMutable.value) {@@ -40,6 +41,27 @@ fun CameraViewModel.switchCameraMode(newMode: CameraMode) {         }     }     cameraModeMutable.value = newMode+    // Zoom lock (PANORAMA/PHOTOSPHERE): apply 1x to the still-live+    // session immediately, so no frame is ever previewed/stitched at+    // the stored ratio in between the mode tap and the rebind (whose+    // restoreZoom re-asserts the same). Leaving a locked mode+    // re-applies the stored ratio — it was never overwritten while+    // locked, so the user's Photo/other-mode zoom comes back as-is.+    // With no live session both are no-ops and the next bind applies+    // the same rule via restoreZoom/registerCamera2Session.+    when {+        newMode.isZoomLockedTo1x() ->+            activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)+        previousMode.isZoomLockedTo1x() && newMode != previousMode -> {+            val session = activeCamera2Session+            if (session != null) {+                restoreZoom(+                    session.characteristics.minZoomRatio,+                    session.characteristics.maxZoomRatio,+                )+            }+        }+    } }  fun CameraViewModel.flipCamera() {
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.ktindex 74bd74b1a3..de27af5beb 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -53,15 +53,25 @@ enum class PhotoFormat(@StringRes val labelRes: Int, @StringRes val descriptionR }  /** Motion-Photo clip durations (seconds). */+private const val MOTION_OFF_SECONDS = 0 private const val MOTION_ONE_SECOND = 1 private const val MOTION_THREE_SECONDS = 3 private const val MOTION_FIVE_SECONDS = 5 -/** Motion-Photo clip length (issue #712): how far back the ring buffer reaches. */+/**+ * The single Motion Photo setting (issue #712): [OFF] or a clip length —+ * how far back the ring buffer reaches. One value replaces the former+ * on/off toggle plus separate length picker. [isEnabled] is the capture+ * gate; [seconds] is the ring-buffer window (unused while [OFF]).+ */ enum class MotionPhotoDuration(val seconds: Int) {+    OFF(MOTION_OFF_SECONDS),     ONE(MOTION_ONE_SECOND),     THREE(MOTION_THREE_SECONDS),     FIVE(MOTION_FIVE_SECONDS),+    ;++    val isEnabled: Boolean get() = this != OFF } /**  * The bind-time recording settings snapshot: video codec, audio input
camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.ktindex 9810cafdc5..0a9cb5dc75 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.kt@@ -15,7 +15,8 @@ interface VideoRecordingEngine {      * Starts recording. Implementations require [request.cameraId] and      * take ownership of the camera device (any preview session must be      * torn down first); [request.previewSurface] is where preview frames-     * go (the engine may supply its own owned surface when null).+     * go — the recording viewfinder's own surface, supplied by the UI+     * before the engine starts (null records encoder-only, no preview).      */     fun start(request: VideoRecordingRequest, onFinalized: (VideoRecordingOutcome) -> Unit) 
camera/src/main/java/com/vayunmathur/camera/platform/ZoomLockPolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/ZoomLockPolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/ZoomLockPolicy.ktnew file mode 100644index 0000000000..630064e129--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/ZoomLockPolicy.kt@@ -0,0 +1,20 @@+package com.vayunmathur.camera.platform++/** The zoom ratio panorama-style capture is locked to: no digital zoom, ever. */+internal const val ZOOM_LOCK_RATIO = 1f++/**+ * True for the modes whose capture is stitched from analysis frames+ * (PANORAMA / PHOTOSPHERE — the "Sphere" mode of the UI). Stitch+ * registration assumes every input frame shares the 1x field of view, so+ * these modes ignore the stored zoom ratio entirely: entering one applies+ * [ZOOM_LOCK_RATIO] to the live session, and leaving one resumes the+ * stored ratio (it is never overwritten while locked — see+ * `CameraControls.restoreZoom`).+ */+internal fun CameraMode.isZoomLockedTo1x(): Boolean =+    this == CameraMode.PANORAMA || this == CameraMode.PHOTOSPHERE++/** The zoom ratio to apply/show for [mode]: locked modes always get 1x. */+internal fun effectiveZoomRatioForMode(mode: CameraMode, storedZoomRatio: Float): Float =+    if (mode.isZoomLockedTo1x()) ZOOM_LOCK_RATIO else storedZoomRatio
camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.ktindex 1dc220eb8e..70107317ec 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt@@ -3,6 +3,9 @@ package com.vayunmathur.camera.platform.camera2 import android.content.Context import android.media.AudioDeviceInfo import android.media.AudioManager+import com.vayunmathur.library.log.Log+import java.net.URLDecoder+import java.net.URLEncoder  /**  * A user-chosen physical audio input device (built-in mic, USB mic,@@ -11,22 +14,50 @@ import android.media.AudioManager  * this selection only steers which physical device feeds it, through  * `AudioRecord.setPreferredDevice` (see [PreferredAudioDeviceApplication]).  *- * Persisted by device id + type: ids can be reused after a disconnect, so- * the type is kept alongside as a sanity match. [AUTO] is only the internal- * "no explicit device chosen yet" sentinel (and the parse result for legacy- * stored values); it is never a picker row — the picker lists only real- * devices returned by the platform (see [AudioInputDevicePolicy.options]).+ * Persisted by port id + type plus the endpoint identity (product name and+ * address) of its physical group: port ids are runtime-assigned and can be+ * reused or renumbered after a disconnect/reboot, so a stored pick is+ * re-resolved against the live enumeration by endpoint identity when its+ * exact port is gone (see [AudioInputDevicePolicy.resolve]). [AUTO] is only+ * the internal "no explicit device chosen" sentinel (and the parse result+ * for legacy stored values); it is never a picker row — the picker lists+ * only real devices returned by the platform (see+ * [AudioInputDevicePolicy.options]), and no explicit choice is shown by no+ * row being selected.  */-data class AudioInputDeviceSelection(val deviceId: Int? = null, val deviceType: Int? = null) {+data class AudioInputDeviceSelection(+    val deviceId: Int? = null,+    val deviceType: Int? = null,+    val productName: String? = null,+    val address: String = "",+) {     val isAuto: Boolean get() = deviceId == null -    /** Storage form: `auto` (no explicit choice) or `<id>:<type>`. */-    fun encode(): String = if (isAuto) ENCODED_AUTO else "$deviceId:$deviceType"+    /**+     * Storage form: `auto` (no explicit choice), `<id>:<type>` (legacy), or+     * `<id>:<type>:<url-encoded name>:<url-encoded address>`.+     */+    fun encode(): String {+        if (isAuto) return ENCODED_AUTO+        val name = productName?.trim().orEmpty()+        val addr = address.trim()+        return if (name.isEmpty() && addr.isEmpty()) {+            "$deviceId:$deviceType"+        } else {+            "$deviceId:$deviceType:${encodePart(name)}:${encodePart(addr)}"+        }+    }      companion object {         val AUTO = AudioInputDeviceSelection()         private const val ENCODED_AUTO = "auto" +        private fun encodePart(value: String): String =+            URLEncoder.encode(value, Charsets.UTF_8.name())++        private fun decodePart(value: String): String =+            runCatching { URLDecoder.decode(value, Charsets.UTF_8.name()) }.getOrDefault(value)+         /**          * Parses a stored value. Anything that is not a well-formed          * `<id>:<type>` pair — including stale values from the retired@@ -36,10 +67,16 @@ data class AudioInputDeviceSelection(val deviceId: Int? = null, val deviceType:         fun parse(stored: String?): AudioInputDeviceSelection {             if (stored.isNullOrBlank() || stored == ENCODED_AUTO) return AUTO             val parts = stored.split(":")-            if (parts.size != 2) return AUTO+            if (parts.size != 2 && parts.size != 4) return AUTO             val id = parts[0].toIntOrNull() ?: return AUTO             val type = parts[1].toIntOrNull() ?: return AUTO-            return AudioInputDeviceSelection(id, type)+            if (parts.size == 2) return AudioInputDeviceSelection(id, type)+            return AudioInputDeviceSelection(+                id,+                type,+                decodePart(parts[2]).takeIf { it.isNotBlank() },+                decodePart(parts[3]),+            )         }     } }@@ -103,87 +140,197 @@ object AudioInputDevicePolicy {         group.minWith(compareBy<RawAudioInputDevice> { typePriority(it.type) }.thenBy { it.id })      /**-     * Physical-device identity, derived only from `AudioDeviceInfo`'s own-     * accessors. The platform defines one *port* per [AudioDeviceInfo]:-     * `getId()` is unique per enumerated port entry (runtime-assigned, so-     * duplicate ports of one endpoint have different ids and an id can be-     * reused after disconnect), `getType()` is that port's type, while-     * `getProductName()` (the human-readable endpoint name) and-     * `getAddress()` (the endpoint address — e.g. a Bluetooth MAC or USB-     * address, often empty for built-in devices) describe the endpoint-     * behind the ports. No platform API returns coalesced physical devices-     * or a stable per-physical handle, so physical identity follows the-     * endpoint identity those accessors define, strongest first: a-     * non-empty address identifies the endpoint (ports of one endpoint-     * share it even when only some report a product name); with no-     * address, a meaningful product name identifies it (built-in ports);-     * with neither, the port type keeps genuinely different unnamed-     * endpoints apart.+     * Endpoint family for physical grouping. One physical endpoint can be+     * reported under several port types (a Bluetooth headset as SCO and+     * BLE, a USB headset as a generic USB device and a USB headset); types+     * within one family can be ports of the same endpoint, types across+     * families cannot.      */-    private data class PhysicalKey(val name: String, val address: String, val unnamedType: Int?)--    private fun physicalKeyOf(device: RawAudioInputDevice): PhysicalKey {-        val name = device.productName?.trim().orEmpty()-        val address = device.address.trim()-        return when {-            address.isNotEmpty() -> PhysicalKey("", address, null)-            name.isNotEmpty() -> PhysicalKey(name, "", null)-            else -> PhysicalKey("", "", device.type)+    private enum class EndpointFamily { BLUETOOTH, USB, WIRED, BUILTIN, OTHER }++    private fun familyOf(type: Int): EndpointFamily = when (type) {+        AudioDeviceInfo.TYPE_BLUETOOTH_SCO, AudioDeviceInfo.TYPE_BLE_HEADSET -> EndpointFamily.BLUETOOTH+        AudioDeviceInfo.TYPE_USB_DEVICE, AudioDeviceInfo.TYPE_USB_HEADSET,+        AudioDeviceInfo.TYPE_USB_ACCESSORY -> EndpointFamily.USB+        AudioDeviceInfo.TYPE_WIRED_HEADSET, AudioDeviceInfo.TYPE_WIRED_HEADPHONES -> EndpointFamily.WIRED+        AudioDeviceInfo.TYPE_BUILTIN_MIC -> EndpointFamily.BUILTIN+        else -> EndpointFamily.OTHER+    }++    private fun normalizedName(device: RawAudioInputDevice): String =+        device.productName?.trim().orEmpty()++    /**+     * Whether [device] can be a port of the physical endpoint [group]+     * already holds. A non-empty address identifies an endpoint on its own+     * (ports of one endpoint share it), so conflicting addresses veto a+     * merge; without a conflict, a shared address merges, and otherwise a+     * shared non-empty product name merges ports of one endpoint family —+     * including the common case where only some of an endpoint's ports+     * carry an address (e.g. a Bluetooth SCO port reports the MAC while+     * its BLE port reports none). Unnamed, addressless ports can only be+     * told apart by type, so they merge only with same-type ports that are+     * equally anonymous.+     */+    private fun canMerge(device: RawAudioInputDevice, group: List<RawAudioInputDevice>): Boolean {+        val deviceAddress = device.address.trim()+        val groupAddresses = group.map { it.address.trim() }.filter { it.isNotEmpty() }.toSet()+        if (deviceAddress.isNotEmpty() && groupAddresses.isNotEmpty() && deviceAddress !in groupAddresses) {+            return false         }+        if (deviceAddress.isNotEmpty() && deviceAddress in groupAddresses) return true+        val deviceName = normalizedName(device)+        if (deviceName.isNotEmpty()) {+            return group.any {+                normalizedName(it) == deviceName && familyOf(it.type) == familyOf(device.type)+            }+        }+        if (deviceAddress.isEmpty()) {+            return group.any {+                it.type == device.type && normalizedName(it).isEmpty() && it.address.trim().isEmpty()+            }+        }+        return false     }      /** Groups raw ports into one list per physical device, in first-seen order. */     fun groupByPhysicalDevice(         devices: List<RawAudioInputDevice>,     ): List<List<RawAudioInputDevice>> {-        val groups = LinkedHashMap<PhysicalKey, MutableList<RawAudioInputDevice>>()-        for (device in devices) groups.getOrPut(physicalKeyOf(device)) { mutableListOf() } += device-        return groups.values.map { it.toList() }+        val groups = mutableListOf<MutableList<RawAudioInputDevice>>()+        for (device in devices) {+            val matching = groups.indices.filter { canMerge(device, groups[it]) }+            if (matching.isEmpty()) {+                groups += mutableListOf(device)+            } else {+                val target = groups[matching.first()]+                target += device+                // A port bridging two groups (e.g. an addressed port whose+                // name also matches an addressless group) unites them.+                for (index in matching.drop(1).sortedDescending()) {+                    target += groups[index]+                    groups.removeAt(index)+                }+            }+        }+        return groups.map { it.toList() }     } +    /** The picker/record selection for one physical group. */+    fun selectionFor(group: List<RawAudioInputDevice>): AudioInputDeviceSelection {+        val representative = representativeOf(group)+        val name = representative.productName?.takeIf { it.isNotBlank() }+            ?: group.firstOrNull { !it.productName.isNullOrBlank() }?.productName+        val address = group.firstOrNull { it.address.isNotBlank() }?.address?.trim().orEmpty()+        return AudioInputDeviceSelection(representative.id, representative.type, name, address)+    }++    private fun bestName(group: List<RawAudioInputDevice>): String? =+        group.firstOrNull { !it.productName.isNullOrBlank() }?.productName?.trim()++    private fun groupAddress(group: List<RawAudioInputDevice>): String =+        group.firstOrNull { it.address.isNotBlank() }?.address?.trim().orEmpty()+     /**      * Picker rows: exactly one per physical device (no synthetic rows).      * Each row's selection is its group's representative entry (the most      * specific port type), and its label is the endpoint's product name —      * never prefixed with an id or a count — falling back to the friendly-     * type label when no port in the group reports a meaningful name.+     * type label when no port in the group reports a meaningful name. When+     * two distinct endpoints share one label, the description carries the+     * endpoint address so the rows stay distinguishable.      */-    fun options(devices: List<RawAudioInputDevice>): List<AudioInputDeviceOption> =-        groupByPhysicalDevice(devices).map { group ->+    fun options(devices: List<RawAudioInputDevice>): List<AudioInputDeviceOption> {+        val groups = groupByPhysicalDevice(devices)+        val built = groups.map { group ->             val representative = representativeOf(group)             val label = labelFor(                 representative.type,                 representative.productName?.takeIf { it.isNotBlank() }                     ?: group.firstOrNull { !it.productName.isNullOrBlank() }?.productName,             )-            val type = typeLabel(representative.type)             AudioInputDeviceOption(-                selection = AudioInputDeviceSelection(representative.id, representative.type),+                selection = selectionFor(group),                 label = label,-                description = type.takeIf { it != label },+                description = typeLabel(representative.type).takeIf { it != label },             )         }+        val labelCounts = built.groupingBy { it.label }.eachCount()+        return built.map { option ->+            if ((labelCounts[option.label] ?: 0) < 2) return@map option+            val hint = option.selection.address.takeIf { it.isNotEmpty() }+                ?: option.selection.deviceId?.let { "device $it" }+                ?: return@map option+            option.copy(+                description = listOfNotNull(option.description, hint).joinToString(" · "),+            )+        }+    }      /**      * The effective selection given what is currently connected. A chosen-     * device stays chosen through its physical group: a stored `<id>:<type>`+     * device stays chosen through its physical group: a stored selection      * naming any port of the device (e.g. a non-representative duplicate      * written before grouping) resolves to the group's representative,-     * rather than demanding that exact port. A device with no live port —-     * or whose id was reused by a different type — yields [AUTO] (no-     * explicit choice), and the record-time fallback takes over.+     * rather than demanding that exact port. When the exact port is gone+     * (ids are runtime-assigned and churn), the stored endpoint identity+     * (address, else name within its family, with no conflicting address)+     * re-resolves to the same physical device under its new port. A device+     * with no live port yields [AUTO] (no explicit choice), and the+     * record-time system route takes over.      */     fun resolve(         selection: AudioInputDeviceSelection,         devices: List<RawAudioInputDevice>,     ): AudioInputDeviceSelection {         if (selection.isAuto) return AudioInputDeviceSelection.AUTO-        val exact = devices.firstOrNull {-            it.id == selection.deviceId && it.type == selection.deviceType-        } ?: return AudioInputDeviceSelection.AUTO-        val group = groupByPhysicalDevice(devices).first { exact in it }-        val representative = representativeOf(group)-        return AudioInputDeviceSelection(representative.id, representative.type)+        val groups = groupByPhysicalDevice(devices)+        val exactGroup = groups.firstOrNull { group ->+            group.any { it.id == selection.deviceId && it.type == selection.deviceType }+        }+        if (exactGroup != null) return selectionFor(exactGroup)+        val wantedAddress = selection.address.trim()+        val wantedName = selection.productName?.trim().orEmpty()+        if (wantedAddress.isEmpty() && wantedName.isEmpty()) {+            return AudioInputDeviceSelection.AUTO+        }+        val candidates = groups.filter { group ->+            val address = groupAddress(group)+            val addressConflict =+                wantedAddress.isNotEmpty() && address.isNotEmpty() && address != wantedAddress+            when {+                addressConflict -> false+                wantedAddress.isNotEmpty() && address == wantedAddress -> true+                else -> wantedName.isNotEmpty() && bestName(group) == wantedName &&+                    group.any { familyOf(it.type) == familyOf(selection.deviceType ?: -1) }+            }+        }+        return candidates.singleOrNull()?.let { selectionFor(it) }+            ?: AudioInputDeviceSelection.AUTO+    }++    /**+     * Whether [routed] (e.g. `AudioRecord.getRoutedDevice()` after recording+     * starts) is a port of the physical device [selection] names. Used for+     * an honest readback of whether a pick actually stuck: the setter+     * accepting a device does not by itself prove the route followed it.+     */+    fun isRoutedTo(+        selection: AudioInputDeviceSelection,+        devices: List<RawAudioInputDevice>,+        routed: RawAudioInputDevice,+    ): Boolean {+        val resolved = resolve(selection, devices)+        if (resolved.isAuto) return false+        val all = if (devices.any { it.id == routed.id && it.type == routed.type }) {+            devices+        } else {+            devices + routed+        }+        val routedGroup = groupByPhysicalDevice(all).firstOrNull { group ->+            group.any { it.id == routed.id && it.type == routed.type }+        } ?: return false+        return selectionFor(routedGroup) == resolved     } } @@ -195,15 +342,16 @@ object AudioInputDevicePolicy {  * [RawAudioInputDevice].  *  * Never fails the caller: when there is no explicit choice, or the chosen- * device has disconnected, the platform's current routed device (supplied- * via [routedDevice], e.g. `AudioRecord.getRoutedDevice`) is used if one- * is available, and otherwise no preference is set so the platform routes- * the new recording itself. A rejected or throwing `setPreferred` is- * swallowed (returns the resolved selection with- * [AppliedPreferredDevice.applied] false) so a recording keeps going —+ * device has disconnected, no preference is set (a null device clears any+ * preference) so the platform routes the new recording itself — absence of+ * a pick *is* the system default, never a substituted device. A rejected+ * or throwing `setPreferred` is swallowed (returns the resolved selection+ * with [AppliedPreferredDevice.applied] false) so a recording keeps going —  * including when the chosen device is disconnected mid-recording, where  * Android reroutes the live `AudioRecord` itself and there is nothing to- * do here.+ * do here. Whether the route actually followed an applied preference is+ * verified separately against the routed device once recording starts+ * (see [AudioInputDevicePolicy.isRoutedTo]).  */ data class AppliedPreferredDevice<T>(     val selection: AudioInputDeviceSelection,@@ -220,12 +368,11 @@ object PreferredAudioDeviceApplication {         setPreferred: (T?) -> Boolean,         nameOf: (T) -> String? = { null },         addressOf: (T) -> String = { "" },-        routedDevice: (() -> T?)? = null,     ): AppliedPreferredDevice<T> {         fun rawOf(device: T) = RawAudioInputDevice(idOf(device), typeOf(device), nameOf(device), addressOf(device))         val raws = devices.map(::rawOf)-        var resolved = AudioInputDevicePolicy.resolve(selection, raws)-        var target: T? = if (resolved.isAuto) {+        val resolved = AudioInputDevicePolicy.resolve(selection, raws)+        val target: T? = if (resolved.isAuto) {             null         } else {             // Prefer the exact persisted port if it is still live (it is a@@ -234,21 +381,6 @@ object PreferredAudioDeviceApplication {             devices.firstOrNull { idOf(it) == selection.deviceId && typeOf(it) == selection.deviceType }                 ?: devices.firstOrNull { idOf(it) == resolved.deviceId && typeOf(it) == resolved.deviceType }         }-        if (target == null && routedDevice != null) {-            val routed = runCatching { routedDevice() }.getOrNull()-            if (routed != null) {-                val routedRaw = rawOf(routed)-                resolved = AudioInputDevicePolicy.resolve(-                    AudioInputDeviceSelection(routedRaw.id, routedRaw.type),-                    raws + routedRaw,-                )-                target = devices.firstOrNull { idOf(it) == routedRaw.id && typeOf(it) == routedRaw.type }-                    ?: devices.firstOrNull {-                        idOf(it) == resolved.deviceId && typeOf(it) == resolved.deviceType-                    }-                    ?: routed-            }-        }         val applied = runCatching { setPreferred(target) }.getOrDefault(false)         return AppliedPreferredDevice(resolved, target, applied)     }@@ -273,8 +405,22 @@ object AudioInputDevices {     fun enumerate(context: Context): List<RawAudioInputDevice> =         enumerateInfos(context).map { it.toRaw() } -    fun options(context: Context): List<AudioInputDeviceOption> =-        AudioInputDevicePolicy.options(enumerate(context))+    fun options(context: Context): List<AudioInputDeviceOption> {+        val raw = enumerate(context)+        val options = AudioInputDevicePolicy.options(raw)+        // Dev breadcrumb: the raw ports the platform enumerates vs the one+        // row per physical device the picker shows, so a wrong list can be+        // compared against the hardware from logcat alone.+        Log.dev(+            "AudioInputDevices",+            "raw=[${raw.joinToString("; ") {+                "id=${it.id} type=${it.type} name=${it.productName} address=${it.address}"+            }}] grouped=[${options.joinToString("; ") {+                "id=${it.selection.deviceId} type=${it.selection.deviceType} label=${it.label}"+            }}]",+        )+        return options+    }      /** The currently-effective selection (disconnected choice -> no explicit choice). */     fun resolve(context: Context, selection: AudioInputDeviceSelection): AudioInputDeviceSelection =
camera/src/main/java/com/vayunmathur/camera/platform/camera2/RecordingSessionTargets.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RecordingSessionTargets.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RecordingSessionTargets.ktnew file mode 100644index 0000000000..cf8d92584b--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RecordingSessionTargets.kt@@ -0,0 +1,94 @@+package com.vayunmathur.camera.platform.camera2++/** One output role in a Camera2 recording capture session. */+enum class RecordingTargetRole {+    /** MediaCodec encoder input surface: the recorded file's frames. */+    ENCODER,++    /**+     * The visible viewfinder's surface. It must be a configure-time AND a+     * repeating-request target for the whole recording: dropping it (or+     * targeting a surface the on-screen view does not own) leaves the+     * encoder recording while the preview goes black.+     */+    PREVIEW,++    /** Low-rate YUV analysis surface (scene-motion sampling). */+    ANALYSIS,+}++/**+ * Target composition for the recording session, pure so the+ * preview-stays-live contract is unit-testable without a HAL.+ *+ * Configure-time and repeating targets are the same list by design: the+ * preview surface is never swapped or dropped mid-recording, and the+ * encoder never records without the viewfinder being fed (when a preview+ * surface was supplied at all).+ */+object RecordingSessionTargets {++    /** Configure-time output targets, encoder first. */+    fun configureTargets(+        hasPreviewSurface: Boolean,+        hasAnalysisSurface: Boolean,+    ): List<RecordingTargetRole> = compose(hasPreviewSurface, hasAnalysisSurface)++    /** Repeating-request targets: identical to [configureTargets]. */+    fun repeatingTargets(+        hasPreviewSurface: Boolean,+        hasAnalysisSurface: Boolean,+    ): List<RecordingTargetRole> = compose(hasPreviewSurface, hasAnalysisSurface)++    private fun compose(+        hasPreviewSurface: Boolean,+        hasAnalysisSurface: Boolean,+    ): List<RecordingTargetRole> = buildList {+        add(RecordingTargetRole.ENCODER)+        if (hasPreviewSurface) add(RecordingTargetRole.PREVIEW)+        if (hasAnalysisSurface) add(RecordingTargetRole.ANALYSIS)+    }+}++/** Which viewfinder the camera screen shows. */+enum class RecordingViewfinder {+    /** The recording preview: a live TextureView fed by the recording session. */+    RECORDING,++    /** The normal (non-recording) preview routing. */+    STANDARD,+}++/**+ * Recording-preview wiring decisions, pure for unit tests.+ *+ * The recording viewfinder is shown for the entire recording (never a+ * black placeholder swapped in at record start), and the recording+ * engine may only open the camera once that viewfinder has published+ * its own surface: the engine targets the *view's* surface, so the+ * frames the HAL writes to the preview target are by construction the+ * frames the on-screen TextureView renders. (The previous wiring let+ * the engine create a detached SurfaceTexture and handed that texture+ * to a fresh TextureView via `setSurfaceTexture`; that adopted texture+ * is not the view's own surface, and the view stayed black while the+ * encoder kept recording.)+ */+object RecordingPreviewPolicy {++    /** The viewfinder to compose for the current recording state. */+    fun viewfinder(recordingActive: Boolean): RecordingViewfinder =+        if (recordingActive) RecordingViewfinder.RECORDING else RecordingViewfinder.STANDARD++    /**+     * True exactly when a pending recording start may proceed: a start+     * was requested, has not been launched yet, and the recording+     * viewfinder has published its surface. A surface arriving with no+     * pending start (or after launch, or a destroyed/null surface)+     * never (re)starts the engine.+     */+    fun shouldStartEngine(+        startPending: Boolean,+        alreadyLaunched: Boolean,+        previewSurfaceAvailable: Boolean,+    ): Boolean = startPending && !alreadyLaunched && previewSurfaceAvailable+}
camera/src/main/java/com/vayunmathur/camera/ui/Camera2RecordingPreview.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2RecordingPreview.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2RecordingPreview.ktindex 983a22020a..9d37be8942 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2RecordingPreview.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2RecordingPreview.kt@@ -1,40 +1,67 @@ package com.vayunmathur.camera.ui  import android.view.TextureView-import androidx.compose.foundation.background-import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.remember import androidx.compose.ui.Modifier-import androidx.compose.ui.graphics.Color import androidx.compose.ui.viewinterop.AndroidView import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.registerRecordingPreviewSurface+import com.vayunmathur.camera.platform.camera2.PreviewSurfaceBridge+import com.vayunmathur.camera.platform.camera2.PreviewSurfaceEvent  /**- * Viewfinder while a Camera2 recording owns the camera: a TextureView- * rendering the recording engine's owned preview texture. The texture- * is published by the ViewModel once the engine has started; until- * then (the sub-second settle/open window) the preview is black, like- * every other bind gap in this UI.+ * Viewfinder while a Camera2 recording owns the camera.+ *+ * The TextureView is unremarkable on purpose: it creates and owns its+ * own SurfaceTexture exactly like every other (working) preview in+ * this UI, and the [PreviewSurfaceBridge] publishes the view's own+ * Surface to the ViewModel. The recording engine is started against+ * that surface, so its preview target and the on-screen view are the+ * same surface by construction.+ *+ * The previous wiring did the inverse — the engine created a detached+ * `SurfaceTexture`, the HAL wrote preview frames into a `Surface`+ * wrapping it, and this composable adopted that foreign texture via+ * `TextureView.setSurfaceTexture`. A TextureView renders the texture+ * it owns; the adopted texture was never the view's own surface, so+ * the viewfinder stayed black for the whole recording while the+ * encoder kept recording. Do not reintroduce an engine-owned texture+ * here.  */ @Composable internal fun Camera2RecordingPreview(     viewModel: CameraViewModel,     modifier: Modifier = Modifier, ) {-    val texture by viewModel.camera2RecordingState.previewTexture.collectAsState()-    val liveTexture = texture-    if (liveTexture == null) {-        Box(modifier = modifier.background(Color.Black))-        return+    // The bridge callback needs the bridge itself (to pin the buffer+    // size before the surface is registered, hence before the engine+    // configures its session against it); events only fire after+    // attachTo below, by which time the assignment has happened.+    lateinit var bridge: PreviewSurfaceBridge+    bridge = remember(viewModel) {+        PreviewSurfaceBridge { event ->+            when (event) {+                is PreviewSurfaceEvent.Available -> {+                    viewModel.camera2RecordingState.previewStreamSize?.let { size ->+                        bridge.setDefaultBufferSize(size.width, size.height)+                    }+                    viewModel.registerRecordingPreviewSurface(event.surface)+                }+                is PreviewSurfaceEvent.SizeChanged ->+                    viewModel.registerRecordingPreviewSurface(event.surface)+                is PreviewSurfaceEvent.Destroyed ->+                    viewModel.registerRecordingPreviewSurface(null)+            }+        }+    }+    DisposableEffect(bridge) {+        onDispose { viewModel.registerRecordingPreviewSurface(null) }     }     AndroidView(         factory = { ctx ->-            TextureView(ctx).also { view ->-                view.setSurfaceTexture(liveTexture)-                viewModel.camera2RecordingState.engine?.markPreviewTextureBorrowed()-            }+            TextureView(ctx).also { view -> bridge.attachTo(view) }         },         modifier = modifier,     )
camera/src/main/java/com/vayunmathur/camera/ui/CameraAspectRatioSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraAspectRatioSettings.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraAspectRatioSettings.ktdeleted file mode 100644index 3e2f82f2ec..0000000000--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraAspectRatioSettings.kt+++ /dev/null@@ -1,87 +0,0 @@-package com.vayunmathur.camera.ui--import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.style.TextAlign-import androidx.compose.ui.text.style.TextOverflow-import androidx.compose.ui.unit.dp-import com.vayunmathur.camera.R-import com.vayunmathur.camera.platform.AspectRatioOption-import com.vayunmathur.library.ui.DropdownMenu-import com.vayunmathur.library.ui.IconArrowDropDown-import com.vayunmathur.library.ui.IconCheck-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.SelectableDropdownMenuItem-import com.vayunmathur.library.ui.SettingsSection-import com.vayunmathur.library.ui.Text--/**- * Photo aspect-ratio picker owned by [SettingsPage]: the explicit- * choice list for the same selection the camera top bar cycles- * (4:3 / 3:2 / 16:9 / 1:1 — the historical set; there was never a- * "Full" entry, the sensor-native framing is the 4:3 choice on this- * hardware). The selection drives both the preview box- * (`previewAspectRatio` / `previewRatioForWindow`) and the saved- * still's centre crop, so what the user frames is what lands.- * Stateless: the caller passes the value plus the change callback,- * following [CameraPhotoFormatSettings].- */-@Composable-fun CameraAspectRatioSettings(-    aspectRatio: AspectRatioOption,-    onAspectRatioChange: (AspectRatioOption) -> Unit,-    modifier: Modifier = Modifier,-) {-    SettingsSection(title = stringResource(R.string.settings_aspect_ratio), modifier = modifier) {-        var expanded by remember { mutableStateOf(false) }-        Box(-            modifier = Modifier-                .fillMaxWidth()-                .padding(horizontal = 16.dp)-        ) {-            OutlinedButton(-                onClick = { expanded = true },-                modifier = Modifier.fillMaxWidth()-            ) {-                Text(-                    aspectRatio.label,-                    modifier = Modifier.weight(1f),-                    textAlign = TextAlign.Start,-                    maxLines = 1,-                    overflow = TextOverflow.Ellipsis,-                )-                IconArrowDropDown()-            }-            DropdownMenu(-                expanded = expanded,-                onDismissRequest = { expanded = false }-            ) {-                // Historical cycle order (4:3 -> 3:2 -> 16:9 -> 1:1).-                listOf(-                    AspectRatioOption.RATIO_4_3,-                    AspectRatioOption.RATIO_3_2,-                    AspectRatioOption.RATIO_16_9,-                    AspectRatioOption.RATIO_1_1,-                ).forEach { option ->-                    SelectableDropdownMenuItem(-                        selected = option == aspectRatio,-                        onClick = {-                            onAspectRatioChange(option)-                            expanded = false-                        },-                        text = { Text(option.label) },-                        selectedLeadingIcon = { IconCheck() },-                    )-                }-            }-        }-    }-}
camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.ktindex e126dd6747..e364fd697a 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt@@ -28,25 +28,23 @@ import com.vayunmathur.library.ui.Text  /**  * Post-processing settings rows owned by [SettingsPage]: the noise-reduction and- * edge-sharpening toggles (issue #662) plus the Motion Photo on/off toggle and- * clip-length picker (issue #712). Stateless: the caller passes values plus+ * edge-sharpening toggles (issue #662) plus the single Motion Photo dropdown+ * (Off or a clip length, issue #712). Stateless: the caller passes values plus  * change callbacks.  *  * [motionPhotoBlockedByAvif] is an effective AVIF selection: a Motion Photo is- * a JPEG with an MP4 trailer, so the toggle renders disabled with that reason- * (its stored value is kept) and captures stay plain stills. The clip-length- * picker only shows while Motion Photo is on.+ * a JPEG with an MP4 trailer, so the dropdown renders disabled showing the+ * forced Off state with that reason (its stored value is kept) and captures+ * stay plain stills.  */ @Composable fun CameraPostProcessingSettings(     noiseReductionEnabled: Boolean,     edgeSharpeningEnabled: Boolean,-    motionPhotoEnabled: Boolean,     motionPhotoDuration: MotionPhotoDuration,     motionPhotoBlockedByAvif: Boolean,     onNoiseReductionChange: (Boolean) -> Unit,     onEdgeSharpeningChange: (Boolean) -> Unit,-    onMotionPhotoEnabledChange: (Boolean) -> Unit,     onMotionDurationChange: (MotionPhotoDuration) -> Unit,     modifier: Modifier = Modifier, ) {@@ -68,24 +66,16 @@ fun CameraPostProcessingSettings(         }          SettingsSection(title = stringResource(R.string.settings_motion_photo)) {-            SettingsSwitchRow(-                title = stringResource(R.string.settings_motion_photo_description),-                supportingText = if (motionPhotoBlockedByAvif) {-                    stringResource(R.string.settings_motion_photo_requires_jpeg)-                } else {-                    null-                },-                checked = motionPhotoEnabled,-                enabled = !motionPhotoBlockedByAvif,-                onCheckedChange = onMotionPhotoEnabledChange,-            )-        }--        if (motionPhotoEnabled) {-        SettingsSection(title = stringResource(R.string.settings_motion_duration)) {             // Built from [OutlinedButton] + [DropdownMenu] like the codec/audio pickers             // in SettingsPage, rather than the library's `ExposedDropdownMenu` wrapper,             // which currently recurses into itself.+            // AVIF forces Off honestly: the button shows Off while blocked+            // (the stored choice is kept and returns when JPEG is selected).+            val displayed = if (motionPhotoBlockedByAvif) {+                MotionPhotoDuration.OFF+            } else {+                motionPhotoDuration+            }             var motionExpanded by remember { mutableStateOf(false) }             Box(                 modifier = Modifier@@ -94,10 +84,11 @@ fun CameraPostProcessingSettings(             ) {                 OutlinedButton(                     onClick = { motionExpanded = true },+                    enabled = !motionPhotoBlockedByAvif,                     modifier = Modifier.fillMaxWidth()                 ) {                     Text(-                        motionDurationLabel(motionPhotoDuration.seconds),+                        motionSettingLabel(displayed),                         modifier = Modifier.weight(1f),                         textAlign = TextAlign.Start,                         maxLines = 1,@@ -111,25 +102,34 @@ fun CameraPostProcessingSettings(                 ) {                     MotionPhotoDuration.entries.forEach { duration ->                         SelectableDropdownMenuItem(-                            selected = duration == motionPhotoDuration,+                            selected = duration == displayed,                             onClick = {                                 onMotionDurationChange(duration)                                 motionExpanded = false                             },                             text = {-                                Text(motionDurationLabel(duration.seconds))+                                Text(motionSettingLabel(duration))                             },                             selectedLeadingIcon = { IconCheck() },                         )                     }                 }             }-        }+            if (motionPhotoBlockedByAvif) {+                Text(+                    stringResource(R.string.settings_motion_photo_requires_jpeg),+                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),+                )+            }         }     } } -/** Localized label for a Motion-Photo clip length ("1 second" / "3 seconds"). */+/** Localized label for one Motion Photo setting ("Off" / "1 second" / "3 seconds"). */ @Composable-private fun motionDurationLabel(seconds: Int): String =-    pluralStringResource(R.plurals.motion_duration, seconds, seconds)+private fun motionSettingLabel(setting: MotionPhotoDuration): String =+    if (setting.isEnabled) {+        pluralStringResource(R.plurals.motion_duration, setting.seconds, setting.seconds)+    } else {+        stringResource(R.string.settings_motion_photo_off)+    }
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex 04740efde6..ee0429ce74 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -41,6 +41,7 @@ import com.vayunmathur.camera.platform.setQrResult import com.vayunmathur.camera.data.setShadows import com.vayunmathur.camera.data.setWarmth import com.vayunmathur.camera.platform.selectLens+import com.vayunmathur.camera.platform.currentZoomRange import com.vayunmathur.camera.platform.setZoomRatio import com.vayunmathur.camera.platform.toggleNightModeOverride import com.vayunmathur.camera.R@@ -163,13 +164,17 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(                 }             }         )-            // Tap-to-focus (gesture, metering, indicator) is owned by-            // TapToFocus.kt; fractions route to the Camera2 session's-            // metering transform (CameraViewModel.tapToFocusAt).+            // Preview gestures (pinch-zoom, tap-to-focus, long-press lock)+            // are owned by the single handler in TapToFocus.kt; fractions+            // route to the Camera2 session's metering transform+            // (CameraViewModel.tapToFocusAt), zoom to setZoomRatio.             .then(-                Modifier.tapToFocus(+                Modifier.previewGestures(                     state = tapToFocusState,                     mirrorPreview = state.mirrorPreview,+                    currentZoom = { viewModel.zoomRatio.value },+                    zoomRange = { viewModel.currentZoomRange() },+                    onZoom = { viewModel.setZoomRatio(it) },                     onFocus = { x, y -> viewModel.startFocusAndMeteringAt(x, y) },                     onLockFocus = { x, y -> viewModel.lockFocusAndMeteringAt(x, y) },                     onFallback = { viewModel.fallbackToDefaultMetering() },
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 9852e0f34d..55173a3eb3 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -43,8 +43,13 @@ internal fun CameraPreviewSurface(     val useCamera2NightPreview = state.useCamera2NightPreview     val useCamera2SloMoPreview = state.useCamera2SloMoPreview -    if (state.camera2Recording) {-        // The recording engine owns the camera + its preview texture.+    if (+        com.vayunmathur.camera.platform.camera2.RecordingPreviewPolicy+            .viewfinder(state.camera2Recording) ==+        com.vayunmathur.camera.platform.camera2.RecordingViewfinder.RECORDING+    ) {+        // The recording engine owns the camera; the recording preview's+        // own TextureView surface is the engine's preview target.         Camera2RecordingPreview(viewModel = viewModel, modifier = previewModifier)         return     }
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.ktindex 786f3d2aa2..b529578746 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenKit.kt@@ -5,6 +5,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import com.vayunmathur.camera.platform.CameraMode+import com.vayunmathur.camera.platform.isZoomLockedTo1x  /** Which settings pane is open below the preview. */ internal enum class CameraSetting {@@ -20,7 +21,10 @@ internal enum class CameraSetting {  *   `CameraControl`, which drives every bound use case — photo stills and  *   the video Preview+VideoCapture alike (preview and recording), and is  *   re-applied on every bind by `refreshCapabilities`/`restoreZoom`. So- *   zoom is offered everywhere the zoom bar already worked.+ *   zoom is offered everywhere the zoom bar already worked — EXCEPT+ *   PANORAMA/PHOTOSPHERE, where stitch input must be at 1x: those modes+ *   lock zoom to 1.0x (see `isZoomLockedTo1x`), so offering a zoom pane+ *   there would be a control that cannot take effect.  * - [CameraSetting.BRIGHTNESS] (exposure compensation): likewise a  *   `CameraControl` call (`setExposureCompensationIndex`), re-applied on  *   video binds too, so it is live for stills and video. Offered for@@ -53,7 +57,11 @@ internal fun settingsForMode(mode: CameraMode): List<CameraSetting> {             add(CameraSetting.ISO)         }         if (mode == CameraMode.PORTRAIT) add(CameraSetting.PORTRAIT_BLUR)-        add(CameraSetting.ZOOM)+        // Zoom-locked modes (PANORAMA/PHOTOSPHERE) get no ZOOM entry at+        // all: the magnifier must not be offered for a locked control,+        // and effectiveSettingForMode then resolves a stale ZOOM pane+        // to null, which CameraSettingsColumn renders without any bars.+        if (!mode.isZoomLockedTo1x()) add(CameraSetting.ZOOM)     } } 
camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.ktindex cea9f32221..e6470542ef 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt@@ -95,6 +95,26 @@ internal fun SettingsButtonRow(     onSelect: (CameraSetting?) -> Unit,     modifier: Modifier = Modifier ) {+    // Offer only settings the capture path honours in this mode (see+    // settingsForMode): elsewhere they'd silently move a preview effect+    // that the capture path drops. Video gets brightness (exposure+    // compensation) and zoom, both CameraControl-driven. Zoom-locked+    // modes (PANORAMA/PHOTOSPHERE) offer nothing at all — in particular+    // no ZOOM magnifier for the locked 1x — so the row itself is hidden+    // rather than rendering an empty pill.+    val settings: List<Pair<CameraSetting, @Composable (Modifier, Color) -> Unit>> =+        settingsForMode(cameraMode).map { setting ->+            setting to when (setting) {+                CameraSetting.BRIGHTNESS -> { m: Modifier, c: Color -> IconSunny(m, c) }+                CameraSetting.SHADOWS -> { m: Modifier, c: Color -> IconContrast(m, c) }+                CameraSetting.WARMTH -> { m: Modifier, c: Color -> IconLightbulb(m, c) }+                CameraSetting.EXPOSURE_TIME -> { m: Modifier, c: Color -> IconTimer(m, c) }+                CameraSetting.ISO -> { m: Modifier, c: Color -> IconIso(m, c) }+                CameraSetting.PORTRAIT_BLUR -> { m: Modifier, c: Color -> IconBlur(m, c) }+                CameraSetting.ZOOM -> { m: Modifier, c: Color -> IconZoomIn(m, c) }+            }+        }+    if (settings.isEmpty()) return     Row(         modifier = modifier             .background(Color(0x99000000), androidx.compose.foundation.shape.RoundedCornerShape(24.dp))@@ -103,22 +123,6 @@ internal fun SettingsButtonRow(         horizontalArrangement = Arrangement.spacedBy(2.dp),         verticalAlignment = Alignment.CenterVertically     ) {-        // Offer only settings the capture path honours in this mode (see-        // settingsForMode): elsewhere they'd silently move a preview effect-        // that the capture path drops. Video gets brightness (exposure-        // compensation) and zoom, both CameraControl-driven.-        val settings: List<Pair<CameraSetting, @Composable (Modifier, Color) -> Unit>> =-            settingsForMode(cameraMode).map { setting ->-                setting to when (setting) {-                    CameraSetting.BRIGHTNESS -> { m: Modifier, c: Color -> IconSunny(m, c) }-                    CameraSetting.SHADOWS -> { m: Modifier, c: Color -> IconContrast(m, c) }-                    CameraSetting.WARMTH -> { m: Modifier, c: Color -> IconLightbulb(m, c) }-                    CameraSetting.EXPOSURE_TIME -> { m: Modifier, c: Color -> IconTimer(m, c) }-                    CameraSetting.ISO -> { m: Modifier, c: Color -> IconIso(m, c) }-                    CameraSetting.PORTRAIT_BLUR -> { m: Modifier, c: Color -> IconBlur(m, c) }-                    CameraSetting.ZOOM -> { m: Modifier, c: Color -> IconZoomIn(m, c) }-                }-            }         settings.forEach { (setting, icon) ->             val isActive = activeSetting == setting             Box(
camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.ktindex b1ef299b49..9f69fe7ec4 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt@@ -14,6 +14,7 @@ import com.vayunmathur.camera.R import com.vayunmathur.camera.domain.isFidoDeepLink import com.vayunmathur.camera.domain.parseWifiQr import com.vayunmathur.camera.platform.CameraMode+import com.vayunmathur.camera.platform.isZoomLockedTo1x import com.vayunmathur.library.ui.IconBlur import com.vayunmathur.library.ui.IconContrast import com.vayunmathur.library.ui.IconIso@@ -87,16 +88,26 @@ internal fun CameraSettingsColumn(         val effectiveSetting = effectiveSettingForMode(activeSetting, cameraMode)         when (effectiveSetting) {             null, CameraSetting.ZOOM -> {-                LensBar(-                    lenses = availableLenses,-                    selected = selectedLens,-                    onSelect = onLensSelected-                )-                ZoomBar(-                    currentZoom = zoomRatio,-                    zoomLevels = availableZoomLevels,-                    onZoomSelected = onZoomSelected-                )+                // Zoom-locked modes (PANORAMA/PHOTOSPHERE) show NEITHER+                // bar: the ZoomBar is a control that cannot take effect+                // at the locked 1x, and the LensBar is hidden too —+                // picking a physical lens (0.5x UW, 3x tele, …) changes+                // the native field of view, which is exactly the zoom+                // change the lock forbids for stitch input. The lens+                // selection itself is left untouched, so leaving the+                // mode restores the previous lens + stored zoom.+                if (!cameraMode.isZoomLockedTo1x()) {+                    LensBar(+                        lenses = availableLenses,+                        selected = selectedLens,+                        onSelect = onLensSelected+                    )+                    ZoomBar(+                        currentZoom = zoomRatio,+                        zoomLevels = availableZoomLevels,+                        onZoomSelected = onZoomSelected+                    )+                }             }             CameraSetting.BRIGHTNESS -> HorizontalSettingSlider(                 value = exposureComp,
camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.ktindex 507fe3718b..6e17778fb1 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt@@ -8,6 +8,7 @@ import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.effectiveZoomRatioForMode  /**  * Collects every [CameraViewModel] flow that [CameraScreenState] reads@@ -115,7 +116,13 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen             timerCountdown = timerCountdown,             qrResult = qrResult,             aspectRatio = aspectRatio,-            zoomRatio = zoomRatio,+            // Zoom-locked modes (PANORAMA/PHOTOSPHERE) expose 1x to every+            // consumer of state.zoomRatio — above all the preview+            // session's LaunchedEffect, which re-applies this value to+            // the session on bind and on any zoom change — regardless of+            // the stored ratio. The stored flow itself is untouched, so+            // leaving the mode restores the user's previous zoom.+            zoomRatio = effectiveZoomRatioForMode(cameraMode, zoomRatio),             mirrorFront = mirrorFront,             timerDuration = timerDuration,             isCapturing = isCapturing,
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex 4532932f35..f20905d0a6 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -31,7 +31,6 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.camera.R import com.vayunmathur.camera.platform.CameraViewModel-import com.vayunmathur.camera.platform.MotionPhotoDuration import com.vayunmathur.camera.platform.requestedStillFormat import com.vayunmathur.camera.data.SafDocuments import com.vayunmathur.camera.data.SaveTarget@@ -41,10 +40,8 @@ import com.vayunmathur.camera.data.setEdgeSharpeningEnabled import com.vayunmathur.camera.data.setLocationEnabled import com.vayunmathur.camera.data.setMirrorFront import com.vayunmathur.camera.data.setMotionPhotoDuration-import com.vayunmathur.camera.data.setMotionPhotoEnabled import com.vayunmathur.camera.data.setNoiseReductionEnabled import com.vayunmathur.camera.data.setSaveTreeUri-import com.vayunmathur.camera.data.setAspectRatio import com.vayunmathur.camera.data.setPhotoFormat import com.vayunmathur.camera.data.setVideoCodec import com.vayunmathur.camera.data.updateLocation@@ -59,7 +56,6 @@ import com.vayunmathur.library.util.NavKey @Composable fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewModel) {     val locationEnabled by viewModel.locationEnabled.collectAsState()-    val aspectRatio by viewModel.aspectRatio.collectAsState()     val videoCodec by viewModel.videoCodec.collectAsState()     val photoFormat by viewModel.photoFormat.collectAsState()     val audioInputDevice by viewModel.audioInputDevice.collectAsState()@@ -67,7 +63,6 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM     val noiseReductionEnabled by viewModel.noiseReductionEnabled.collectAsState()     val edgeSharpeningEnabled by viewModel.edgeSharpeningEnabled.collectAsState()     val motionPhotoDuration by viewModel.motionPhotoDuration.collectAsState()-    val motionPhotoEnabled by viewModel.motionPhotoEnabled.collectAsState()     val saveTarget by viewModel.saveTarget.collectAsState()     val context = LocalContext.current     // Physical input devices, refreshed when devices connect/disconnect.@@ -184,11 +179,6 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                 )             } -            CameraAspectRatioSettings(-                aspectRatio = aspectRatio,-                onAspectRatioChange = { viewModel.setAspectRatio(it); noteIfDeferred() },-            )-             CameraPhotoFormatSettings(                 photoFormat = photoFormat,                 onPhotoFormatChange = { viewModel.setPhotoFormat(it); noteIfDeferred() },@@ -197,7 +187,6 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM             CameraPostProcessingSettings(                 noiseReductionEnabled = noiseReductionEnabled,                 edgeSharpeningEnabled = edgeSharpeningEnabled,-                motionPhotoEnabled = motionPhotoEnabled,                 motionPhotoDuration = motionPhotoDuration,                 // Effective AVIF only (native encoder present): a JPEG-fallback                 // AVIF selection leaves Motion Photo available, as at capture.@@ -205,7 +194,6 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                     .avifPrecludesMotionPhoto(viewModel.requestedStillFormat(), com.vayunmathur.camera.platform.StitchNative.isAvailable),                 onNoiseReductionChange = { viewModel.setNoiseReductionEnabled(it) },                 onEdgeSharpeningChange = { viewModel.setEdgeSharpeningEnabled(it) },-                onMotionPhotoEnabledChange = { viewModel.setMotionPhotoEnabled(it) },                 onMotionDurationChange = { viewModel.setMotionPhotoDuration(it) },             ) 
camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt b/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.ktindex 2d05b2abff..e251dd3614 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt@@ -1,7 +1,9 @@ package com.vayunmathur.camera.ui  import android.os.SystemClock-import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculateZoom import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue@@ -12,8 +14,10 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.pointerInput+import com.vayunmathur.camera.domain.PreviewGestureRouter import com.vayunmathur.library.log.Log import kotlinx.coroutines.delay+import kotlinx.coroutines.withTimeoutOrNull  /** Minimum gap between two tap-to-focus requests; faster repeats are one gesture, not two. */ private const val FOCUS_TAP_DEBOUNCE_MS = 120L@@ -71,19 +75,28 @@ internal class TapToFocusState { }  /**- * Tap-to-focus gestures on the preview surface itself, in the same single- * detector as long-press-to-lock. CameraXViewfinder's built-in tap gesture- * stays disabled: it raced this detector, gave no tap indicator, silently- * returned when the transformed point left 0..1, and its result was- * invisible to the app.+ * The preview's single authoritative gesture handler: pinch-to-zoom,+ * tap-to-focus and long-press-to-lock focus, all routed by one+ * [PreviewGestureRouter] inside one `awaitEachGesture` block.  *- * Keyed on [surfaceRequest] + [mirrorPreview], NOT only on a settings key:- * with a stale key the block captured the first-composed surfaceRequest- * (null before the session binds), so every metering point came back null.+ * This replaces two historical handlers that each owned half the job:+ * CameraXViewfinder's built-in pinch (deleted with CameraX in 846c79fe2)+ * and a lone `detectTapGestures` tap detector. With only the tap detector+ * left, a pinch surfaced as a tap and fired autofocus instead of zooming.+ * Two competing `pointerInput` detectors would race the same way, so+ * there is exactly one here: a second pointer converts the gesture to a+ * pinch and no focus event is ever emitted for it.+ *+ * Zoom is read live at pinch start via [currentZoom]/[zoomRange] (never a+ * bind-time snapshot) and applied live via [onZoom], which the ViewModel+ * forwards to the Camera2 session (and clamps again there).  */-internal fun Modifier.tapToFocus(+internal fun Modifier.previewGestures(     state: TapToFocusState,     mirrorPreview: Boolean,+    currentZoom: () -> Float,+    zoomRange: () -> Pair<Float, Float>,+    onZoom: (Float) -> Unit,     onFocus: (Float, Float) -> Unit,     onLockFocus: (Float, Float) -> Unit,     onFallback: () -> Unit,@@ -99,29 +112,77 @@ internal fun Modifier.tapToFocus(         }         state.show(visual, locked)     }-    detectTapGestures(-        onTap = { tapOffset ->++    fun focusAt(x: Float, y: Float, locked: Boolean) {+        // Indicator first, regardless of AF outcome: it proves the tap+        // registered even if metering then fails.+        showIndicator(Offset(x, y), locked)+        if (size.width > 0 && size.height > 0) {+            val handler = if (locked) onLockFocus else onFocus+            handler(x / size.width, y / size.height)+        } else {+            onFallback()+        }+    }++    val router = PreviewGestureRouter(+        onZoom = onZoom,+        onTap = { x, y ->             val now = SystemClock.uptimeMillis()-            if (now - state.lastTapMs < FOCUS_TAP_DEBOUNCE_MS) return@detectTapGestures-            state.lastTapMs = now-            // Indicator first, regardless of AF outcome: it proves the tap-            // registered even if metering then fails.-            showIndicator(tapOffset, locked = false)-            if (size.width > 0 && size.height > 0) {-                onFocus(tapOffset.x / size.width, tapOffset.y / size.height)-            } else {-                onFallback()+            if (now - state.lastTapMs >= FOCUS_TAP_DEBOUNCE_MS) {+                state.lastTapMs = now+                focusAt(x, y, locked = false)             }         },-        onLongPress = { tapOffset ->-            showIndicator(tapOffset, locked = true)-            if (size.width > 0 && size.height > 0) {-                onLockFocus(tapOffset.x / size.width, tapOffset.y / size.height)-            } else {-                onFallback()+        onLongPress = { x, y -> focusAt(x, y, locked = true) },+    )++    awaitEachGesture {+        val down = awaitFirstDown(requireUnconsumed = false)+        router.pointerDown(1, down.position.x, down.position.y, currentZoom())+        val longPressDeadlineMs = down.uptimeMillis + viewConfiguration.longPressTimeoutMillis+        var lastEventMs = down.uptimeMillis+        try {+            while (true) {+                val event = if (router.isLongPressPending) {+                    val remaining = (longPressDeadlineMs - lastEventMs).coerceAtLeast(0L)+                    withTimeoutOrNull(remaining) { awaitPointerEvent() }+                } else {+                    awaitPointerEvent()+                }+                if (event == null) {+                    router.longPressTimeout()+                    continue+                }+                lastEventMs = event.changes.maxOf { it.uptimeMillis }+                val pressed = event.changes.filter { it.pressed }+                when {+                    pressed.size >= 2 -> {+                        val (minZoom, maxZoom) = zoomRange()+                        router.updateZoomRange(minZoom, maxZoom)+                        router.pointerDown(+                            pressed.size,+                            pressed.map { it.position.x }.average().toFloat(),+                            pressed.map { it.position.y }.average().toFloat(),+                            currentZoom(),+                        )+                        router.pinch(event.calculateZoom())+                        event.changes.forEach { it.consume() }+                    }+                    pressed.size == 1 -> router.pointerMoved(+                        pressed[0].position.x,+                        pressed[0].position.y,+                        viewConfiguration.touchSlop,+                    )+                    else -> break+                }             }+            router.gestureEnd()+        } catch (e: Exception) {+            router.gestureCancel()+            throw e         }-    )+    } }  /**
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex e23e1ee71f..d14abd9faf 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -96,8 +96,10 @@     <string name="settings_motion_photo">Motion photo</string>     <!-- SettingsPage: summary explaining the motion-photo toggle -->     <string name="settings_motion_photo_description">Save a short clip with each photo</string>-    <!-- SettingsPage: reason shown under the disabled motion-photo toggle when AVIF is the effective format -->+    <!-- SettingsPage: reason shown under the disabled motion-photo dropdown when AVIF is the effective format -->     <string name="settings_motion_photo_requires_jpeg">Motion Photo needs JPEG</string>+    <!-- SettingsPage: Off entry of the single motion-photo dropdown -->+    <string name="settings_motion_photo_off">Off</string>     <!-- SettingsPage: section header for motion-photo clip-length selection -->     <string name="settings_motion_duration">Motion photo length</string>     <!-- Motion-Photo duration: clip length in seconds. %1$d = seconds -->
camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.kt b/camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.ktindex 727d6ee1ef..f133d92a1c 100644--- a/camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.kt@@ -4,14 +4,17 @@ import android.os.Looper import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.MotionPhotoDuration import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Shadows import kotlin.test.assertEquals-import kotlin.test.assertFalse import kotlin.test.assertTrue -/** Motion Photo on/off persistence: default on, explicit off survives a new ViewModel. */+/**+ * The single Motion Photo setting: default on at 3s, Off and lengths persist+ * under one key, and the retired toggle+length pair migrates cleanly.+ */ @RunWith(AndroidJUnit4::class) class CameraMotionPhotoSettingsTest { @@ -22,37 +25,53 @@ class CameraMotionPhotoSettingsTest {      * synchronous mirror. The setter launches on `viewModelScope` (main), so      * the main looper is idled between polls instead of blocked on.      */-    private fun awaitStored(viewModel: CameraViewModel, expected: String) {+    private fun awaitStored(viewModel: CameraViewModel, key: String, expected: String?) {         val deadline = System.currentTimeMillis() + 5_000-        while (viewModel.ds.getString(KEY) != expected) {-            assertTrue(System.currentTimeMillis() < deadline, "stored $KEY never became $expected")+        while (viewModel.ds.getString(key) != expected) {+            assertTrue(System.currentTimeMillis() < deadline, "stored $key never became $expected")             Shadows.shadowOf(Looper.getMainLooper()).idle()             Thread.sleep(20)         }-        assertEquals(expected, viewModel.ds.getString(KEY))+        assertEquals(expected, viewModel.ds.getString(key))     }      @Test-    fun motionPhotoEnabledDefaultsOnAndPersistsOffAndOn() {+    fun motionPhotoDefaultsOnAtThreeSecondsAndPersistsOffAndLengths() {         val first = vm()         try {-            assertTrue(first.motionPhotoEnabled.value, "default must be on")+            assertEquals(MotionPhotoDuration.THREE, first.motionPhotoDuration.value, "default must be on at 3s") -            first.setMotionPhotoEnabled(false)-            assertFalse(first.motionPhotoEnabled.value)-            awaitStored(first, "false")-            // A fresh ViewModel loads the persisted off state at startup.-            assertFalse(vm().motionPhotoEnabled.value)+            first.setMotionPhotoDuration(MotionPhotoDuration.OFF)+            assertEquals(MotionPhotoDuration.OFF, first.motionPhotoDuration.value)+            awaitStored(first, KEY, "OFF")+            assertEquals(MotionPhotoDuration.OFF, vm().motionPhotoDuration.value)++            first.setMotionPhotoDuration(MotionPhotoDuration.FIVE)+            awaitStored(first, KEY, "FIVE")+            assertEquals(MotionPhotoDuration.FIVE, vm().motionPhotoDuration.value)         } finally {-            // Leave the shared store on for other tests, with the restore-            // landed rather than only launched.-            first.setMotionPhotoEnabled(true)-            awaitStored(first, "true")+            first.setMotionPhotoDuration(MotionPhotoDuration.THREE)+            awaitStored(first, KEY, "THREE")         }-        assertTrue(vm().motionPhotoEnabled.value)+        assertEquals(MotionPhotoDuration.THREE, vm().motionPhotoDuration.value)+    }++    @Test+    fun legacyToggleAndLengthMigrateToTheSingleSetting() {+        // Pure migration matrix (no stored values -> current default behaviour).+        assertEquals(MotionPhotoDuration.THREE, migratedMotionPhotoDuration(null, null, null))+        assertEquals(MotionPhotoDuration.OFF, migratedMotionPhotoDuration(null, "false", "FIVE"))+        assertEquals(MotionPhotoDuration.FIVE, migratedMotionPhotoDuration(null, "true", "FIVE"))+        assertEquals(MotionPhotoDuration.ONE, migratedMotionPhotoDuration(null, null, "ONE"))+        assertEquals(MotionPhotoDuration.THREE, migratedMotionPhotoDuration(null, "true", null))+        // The current key wins over any legacy pair; malformed values fall back.+        assertEquals(MotionPhotoDuration.ONE, migratedMotionPhotoDuration("ONE", "false", "FIVE"))+        assertEquals(MotionPhotoDuration.OFF, migratedMotionPhotoDuration("OFF", "true", "FIVE"))+        assertEquals(MotionPhotoDuration.THREE, migratedMotionPhotoDuration("bogus", null, null))+        assertEquals(MotionPhotoDuration.THREE, migratedMotionPhotoDuration(null, "true", "bogus"))     }      private companion object {-        const val KEY = "camera_motion_photo_enabled"+        const val KEY = "camera_motion_photo"     } }
camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.ktnew file mode 100644index 0000000000..f8689431ad--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewGestureRouterTest.kt@@ -0,0 +1,146 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Pinch/tap/long-press routing for the preview's single gesture handler. */+class PreviewGestureRouterTest {++    private class Recorder {+        val zooms = mutableListOf<Float>()+        val taps = mutableListOf<Pair<Float, Float>>()+        val longPresses = mutableListOf<Pair<Float, Float>>()+        val router = PreviewGestureRouter(+            onZoom = { zooms.add(it) },+            onTap = { x, y -> taps.add(x to y) },+            onLongPress = { x, y -> longPresses.add(x to y) },+        )++        fun pinchGesture(startZoom: Float = 1f, vararg scaleSteps: Float) {+            router.updateZoomRange(0.5f, 10f)+            router.pointerDown(1, 100f, 100f, startZoom)+            router.pointerDown(2, 150f, 100f, startZoom)+            scaleSteps.forEach { router.pinch(it) }+            router.gestureEnd()+        }+    }++    @Test+    fun pinchEmitsAccumulatedZoomAndNoFocusEvents() {+        val r = Recorder()+        r.pinchGesture(startZoom = 1f, 1.5f, 1.5f)+        // 1 x 1.5 x 1.5, applied live per step.+        assertEquals(listOf(1.5f, 2.25f), r.zooms)+        assertTrue(r.taps.isEmpty(), "pinch must not fire tap-to-focus")+        assertTrue(r.longPresses.isEmpty(), "pinch must not fire focus lock")+    }++    @Test+    fun pinchStartsFromZoomAtGestureStartNotOne() {+        val r = Recorder()+        r.pinchGesture(startZoom = 2f, 1.5f)+        assertEquals(listOf(3f), r.zooms)+    }++    @Test+    fun pinchClampsAtMaxZoom() {+        val r = Recorder()+        r.pinchGesture(startZoom = 1f, 4f, 4f, 4f)+        assertEquals(listOf(4f, 10f, 10f), r.zooms)+    }++    @Test+    fun pinchClampsAtMinZoom() {+        val r = Recorder()+        r.pinchGesture(startZoom = 2f, 0.5f, 0.1f)+        assertEquals(listOf(1f, 0.5f), r.zooms)+    }++    @Test+    fun pinchAfterSecondFingerSuppressesEarlierTapIntent() {+        val r = Recorder()+        r.router.updateZoomRange(0.5f, 10f)+        r.router.pointerDown(1, 10f, 10f, 1f)+        // Second finger lands before any up: the whole gesture is a pinch.+        r.router.pointerDown(2, 60f, 10f, 1f)+        r.router.pinch(2f)+        r.router.gestureEnd()+        assertEquals(listOf(2f), r.zooms)+        assertTrue(r.taps.isEmpty())+    }++    @Test+    fun singleTapEmitsExactlyOneFocusEventAndNoZoom() {+        val r = Recorder()+        r.router.pointerDown(1, 40f, 80f, 1f)+        r.router.gestureEnd()+        assertEquals(listOf(40f to 80f), r.taps)+        assertTrue(r.zooms.isEmpty())+        assertTrue(r.longPresses.isEmpty())+    }++    @Test+    fun longPressEmitsLockAndSuppressesTapOnRelease() {+        val r = Recorder()+        r.router.pointerDown(1, 30f, 30f, 1f)+        r.router.longPressTimeout()+        r.router.gestureEnd()+        assertEquals(listOf(30f to 30f), r.longPresses)+        assertTrue(r.taps.isEmpty())+        assertTrue(r.zooms.isEmpty())+    }++    @Test+    fun longPressDoesNotFireDuringPinch() {+        val r = Recorder()+        r.router.updateZoomRange(0.5f, 10f)+        r.router.pointerDown(1, 10f, 10f, 1f)+        r.router.pointerDown(2, 50f, 10f, 1f)+        r.router.longPressTimeout()+        assertTrue(r.longPresses.isEmpty())+    }++    @Test+    fun movementBeyondSlopSuppressesTapAndLongPress() {+        val r = Recorder()+        r.router.pointerDown(1, 0f, 0f, 1f)+        r.router.pointerMoved(100f, 0f, touchSlopPx = 10f)+        r.router.longPressTimeout()+        r.router.gestureEnd()+        assertTrue(r.taps.isEmpty())+        assertTrue(r.longPresses.isEmpty())+    }++    @Test+    fun cancelledGestureEmitsNothing() {+        val r = Recorder()+        r.router.pointerDown(1, 5f, 5f, 1f)+        r.router.gestureCancel()+        assertTrue(r.taps.isEmpty())+        assertTrue(r.zooms.isEmpty())+    }++    @Test+    fun invalidPinchFactorsAreDropped() {+        val r = Recorder()+        r.router.updateZoomRange(0.5f, 10f)+        r.router.pointerDown(1, 0f, 0f, 1f)+        r.router.pointerDown(2, 10f, 0f, 1f)+        r.router.pinch(Float.NaN)+        r.router.pinch(0f)+        r.router.pinch(-1f)+        r.router.pinch(2f)+        assertEquals(listOf(2f), r.zooms)+    }++    @Test+    fun degenerateZoomRangeCollapsesToOne() {+        val r = Recorder()+        r.router.updateZoomRange(Float.NaN, -1f)+        r.router.pointerDown(1, 0f, 0f, 1f)+        r.router.pointerDown(2, 10f, 0f, 1f)+        r.router.pinch(3f)+        assertEquals(listOf(1f), r.zooms)+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.ktindex 8a3561ee7e..c5aeb5f8e4 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.kt@@ -151,10 +151,10 @@ class MotionPhotoCaptureStateTest {     @Test     fun motionPhotoOffRoutesToPlainStillAndBuffersNothing() {         val v = vm()-        // Default is on, preserving the pre-toggle behaviour.-        assertTrue(v.motionPhotoEnabled.value)-        v.motionPhotoEnabledMutable.value = false-        // 4:3 + JPEG + a length set: still a plain still, queue untouched.+        // Default is on at 3s, preserving the pre-dropdown behaviour.+        assertEquals(MotionPhotoDuration.THREE, v.motionPhotoDuration.value)+        v.motionPhotoDurationMutable.value = MotionPhotoDuration.OFF+        // 4:3 + JPEG: still a plain still, queue untouched.         assertEquals(StillRoute.SINGLE, v.routeStillCapture())         assertEquals(0, v.motionSaveQueue.pending)         // No ring-buffer accumulation while off (bitmap is recycled).@@ -162,8 +162,8 @@ class MotionPhotoCaptureStateTest {         v.addMotionFrame(frame, 0L, 90)         assertTrue(frame.isRecycled)         assertTrue(v.drainMotionFrames().isEmpty())-        // Re-enabling restores the previous diversion.-        v.motionPhotoEnabledMutable.value = true+        // Picking a length again restores the diversion.+        v.motionPhotoDurationMutable.value = MotionPhotoDuration.THREE         assertEquals(StillRoute.MOTION_PHOTO, v.routeStillCapture())     } 
camera/src/test/java/com/vayunmathur/camera/platform/PanoramaZoomLockTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/PanoramaZoomLockTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/PanoramaZoomLockTest.ktnew file mode 100644index 0000000000..596e14dfc7--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/PanoramaZoomLockTest.kt@@ -0,0 +1,195 @@+package com.vayunmathur.camera.platform++import android.graphics.ImageFormat+import android.util.Range+import android.util.Size+import android.view.Surface+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.camera.platform.camera2.Camera2Driver+import com.vayunmathur.camera.platform.camera2.Camera2Executor+import com.vayunmathur.camera.platform.camera2.Camera2Session+import com.vayunmathur.camera.platform.camera2.CaptureSessionCallback+import com.vayunmathur.camera.platform.camera2.CaptureSessionHandle+import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade+import com.vayunmathur.camera.platform.camera2.DeviceCallback+import com.vayunmathur.camera.platform.camera2.DeviceHandle+import com.vayunmathur.camera.platform.camera2.FrameSize+import com.vayunmathur.camera.platform.camera2.LensCharacteristicsSnapshot+import com.vayunmathur.camera.platform.camera2.ResolvedRequestParams+import com.vayunmathur.camera.platform.camera2.StillOutput+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Panorama/Photosphere zoom lock: the session must sit at 1x no matter+ * what zoom the user had stored from Photo/other modes, and the stored+ * ratio must survive the mode so leaving restores it untouched.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PanoramaZoomLockTest {++    private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext())++    private class FakeHandle : CaptureSessionHandle {+        override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}+        override fun captureStill(+            params: com.vayunmathur.camera.platform.camera2.ResolvedStillParams,+            stillTarget: Surface,+            callback: com.vayunmathur.camera.platform.camera2.StillResultCallback,+        ) {+            callback.onCompleted(com.vayunmathur.camera.platform.camera2.RawStillMetadata())+        }+        override fun close() {}+    }++    private class FakeDevice : DeviceHandle {+        override val cameraId: String = "0"+        override fun createCaptureSession(surfaces: List<Surface>, callback: CaptureSessionCallback) {+            callback.onConfigured(FakeHandle())+        }+        override fun close() {}+    }++    private class FakeDriver : Camera2Driver {+        override fun openCamera(cameraId: String, callback: DeviceCallback) {+            callback.onOpened(FakeDevice())+        }+        override fun createStillOutput(size: FrameSize): StillOutput? = null+    }++    private fun snapshot(): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+        cameraId = "0", zoomRatioRange = Range(0.5f, 8f), hasFlashUnit = true,+        sensitivityRange = Range(50, 6400), exposureCompensationEvRange = Range(-4f, 4f),+        exposureTimeRangeNs = Range(1_000_000L, 1_000_000_000L),+        sizesByFormat = mapOf(ImageFormat.PRIVATE to listOf(Size(1920, 1080))),+        activeArrayWidth = 4000, activeArrayHeight = 3000,+        exposureCompensationStepEv = 1f / 6f, maxAfRegions = 1, maxAeRegions = 1,+    ).snapshot++    private fun Camera2Executor.drain() {+        val latch = CountDownLatch(1)+        execute { latch.countDown() }+        assertTrue(latch.await(5, TimeUnit.SECONDS))+    }++    @Test+    fun lockedModesAreExactlyPanoramaAndPhotosphere() {+        assertTrue(CameraMode.PANORAMA.isZoomLockedTo1x())+        assertTrue(CameraMode.PHOTOSPHERE.isZoomLockedTo1x())+        for (mode in CameraMode.entries - CameraMode.PANORAMA - CameraMode.PHOTOSPHERE) {+            assertFalse(mode.isZoomLockedTo1x(), "mode $mode must not be zoom-locked")+            assertEquals(3f, effectiveZoomRatioForMode(mode, 3f))+        }+        assertEquals(1f, effectiveZoomRatioForMode(CameraMode.PANORAMA, 3f))+        assertEquals(1f, effectiveZoomRatioForMode(CameraMode.PHOTOSPHERE, 0.5f))+    }++    @Test+    fun bindApplies1xDespiteStoredZoomAndKeepsStoredZoom() {+        for (mode in listOf(CameraMode.PANORAMA, CameraMode.PHOTOSPHERE)) {+            val executor = Camera2Executor("pano-lock-$mode")+            val session = Camera2Session(FakeDriver(), executor, snapshot())+            val viewModel = vm()+            try {+                viewModel.cameraModeMutable.value = mode+                viewModel.zoomRatioMutable.value = 3f+                // Session left over from Photo at the stored zoom.+                session.setZoomRatio(3f)+                executor.drain()+                assertEquals(3f, session.controlState.zoomRatio)++                viewModel.registerCamera2Session(session)+                executor.drain()+                assertEquals(1f, session.controlState.zoomRatio, "bind in $mode")+                assertEquals(3f, viewModel.zoomRatio.value, "stored zoom must survive $mode")++                // Same guarantee through the capability-refresh bind path.+                session.setZoomRatio(3f)+                executor.drain()+                viewModel.restoreZoom(0.5f, 8f)+                executor.drain()+                assertEquals(1f, session.controlState.zoomRatio, "restoreZoom in $mode")+                assertEquals(3f, viewModel.zoomRatio.value)+            } finally {+                executor.shutdown()+            }+        }+    }++    @Test+    fun zoomChangesWhileLockedAreIgnoredAndStoredZoomSurvives() {+        val executor = Camera2Executor("pano-lock-ignore")+        val session = Camera2Session(FakeDriver(), executor, snapshot())+        val viewModel = vm()+        try {+            viewModel.activeCamera2Session = session+            viewModel.cameraModeMutable.value = CameraMode.PANORAMA+            viewModel.zoomRatioMutable.value = 2.5f++            viewModel.setZoomRatio(5f)+            viewModel.onViewfinderZoomRatio(5f)+            executor.drain()++            assertEquals(1f, session.controlState.zoomRatio)+            assertEquals(2.5f, viewModel.zoomRatio.value)+        } finally {+            executor.shutdown()+        }+    }++    @Test+    fun enteringLockedModeApplies1xAndLeavingRestoresStoredZoom() {+        val executor = Camera2Executor("pano-lock-switch")+        val session = Camera2Session(FakeDriver(), executor, snapshot())+        val viewModel = vm()+        try {+            viewModel.activeCamera2Session = session+            viewModel.zoomRatioMutable.value = 2.5f+            session.setZoomRatio(2.5f)+            executor.drain()++            viewModel.switchCameraMode(CameraMode.PHOTOSPHERE)+            executor.drain()+            assertEquals(1f, session.controlState.zoomRatio)+            assertEquals(2.5f, viewModel.zoomRatio.value)++            viewModel.switchCameraMode(CameraMode.PHOTO)+            executor.drain()+            assertEquals(2.5f, session.controlState.zoomRatio)+            assertEquals(2.5f, viewModel.zoomRatio.value)+        } finally {+            executor.shutdown()+        }+    }++    @Test+    fun otherModesStillApplyStoredZoomAtBind() {+        val executor = Camera2Executor("zoom-unlocked")+        val session = Camera2Session(FakeDriver(), executor, snapshot())+        val viewModel = vm()+        try {+            viewModel.activeCamera2Session = session+            viewModel.cameraModeMutable.value = CameraMode.PHOTO+            viewModel.zoomRatioMutable.value = 3f++            viewModel.restoreZoom(0.5f, 8f)+            executor.drain()+            assertEquals(3f, session.controlState.zoomRatio)++            viewModel.setZoomRatio(99f)+            executor.drain()+            assertEquals(8f, session.controlState.zoomRatio)+            assertEquals(8f, viewModel.zoomRatio.value)+        } finally {+            executor.shutdown()+        }+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.ktindex f647af61ee..e8757ed6d1 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt@@ -69,7 +69,10 @@ class AudioInputDevicesTest {         val usbHeadset = RawAudioInputDevice(21, AudioDeviceInfo.TYPE_USB_HEADSET, "USB Mic Pro", "card=1;device=0")         val usbOptions = AudioInputDevicePolicy.options(listOf(usbGeneric, usbHeadset))         assertEquals(1, usbOptions.size)-        assertEquals(AudioInputDeviceSelection(21, AudioDeviceInfo.TYPE_USB_HEADSET), usbOptions[0].selection)+        assertEquals(+            AudioInputDeviceSelection(21, AudioDeviceInfo.TYPE_USB_HEADSET, "USB Mic Pro", "card=1;device=0"),+            usbOptions[0].selection,+        )         assertEquals("USB Mic Pro", usbOptions[0].label)         assertEquals("USB headset", usbOptions[0].description) @@ -79,7 +82,27 @@ class AudioInputDevicesTest {         val ble = RawAudioInputDevice(31, AudioDeviceInfo.TYPE_BLE_HEADSET, "Buds", "AA:BB:CC:DD:EE:FF")         val btOptions = AudioInputDevicePolicy.options(listOf(sco, ble))         assertEquals(1, btOptions.size)-        assertEquals(AudioInputDeviceSelection(31, AudioDeviceInfo.TYPE_BLE_HEADSET), btOptions[0

Diff truncated.