camera: use zero-shutter-lag capture when it can't change the photo (#914)
- Commit
3038373eb1d7769d912572c89cef679cb1ee8556- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-12 05:05 UTC (24 days ago)
- Parents
32bf570
Symptom (#914): shutter lag noticeably longer than the stock GrapheneOS and Pixel cameras on a Pixel 9 Pro XL. Root cause (part): buildPhotoCapture() never set a capture mode, so the photo session used CameraX's default, CAPTURE_MODE_MINIMIZE_LATENCY: every press starts a new still request and waits for its exposure. (Triage assumed the default was a slower mode; CameraX 1.7.0-alpha03 defaults to MINIMIZE_LATENCY, verified in the ImageCapture bytecode.) CAPTURE_MODE_ZERO_SHUTTER_LAG instead reprocesses a frame CameraX already holds in a ring buffer from the moment of the press. What CameraX 1.7.0-alpha03 does with ZSL (read from the camera-core and camera-camera2 bytecode, no sources ship): - ZSL is used only when CameraInfo.isZslSupported (PRIVATE reprocessing, no ZslDisablerQuirk); it is skipped per shot while flash is ON/AUTO, with VideoCapture bound, and under extensions. - The ring buffer only accepts frames whose AF is focused, AE CONVERGED and AWB CONVERGED, drops the rest, and is not flushed while bound. With a manual exposure (AE_MODE_OFF) or the night burst/override (AE off + AWB lock) every new frame is rejected, so a ZSL capture would return a stale frame from before the change. - A ZSL ImageCapture's sizes are filtered to PRIVATE-reprocessing input sizes, which drops the high-resolution-only sizes that PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE (the max-res first bind) adds. So max-res and ZSL do conflict: ZSL wins, at the default resolution, as instructed. - CameraX does not gate ZSL on Ultra HDR: a ZSL frame is reprocessed to the ImageCapture surface whatever its format, and its ZSL size check only requires JPEG as a reprocess output, not JPEG_R. - Without an explicit JPEG quality, MINIMIZE_LATENCY and ZSL both encode at 95 (MAXIMIZE_QUALITY would be 100), so quality is unchanged. Changes: - domain/StillCaptureModePolicy picks ZSL when the camera supports it, exposure and ISO are on Auto, night mode is off, and the still is plain JPEG or the camera lists JPEG_R as a reprocessing output for PRIVATE input (API 34+, read via Camera2CameraInfo). Otherwise MINIMIZE_LATENCY, now set explicitly (same as before). Flash is not an input because CameraX already skips ZSL per shot with flash on, and flash changes without a rebind. - chooseStillCaptureMode() evaluates it per bind attempt for the lens actually being bound; buildPhotoCapture() takes the mode, drops the max-res selector when ZSL is chosen, and the bind log now prints the still resolution and mode for on-device checks. - CameraViewModel.zslCompatible (Auto exposure and night off) joins the photo session's rebind keys, so entering manual exposure or night mode rebinds without ZSL and leaving them rebinds with it. While a shot is in flight the previous value is held, so a night burst brightening the scene can't trigger a rebind under it. - nightCaptureApplies() replaces the duplicated night condition in the router and in captureSinglePhoto's override, and also requires a non-ZSL ImageCapture, so a night shot fired in the frame before the rebind takes a plain photo instead of a stale one. This also clears the pre-existing ComplexCondition detekt finding there. - Portrait, night-extension and video sessions keep their own ImageCapture builders and are unchanged. Alternatives considered: - ZSL always on, relying on CameraX: wrong pictures with manual exposure and in night mode (stale buffered frames). - Dropping Ultra HDR to get ZSL everywhere: trades a quality setting for latency; the app keeps Ultra HDR unless JPEG_R reprocessing is advertised. - Rebinding around each night shot instead of on night engage: two rebinds per night photo instead of one per engage. - Keeping max-res with ZSL: CameraX would filter those sizes anyway. User-visible effect: on devices that support it, auto-exposure photos are taken from the frame at the press instead of a new exposure. On sensors whose largest still is a high-resolution-only size, ZSL shots are at the largest ZSL size instead. Switching between Auto and manual exposure, or night mode engaging/disengaging, now causes one brief preview rebind. Where Ultra HDR is supported but JPEG_R reprocessing is not advertised, Ultra HDR is kept and ZSL is not used. Verification: :camera:compileDevKotlin, :camera:testDevUnitTest (new StillCaptureModePolicyTest; new Robolectric ZslGatingTest: manual exposure/ISO and night mode turn zslCompatible off and back on, the value is held while a capture is in flight and applied after, and a ZSL-built ImageCapture never takes the night path), :camera:lint and :camera:detekt clean for the touched files. Not verified on a device: whether the Pixel 9 Pro XL advertises JPEG_R reprocessing, the ZSL session's stream configuration, and the resulting still resolution.
Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex dab42fe2b7..69d02de65f 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -34,6 +34,7 @@ _Install: ./install camera (dev by default)._ - com/vayunmathur/camera/domain/LensSelectionLogic.kt - com/vayunmathur/camera/domain/ArgbToI420Converter.kt — bulk ARGB→YUV 4:2:0 for the Motion Photo clip - com/vayunmathur/camera/domain/MotionSaveQueue.kt — bound on Motion Photos still saving after the shutter+- com/vayunmathur/camera/domain/StillCaptureModePolicy.kt — ZSL vs MINIMIZE_LATENCY choice ### platform/ — capability queries - com/vayunmathur/camera/platform/CameraCapabilities.kt - com/vayunmathur/camera/platform/LensSelector.kt
camera/src/main/java/com/vayunmathur/camera/domain/StillCaptureModePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/StillCaptureModePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/domain/StillCaptureModePolicy.ktnew file mode 100644index 0000000000..2013878760--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/StillCaptureModePolicy.kt@@ -0,0 +1,53 @@+package com.vayunmathur.camera.domain++/** CameraX capture mode for the photo session's still use case. */+enum class StillCaptureMode { ZERO_SHUTTER_LAG, MINIMIZE_LATENCY }++/**+ * What the capture-mode choice depends on, snapshotted when the photo session binds.+ *+ * @property zslSupported the bound camera reports ZSL support (CameraInfo.isZslSupported:+ * PRIVATE reprocessing, no ZSL-disabling quirk).+ * @property ultraHdr the still is Ultra HDR (JPEG_R) rather than plain JPEG.+ * @property ultraHdrReprocessable the camera lists JPEG_R as a valid reprocessing output for+ * PRIVATE input, i.e. a ZSL frame can be reprocessed straight to Ultra HDR.+ * @property autoExposure exposure and ISO are both on Auto (no live manual AE override).+ * @property nightMode night mode is engaged (its capture paths lock AE/AWB per shot).+ */+data class StillCaptureInputs(+ val zslSupported: Boolean,+ val ultraHdr: Boolean,+ val ultraHdrReprocessable: Boolean,+ val autoExposure: Boolean,+ val nightMode: Boolean,+)++/**+ * Chooses zero-shutter-lag capture whenever it can't change the picture (#914).+ *+ * ZSL hands back a frame CameraX already holds in a small ring buffer instead of starting a new+ * exposure, but that buffer only accepts frames whose auto-exposure, auto-white-balance and+ * focus have converged, and it is never flushed while bound. With a manual exposure or a night+ * lock applied, every new frame is rejected and a press would return a stale frame from before+ * the change, so those states keep the regular pipeline. Ultra HDR stays on unless ZSL frames+ * can be reprocessed to JPEG_R, so the quality setting wins over latency there.+ *+ * Flash is deliberately not an input: CameraX already skips ZSL per shot while flash is ON or+ * AUTO, and flash can change without a rebind. Extensions never share this session (the night+ * extension binds its own ImageCapture), and CameraX ignores ZSL under an extension anyway.+ *+ * MINIMIZE_LATENCY is CameraX's default, so the fallback keeps the existing behaviour (and the+ * same default JPEG quality, 95) rather than switching to MAXIMIZE_QUALITY's slower pipeline.+ */+object StillCaptureModePolicy {+ /** ZSL when [inputs] allow it, else MINIMIZE_LATENCY. */+ fun choose(inputs: StillCaptureInputs): StillCaptureMode {+ val hdrCompatible = !inputs.ultraHdr || inputs.ultraHdrReprocessable+ val stateCompatible = inputs.autoExposure && !inputs.nightMode+ return if (inputs.zslSupported && hdrCompatible && stateCompatible) {+ StillCaptureMode.ZERO_SHUTTER_LAG+ } else {+ StillCaptureMode.MINIMIZE_LATENCY+ }+ }+}
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 2673949b03..9a234eac3d 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -8,6 +8,8 @@ import androidx.camera.core.ImageAnalysis import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalContext@@ -236,8 +238,12 @@ internal fun CameraScreenEffects( // Codec/audio/mirror are fixed at bind time (Recorder mime, AudioSource, MirrorMode), so // they join the effect keys: changing them in Settings rebinds instead of silently waiting // for the next mode switch. Aspect ratio is applied live (setCropAspectRatio) — no rebind.- LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, state.videoCodec, state.audioInputSource, state.mirrorFront, lifecycleOwner) {- Log.dev("NightPreview", "CameraScreen session LaunchedEffect START keys lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview codec=${state.videoCodec} audio=${state.audioInputSource} mirror=${state.mirrorFront} lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}")+ // The photo session's capture mode (ZSL or not) is fixed at bind time too, so it rebinds when+ // manual exposure or night mode makes ZSL unsafe, or safe again (#914). Other kinds ignore it.+ val zslCompatible by viewModel.zslCompatible.collectAsState()+ val zslKey = if (sessionKind == SessionKind.PHOTO) zslCompatible else null+ LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, zslKey, state.videoCodec, state.audioInputSource, state.mirrorFront, lifecycleOwner) {+ Log.dev("NightPreview", "CameraScreen session LaunchedEffect START keys zsl=$zslKey lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview codec=${state.videoCodec} audio=${state.audioInputSource} mirror=${state.mirrorFront} lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}") lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { Log.dev("NightPreview", "CameraScreen repeatOnLifecycle STARTED – calling teardownSession()") viewModel.teardownSession()
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 d36d7fcb18..1ae2065b73 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt@@ -2,7 +2,9 @@ package com.vayunmathur.camera.util import android.graphics.Bitmap import android.net.Uri+import androidx.annotation.OptIn import com.vayunmathur.library.log.Log+import androidx.camera.core.ExperimentalZeroShutterLag import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.camera.core.ImageProxy@@ -66,12 +68,7 @@ internal fun CameraViewModel.routeStillCapture(): StillRoute = when { // extension, so a plain single capture through that ImageCapture lets the vendor pipeline // produce the multi-frame night image. nightPreviewActiveMutable.value -> StillRoute.SINGLE- // Multi-frame night capture only when night mode is active, exposure is fully auto,- // and flash is off: the night paths lock AE off (CONTROL_AE_MODE_OFF) with a forced- // long exposure, which breaks flash metering/timing and double-exposes (issue #721).- // With flash on, fall through to the plain single capture so the shot is an instant- // flash photo with no long-exposure countdown overlay.- nightModeActive.value && isExposureAuto() && flashModeMutable.value == FlashMode.OFF -> StillRoute.NIGHT+ nightCaptureApplies() -> StillRoute.NIGHT !motionPhotoEligible() -> StillRoute.SINGLE motionSaveQueue.tryReserve() -> StillRoute.MOTION_PHOTO else -> {@@ -83,6 +80,25 @@ internal fun CameraViewModel.routeStillCapture(): StillRoute = when { } } +/**+ * Whether a shot takes the night path (multi-frame burst, or the single-frame long-exposure+ * override): night mode active, exposure fully auto and flash off. The night paths lock AE off+ * (CONTROL_AE_MODE_OFF) with a forced long exposure, which breaks flash metering/timing and+ * double-exposes (issue #721); with flash on the shot stays an instant flash photo with no+ * long-exposure countdown overlay. Also requires a non-ZSL ImageCapture: a ZSL capture returns+ * a frame buffered before the AE lock, so a night shot fired in the moment before the session+ * rebinds without ZSL (see [CameraViewModel.zslCompatible]) takes a plain photo instead (#914).+ */+internal fun CameraViewModel.nightCaptureApplies(): Boolean {+ val nightAuto = nightModeActive.value && isExposureAuto()+ return nightAuto && flashModeMutable.value == FlashMode.OFF && !stillCaptureIsZsl()+}++/** True when the bound ImageCapture was built for zero-shutter-lag capture. */+@OptIn(ExperimentalZeroShutterLag::class)+internal fun CameraViewModel.stillCaptureIsZsl(): Boolean =+ imageCapture?.captureMode == ImageCapture.CAPTURE_MODE_ZERO_SHUTTER_LAG+ /** * Motion Photo for plain PHOTO captures (no warmth/shadows bake, not capturing for a caller). * Only at the native 4:3 ratio: the motion still is saved as raw JPEG bytes (to preserve the
camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.ktindex d52692693a..7547f0f17a 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.kt@@ -1,8 +1,16 @@ package com.vayunmathur.camera.util +import android.graphics.ImageFormat+import android.hardware.camera2.CameraCharacteristics+import android.os.Build+import androidx.annotation.OptIn import com.vayunmathur.library.log.Log+import androidx.camera.camera2.interop.Camera2CameraInfo+import androidx.camera.camera2.interop.ExperimentalCamera2Interop import androidx.camera.core.Camera+import androidx.camera.core.CameraInfo import androidx.camera.core.CameraSelector+import androidx.camera.core.ExperimentalZeroShutterLag import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageCapture import androidx.camera.core.Preview@@ -11,6 +19,9 @@ import androidx.camera.core.resolutionselector.ResolutionStrategy import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.lifecycle.awaitInstance import android.util.Size+import com.vayunmathur.camera.domain.StillCaptureInputs+import com.vayunmathur.camera.domain.StillCaptureMode+import com.vayunmathur.camera.domain.StillCaptureModePolicy import com.vayunmathur.camera.platform.bindWithFallback import com.vayunmathur.camera.platform.currentLensFamily import com.vayunmathur.camera.platform.ensureLensesEnumerated@@ -21,7 +32,9 @@ import com.vayunmathur.camera.platform.refreshCapabilities * Binds a manual Preview + ImageCapture + ImageAnalysis session for the photo modes * (PHOTO / PORTRAIT / PANORAMA / PHOTOSPHERE / QR). ImageCapture requests the sensor's * maximum resolution; if the 3-stream max-res combination exceeds a device's stream-config- * limits, it falls back to a default ImageCapture resolution. ImageAnalysis is always+ * limits, it falls back to a default ImageCapture resolution. It captures with zero shutter+ * lag when [chooseStillCaptureMode] allows (then at the default resolution, see+ * [buildPhotoCapture]). ImageAnalysis is always * capped (~1.2 MP) — see the note in [CameraViewModel.bindSession]. */ suspend fun CameraViewModel.setupPhotoSession(): Boolean {@@ -169,12 +182,14 @@ internal fun CameraViewModel.bindPhotoUseCases( "START thread=${Thread.currentThread().name}" ) return try {- val capture = buildPhotoCapture(maxRes, ultraHdr)+ val mode = chooseStillCaptureMode(session.provider, lensSelector, ultraHdr)+ val capture = buildPhotoCapture(maxRes, ultraHdr, mode) val analysis = buildPhotoAnalysis() bindSession(session.provider, session.owner, lensSelector, session.preview, capture, analysis).also { Log.dev( "NightPreview", "setupPhotoSession() bind SUCCESS res=${it.cameraInfo} " ++ "still=${capture.resolutionInfo?.resolution} mode=$mode " + "zoom min=${it.cameraInfo.zoomState.value?.minZoomRatio} " + "max=${it.cameraInfo.zoomState.value?.maxZoomRatio}" )@@ -198,11 +213,24 @@ internal fun CameraViewModel.bindPhotoUseCases( } } -/** Builds the max/default-res ImageCapture with the still crop applied. */-internal fun CameraViewModel.buildPhotoCapture(maxRes: Boolean, ultraHdr: Boolean): ImageCapture {+/**+ * Builds the max/default-res ImageCapture with the still crop applied, in [mode].+ *+ * ZSL reprocesses a buffered PRIVATE frame, and CameraX restricts a ZSL ImageCapture to sizes+ * that are also PRIVATE reprocessing inputs. That drops the high-resolution-only sizes that+ * [maxRes] (PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE) exists to add, so a ZSL capture binds+ * at the default resolution instead of asking for sizes CameraX would filter out (#914).+ */+@OptIn(ExperimentalZeroShutterLag::class)+internal fun CameraViewModel.buildPhotoCapture(+ maxRes: Boolean,+ ultraHdr: Boolean,+ mode: StillCaptureMode = StillCaptureMode.MINIMIZE_LATENCY+): ImageCapture {+ val zsl = mode == StillCaptureMode.ZERO_SHUTTER_LAG val selectorBuilder = ResolutionSelector.Builder() .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)- if (maxRes) {+ if (maxRes && !zsl) { selectorBuilder.setAllowedResolutionMode( ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE )@@ -210,6 +238,10 @@ internal fun CameraViewModel.buildPhotoCapture(maxRes: Boolean, ultraHdr: Boolea val captureBuilder = ImageCapture.Builder() .setResolutionSelector(selectorBuilder.build()) .setFlashMode(getImageCaptureFlashMode())+ // MINIMIZE_LATENCY is also CameraX's default; set explicitly so the choice is visible.+ .setCaptureMode(+ if (zsl) ImageCapture.CAPTURE_MODE_ZERO_SHUTTER_LAG else ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY+ ) if (ultraHdr) { captureBuilder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR) }@@ -221,6 +253,49 @@ internal fun CameraViewModel.buildPhotoCapture(maxRes: Boolean, ultraHdr: Boolea return capture } +/**+ * Picks ZSL or MINIMIZE_LATENCY for the camera behind [lensSelector] from its capabilities and+ * the live exposure/night state ([StillCaptureModePolicy]). Any query failure means no ZSL.+ */+@OptIn(ExperimentalZeroShutterLag::class)+internal fun CameraViewModel.chooseStillCaptureMode(+ provider: ProcessCameraProvider,+ lensSelector: CameraSelector,+ ultraHdr: Boolean+): StillCaptureMode {+ val info = try {+ provider.getCameraInfo(lensSelector)+ } catch (e: IllegalArgumentException) {+ Log.status("NightPreview", "setupPhotoSession() no CameraInfo for ZSL probe; not using ZSL", e)+ return StillCaptureMode.MINIMIZE_LATENCY+ }+ val zslSupported = info.isZslSupported+ val inputs = StillCaptureInputs(+ zslSupported = zslSupported,+ ultraHdr = ultraHdr,+ ultraHdrReprocessable = zslSupported && ultraHdr && isJpegRReprocessable(info),+ autoExposure = isExposureAuto(),+ nightMode = nightModeActive.value,+ )+ return StillCaptureModePolicy.choose(inputs).also {+ Log.dev("NightPreview", "setupPhotoSession() captureMode=$it from $inputs")+ }+}++/** True when the camera lists JPEG_R (Ultra HDR) as a reprocessing output for PRIVATE input. */+@OptIn(ExperimentalCamera2Interop::class)+private fun isJpegRReprocessable(info: CameraInfo): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return false+ return try {+ val map = Camera2CameraInfo.from(info)+ .getCameraCharacteristic(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)+ map != null && ImageFormat.JPEG_R in map.getValidOutputFormatsForInput(ImageFormat.PRIVATE)+ } catch (e: IllegalArgumentException) {+ Log.status("NightPreview", "setupPhotoSession() reprocess formats unavailable", e)+ false+ }+}+ /** * Builds the capped (~1.2 MP) analysis stream, independently of [maxRes] (which stays * about ImageCapture — stills are unaffected and still come off the sensor at
camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.ktindex 251d0fe6dc..c97b89bb06 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt@@ -69,12 +69,10 @@ private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill): Singl // Skip it when the vendor NIGHT extension preview is bound: that session runs its own // multi-frame AE and rejects Camera2-interop AE_MODE_OFF/manual-exposure options, which makes // the capture fail. In that case a plain takePicture() lets the extension produce the shot.- // Also skip it when flash is on: the night override locks AE off with a forced long- // exposure, which breaks flash metering/timing and double-exposes (issue #721). The- // capturePhoto() router already keeps flash shots on the plain path; this guard covers- // any direct captureSinglePhoto() entry (e.g. night-burst fallback) the same way.- val nightExposure = if (nightModeActive.value && isExposureAuto() && !nightPreviewActiveMutable.value &&- flashModeMutable.value == FlashMode.OFF) {+ // Also skip it when flash is on (issue #721) or the ImageCapture is ZSL (#914); see+ // nightCaptureApplies(). The capturePhoto() router already keeps those shots on the plain+ // path; this guard covers any direct captureSinglePhoto() entry (e.g. night-burst fallback).+ val nightExposure = if (nightCaptureApplies() && !nightPreviewActiveMutable.value) { computeNightExposure() } else { null
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 91607a0cfd..3ee058951e 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -39,6 +39,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.runningFold import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex@@ -352,6 +353,15 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { val nightModeActive = combine(lowLightDetectedMutable, nightModeOverriddenOffMutable) { low, off -> low && !off } .stateIn(viewModelScope, SharingStarted.Eagerly, false) + // Whether live state lets the photo session use zero-shutter-lag capture: exposure and ISO on+ // Auto, night off (see StillCaptureModePolicy). The photo session rebinds when this flips,+ // but never mid-shot: while a capture is in flight the previous value is held (#914).+ val zslCompatible = combine(+ exposureTimeIndexMutable, manualIsoIndexMutable, nightModeActive, isCapturingMutable+ ) { exposure, iso, night, capturing -> ZslGate(exposure == 0 && iso == 0 && !night, capturing) }+ .runningFold(true) { held, gate -> if (gate.capturing) held else gate.compatible }+ .stateIn(viewModelScope, SharingStarted.Eagerly, true)+ // Whether to offer the vendor NIGHT extension. We optimistically probe with the // isSessionConfigSupported check, but the authoritative signal is the actual bind: if // the night preview session ever fails to bind on this device, we remember that (persisted, with a@@ -691,3 +701,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { } } // (ManualLifecycleOwner lives in CameraViewModelTypes.kt.)++/** One [CameraViewModel.zslCompatible] input sample: wanted value plus whether a shot is in flight. */+internal class ZslGate(val compatible: Boolean, val capturing: Boolean)
camera/src/test/java/com/vayunmathur/camera/domain/StillCaptureModePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/StillCaptureModePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/StillCaptureModePolicyTest.ktnew file mode 100644index 0000000000..ed2a2d69a4--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/StillCaptureModePolicyTest.kt@@ -0,0 +1,54 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals++class StillCaptureModePolicyTest {++ private val zslFriendly = StillCaptureInputs(+ zslSupported = true,+ ultraHdr = false,+ ultraHdrReprocessable = false,+ autoExposure = true,+ nightMode = false,+ )++ private fun choose(inputs: StillCaptureInputs) = StillCaptureModePolicy.choose(inputs)++ @Test+ fun supportedAutoJpegUsesZsl() {+ assertEquals(StillCaptureMode.ZERO_SHUTTER_LAG, choose(zslFriendly))+ }++ @Test+ fun unsupportedCameraUsesMinimizeLatency() {+ assertEquals(StillCaptureMode.MINIMIZE_LATENCY, choose(zslFriendly.copy(zslSupported = false)))+ }++ @Test+ fun manualExposureUsesMinimizeLatency() {+ assertEquals(StillCaptureMode.MINIMIZE_LATENCY, choose(zslFriendly.copy(autoExposure = false)))+ }++ @Test+ fun nightModeUsesMinimizeLatency() {+ assertEquals(StillCaptureMode.MINIMIZE_LATENCY, choose(zslFriendly.copy(nightMode = true)))+ }++ @Test+ fun ultraHdrKeepsQualityUnlessJpegRIsReprocessable() {+ assertEquals(StillCaptureMode.MINIMIZE_LATENCY, choose(zslFriendly.copy(ultraHdr = true)))+ assertEquals(+ StillCaptureMode.ZERO_SHUTTER_LAG,+ choose(zslFriendly.copy(ultraHdr = true, ultraHdrReprocessable = true))+ )+ }++ @Test+ fun reprocessableFlagAloneDoesNotEnableUnsupportedZsl() {+ assertEquals(+ StillCaptureMode.MINIMIZE_LATENCY,+ choose(zslFriendly.copy(zslSupported = false, ultraHdr = true, ultraHdrReprocessable = true))+ )+ }+}
camera/src/test/java/com/vayunmathur/camera/util/ZslGatingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/util/ZslGatingTest.kt b/camera/src/test/java/com/vayunmathur/camera/util/ZslGatingTest.ktnew file mode 100644index 0000000000..75ab834200--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/util/ZslGatingTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.camera.util++import android.os.Looper+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 org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * ZSL gating (#914): the session-rebind signal flips with manual exposure and night mode but is+ * held while a shot is in flight, and a ZSL-bound ImageCapture never takes the night path.+ */+@RunWith(AndroidJUnit4::class)+class ZslGatingTest {++ private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext())++ private fun idle() = shadowOf(Looper.getMainLooper()).idle()++ private fun CameraViewModel.engageNight() {+ repeat(CameraViewModel.NIGHT_DEBOUNCE_FRAMES) { onLuminance(5f) }+ idle()+ }++ @Test+ fun manualExposureAndNightTurnZslOff() {+ val v = vm()+ idle()+ assertTrue(v.zslCompatible.value)++ v.exposureTimeIndexMutable.value = 3+ idle()+ assertFalse(v.zslCompatible.value)+ v.exposureTimeIndexMutable.value = 0+ v.manualIsoIndexMutable.value = 2+ idle()+ assertFalse(v.zslCompatible.value)+ v.manualIsoIndexMutable.value = 0+ idle()+ assertTrue(v.zslCompatible.value)++ v.engageNight()+ assertTrue(v.nightModeActive.value)+ assertFalse(v.zslCompatible.value)+ }++ @Test+ fun valueHeldWhileCapturingThenApplied() {+ val v = vm()+ idle()+ v.isCapturingMutable.value = true+ idle()+ // Night engaging mid-shot must not rebind the session under the capture.+ v.engageNight()+ assertTrue(v.zslCompatible.value)++ v.isCapturingMutable.value = false+ idle()+ assertFalse(v.zslCompatible.value)+ }++ @OptIn(ExperimentalZeroShutterLag::class)+ @Test+ fun zslBoundCaptureNeverTakesTheNightPath() {+ val v = vm()+ v.engageNight()+ v.imageCapture = ImageCapture.Builder()+ .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)+ .build()+ assertTrue(v.nightCaptureApplies())+ assertTrue(v.routeStillCapture() == StillRoute.NIGHT)++ v.imageCapture = ImageCapture.Builder()+ .setCaptureMode(ImageCapture.CAPTURE_MODE_ZERO_SHUTTER_LAG)+ .build()+ assertTrue(v.stillCaptureIsZsl())+ assertFalse(v.nightCaptureApplies())+ assertTrue(v.routeStillCapture() != StillRoute.NIGHT)+ }+}