camera: recover transient Camera2 failures instead of sticking
- Commit
22c158b01e73f6586dacfd623e0659e3102f6de1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 14:30 UTC (22 hours ago)
- Parents
7998acd
The 'camera couldn't start' error stuck until process restart (or an unrelated mode/lens change) because transient lifecycle failures became permanent state in three places. Bind-latch vs lifecycle: a failed Camera2 bind latches sessionBindFailed + a per-engine fallback key, which flips useCamera2Preview off; the only latch-clear sat inside that same branch's repeatOnLifecycle block, so after a failure the branch was never entered again and no resume could clear it. Manual retry also cleared only the regular-preview latch, so a slo-mo or night failure retried into a black box. Fix: clearBindFailuresOnResume() clears every latch + the bind-failed flag; manual retry and an independent lifecycle-STARTED effect in CameraScreenEffects both use it, so leave-and-return is a fresh bind attempt. Session state machine: ERROR was terminal (no OPEN_REQUESTED) and DEVICE_CLOSED was illegal from OPENING/OPEN/CONFIGURING/STREAMING, and Camera2Session.open() silently dropped any open not made from CLOSED — so a sync openCamera throw, a device error, or a configure failure (which fell back to OPEN with a live device) wedged the session. Fix: ERROR can re-enter OPENING, DEVICE_CLOSED reaches CLOSED from any live state, and every device/configure/open failure in Camera2Session, Camera2ExtensionSession and Camera2HighSpeedSession now runs the synchronous executor-thread teardownNow(): capture session, all still/ring/analysis outputs and the device are closed and the session lands in CLOSED, so the next surface/lifecycle open on the same session object succeeds. The existing parked-reopen serialization (awaiting the old device's real onClosed) is unchanged. Leaks on the paths touched: the failure paths above previously left readers and the device open, the classic cause of the NEXT launch failing camera-in-use; Camera2VideoRecordingEngine.releaseAll now also closes its capture session/device (its start/error paths reach it without a clean stop), and its onDisconnected now surfaces an engine error instead of leaving the UI in a stuck recording state with a dead device. Tests (written first, red before the fix): SessionStateMachineTest gains ERROR-reopen and DEVICE_CLOSED recovery transitions; Camera2SessionTest gains configure-fail, device-error and sync-open-throw cases proving the device/session are released and a reopen streams on the same session (the existing configure-failure expectations in the session/extension/high-speed tests move from stuck OPEN to recovered CLOSED); CameraSessionBindRetryTest gains all-latch manual-retry and resume-clear cases. Verified: ./gradlew :camera:lint :camera:lintVitalRelease :camera:testDevUnitTest --max-workers=128 BUILD SUCCESSFUL, plus a --rerun-tasks run of the five touched test classes after a whitespace-only cleanup. :camera:ktlintCheck fails module-wide on pre-existing violations in untouched files (data/, androidTest/, screenshotTest/); the required Android lint gate is green.
Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex 2676cb591a..6632e860fd 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -58,7 +58,7 @@ for a direct open-on-phone broadcast. - Watch listing screenshots are the `group = "wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt`, collected by `:camera:metadata` into `metadata_data/photos/camera/wear/`; phone/tablet shots keep their buckets. **Gotchas:** - Capture code lives in `platform/` (the Camera2 driver in `platform/camera2/`); there is no `util/` root in this module-- Camera2 session reopen after a surface destroy (background/resume, size change) is serialized in `platform/camera2/`: a session parks a reopen until the previous device's real `onClosed` (device `close()` only initiates HAL teardown), and `PreviewSurfaceBridge` forgets its pinned stream size on destroy so a new `SurfaceTexture` is re-pinned before configure+- Camera2 session reopen after a surface destroy (background/resume, size change) is serialized in `platform/camera2/`: a session parks a reopen until the previous device's real `onClosed` (device `close()` only initiates HAL teardown), and `PreviewSurfaceBridge` forgets its pinned stream size on destroy so a new `SurfaceTexture` is re-pinned before configure. A device/configure failure tears the session down to CLOSED (capture session, every output and the device are closed, never leaked) so the next surface/lifecycle open on the same session can succeed; bind-failure latches for every preview engine are cleared on manual retry and on each lifecycle STARTED entry (`clearBindFailuresOnResume`), otherwise a latched failure would keep its own preview branch uncomposed and could never re-arm - Listing screenshots are preview-rendered (`:camera:metadata`): Layoutlib can't open a camera, so `src/screenshotTest` draws the deterministic `FakeCameraPreview` scene behind the real top bar/grid/shutter/mode controls. `Route.Settings` is captured from the stateless `CameraSettingsContent` slice in `ui/SettingsPage.kt` with literal fixtures. The `screenshotFakePreview` parameter on `CameraScreen`/`CameraPreviewSurface` is the same seam in `main` — production-default null, never passed by `MainActivity`, so no fake frame can appear on device - Volume keys act as the shutter, gated on the camera route being foreground; Esc/space covers desktop keyboards - `.maml` model assets ship uncompressed (`noCompress`) — never compress them
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 4f8b9b9501..7acb23733f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -351,6 +351,10 @@ class Camera2VideoRecordingEngine( override fun onDisconnected(device: CameraDevice) { device.close() cameraDevice = null+ // A disconnect is an engine failure like onError: without+ // surfacing it the ViewModel stayed in "recording" with+ // a dead device and a frozen recording preview forever.+ onError(IllegalStateException("Custom recorder camera disconnected")) } override fun onError(device: CameraDevice, error: Int) {@@ -441,6 +445,13 @@ class Camera2VideoRecordingEngine( } private fun releaseAll() {+ // Close the session/device here too, not only in stop(): the+ // start-failure and engine-error paths reach releaseAll without+ // a clean stop, and a leaked device is the classic cause of+ // the NEXT open failing with camera-in-use.+ try { captureSession?.close() } catch (_: Exception) {}+ try { cameraDevice?.close() } catch (_: Exception) {}+ cameraDevice = null try { analysisReader?.close() } catch (_: Exception) {} // The preview surface is owned by the recording viewfinder's // TextureView (via its bridge), never released here.
camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.ktindex afe6f203b9..8b752d0a22 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt@@ -37,9 +37,11 @@ internal suspend fun runSessionBindWithRetry( * effect is keyed on, which cancels the parked effect and rebinds. */ fun CameraViewModel.retrySessionBind() {- sessionBindFailedMutable.value = false- // A manual retry is a fresh bind attempt: Camera2 may be tried once again.- clearCamera2Fallback()+ // A manual retry is a fresh bind attempt for whichever engine+ // actually failed: clearing only the regular-preview latch left a+ // slo-mo/night failure latched, so Retry fell back to a black box+ // instead of rebinding the failed preview.+ clearBindFailuresOnResume() sessionBindRetryMutable.value += 1 }
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.ktindex c2b235244d..35c6742fcd 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt@@ -61,6 +61,24 @@ fun CameraViewModel.clearCamera2SloMoFallback() { camera2SloMoFallbackBindKeyMutable.value = null } +/**+ * Clears every bind-failure latch and the bind-failed flag. Used when+ * the lifecycle returns to STARTED: leaving and returning is a fresh+ * bind attempt, so a transient failure (camera briefly held by+ * another app, HAL still tearing down at first bind) must not stick+ * as a permanent "couldn't start" across pause/resume. Clearing them+ * inside the Camera2 branch of the session effect was unreachable+ * exactly when it mattered — a latched failure flips+ * `useCamera2Preview` off, that branch is never entered again, and+ * its `repeatOnLifecycle` block never re-runs to clear the latch.+ */+fun CameraViewModel.clearBindFailuresOnResume() {+ sessionBindFailedMutable.value = false+ clearCamera2Fallback()+ clearCamera2SloMoFallback()+ clearCamera2NightFallback()+}+ /** Registers the live slo-mo high-speed session (null when it leaves composition). */ internal fun CameraViewModel.registerCamera2HighSpeedSession( session: com.vayunmathur.camera.platform.camera2.Camera2HighSpeedSession?,
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.ktindex be47a5f738..a20d6d6adf 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt@@ -135,6 +135,7 @@ class Camera2ExtensionSession( /** The [open] body; must run on the executor thread (or a device callback on it). */ private fun openOnExecutor(cameraId: String, surface: Surface, requestedSize: FrameSize) {+ if (stateMachine.state == SessionState.ERROR) teardownNow() if (stateMachine.state != SessionState.CLOSED) return val probe = Camera2ExtensionProbe.probeNight(snapshot) probeResult = probe@@ -164,6 +165,7 @@ class Camera2ExtensionSession( }.onFailure { dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("openCamera failed for $cameraId: ${it.message}")+ teardownNow() } } @@ -217,36 +219,39 @@ class Camera2ExtensionSession( /** Tears the session down; idempotent and terminal. */ fun close() {- executor.execute {- pendingOpen = null- if (stateMachine.state == SessionState.CLOSED) return@execute- val gen = stateMachine.beginTeardown()- pendingStill?.let { pending ->- pendingStill = null- runCatching { pending.callback.onStillFailed("session closed during capture") }- }- runCatching { captureSession?.close() }- captureSession = null- runCatching { stillOutput?.close() }- stillOutput = null- stillSize = null- val closingDevice = device- if (closingDevice != null) {- awaitingDeviceClosedGeneration =- deviceCallbackGeneration?.takeIf { it != deviceClosedGeneration }- runCatching { closingDevice.close() }- .onFailure { awaitingDeviceClosedGeneration = null }- }- device = null- previewSurface = null- dispatch(gen, SessionEvent.DEVICE_CLOSED)- if (stateMachine.state == SessionState.CLOSING) {- stateMachine.completeTeardown()- }- notifyState()- }+ executor.execute { teardownNow() } } + /** Synchronous executor-thread teardown; also the failure-recovery path. */+ internal fun teardownNow() {+ pendingOpen = null+ if (stateMachine.state == SessionState.CLOSED) return+ val gen = stateMachine.beginTeardown()+ pendingStill?.let { pending ->+ pendingStill = null+ runCatching { pending.callback.onStillFailed("session closed during capture") }+ }+ runCatching { captureSession?.close() }+ captureSession = null+ runCatching { stillOutput?.close() }+ stillOutput = null+ stillSize = null+ val closingDevice = device+ if (closingDevice != null) {+ awaitingDeviceClosedGeneration =+ deviceCallbackGeneration?.takeIf { it != deviceClosedGeneration }+ runCatching { closingDevice.close() }+ .onFailure { awaitingDeviceClosedGeneration = null }+ }+ device = null+ previewSurface = null+ dispatch(gen, SessionEvent.DEVICE_CLOSED)+ if (stateMachine.state == SessionState.CLOSING) {+ stateMachine.completeTeardown()+ }+ notifyState()+}+ // -- internals (executor thread only) ------------------------------------ private fun onStillResult(pending: PendingStill, metadata: RawStillMetadata) {@@ -326,6 +331,7 @@ class Camera2ExtensionSession( if (output == null) { dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("no JPEG still output for Camera2 NIGHT extension session")+ teardownNow() return } val surfaces = listOf(surface, output.surface)@@ -338,6 +344,7 @@ class Camera2ExtensionSession( }.onFailure { dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("createExtensionCaptureSession failed: ${it.message}")+ teardownNow() } } @@ -395,12 +402,14 @@ class Camera2ExtensionSession( if (!stateMachine.isCurrent(gen)) return dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("camera disconnected")+ teardownNow() } override fun onError(errorCode: Int) { if (!stateMachine.isCurrent(gen)) return dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("camera open error $errorCode")+ teardownNow() } } @@ -425,6 +434,7 @@ class Camera2ExtensionSession( if (!stateMachine.isCurrent(gen)) return dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("extension capture session configure failed")+ teardownNow() } override fun onClosed() {
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.ktindex 465e0c5621..fef49da503 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt@@ -74,6 +74,7 @@ class Camera2HighSpeedSession( /** The [open] body; must run on the executor thread (or a device callback on it). */ private fun openOnExecutor(cameraId: String, encoderSurface: Surface, previewSurface: Surface) {+ if (stateMachine.state == SessionState.ERROR) teardownNow() if (stateMachine.state != SessionState.CLOSED) return val selected = HighSpeedPlanner.select(snapshot) if (selected == null) {@@ -91,6 +92,7 @@ class Camera2HighSpeedSession( }.onFailure { dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("openCamera failed for $cameraId: ${it.message}")+ teardownNow() } } @@ -121,28 +123,31 @@ class Camera2HighSpeedSession( * and are not released here. */ fun close() {- executor.execute {- pendingOpen = null- if (stateMachine.state == SessionState.CLOSED) return@execute- val gen = stateMachine.beginTeardown()- runCatching { captureSession?.close() }- captureSession = null- val closingDevice = device- if (closingDevice != null) {- awaitingDeviceClosedGeneration =- deviceCallbackGeneration?.takeIf { it != deviceClosedGeneration }- runCatching { closingDevice.close() }- .onFailure { awaitingDeviceClosedGeneration = null }- }- device = null- dispatch(gen, SessionEvent.DEVICE_CLOSED)- if (stateMachine.state == SessionState.CLOSING) {- stateMachine.completeTeardown()- }- notifyState()- }+ executor.execute { teardownNow() } } + /** Synchronous executor-thread teardown; also the failure-recovery path. */+ internal fun teardownNow() {+ pendingOpen = null+ if (stateMachine.state == SessionState.CLOSED) return+ val gen = stateMachine.beginTeardown()+ runCatching { captureSession?.close() }+ captureSession = null+ val closingDevice = device+ if (closingDevice != null) {+ awaitingDeviceClosedGeneration =+ deviceCallbackGeneration?.takeIf { it != deviceClosedGeneration }+ runCatching { closingDevice.close() }+ .onFailure { awaitingDeviceClosedGeneration = null }+ }+ device = null+ dispatch(gen, SessionEvent.DEVICE_CLOSED)+ if (stateMachine.state == SessionState.CLOSING) {+ stateMachine.completeTeardown()+ }+ notifyState()+}+ // -- internals (executor thread only) ------------------------------------ private fun configureSession(@@ -160,6 +165,7 @@ class Camera2HighSpeedSession( }.onFailure { dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("createConstrainedHighSpeedCaptureSession failed: ${it.message}")+ teardownNow() } } @@ -229,12 +235,14 @@ class Camera2HighSpeedSession( if (!stateMachine.isCurrent(gen)) return dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("camera disconnected")+ teardownNow() } override fun onError(errorCode: Int) { if (!stateMachine.isCurrent(gen)) return dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("camera open error $errorCode")+ teardownNow() } } @@ -261,6 +269,7 @@ class Camera2HighSpeedSession( if (!stateMachine.isCurrent(gen)) return dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("constrained high-speed session configure failed")+ teardownNow() } override fun onClosed() {
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktindex ee9c42570c..be87ca2143 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt@@ -188,6 +188,13 @@ class Camera2Session( /** The [open] body; must run on the executor thread (or a device callback on it). */ private fun openOnExecutor(cameraId: String, surface: Surface, requestedSize: FrameSize) {+ if (stateMachine.state == SessionState.ERROR) {+ // A previous transient failure left the session in ERROR:+ // release whatever it still holds and reopen from clean+ // CLOSED instead of silently dropping this open (the+ // stuck "couldn't start" until process restart).+ teardownNow()+ } if (stateMachine.state != SessionState.CLOSED) return // LIMITED guaranteed combinations cap the preview target at // 1080p alongside JPEG(MAX)+YUV: never select a larger preview@@ -216,6 +223,7 @@ class Camera2Session( }.onFailure { dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("openCamera failed for $cameraId: ${it.message}")+ teardownNow() } } @@ -525,62 +533,73 @@ class Camera2Session( * device. Idempotent. */ fun close() {- executor.execute {- // A parked reopen is cancelled by any later teardown (the- // surface went away again before the old device finished- // closing); it must not resurrect the camera afterwards.- pendingOpen = null- if (stateMachine.state == SessionState.CLOSED) return@execute- val gen = stateMachine.beginTeardown()- pendingStill?.let { pending ->- pendingStill = null- runCatching { pending.callback.onStillFailed("session closed during capture") }- }- runCatching { captureSession?.close() }- captureSession = null- runCatching { stillOutput?.close() }- stillOutput = null- stillSize = null- runCatching { ultraHdrOutput?.close() }- ultraHdrOutput = null- ultraHdrSize = null- runCatching { ringOutput?.close() }- ringOutput = null- ringSize = null- ring.drainAll().forEach { runCatching { it.close() } }- runCatching { analysisOutput?.close() }- analysisOutput = null- analysisSize = null- runCatching { rawRingOutput?.close() }- rawRingOutput = null- rawRingSize = null- rawRingFormat = null- rawRing.drainAll().forEach { runCatching { it.close() } }- previewMetas.clear()- // The session reports CLOSED below so its own bookkeeping can- // proceed, but the HAL device is only closing: record which- // generation's real onClosed completes the teardown so a- // following open waits for it (see pendingOpen).- val closingDevice = device- if (closingDevice != null) {- // Only await a close that has not already been signalled- // (a device that errored/disconnected may have delivered- // its onClosed before this teardown ran).- awaitingDeviceClosedGeneration =- deviceCallbackGeneration?.takeIf { it != deviceClosedGeneration }- runCatching { closingDevice.close() }- .onFailure { awaitingDeviceClosedGeneration = null }- }- device = null- previewSurface = null- dispatch(gen, SessionEvent.DEVICE_CLOSED)- if (stateMachine.state == SessionState.CLOSING) {- stateMachine.completeTeardown()- }- notifyState()- }+ executor.execute { teardownNow() } } + /**+ * Synchronous teardown on the executor thread (see [close]). Also+ * the recovery path for device/configure failures: an errored+ * session must release its capture session, every reader/output and+ * the device and return to CLOSED, otherwise the leaked readers and+ * the non-CLOSED state make the next open fail or be dropped — the+ * transient failure becomes permanent until process restart.+ */+ internal fun teardownNow() {+ // A parked reopen is cancelled by any later teardown (the+ // surface went away again before the old device finished+ // closing); it must not resurrect the camera afterwards.+ pendingOpen = null+ if (stateMachine.state == SessionState.CLOSED) return+ val gen = stateMachine.beginTeardown()+ pendingStill?.let { pending ->+ pendingStill = null+ runCatching { pending.callback.onStillFailed("session closed during capture") }+ }+ runCatching { captureSession?.close() }+ captureSession = null+ runCatching { stillOutput?.close() }+ stillOutput = null+ stillSize = null+ runCatching { ultraHdrOutput?.close() }+ ultraHdrOutput = null+ ultraHdrSize = null+ runCatching { ringOutput?.close() }+ ringOutput = null+ ringSize = null+ ring.drainAll().forEach { runCatching { it.close() } }+ runCatching { analysisOutput?.close() }+ analysisOutput = null+ analysisSize = null+ analysisComboDropped = false+ runCatching { rawRingOutput?.close() }+ rawRingOutput = null+ rawRingSize = null+ rawRingFormat = null+ rawRing.drainAll().forEach { runCatching { it.close() } }+ previewMetas.clear()+ // The session reports CLOSED below so its own bookkeeping can+ // proceed, but the HAL device is only closing: record which+ // generation's real onClosed completes the teardown so a+ // following open waits for it (see pendingOpen).+ val closingDevice = device+ if (closingDevice != null) {+ // Only await a close that has not already been signalled+ // (a device that errored/disconnected may have delivered+ // its onClosed before this teardown ran).+ awaitingDeviceClosedGeneration =+ deviceCallbackGeneration?.takeIf { it != deviceClosedGeneration }+ runCatching { closingDevice.close() }+ .onFailure { awaitingDeviceClosedGeneration = null }+ }+ device = null+ previewSurface = null+ dispatch(gen, SessionEvent.DEVICE_CLOSED)+ if (stateMachine.state == SessionState.CLOSING) {+ stateMachine.completeTeardown()+ }+ notifyState()+}+ // -- internals (executor thread only) ------------------------------------ private fun issueRepeatingRequest() {@@ -668,12 +687,14 @@ class Camera2Session( if (!stateMachine.isCurrent(gen)) return dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("camera disconnected")+ teardownNow() } override fun onError(errorCode: Int) { if (!stateMachine.isCurrent(gen)) return dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("camera open error $errorCode")+ teardownNow() } } @@ -709,6 +730,10 @@ class Camera2Session( } dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("capture session configure failed")+ // Release device + outputs and land in CLOSED: leaving the+ // session in OPEN with a live device made the next open a+ // silent no-op and leaked the readers for the next attempt.+ teardownNow() } override fun onClosed() {
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.ktindex d625fe7a45..216fc8c882 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt@@ -156,6 +156,7 @@ internal fun Camera2Session.createCaptureSessionWithAnalysisFallback(opened: Dev } else { dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("createCaptureSession failed: ${it.message}")+ teardownNow() } } }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.ktindex c438d105b8..d9e27d7d57 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.kt@@ -112,12 +112,14 @@ class SessionStateMachine { } SessionState.OPENING -> when (event) { SessionEvent.DEVICE_OPENED -> SessionState.OPEN+ SessionEvent.DEVICE_CLOSED -> SessionState.CLOSED SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING SessionEvent.ERROR_OCCURRED -> SessionState.ERROR else -> null } SessionState.OPEN -> when (event) { SessionEvent.CONFIGURE_REQUESTED -> SessionState.CONFIGURING+ SessionEvent.DEVICE_CLOSED -> SessionState.CLOSED SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING SessionEvent.ERROR_OCCURRED -> SessionState.ERROR else -> null@@ -125,12 +127,14 @@ class SessionStateMachine { SessionState.CONFIGURING -> when (event) { SessionEvent.SESSION_CONFIGURED -> SessionState.STREAMING SessionEvent.CONFIGURE_FAILED -> SessionState.OPEN+ SessionEvent.DEVICE_CLOSED -> SessionState.CLOSED SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING SessionEvent.ERROR_OCCURRED -> SessionState.ERROR else -> null } SessionState.STREAMING -> when (event) { SessionEvent.CONFIGURE_REQUESTED -> SessionState.CONFIGURING+ SessionEvent.DEVICE_CLOSED -> SessionState.CLOSED SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING SessionEvent.ERROR_OCCURRED -> SessionState.ERROR else -> null@@ -141,6 +145,12 @@ class SessionStateMachine { else -> null } SessionState.ERROR -> when (event) {+ // ERROR is recoverable, not terminal: the owning session+ // releases its device/outputs when it reports the error,+ // so the next open attempt (surface re-available, resume,+ // holder retry) may re-enter OPENING instead of being+ // silently dropped until an explicit close() happens.+ SessionEvent.OPEN_REQUESTED -> SessionState.OPENING SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING SessionEvent.DEVICE_CLOSED -> SessionState.CLOSED else -> null
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex 029dba50bc..0ccb5694cb 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -20,6 +20,7 @@ import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.PhotoAnalyzer import com.vayunmathur.camera.platform.addMotionFrame import com.vayunmathur.camera.platform.applyExposureCompensation+import com.vayunmathur.camera.platform.clearBindFailuresOnResume import com.vayunmathur.camera.platform.clearCamera2Fallback import com.vayunmathur.camera.platform.clearCamera2NightFallback import com.vayunmathur.camera.platform.applyImageCaptureFlashMode@@ -274,6 +275,20 @@ internal fun CameraScreenEffects( // backgrounded and rebound on resume. Without this the ManualLifecycleOwner stays RESUMED, // the OS reclaims the camera while we're away, and the preview comes back frozen. val lifecycleOwner = LocalLifecycleOwner.current+ // Resume re-arms bind failures, independently of which preview+ // branch is currently selected: a latched failure flips+ // useCamera2Preview off, so clearing the latch inside that+ // branch's own lifecycle block could never run again and the+ // error stuck across pause/resume until a mode/lens change or+ // process restart. Each STARTED entry is a fresh bind attempt;+ // clearing here flips the preview branch back on, which rebuilds+ // its session holder and reopens on the live surface.+ LaunchedEffect(lifecycleOwner) {+ lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {+ viewModel.clearBindFailuresOnResume()+ try { awaitCancellation() } finally { }+ }+ } // Codec/audio-device/mirror are fixed at bind time (Recorder mime, preferred device, MirrorMode), so // they join the effect keys: changing them in Settings rebinds instead of silently waiting // for the next mode switch. The keys are the APPLIED snapshot (bindTimeSettings), not the
camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.ktindex d3f43e2c97..be11638c80 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.kt@@ -72,6 +72,38 @@ class CameraSessionBindRetryTest { assertEquals(1, attempts) } + @Test fun manualRetryClearsEveryBindLatch() {+ // A retry tap must re-arm whichever engine actually failed:+ // clearing only the regular-preview latch left a slo-mo (or+ // night) failure latched, so Retry returned to a black box+ // instead of rebinding the failed preview.+ val viewModel = CameraViewModel(ApplicationProvider.getApplicationContext())+ viewModel.onCamera2PreviewFailed("0")+ viewModel.onCamera2SloMoFailed("0")+ viewModel.onCamera2NightPreviewFailed("0")+ assertTrue(viewModel.sessionBindFailedMutable.value)+ viewModel.retrySessionBind()+ assertFalse(viewModel.sessionBindFailedMutable.value)+ assertEquals(null, viewModel.camera2FallbackBindKeyMutable.value)+ assertEquals(null, viewModel.camera2SloMoFallbackBindKeyMutable.value)+ assertEquals(null, viewModel.camera2NightFallbackBindKeyMutable.value)+ }++ @Test fun resumeClearingBindFailuresRearmsEveryEngine() {+ // Leaving and returning (lifecycle STARTED again) is a fresh+ // bind attempt: transient failures must not stick across a+ // pause/resume that never changed mode or lens.+ val viewModel = CameraViewModel(ApplicationProvider.getApplicationContext())+ viewModel.onCamera2PreviewFailed("0")+ viewModel.onCamera2SloMoFailed("0")+ viewModel.onCamera2NightPreviewFailed("0")+ viewModel.clearBindFailuresOnResume()+ assertFalse(viewModel.sessionBindFailedMutable.value)+ assertEquals(null, viewModel.camera2FallbackBindKeyMutable.value)+ assertEquals(null, viewModel.camera2SloMoFallbackBindKeyMutable.value)+ assertEquals(null, viewModel.camera2NightFallbackBindKeyMutable.value)+ }+ @Test fun manualRetryClearsFailureAndBumpsRetryCounter() { val viewModel = CameraViewModel(ApplicationProvider.getApplicationContext()) viewModel.sessionBindFailedMutable.value = true
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.ktindex 40a311bb55..efd74e3c81 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.kt@@ -231,7 +231,7 @@ class Camera2ExtensionSessionTest { val session = Camera2ExtensionSession(driver, executor, snapshot(), listener = listener) session.open("0", mock(Surface::class.java), FrameSize(1280, 720)) executor.drain()- assertEquals(SessionState.OPEN, session.state)+ assertEquals(SessionState.CLOSED, session.state) assertTrue(listener.errors.any { it.contains("configure failed") }) assertTrue(listener.streaming.isEmpty()) } finally {@@ -249,7 +249,7 @@ class Camera2ExtensionSessionTest { session.open("0", mock(Surface::class.java), FrameSize(1280, 720)) executor.drain() assertTrue(!device.regularSessionRequested)- assertEquals(SessionState.OPEN, session.state)+ assertEquals(SessionState.CLOSED, session.state) assertTrue(listener.errors.any { it.contains("configure failed") }) } finally { executor.shutdown()
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.ktindex 90b8925b3c..036f42f951 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt@@ -186,7 +186,7 @@ class Camera2HighSpeedSessionTest { } } - @Test fun configureFailureReportsErrorAndStaysOpen() {+ @Test fun configureFailureReportsErrorAndReturnsToClosed() { val executor = Camera2Executor("HighSpeedSessionTest-cfgfail") try { val driver = FakeDriver(FakeDeviceHandle(failConfigure = true))@@ -194,7 +194,7 @@ class Camera2HighSpeedSessionTest { val session = Camera2HighSpeedSession(driver, executor, snapshot(), listener = listener) session.open("0", mock(Surface::class.java), mock(Surface::class.java)) executor.drain()- assertEquals(SessionState.OPEN, session.state)+ assertEquals(SessionState.CLOSED, session.state) assertTrue(listener.errors.any { it.contains("configure failed") }) assertTrue(listener.streaming.isEmpty()) } finally {
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.ktindex e071366988..e9b388b890 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt@@ -212,7 +212,7 @@ class Camera2SessionTest { } } - @Test fun configureFailureFallsBackToOpenWithError() {+ @Test fun configureFailureReturnsToClosedWithError() { val executor = Camera2Executor("Camera2SessionTest-cfgfail") try { val driver = FakeDriver(failConfigure = true)@@ -221,7 +221,7 @@ class Camera2SessionTest { session.open("0", mock(Surface::class.java), FrameSize(1280, 720)) executor.drain() - assertEquals(SessionState.OPEN, session.state)+ assertEquals(SessionState.CLOSED, session.state) assertTrue(listener.errors.any { it.contains("configure failed") }) assertTrue(listener.streamingSizes.isEmpty()) } finally {@@ -326,6 +326,109 @@ class Camera2SessionTest { } } + /**+ * Transient configure failure: the session must release the device+ * and its capture session and return to CLOSED, so the next open+ * (surface re-available / resume / holder retry) can succeed on the+ * same session object instead of being silently dropped because the+ * machine is stuck in OPEN after CONFIGURE_FAILED.+ */+ @Test fun configureFailureReleasesDeviceAndReopenSucceeds() {+ val executor = Camera2Executor("Camera2SessionTest-cfg-retry")+ try {+ var failConfigure = true+ var openCount = 0+ val devices = mutableListOf<FakeDeviceHandle>()+ var lastCallback: DeviceCallback? = null+ val driver = object : Camera2Driver {+ override fun openCamera(cameraId: String, callback: DeviceCallback) {+ openCount+++ lastCallback = callback+ val handed = FakeDeviceHandle(cameraId, failConfigure = failConfigure)+ devices += handed+ handed.onClosedHook = { callback.onClosed() }+ callback.onOpened(handed)+ }+ override fun createStillOutput(size: FrameSize): StillOutput? = null+ }+ val listener = RecordingListener()+ val session = newSession(driver, executor, listener)+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertTrue(listener.errors.any { it.contains("configure failed") })+ assertEquals(SessionState.CLOSED, session.state)+ assertTrue(devices.single().closed, "failed configure must close the device")++ failConfigure = false+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(2, openCount)+ assertEquals(SessionState.STREAMING, session.state)+ } finally {+ executor.shutdown()+ }+ }++ /**+ * Device error mid-stream (camera in use / disconnect): the session+ * closes its capture session and device instead of leaking them in+ * ERROR, returns to CLOSED, and a later surface open streams again+ * without the owner having to call close() first.+ */+ @Test fun deviceErrorReleasesSessionAndReopenSucceeds() {+ val executor = Camera2Executor("Camera2SessionTest-dev-err")+ try {+ val driver = FakeDriver()+ val listener = RecordingListener()+ val session = newSession(driver, executor, listener)+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)++ driver.deviceCallback!!.onError(4)+ executor.drain()+ assertEquals(SessionState.CLOSED, session.state)+ assertTrue(driver.device.sessionHandleRef.closed)+ assertTrue(driver.device.closed)++ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ assertEquals(2, driver.openCount)+ } finally {+ executor.shutdown()+ }+ }++ /** A synchronous openCamera throw leaves the session reopenable, not stuck in ERROR. */+ @Test fun syncOpenFailureReopenSucceeds() {+ val executor = Camera2Executor("Camera2SessionTest-open-throw")+ try {+ var throwOnOpen = true+ val delegate = FakeDriver()+ val driver = object : Camera2Driver {+ override fun openCamera(cameraId: String, callback: DeviceCallback) {+ if (throwOnOpen) throw IllegalStateException("camera in use")+ delegate.openCamera(cameraId, callback)+ }+ override fun createStillOutput(size: FrameSize): StillOutput? = null+ }+ val listener = RecordingListener()+ val session = newSession(driver, executor, listener)+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.CLOSED, session.state)+ assertTrue(listener.errors.isNotEmpty())++ throwOnOpen = false+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ } finally {+ executor.shutdown()+ }+ }+ @Test fun parkedReopenIsCancelledByAnotherClose() { val executor = Camera2Executor("Camera2SessionTest-reopen-cancelled") try {
camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.ktindex 72f489624b..eb5defaf5c 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.kt@@ -109,6 +109,40 @@ class SessionStateMachineTest { assertIs<TransitionResult.Rejected>(m.completeTeardown()) } + @Test fun errorStateCanReopenWithoutExplicitClose() {+ // Transient open/configure failures (camera briefly in use,+ // disconnect during configure) must not be a terminal stuck+ // state: the next open attempt — surface re-available, resume,+ // lifecycle retry — re-enters OPENING from ERROR.+ val m = streamingMachine()+ m.transition(SessionEvent.ERROR_OCCURRED)+ assertEquals(SessionState.ERROR, m.state)+ assertIs<TransitionResult.Applied>(m.transition(SessionEvent.OPEN_REQUESTED))+ assertEquals(SessionState.OPENING, m.state)+ assertIs<TransitionResult.Applied>(m.transition(SessionEvent.DEVICE_OPENED))+ assertEquals(SessionState.OPEN, m.state)+ }++ @Test fun deviceClosedWhileActiveReturnsToClosed() {+ // A device that closes underneath an active session (HAL+ // teardown completing after an error, or a disconnect racing+ // the open) lands the machine in CLOSED from any live state,+ // so a following open is legal instead of silently dropped.+ for (target in listOf(+ SessionState.OPENING, SessionState.OPEN, SessionState.CONFIGURING,+ SessionState.STREAMING,+ )) {+ val m = SessionStateMachine()+ driveTo(m, target)+ assertIs<TransitionResult.Applied>(+ m.transition(SessionEvent.DEVICE_CLOSED),+ "DEVICE_CLOSED from $target",+ )+ assertEquals(SessionState.CLOSED, m.state)+ assertIs<TransitionResult.Applied>(m.transition(SessionEvent.OPEN_REQUESTED))+ }+ }+ @Test fun legalTableAgreesWithMachine() { for (from in SessionState.entries) { for (event in SessionEvent.entries) {