Modern Apps git

← Modern-Apps.git

camera: wait for AE convergence before ZSL capture (#camera-ae)

Commit
15593f56fd7de966339ed8f01483b8ced13d56ec
Author
Vayun Mathur <[email protected]>
When
2026-11-16 15:01 UTC (20 days ago)
Parents
8b42aa3
Symptom: auto mode "often way overexposes sometimes" — intermittent
strong overexposure in otherwise correctly-exposed auto shots, with
the preview already looking right.

Root cause: zero-shutter-lag capture (#914, 3038373eb). Verified in
the CameraX 1.7.0-alpha03 bytecode and documented in
StillCaptureModePolicy: the ZSL ring buffer only accepts frames whose
AE/AWB/AF have CONVERGED, drops the rest, and is never flushed while
bound. After a lighting change (dark room to bright window, indoors
to outdoors) AE needs a few hundred ms to reconverge; a press in that
window reprocesses the newest buffered frame, which still carries the
previous scene's converged exposure (long shutter / high ISO), so
the saved shot is blown out while the live preview has already
reconverged and looks correct. Manual exposure and night already
exclude ZSL (rebind to MINIMIZE_LATENCY, whose pipeline runs its own
precapture convergence), which is why this only hits fully-auto
shots on ZSL-supported devices.

Nothing in camera/ read CONTROL_AE_STATE or gated a capture on AE
convergence: aeSnapshotCallback snapshotted only SENSOR_SENSITIVITY /
SENSOR_EXPOSURE_TIME for the half-manual seed. Suspects ruled out
with evidence: exposure compensation is never persisted (no
DataStore key) and is re-applied from the flow on every bind; manual
AE state cannot leak back into auto because CameraX
setCaptureRequestOptions clears-then-adds (verified in the
camera-camera2 bytecode), so applyManualControls' empty auto options
clear AE_MODE_OFF/SENSOR_*; night burst/single restores re-assert it.

Fix (smallest correct, keeps the #914 latency win): track
CONTROL_AE_STATE from the existing preview session callback, and
when the bound still capture is ZSL hold the shutter until AE
reports CONVERGED or LOCKED (bounded, 1.2s, 50ms poll; on timeout
the shot is taken anyway so flicker-hunting AE can never deaden the
shutter). In steady light AE is already converged, so the press path
is unchanged and adds zero latency. Applied to capturePhoto() (all
still routes incl. Motion Photo, which shares the ZSL ImageCapture)
and to the first burst frame; a teardown landing mid-wait drops the
press instead of capturing into the next session. Null AE state (HAL
hasn't reported; buffer can't hold a stale frame yet) never gates.

Verified: :camera:testDevUnitTest (full suite, incl. 8 new
AeConvergenceGateTest tests: state truth table, snapshot-callback
wiring via a mocked TotalCaptureResult, wait/skip/timeout behaviour
via a fake ZSL ImageCapture), :camera:detekt, :camera:lint and
:camera:compileDevKotlin all green. No on-device run; the bound-
camera buffer behaviour itself is HAL/CameraX-internal.

Diff

camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.ktindex 1ae2065b73..ebb48684be 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt@@ -11,13 +11,58 @@ import androidx.camera.core.ImageProxy import androidx.core.content.ContextCompat import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withTimeoutOrNull import kotlin.math.roundToInt  /** Shutter-timer countdown tick (1s). */ internal const val TIMER_TICK_MS = 1000L +/** Poll step while waiting for AE to converge before a ZSL capture. */+private const val AE_CONVERGENCE_POLL_MS = 50L++/**+ * Longest the shutter waits for AE convergence before a ZSL capture. AE normally+ * reconverges in a few hundred ms after a lighting change; past this the shot is+ * taken anyway (a slightly-off exposure beats a dead shutter, e.g. under flickering+ * light where AE keeps searching).+ */+private const val AE_CONVERGENCE_TIMEOUT_MS = 1200L++/**+ * Whether [state] (a CameraMetadata.CONTROL_AE_STATE_*) means the newest ZSL-buffered+ * frame is exposed for the current scene. CONVERGED is the steady state; LOCKED is the+ * user's own AE lock, whose exposure is intentional. A null state (the HAL hasn't+ * reported yet, so the ring buffer can't hold a stale frame either) doesn't gate.+ * SEARCHING / PRECAPTURE / FLASH_REQUIRED mean AE hasn't settled on this scene yet:+ * the buffer's newest converged frame still carries the previous scene's exposure,+ * which is the intermittent strong overexposure seen in auto mode.+ */+internal fun aeStateReadyForCapture(state: Int?): Boolean = when (state) {+    null,+    android.hardware.camera2.CameraMetadata.CONTROL_AE_STATE_CONVERGED,+    android.hardware.camera2.CameraMetadata.CONTROL_AE_STATE_LOCKED -> true+    else -> false+}++/** True when the preview's AE has converged (or never reported) for this scene. */+internal fun CameraViewModel.isAeConvergedForCapture(): Boolean = aeStateReadyForCapture(lastAeState)++/**+ * Waits until AE reports convergence, bounded by [timeoutMs]. Only meaningful for a+ * ZSL-bound still capture: the regular pipeline runs its own precapture convergence,+ * so it never waits. Returns false on timeout (the caller captures anyway).+ */+internal suspend fun CameraViewModel.awaitAeConvergence(timeoutMs: Long = AE_CONVERGENCE_TIMEOUT_MS): Boolean {+    if (!stillCaptureIsZsl() || isAeConvergedForCapture()) return true+    return withTimeoutOrNull(timeoutMs) {+        while (!isAeConvergedForCapture()) delay(AE_CONVERGENCE_POLL_MS)+        true+    } ?: false+}+ fun CameraViewModel.takePhoto() {     // Second tap cancels an armed timer, mirroring toggleRecording().     if (timerCountdownMutable.value > 0) {@@ -47,6 +92,24 @@ internal fun CameraViewModel.capturePhoto() {     // can't start a concurrent capture. Every path clears it once its frame is captured     // (Motion Photo) or saved (the other paths) — never later.     isCapturingMutable.value = true+    // A ZSL press reprocesses the ring buffer's newest converged frame. While AE is+    // still searching after a lighting change that frame is exposed for the previous+    // scene (the intermittent strong overexposure in auto mode), so hold the shutter+    // until AE converges — zero added latency in steady light, where it already has.+    if (stillCaptureIsZsl() && !isAeConvergedForCapture()) {+        viewModelScope.launch {+            awaitAeConvergence()+            // Teardown claims the flag while we wait; a dead session must not capture.+            if (!isCapturingMutable.value || imageCapture == null) return@launch+            routeAndCapture()+        }+    } else {+        routeAndCapture()+    }+}++/** Routes the claimed shutter press to its capture path (see [routeStillCapture]). */+private fun CameraViewModel.routeAndCapture() {     when (routeStillCapture()) {         StillRoute.NIGHT -> captureNightPhoto()         StillRoute.MOTION_PHOTO -> captureMotionPhoto()@@ -165,7 +228,16 @@ fun CameraViewModel.startBurst() {             }         )     }-    shootNext(1)+    // Same ZSL stale-frame gate as capturePhoto(): only the first frame can predate+    // AE convergence — once it lands, AE has settled for the rest of the burst.+    if (stillCaptureIsZsl() && !isAeConvergedForCapture()) {+        viewModelScope.launch {+            awaitAeConvergence()+            if (burstActiveMutable.value) shootNext(1) else finishBurst()+        }+    } else {+        shootNext(1)+    } }  fun CameraViewModel.stopBurst() {
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex 3ee058951e..faac29dae9 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -331,6 +331,13 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     @Volatile internal var lastAeIso: Int? = null     @Volatile internal var lastAeExposureNanos: Long? = null +    // Last CONTROL_AE_STATE reported by the preview stream (CameraMetadata.CONTROL_AE_STATE_*),+    // or null before the first result. The ZSL capture gate (CameraPhotoCapture.kt) reads it:+    // CameraX's zero-shutter-lag ring buffer only holds converged frames, so while AE is still+    // searching after a lighting change the newest buffered frame is exposed for the previous+    // scene and a press would save that stale exposure.+    @Volatile internal var lastAeState: Int? = null+     internal val aeSnapshotCallback = object : android.hardware.camera2.CameraCaptureSession.CaptureCallback() {         override fun onCaptureCompleted(             session: android.hardware.camera2.CameraCaptureSession,@@ -339,6 +346,7 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {         ) {             result.get(android.hardware.camera2.CaptureResult.SENSOR_SENSITIVITY)?.let { lastAeIso = it }             result.get(android.hardware.camera2.CaptureResult.SENSOR_EXPOSURE_TIME)?.let { lastAeExposureNanos = it }+            result.get(android.hardware.camera2.CaptureResult.CONTROL_AE_STATE)?.let { lastAeState = it }         }     } 
camera/src/test/java/com/vayunmathur/camera/util/AeConvergenceGateTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/util/AeConvergenceGateTest.kt b/camera/src/test/java/com/vayunmathur/camera/util/AeConvergenceGateTest.ktnew file mode 100644index 0000000000..218d1bc11b--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/util/AeConvergenceGateTest.kt@@ -0,0 +1,113 @@+package com.vayunmathur.camera.util++import android.hardware.camera2.CameraMetadata+import android.hardware.camera2.CaptureResult+import android.hardware.camera2.TotalCaptureResult+import androidx.annotation.OptIn+import androidx.camera.core.ExperimentalZeroShutterLag+import androidx.camera.core.ImageCapture+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.Test+import org.junit.runner.RunWith+import org.mockito.Mockito+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * AE-convergence gate for ZSL captures: the ring buffer only holds converged frames,+ * so a press while AE is still searching after a lighting change would reprocess a+ * frame exposed for the previous scene (intermittent strong overexposure in auto).+ */+@RunWith(AndroidJUnit4::class)+class AeConvergenceGateTest {++    private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext())++    @OptIn(ExperimentalZeroShutterLag::class)+    private fun CameraViewModel.bindZslCapture() {+        imageCapture = ImageCapture.Builder()+            .setCaptureMode(ImageCapture.CAPTURE_MODE_ZERO_SHUTTER_LAG)+            .build()+    }++    // ---- Ready-state truth table ----++    @Test fun convergedAndLockedAreReady() {+        assertTrue(aeStateReadyForCapture(CameraMetadata.CONTROL_AE_STATE_CONVERGED))+        assertTrue(aeStateReadyForCapture(CameraMetadata.CONTROL_AE_STATE_LOCKED))+    }++    @Test fun unsettledStatesAreNotReady() {+        assertFalse(aeStateReadyForCapture(CameraMetadata.CONTROL_AE_STATE_INACTIVE))+        assertFalse(aeStateReadyForCapture(CameraMetadata.CONTROL_AE_STATE_SEARCHING))+        assertFalse(aeStateReadyForCapture(CameraMetadata.CONTROL_AE_STATE_FLASH_REQUIRED))+        assertFalse(aeStateReadyForCapture(CameraMetadata.CONTROL_AE_STATE_PRECAPTURE))+    }++    @Test fun unreportedStateDoesNotGate() {+        assertTrue(aeStateReadyForCapture(null))+    }++    // ---- Snapshot callback feeds the gate ----++    @Test fun snapshotCallbackRecordsAeStateAndValues() {+        val v = vm()+        val result = Mockito.mock(TotalCaptureResult::class.java)+        Mockito.`when`(result.get(CaptureResult.CONTROL_AE_STATE))+            .thenReturn(CameraMetadata.CONTROL_AE_STATE_SEARCHING)+        Mockito.`when`(result.get(CaptureResult.SENSOR_SENSITIVITY)).thenReturn(800)+        Mockito.`when`(result.get(CaptureResult.SENSOR_EXPOSURE_TIME)).thenReturn(33_333_333L)++        v.aeSnapshotCallback.onCaptureCompleted(+            Mockito.mock(android.hardware.camera2.CameraCaptureSession::class.java),+            Mockito.mock(android.hardware.camera2.CaptureRequest::class.java),+            result+        )++        assertEquals(CameraMetadata.CONTROL_AE_STATE_SEARCHING, v.lastAeState)+        assertEquals(800, v.lastAeIso)+        assertEquals(33_333_333L, v.lastAeExposureNanos)+        assertFalse(v.isAeConvergedForCapture())+    }++    // ---- The wait itself ----++    @Test fun awaitReturnsImmediatelyWhenConverged() = runBlocking {+        val v = vm()+        v.bindZslCapture()+        v.lastAeState = CameraMetadata.CONTROL_AE_STATE_CONVERGED+        assertTrue(v.awaitAeConvergence(timeoutMs = 5_000L))+    }++    @Test fun awaitSkipsNonZslCaptures() = runBlocking {+        val v = vm()+        // No ZSL capture bound: the regular pipeline converges on its own.+        v.lastAeState = CameraMetadata.CONTROL_AE_STATE_SEARCHING+        assertTrue(v.awaitAeConvergence(timeoutMs = 5_000L))+    }++    @Test fun awaitWaitsForConvergence() = runBlocking {+        val v = vm()+        v.bindZslCapture()+        v.lastAeState = CameraMetadata.CONTROL_AE_STATE_SEARCHING+        val waiting = async { v.awaitAeConvergence(timeoutMs = 5_000L) }+        delay(150L)+        assertFalse(waiting.isCompleted)+        v.lastAeState = CameraMetadata.CONTROL_AE_STATE_CONVERGED+        assertTrue(waiting.await())+    }++    @Test fun awaitTimesOutAndCapturesAnyway() = runBlocking {+        val v = vm()+        v.bindZslCapture()+        v.lastAeState = CameraMetadata.CONTROL_AE_STATE_SEARCHING+        val started = System.currentTimeMillis()+        assertFalse(v.awaitAeConvergence(timeoutMs = 200L))+        assertTrue(System.currentTimeMillis() - started >= 200L)+    }+}