camera: serialize reopen on real HAL close after backgrounding
- Commit
f2bb4896cd3fc2ec0a33af87ec8e81319db26cd1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-25 21:58 UTC (10 days ago)
- Parents
3ebeada
On background, Camera2Session.close() fired device.close() on the Camera2Executor and synthetically reported CLOSED, but CameraDevice.close() only initiates HAL teardown — the camera stays busy until the real StateCallback.onClosed. On resume, open() then issued openCamera against a still-closing device, failing the first bind; Retry worked only because the error path disposed the holder and built a fresh session after the old device had finished closing. PreviewSurfaceBridge also kept its pinned stream size across surface destruction, so the new SurfaceTexture never got setDefaultBufferSize re-applied. Fix: sessions (regular, extension, high-speed) park a reopen that arrives while a close is in flight and issue it only from the previous device's real onClosed; a later close cancels the parked open. PreviewSurfaceBridge forgets the pinned size on destroy so a new texture is re-pinned before configure. Ring capture moved verbatim to Camera2SessionRingCapture.kt to stay under the FileLength lint. Regression tests: reopenIsDeferredUntilPreviousDeviceClosed and parkedReopenIsCancelledByAnotherClose (fake HAL withholds onClosed), and PreviewSurfaceBridgeTest.newTextureAfterDestroyIsPinnedAgain — both fail before the fix. Verified: :camera:testDevUnitTest 605 tests, 0 failures; :camera:lint clean except the pre-existing RouteScreenshotCoverage error on Route.kt from in-flight screenshot work.
Diff
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.ktindex 70c7b1186c..c23fcff958 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt@@ -4,6 +4,7 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.camera.data.saveProcessedStill import com.vayunmathur.camera.data.setLastCaptureUri import com.vayunmathur.camera.platform.camera2.Camera2Session+import com.vayunmathur.camera.platform.camera2.captureRawBurst import com.vayunmathur.camera.platform.camera2.DngMetadataAssembler import com.vayunmathur.camera.platform.camera2.RawNightInput import com.vayunmathur.camera.platform.camera2.RawNightMerger
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 28198978da..7aad737a63 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -12,6 +12,7 @@ import com.vayunmathur.camera.domain.StillFormat import com.vayunmathur.camera.domain.StillFormatRouting import com.vayunmathur.camera.domain.UltraHdrIntentPolicy import com.vayunmathur.camera.platform.camera2.Camera2Session+import com.vayunmathur.camera.platform.camera2.captureFromRing import com.vayunmathur.camera.platform.camera2.CapturedStill import com.vayunmathur.camera.platform.camera2.StillOutputTag import com.vayunmathur.camera.platform.camera2.StillEngineInput
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 9a8b6bb0f8..7ee12442a6 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@@ -61,6 +61,19 @@ class Camera2ExtensionSession( private var stillSize: FrameSize? = null private var probeResult: ExtensionProbeResult? = null private var pendingStill: PendingStill? = null++ // Reopen serialization, mirroring Camera2Session: a device close only+ // completes at its real onClosed, so an open in that window is parked.+ private var awaitingDeviceClosedGeneration: Long? = null+ private var deviceCallbackGeneration: Long? = null+ private var deviceClosedGeneration: Long? = null+ private var pendingOpen: PendingOpen? = null++ private class PendingOpen(+ val cameraId: String,+ val surface: Surface,+ val requestedSize: FrameSize,+ ) private var displayRotationDegrees: Int = 0 private var controls: Camera2ControlState = Camera2ControlState.DEFAULT @@ -102,12 +115,22 @@ class Camera2ExtensionSession( */ fun open(cameraId: String, surface: Surface, requestedSize: FrameSize) { executor.execute {- if (stateMachine.state != SessionState.CLOSED) return@execute+ if (awaitingDeviceClosedGeneration != null) {+ pendingOpen = PendingOpen(cameraId, surface, requestedSize)+ return@execute+ }+ openOnExecutor(cameraId, surface, requestedSize)+ }+ }++ /** 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.CLOSED) return val probe = Camera2ExtensionProbe.probeNight(snapshot) probeResult = probe if (!probe.usable) { reportError("Camera2 NIGHT extension unusable for camera $cameraId: ${probe.rejectionReason}")- return@execute+ return } val previewSizes = snapshot.extensionSupportFor(probe.mode)?.previewSizes .orEmpty().map { FrameSize.from(it) }.distinct()@@ -117,21 +140,21 @@ class Camera2ExtensionSession( ) if (selected == null) { reportError("no extension preview sizes for camera $cameraId")- return@execute+ return } previewSurface = surface previewSize = selected if (transition(SessionEvent.OPEN_REQUESTED) !is TransitionResult.Applied) {- return@execute+ return } val gen = stateMachine.generation+ deviceCallbackGeneration = gen runCatching { driver.openCamera(cameraId, DeviceCallbackImpl(gen)) }.onFailure { dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("openCamera failed for $cameraId: ${it.message}") }- } } /**@@ -185,6 +208,7 @@ 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 ->@@ -196,7 +220,13 @@ class Camera2ExtensionSession( runCatching { stillOutput?.close() } stillOutput = null stillSize = null- runCatching { device?.close() }+ 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)@@ -338,6 +368,16 @@ class Camera2ExtensionSession( } override fun onClosed() {+ deviceClosedGeneration = gen+ if (awaitingDeviceClosedGeneration == gen) {+ awaitingDeviceClosedGeneration = null+ val pending = pendingOpen+ pendingOpen = null+ if (pending != null && stateMachine.state == SessionState.CLOSED) {+ openOnExecutor(pending.cameraId, pending.surface, pending.requestedSize)+ }+ return+ } dispatch(gen, SessionEvent.DEVICE_CLOSED) }
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 6941780a5c..465e0c5621 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@@ -42,6 +42,19 @@ class Camera2HighSpeedSession( private var captureSession: CaptureSessionHandle? = null private var selection: HighSpeedSelection? = null + // Reopen serialization, mirroring Camera2Session: a device close only+ // completes at its real onClosed, so an open in that window is parked.+ private var awaitingDeviceClosedGeneration: Long? = null+ private var deviceCallbackGeneration: Long? = null+ private var deviceClosedGeneration: Long? = null+ private var pendingOpen: PendingOpen? = null++ private class PendingOpen(+ val cameraId: String,+ val encoderSurface: Surface,+ val previewSurface: Surface,+ )+ /** * Opens [cameraId] for slo-mo: [encoderSurface] receives the HFR frames * for the codec, [previewSurface] the viewfinder. The operating point@@ -51,24 +64,34 @@ class Camera2HighSpeedSession( */ fun open(cameraId: String, encoderSurface: Surface, previewSurface: Surface) { executor.execute {- if (stateMachine.state != SessionState.CLOSED) return@execute+ if (awaitingDeviceClosedGeneration != null) {+ pendingOpen = PendingOpen(cameraId, encoderSurface, previewSurface)+ return@execute+ }+ openOnExecutor(cameraId, encoderSurface, previewSurface)+ }+ }++ /** 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.CLOSED) return val selected = HighSpeedPlanner.select(snapshot) if (selected == null) { reportError("no constrained high-speed slo-mo point for camera $cameraId")- return@execute+ return } selection = selected if (transition(SessionEvent.OPEN_REQUESTED) !is TransitionResult.Applied) {- return@execute+ return } val gen = stateMachine.generation+ deviceCallbackGeneration = gen runCatching { driver.openCamera(cameraId, DeviceCallbackImpl(gen, encoderSurface, previewSurface)) }.onFailure { dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("openCamera failed for $cameraId: ${it.message}") }- } } /** The operating point chosen at [open], or null before a successful open. */@@ -99,11 +122,18 @@ class Camera2HighSpeedSession( */ fun close() { executor.execute {+ pendingOpen = null if (stateMachine.state == SessionState.CLOSED) return@execute val gen = stateMachine.beginTeardown() runCatching { captureSession?.close() } captureSession = null- runCatching { device?.close() }+ 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) {@@ -182,6 +212,16 @@ class Camera2HighSpeedSession( } override fun onClosed() {+ deviceClosedGeneration = gen+ if (awaitingDeviceClosedGeneration == gen) {+ awaitingDeviceClosedGeneration = null+ val pending = pendingOpen+ pendingOpen = null+ if (pending != null && stateMachine.state == SessionState.CLOSED) {+ openOnExecutor(pending.cameraId, pending.encoderSurface, pending.previewSurface)+ }+ return+ } dispatch(gen, SessionEvent.DEVICE_CLOSED) }
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 421869a2be..55b16115cd 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@@ -84,7 +84,7 @@ class Camera2Session( fun previewMetadataFor(timestampNs: Long): RawStillMetadata? = previewMetas[timestampNs] private var device: DeviceHandle? = null- private var captureSession: CaptureSessionHandle? = null+ internal var captureSession: CaptureSessionHandle? = null internal var previewSurface: Surface? = null private var previewSize: FrameSize? = null internal var stillOutput: StillOutput? = null@@ -93,7 +93,7 @@ class Camera2Session( internal var ultraHdrSize: FrameSize? = null internal var ringOutput: RingOutput? = null internal var ringSize: FrameSize? = null- private val ring = ReprocessRing<RingHeldFrame>(ringConfig.capacity)+ internal val ring = ReprocessRing<RingHeldFrame>(ringConfig.capacity) internal var analysisOutput: AnalysisOutput? = null internal var analysisSize: FrameSize? = null /** Set once a configure failure has dropped analysis: never re-add it. */@@ -101,15 +101,44 @@ class Camera2Session( internal var rawRingOutput: RawRingOutput? = null internal var rawRingSize: FrameSize? = null internal var rawRingFormat: RingFormat? = null- private val rawRing = ReprocessRing<RawHeldFrame>(rawRingConfig.capacity)- private var latestPreviewTimestampNs: Long? = null+ internal val rawRing = ReprocessRing<RawHeldFrame>(rawRingConfig.capacity)+ internal var latestPreviewTimestampNs: Long? = null private val previewMetas = LinkedHashMap<Long, RawStillMetadata>() + /**+ * Generation of the device whose HAL close [close] initiated and whose+ * real `onClosed` has not been delivered yet, or null. `CameraDevice.close()`+ * only *initiates* teardown — the device stays busy in the camera service+ * until `onClosed` — so an [open] that arrives in this window (the+ * background → resume surface bounce, or close+open on a size change) must+ * not issue `openCamera` yet: it would fail camera-in-use on a device the+ * session itself is still closing. The open is parked in [pendingOpen]+ * and issued from that device's `onClosed` instead. This is why a resume+ * used to fail once and a manual Retry (fresh holder, old device long+ * closed) succeeded.+ */+ private var awaitingDeviceClosedGeneration: Long? = null++ /** Generation captured by the live device's callback, for [awaitingDeviceClosedGeneration]. */+ private var deviceCallbackGeneration: Long? = null++ /** Generation whose real `onClosed` has already been delivered, if any. */+ private var deviceClosedGeneration: Long? = null++ /** An [open] parked until the previous device's `onClosed` lands. */+ private var pendingOpen: PendingOpen? = null++ private class PendingOpen(+ val cameraId: String,+ val surface: Surface,+ val requestedSize: FrameSize,+ )+ @Volatile private var latestPreviewMeta: RawStillMetadata? = null internal var pendingStill: PendingStill? = null internal var displayRotationDegrees: Int = 0- private var controls: Camera2ControlState = Camera2ControlState.DEFAULT+ internal var controls: Camera2ControlState = Camera2ControlState.DEFAULT /** In-flight still: JPEG bytes and result metadata pair up by arrival. */ internal class PendingStill(@@ -132,7 +161,21 @@ class Camera2Session( */ fun open(cameraId: String, surface: Surface, requestedSize: FrameSize) { executor.execute {- if (stateMachine.state != SessionState.CLOSED) return@execute+ // Previous device still closing in the HAL (see+ // awaitingDeviceClosedGeneration): park this open and let that+ // device's onClosed issue it, instead of racing openCamera+ // against the close and failing the first resume attempt.+ if (awaitingDeviceClosedGeneration != null) {+ pendingOpen = PendingOpen(cameraId, surface, requestedSize)+ return@execute+ }+ openOnExecutor(cameraId, surface, requestedSize)+ }+ }++ /** 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.CLOSED) return // LIMITED guaranteed combinations cap the preview target at // 1080p alongside JPEG(MAX)+YUV: never select a larger preview // size on such a lens when a capped size exists. The surface@@ -146,21 +189,21 @@ class Camera2Session( "no supported preview sizes for camera $cameraId " + "(requested ${requestedSize.width}x${requestedSize.height})", )- return@execute+ return } previewSurface = surface previewSize = selected if (transition(SessionEvent.OPEN_REQUESTED) !is TransitionResult.Applied) {- return@execute+ return } val gen = stateMachine.generation+ deviceCallbackGeneration = gen runCatching { driver.openCamera(cameraId, DeviceCallbackImpl(gen)) }.onFailure { dispatch(gen, SessionEvent.ERROR_OCCURRED) reportError("openCamera failed for $cameraId: ${it.message}") }- } } /** Replaces the whole control state and re-issues the repeating request. */@@ -325,149 +368,6 @@ class Camera2Session( /** Facade-reported RAW ring support for this lens. */ val rawSupported: Boolean get() = snapshot.supportsRawRing - /**- * Takes one still from the ring: picks the exposure-complete frame- * nearest [shutterTimestampNs] (or the latest preview timestamp when- * null), then either reprocesses it on the reprocessable session or- * direct-encodes it, delivering through the same [StillCallback]- * shape as [capture]. A ring miss (empty / nothing fully exposed)- * and a runtime reprocess refusal both fall back to the regular- * still capture — the shutter is never lost to the ring.- */- fun captureFromRing(- callback: StillCallback,- shutterTimestampNs: Long? = null,- displayRotationDegrees: Int? = null,- mirrored: Boolean = false,- ) {- executor.execute {- val session = captureSession- when {- stateMachine.state != SessionState.STREAMING || session == null ->- callback.onStillFailed("ring capture requires a streaming session")- ringOutput == null ->- callback.onStillFailed("no YUV ring output on this session")- pendingStill != null ->- callback.onStillFailed("a still capture is already in flight")- else -> {- val shutter = shutterTimestampNs- ?: latestPreviewTimestampNs- ?: ring.metas().maxOfOrNull { it.sensorTimestampNs }- val selection = shutter?.let { ring.select(it) }- if (selection !is RingSelection.Hit) {- // No already-exposed frame: take a fresh still.- startStillCapture(callback, displayRotationDegrees, mirrored)- return@execute- }- val held = ring.remove(selection.meta.sensorTimestampNs)- if (held == null) {- startStillCapture(callback, displayRotationDegrees, mirrored)- return@execute- }- val params = StillCapturePlanner.resolve(- state = controls,- snapshot = snapshot,- displayRotationDegrees = displayRotationDegrees- ?: [email protected],- mirrored = mirrored,- )- val output = stillOutput- val reprocessed = output != null && snapshot.supportsYuvRingReprocess &&- runCatching {- val pending = PendingStill(params, callback)- pendingStill = pending- val started = session.captureReprocess(- params, output.surface, held,- object : StillResultCallback {- override fun onCompleted(metadata: RawStillMetadata) =- onStillResult(pending, metadata)-- override fun onFailed(message: String) =- failPending(pending, message)- },- )- if (!started && pendingStill === pending) pendingStill = null- started- }.getOrDefault(false)- if (reprocessed) {- // ImageWriter owns the held image from here.- return@execute- }- // Direct fallback: encode the already-exposed frame.- val jpeg = held.encodeJpeg()- // The ring's copy carries preview-result patches;- // the held frame's own meta may predate them.- val meta = selection.meta- held.close()- if (jpeg == null) {- startStillCapture(callback, displayRotationDegrees, mirrored)- return@execute- }- callback.onStillCaptured(- CapturedStill(- jpegBytes = jpeg,- jpegWidth = meta.width,- jpegHeight = meta.height,- metadata = StillMetadataMapper.map(- RawStillMetadata(- sensorTimestampNs = meta.sensorTimestampNs,- exposureTimeNs = meta.exposureTimeNs,- iso = meta.iso,- frameNumber = meta.frameNumber,- ),- params.jpegOrientationDegrees, params.mirrored,- ),- ),- )- }- }- }- }-- /**- * Hands the newest [count] exposure-complete RAW ring frames (oldest- * first, so frame 0 is the merge reference) to [callback]. The frames- * are removed from the ring; the caller owns closing them. Fewer than- * two frames is a failure — a one-frame "merge" would silently be a- * single RAW shot, and the caller falls back to the YUV night path.- */- fun captureRawBurst(- count: Int,- callback: RawBurstCallback,- shutterTimestampNs: Long? = null,- ) {- executor.execute {- when {- stateMachine.state != SessionState.STREAMING ->- callback.onRawBurstFailed("RAW burst requires a streaming session")- rawRingOutput == null ->- callback.onRawBurstFailed("no RAW ring output on this session")- else -> {- val shutter = shutterTimestampNs- ?: latestPreviewTimestampNs- ?: rawRing.metas().maxOfOrNull { it.sensorTimestampNs }- val burst = shutter?.let { rawRing.latestCompleteBurst(count, it) }- .orEmpty()- if (burst.size < 2) {- callback.onRawBurstFailed(- "RAW ring holds ${burst.size} complete frames, need 2+",- )- return@execute- }- val frames = burst.mapNotNull { (frame, meta) ->- rawRing.remove(meta.sensorTimestampNs)?.let { frame }- }- if (frames.size < 2) {- frames.forEach { runCatching { it.close() } }- callback.onRawBurstFailed("RAW ring frames vanished during burst selection")- return@execute- }- callback.onRawBurst(frames, burst.map { it.second })- }- }- }- }- /** * Takes one plain still: issues `TEMPLATE_STILL_CAPTURE` carrying the * session's current control state plus flash resolution, and delivers@@ -498,7 +398,7 @@ class Camera2Session( } /** Regular TEMPLATE_STILL_CAPTURE path (capture + ring-miss fallback). */- private fun startStillCapture(+ internal fun startStillCapture( callback: StillCallback, displayRotationDegrees: Int?, mirrored: Boolean,@@ -607,6 +507,10 @@ class Camera2Session( */ 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 ->@@ -634,7 +538,20 @@ class Camera2Session( rawRingFormat = null rawRing.drainAll().forEach { runCatching { it.close() } } previewMetas.clear()- runCatching { device?.close() }+ // 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)@@ -710,6 +627,21 @@ class Camera2Session( } override fun onClosed() {+ deviceClosedGeneration = gen+ if (awaitingDeviceClosedGeneration == gen) {+ // The real HAL close this session's close() initiated has+ // completed. The state machine already reached CLOSED via+ // close()'s synthetic dispatch (this callback's generation+ // is stale by design), so only the parked reopen is left:+ // issue it now, on this callback, never before.+ awaitingDeviceClosedGeneration = null+ val pending = pendingOpen+ pendingOpen = null+ if (pending != null && stateMachine.state == SessionState.CLOSED) {+ openOnExecutor(pending.cameraId, pending.surface, pending.requestedSize)+ }+ return+ } dispatch(gen, SessionEvent.DEVICE_CLOSED) }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.ktnew file mode 100644index 0000000000..cd5f6bd3d3--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt@@ -0,0 +1,152 @@+package com.vayunmathur.camera.platform.camera2++/**+ * Ring still captures for [Camera2Session]: serving a shutter from the+ * YUV reprocess ring (reprocess or direct encode) and handing RAW ring+ * bursts to the night merge. Moved verbatim from the session as+ * extensions (see Camera2SessionStillDelivery.kt); all state is touched+ * only on the session executor, as before.+ */++/**+ * Takes one still from the ring: picks the exposure-complete frame+ * nearest [shutterTimestampNs] (or the latest preview timestamp when+ * null), then either reprocesses it on the reprocessable session or+ * direct-encodes it, delivering through the same [Camera2Session.StillCallback]+ * shape as a plain still capture. A ring miss (empty / nothing fully exposed)+ * and a runtime reprocess refusal both fall back to the regular+ * still capture — the shutter is never lost to the ring.+ */+fun Camera2Session.captureFromRing(+ callback: Camera2Session.StillCallback,+ shutterTimestampNs: Long? = null,+ displayRotationDegrees: Int? = null,+ mirrored: Boolean = false,+) {+ executor.execute {+ val session = captureSession+ when {+ state != SessionState.STREAMING || session == null ->+ callback.onStillFailed("ring capture requires a streaming session")+ ringOutput == null ->+ callback.onStillFailed("no YUV ring output on this session")+ pendingStill != null ->+ callback.onStillFailed("a still capture is already in flight")+ else -> {+ val shutter = shutterTimestampNs+ ?: latestPreviewTimestampNs+ ?: ring.metas().maxOfOrNull { it.sensorTimestampNs }+ val selection = shutter?.let { ring.select(it) }+ if (selection !is RingSelection.Hit) {+ // No already-exposed frame: take a fresh still.+ startStillCapture(callback, displayRotationDegrees, mirrored)+ return@execute+ }+ val held = ring.remove(selection.meta.sensorTimestampNs)+ if (held == null) {+ startStillCapture(callback, displayRotationDegrees, mirrored)+ return@execute+ }+ val params = StillCapturePlanner.resolve(+ state = controls,+ snapshot = snapshot,+ displayRotationDegrees = displayRotationDegrees+ ?: [email protected],+ mirrored = mirrored,+ )+ val output = stillOutput+ val reprocessed = output != null && snapshot.supportsYuvRingReprocess &&+ runCatching {+ val pending = Camera2Session.PendingStill(params, callback)+ pendingStill = pending+ val started = session.captureReprocess(+ params, output.surface, held,+ object : StillResultCallback {+ override fun onCompleted(metadata: RawStillMetadata) =+ onStillResult(pending, metadata)++ override fun onFailed(message: String) =+ failPending(pending, message)+ },+ )+ if (!started && pendingStill === pending) pendingStill = null+ started+ }.getOrDefault(false)+ if (reprocessed) {+ // ImageWriter owns the held image from here.+ return@execute+ }+ // Direct fallback: encode the already-exposed frame.+ val jpeg = held.encodeJpeg()+ // The ring's copy carries preview-result patches;+ // the held frame's own meta may predate them.+ val meta = selection.meta+ held.close()+ if (jpeg == null) {+ startStillCapture(callback, displayRotationDegrees, mirrored)+ return@execute+ }+ callback.onStillCaptured(+ CapturedStill(+ jpegBytes = jpeg,+ jpegWidth = meta.width,+ jpegHeight = meta.height,+ metadata = StillMetadataMapper.map(+ RawStillMetadata(+ sensorTimestampNs = meta.sensorTimestampNs,+ exposureTimeNs = meta.exposureTimeNs,+ iso = meta.iso,+ frameNumber = meta.frameNumber,+ ),+ params.jpegOrientationDegrees, params.mirrored,+ ),+ ),+ )+ }+ }+ }+}++/**+ * Hands the newest [count] exposure-complete RAW ring frames (oldest+ * first, so frame 0 is the merge reference) to [callback]. The frames+ * are removed from the ring; the caller owns closing them. Fewer than+ * two frames is a failure — a one-frame "merge" would silently be a+ * single RAW shot, and the caller falls back to the YUV night path.+ */+fun Camera2Session.captureRawBurst(+ count: Int,+ callback: Camera2Session.RawBurstCallback,+ shutterTimestampNs: Long? = null,+) {+ executor.execute {+ when {+ state != SessionState.STREAMING ->+ callback.onRawBurstFailed("RAW burst requires a streaming session")+ rawRingOutput == null ->+ callback.onRawBurstFailed("no RAW ring output on this session")+ else -> {+ val shutter = shutterTimestampNs+ ?: latestPreviewTimestampNs+ ?: rawRing.metas().maxOfOrNull { it.sensorTimestampNs }+ val burst = shutter?.let { rawRing.latestCompleteBurst(count, it) }+ .orEmpty()+ if (burst.size < 2) {+ callback.onRawBurstFailed(+ "RAW ring holds ${burst.size} complete frames, need 2+",+ )+ return@execute+ }+ val frames = burst.mapNotNull { (frame, meta) ->+ rawRing.remove(meta.sensorTimestampNs)?.let { frame }+ }+ if (frames.size < 2) {+ frames.forEach { runCatching { it.close() } }+ callback.onRawBurstFailed("RAW ring frames vanished during burst selection")+ return@execute+ }+ callback.onRawBurst(frames, burst.map { it.second })+ }+ }+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.ktindex b1113026df..f3b638bc7d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt@@ -174,6 +174,14 @@ class PreviewSurfaceBridge( override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean { this.texture = null+ // The pinned buffer size was applied to the texture that just+ // died; a new texture (resume re-attach) starts unpinned. Forget+ // the pin so the next setPreviewStream re-applies+ // setDefaultBufferSize to it even when the stream size is+ // unchanged — otherwise the resume configure runs against the+ // new texture's default buffer size and fails once, while a+ // fresh bridge (cold start / manual Retry) pins correctly.+ streamSize = null val current = state.surface state = PreviewSurfaceState() if (current != null) {
camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.ktindex fa3fbb3fd6..15fe329fcf 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt@@ -14,6 +14,7 @@ import com.vayunmathur.camera.data.saveProcessedStill 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.captureFromRing import com.vayunmathur.camera.platform.camera2.CaptureSessionCallback import com.vayunmathur.camera.platform.camera2.CaptureSessionHandle import com.vayunmathur.camera.platform.camera2.CapturedStill
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 f35e210fdc..71b7374b4e 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@@ -49,6 +49,8 @@ class Camera2SessionTest { ) : DeviceHandle { var sessionCallback: CaptureSessionCallback? = null var closed = false+ /** Models the HAL's async close completion; null withholds it. */+ var onClosedHook: (() -> Unit)? = null val sessionHandleRef: FakeSessionHandle get() = sessionHandle override fun createCaptureSession( surfaces: List<Surface>,@@ -58,7 +60,10 @@ class Camera2SessionTest { if (failConfigure) callback.onConfigureFailed() else callback.onConfigured(sessionHandle) }- override fun close() { closed = true }+ override fun close() {+ closed = true+ onClosedHook?.invoke()+ } } private class FakeDriver(@@ -66,13 +71,21 @@ class Camera2SessionTest { private val failConfigure: Boolean = false, ) : Camera2Driver { var openedCameraId: String? = null+ var openCount: Int = 0 var deviceCallback: DeviceCallback? = null override fun openCamera(cameraId: String, callback: DeviceCallback) { openedCameraId = cameraId+ openCount++ deviceCallback = callback- callback.onOpened(- if (failConfigure) FakeDeviceHandle(cameraId, failConfigure = true) else device,- )+ val handed = if (failConfigure) {+ FakeDeviceHandle(cameraId, failConfigure = true)+ } else {+ device+ }+ // Android delivers onClosed for a closed device; wire it here+ // unless a test withholds it by clearing the hook.+ handed.onClosedHook = { callback.onClosed() }+ callback.onOpened(handed) } override fun createStillOutput(size: FrameSize): StillOutput? = null }@@ -274,4 +287,66 @@ class Camera2SessionTest { executor.shutdown() } }++ /**+ * Regression (resume-after-background): the pause surface bounce is+ * close() followed immediately by open() on the *same* session, while+ * the HAL has only initiated — not completed — the old device's close.+ * The reopen must be parked until that device's onClosed; issuing+ * openCamera earlier is the first-attempt resume failure (and a later+ * manual Retry, on a fresh session, always worked). Before the fix the+ * second openCamera was issued as soon as its executor task ran.+ */+ @Test fun reopenIsDeferredUntilPreviousDeviceClosed() {+ val executor = Camera2Executor("Camera2SessionTest-reopen-deferred")+ try {+ val driver = FakeDriver()+ val session = newSession(driver, executor)+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ assertEquals(1, driver.openCount)++ // Withhold the HAL's close completion, as on a real resume+ // where onClosed has not been delivered yet.+ driver.device.onClosedHook = null+ session.close()+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()++ // Session is locally CLOSED but no new openCamera may exist yet.+ assertEquals(SessionState.CLOSED, session.state)+ assertEquals(1, driver.openCount)++ // The old device finishes closing: the parked open is issued.+ driver.deviceCallback!!.onClosed()+ executor.drain()+ assertEquals(2, driver.openCount)+ assertEquals(SessionState.STREAMING, session.state)+ } finally {+ executor.shutdown()+ }+ }++ @Test fun parkedReopenIsCancelledByAnotherClose() {+ val executor = Camera2Executor("Camera2SessionTest-reopen-cancelled")+ try {+ val driver = FakeDriver()+ val session = newSession(driver, executor)+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ driver.device.onClosedHook = null+ session.close()+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ // Surface destroyed again before the old device closed.+ session.close()+ executor.drain()+ driver.deviceCallback!!.onClosed()+ executor.drain()+ assertEquals(1, driver.openCount)+ assertEquals(SessionState.CLOSED, session.state)+ } finally {+ executor.shutdown()+ }+ } }
camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridgeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridgeTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridgeTest.ktnew file mode 100644index 0000000000..b86be0ce73--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridgeTest.kt@@ -0,0 +1,42 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.SurfaceTexture+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.mockito.Mockito.mock+import org.mockito.Mockito.verify+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Bridge lifecycle: a stream size pinned onto one SurfaceTexture must be+ * re-pinned onto the *next* texture after a destroy (resume re-attach),+ * even when the selected stream size itself is unchanged.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PreviewSurfaceBridgeTest {++ @Test fun newTextureAfterDestroyIsPinnedAgain() {+ val bridge = PreviewSurfaceBridge { }+ val first = mock(SurfaceTexture::class.java)+ val second = mock(SurfaceTexture::class.java)+ val stream = FrameSize(1920, 1080)++ bridge.onSurfaceTextureAvailable(first, 100, 100)+ bridge.setPreviewStream(stream, 90, null)+ verify(first).setDefaultBufferSize(1920, 1080)++ // Background: the texture dies. Resume: a new texture arrives and+ // the same stream size is selected again.+ assertTrue(bridge.onSurfaceTextureDestroyed(first))+ bridge.onSurfaceTextureAvailable(second, 100, 100)+ bridge.setPreviewStream(stream, 90, null)++ // Before the fix the unchanged-size check skipped this call, so the+ // resume configure ran against the new texture's default buffer+ // size and failed once (a fresh bridge, as on Retry, worked).+ verify(second).setDefaultBufferSize(1920, 1080)+ }+}