camera: long exposure no longer drags the preview to 1fps
- Commit
a8647089fc8b85821c241a5a57279f71c69b2a40- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 16:01 UTC (15 days ago)
- Parents
109d5f4
Manual/night long exposures were pushed into the shared session's repeating request, so a 1s shutter capped the preview at 1 frame per second (4s: 0.25). CameraX 1.7's generic interop can't split exposure per use case, so the split is temporal: PreviewExposurePolicy caps the preview at 1/30s with proportionally boosted ISO (brightness approximates the still), and the full long exposure applies transiently to the still capture only - the channel the night paths already prove. Capture output is unchanged; the preview ceiling is now ~30fps for any shutter at or below 1/30. Motion Photo routes to a single capture when a still override is required instead of inheriting preview exposure. Verified in the integrated 548-test green run, incl. new policy math and controller-level split tests.
Diff
camera/src/main/java/com/vayunmathur/camera/domain/PreviewExposurePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/PreviewExposurePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewExposurePolicy.ktnew file mode 100644index 0000000000..4df782612c--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewExposurePolicy.kt@@ -0,0 +1,66 @@+package com.vayunmathur.camera.domain++import kotlin.math.roundToLong++/**+ * Splits a manual still exposure into the exposure the live preview may run and the+ * exposure the still itself must get.+ *+ * The sensor produces one frame stream per capture session: CameraX merges the+ * Preview, ImageCapture and ImageAnalysis use cases bound together into a single+ * repeating capture request, so a 1s SENSOR_EXPOSURE_TIME pushed onto that request+ * (via Camera2CameraControl, which overlays the whole session) caps every stream —+ * preview included — at ~1 fps. Real cameras keep the viewfinder smooth by never+ * running the long exposure in preview: the preview runs a short exposure instead+ * and the long exposure is only in effect for the still.+ *+ * [split] therefore caps the preview at [PREVIEW_MAX_EXPOSURE_NANOS] (1/30s, so the+ * viewfinder keeps ~30 fps) and raises the preview ISO in proportion to the capped+ * time, so the preview stays about as bright as the still will be (clamped to the+ * sensor's ISO ceiling when known; the HAL clamps again regardless). The still+ * values pass through untouched, so what a capture exposes never changes — the+ * caller applies them only at capture time and restores the preview split after.+ */+object PreviewExposurePolicy {++ /** Longest exposure the preview stream may run: 1/30s (~30 fps viewfinder). */+ const val PREVIEW_MAX_EXPOSURE_NANOS: Long = 33_333_333L++ /** Preview/still pair derived from one manual exposure; see [split]. */+ data class SplitExposure(+ val previewNanos: Long,+ val previewIso: Int,+ val stillNanos: Long,+ val stillIso: Int,+ ) {+ /** True when the still cannot just inherit the live (preview) exposure. */+ val stillOverrideRequired: Boolean+ get() = previewNanos != stillNanos || previewIso != stillIso+ }++ /**+ * Splits [stillNanos]/[stillIso] for preview vs still. Exposures at or below+ * the preview cap split to themselves (no override needed at capture time).+ * [isoMax] is the sensor's sensitivity ceiling when known, else null.+ */+ fun split(stillNanos: Long, stillIso: Int, isoMax: Int?): SplitExposure {+ if (stillNanos <= PREVIEW_MAX_EXPOSURE_NANOS) {+ return SplitExposure(stillNanos, stillIso, stillNanos, stillIso)+ }+ val gain = stillNanos.toDouble() / PREVIEW_MAX_EXPOSURE_NANOS.toDouble()+ var previewIso = (stillIso * gain).roundToLong()+ .coerceAtLeast(stillIso.toLong())+ .coerceAtLeast(1L)+ if (isoMax != null) previewIso = previewIso.coerceAtMost(isoMax.toLong())+ return SplitExposure(+ previewNanos = PREVIEW_MAX_EXPOSURE_NANOS,+ previewIso = previewIso.toInt(),+ stillNanos = stillNanos,+ stillIso = stillIso,+ )+ }++ /** Frame-rate ceiling (fps) a repeating request with [exposureNanos] can run. */+ fun maxFps(exposureNanos: Long): Double =+ if (exposureNanos <= 0L) Double.POSITIVE_INFINITY else 1_000_000_000.0 / exposureNanos+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.ktindex 9c2e91f87e..a79f4189b8 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt@@ -4,6 +4,7 @@ import androidx.annotation.OptIn import androidx.camera.camera2.interop.ExperimentalCamera2Interop import com.vayunmathur.library.log.Log+import com.vayunmathur.camera.domain.PreviewExposurePolicy fun CameraViewModel.setExposureTimeIndex(index: Int) { exposureTimeIndexMutable.value = index.coerceIn(0, CameraViewModel.EXPOSURE_TIME_STOPS.lastIndex)@@ -40,11 +41,57 @@ internal fun CameraViewModel.manualIso(): Int? = internal fun CameraViewModel.isExposureAuto(): Boolean = exposureTimeIndexMutable.value == 0 && manualIsoIndexMutable.value == 0 +/**+ * The current manual exposure split into preview vs still (see [PreviewExposurePolicy]),+ * or null when shutter and ISO are both Auto. The un-set half of a half-manual exposure+ * is seeded from the last auto-converged value (or a sensible default), exactly as the+ * still has always been seeded; only the preview half is capped/brightened.+ */+internal fun CameraViewModel.currentExposureSplit(): PreviewExposurePolicy.SplitExposure? {+ val manualShutter = CameraViewModel.EXPOSURE_TIME_STOPS[exposureTimeIndexMutable.value].nanos+ val manualIso = manualIso()+ if (manualShutter == null && manualIso == null) return null+ val stillNanos = manualShutter ?: lastAeExposureNanos ?: 16_666_667L // ~1/60s+ val stillIso = manualIso ?: lastAeIso ?: isoStopsMutable.value.getOrNull(isoStopsMutable.value.size / 2) ?: 400+ return PreviewExposurePolicy.split(stillNanos, stillIso, isoStopsMutable.value.maxOrNull())+}++/** True when the next still needs its full exposure applied at capture time. */+internal fun CameraViewModel.stillExposureOverrideRequired(): Boolean =+ currentExposureSplit()?.stillOverrideRequired == true++/** AE-off + [nanos]/[iso] capture options for one still, shared by the capture paths. */+@Suppress("DEPRECATION")+@OptIn(ExperimentalCamera2Interop::class)+internal fun stillCaptureRequestOptions(+ nanos: Long,+ iso: Int?+): androidx.camera.camera2.interop.CaptureRequestOptions {+ val builder = androidx.camera.camera2.interop.CaptureRequestOptions.Builder()+ .setCaptureRequestOption(+ android.hardware.camera2.CaptureRequest.CONTROL_AE_MODE,+ android.hardware.camera2.CameraMetadata.CONTROL_AE_MODE_OFF+ )+ .setCaptureRequestOption(+ android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME, nanos+ )+ if (iso != null) {+ builder.setCaptureRequestOption(+ android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY, iso+ )+ }+ return builder.build()+}+ /** * Rebuilds a single [CaptureRequestOptions] from the current manual exposure/ISO state and- * pushes it to the bound camera, affecting the live preview and subsequent stills. When on Auto- * the options are cleared, reverting to CameraX's default auto behavior (including tap-to-focus).- * Called on every manual-control change and re-applied after a session rebind.+ * pushes it to the bound camera. This drives the LIVE (repeating) request shared by preview+ * and analysis, so it carries only the preview half of [currentExposureSplit]: a long manual+ * shutter is capped at 1/30s with a compensating ISO boost, keeping the viewfinder smooth —+ * the full still exposure is applied transiently at capture time instead (see+ * CameraSingleCapture). When on Auto the options are cleared, reverting to CameraX's default+ * auto behavior (including tap-to-focus). Called on every manual-control change and+ * re-applied after a session rebind. */ @Suppress("DEPRECATION") @OptIn(ExperimentalCamera2Interop::class)@@ -52,22 +99,20 @@ fun CameraViewModel.applyManualControls() { val cam2 = camera2ControlOrNull() ?: return val builder = androidx.camera.camera2.interop.CaptureRequestOptions.Builder() - // Manual exposure / ISO with linkage: if either is manual, lock AE off and set both,- // seeding the un-set one from the last auto-converged value (or a sensible default).- val manualShutter = CameraViewModel.EXPOSURE_TIME_STOPS[exposureTimeIndexMutable.value].nanos- val manualIso = manualIso()- if (manualShutter != null || manualIso != null) {- val exposure = manualShutter ?: lastAeExposureNanos ?: 16_666_667L // ~1/60s- val iso = manualIso ?: lastAeIso ?: isoStopsMutable.value.getOrNull(isoStopsMutable.value.size / 2) ?: 400+ // Manual exposure / ISO with linkage: if either is manual, lock AE off and set both.+ // Only the preview half goes on this live request (long shutters capped, ISO boosted+ // to compensate); the still half is applied at capture time.+ val split = currentExposureSplit()+ if (split != null) { builder.setCaptureRequestOption( android.hardware.camera2.CaptureRequest.CONTROL_AE_MODE, android.hardware.camera2.CameraMetadata.CONTROL_AE_MODE_OFF ) builder.setCaptureRequestOption(- android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME, exposure+ android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME, split.previewNanos ) builder.setCaptureRequestOption(- android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY, iso+ android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY, split.previewIso ) }
camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.ktindex df5380add9..c5fff405b2 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -139,6 +139,10 @@ internal fun CameraViewModel.routeStillCapture(): StillRoute = when { // produce the multi-frame night image. nightPreviewActiveMutable.value -> StillRoute.SINGLE nightCaptureApplies() -> StillRoute.NIGHT+ // A Motion Photo still must carry the manual exposure; with a long shutter the+ // preview runs a capped split, so take the single path that locks the full+ // exposure for the shot instead of inheriting the preview's.+ stillExposureOverrideRequired() -> StillRoute.SINGLE !motionPhotoEligible() -> StillRoute.SINGLE motionSaveQueue.tryReserve() -> StillRoute.MOTION_PHOTO else -> {@@ -186,6 +190,8 @@ private fun CameraViewModel.motionPhotoEligible(): Boolean { * flight at a time) with `IMG_<ts>_BURSTn` names, until [stopBurst] or [CameraViewModel.BURST_MAX] * is reached. Uses the plain capture path (no night/manual special-casing). */+@Suppress("DEPRECATION")+@OptIn(androidx.camera.camera2.interop.ExperimentalCamera2Interop::class) fun CameraViewModel.startBurst() { if (burstActiveMutable.value || isCapturingMutable.value) return // A burst is immediate: an armed shutter timer no longer applies.@@ -197,10 +203,19 @@ fun CameraViewModel.startBurst() { burstActiveMutable.value = true burstCountMutable.value = 0 val ts = MediaStoreSaver.timestamp()+ // Long manual shutter: lock the full still exposure for the burst's frames (the+ // live preview otherwise runs the capped split) and restore it when the burst ends.+ val burstSplit = currentExposureSplit()?.takeIf { it.stillOverrideRequired }+ val burstCam2 = if (burstSplit != null) camera2ControlOrNull() else null+ var burstExposureLocked = false fun finishBurst() { burstActiveMutable.value = false isCapturingMutable.value = false+ if (burstExposureLocked) {+ burstExposureLocked = false+ applyManualControls()+ } } fun shootNext(n: Int) {@@ -235,15 +250,36 @@ fun CameraViewModel.startBurst() { } ) }+ fun beginBurst() {+ if (burstSplit == null || burstCam2 == null) {+ shootNext(1)+ return+ }+ try {+ burstCam2.setCaptureRequestOptions(+ stillCaptureRequestOptions(burstSplit.stillNanos, burstSplit.stillIso)+ ).addListener({+ burstExposureLocked = true+ if (burstActiveMutable.value) shootNext(1) else finishBurst()+ }, ContextCompat.getMainExecutor(app))+ } catch (e: IllegalStateException) {+ Log.status("CameraViewModel", "Failed to lock burst exposure", e)+ shootNext(1)+ } catch (e: IllegalArgumentException) {+ Log.status("CameraViewModel", "Failed to lock burst exposure", e)+ 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()+ if (burstActiveMutable.value) beginBurst() else finishBurst() } } else {- shootNext(1)+ beginBurst() } }
camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.ktindex 31edf577d5..cdddf2b93c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt@@ -72,8 +72,9 @@ private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill): Singl val outputOptions = pending.outputOptions val stop = CameraViewModel.EXPOSURE_TIME_STOPS[exposureTimeIndexMutable.value]- // Manual shutter/ISO are already applied live via applyManualControls(); the only transient- // per-capture override here is the night-mode emulation (fully-auto exposure + night active).+ // applyManualControls() applies only the preview half of a manual exposure live; the+ // transient per-capture overrides here are the night-mode emulation (fully-auto+ // exposure + night active) and, below, the full manual still exposure. // 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.@@ -85,6 +86,14 @@ private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill): Singl } else { null }+ // Long manual shutter: the live request runs the capped preview split, so the still+ // needs its full exposure locked at capture time via the same transient slot the+ // night override uses (night takes precedence — it only applies on a fully-auto+ // exposure, where there is no manual split). The plan's nightExposure/nightIso+ // fields therefore carry whichever transient still exposure this shot needs.+ val stillExposure = nightExposure ?: currentExposureSplit()+ ?.takeIf { it.stillOverrideRequired }+ ?.let { NightExposure(it.stillNanos, it.stillIso) } // Used only to drive the long-exposure countdown overlay. val exposureNanos = stop.nanos ?: nightExposure?.nanos val cam2Control = try {@@ -103,9 +112,9 @@ private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill): Singl pending = pending, outputOptions = outputOptions, exposureNanos = exposureNanos,- nightIso = nightExposure?.iso,+ nightIso = stillExposure?.iso, cam2Control = cam2Control,- nightExposure = nightExposure,+ nightExposure = stillExposure, warmth = warmthMutable.value, shadows = shadowsMutable.value, mirror = mirrorCaptures,@@ -114,27 +123,14 @@ private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill): Singl ) } -/** Applies the transient night exposure, then runs the capture (or the capture directly). */+/** Applies the transient night/manual still exposure, then runs the capture (or directly). */ @Suppress("DEPRECATION") @OptIn(ExperimentalCamera2Interop::class) private fun CameraViewModel.applyNightExposureThen(plan: SingleCapturePlan, doCapture: (SingleCapturePlan) -> Unit) { try {- val options = androidx.camera.camera2.interop.CaptureRequestOptions.Builder()- .setCaptureRequestOption(- android.hardware.camera2.CaptureRequest.CONTROL_AE_MODE,- android.hardware.camera2.CameraMetadata.CONTROL_AE_MODE_OFF- )- .setCaptureRequestOption(- android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME,- plan.nightExposure!!.nanos- )- if (plan.nightIso != null) {- options.setCaptureRequestOption(- android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY,- plan.nightIso- )- }- plan.cam2Control!!.setCaptureRequestOptions(options.build())+ plan.cam2Control!!.setCaptureRequestOptions(+ stillCaptureRequestOptions(plan.nightExposure!!.nanos, plan.nightIso)+ ) .addListener({ doCapture(plan) }, ContextCompat.getMainExecutor(app)) } catch (e: IllegalStateException) { Log.status("CameraViewModel", "Failed to set night exposure", e)@@ -152,7 +148,7 @@ private fun CameraViewModel.runSingleCapture(plan: SingleCapturePlan) { } fun restoreAfterNight() {- // Undo the transient night override by re-asserting the (auto) manual-control state.+ // Undo the transient still override by re-asserting the live (preview) control state. if (plan.nightExposure != null) applyManualControls() } @@ -261,9 +257,38 @@ private fun CameraViewModel.processSingleFrame( * Capture path for the system IMAGE_CAPTURE intent. If the caller supplied an EXTRA_OUTPUT * Uri, the full-resolution JPEG is written there and [onSaved] is invoked with a null * thumbnail (the documented "no data extra needed" contract). Otherwise a downscaled- * thumbnail Bitmap is returned for the result "data" extra.+ * thumbnail Bitmap is returned for the result "data" extra. Locks the full still+ * exposure first when the preview runs a capped split of a long manual shutter,+ * restoring the preview split on completion. */+@Suppress("DEPRECATION")+@OptIn(ExperimentalCamera2Interop::class) fun CameraViewModel.capturePhotoForResult(onSaved: (Bitmap?) -> Unit, onError: () -> Unit) {+ val split = currentExposureSplit()?.takeIf { it.stillOverrideRequired }+ val cam2 = if (split != null) camera2ControlOrNull() else null+ // A capture already in flight keeps its silent no-op path (no callbacks to restore on).+ if (split == null || cam2 == null || isCapturingMutable.value) {+ capturePhotoForResultInternal(onSaved, onError)+ return+ }+ try {+ cam2.setCaptureRequestOptions(stillCaptureRequestOptions(split.stillNanos, split.stillIso))+ .addListener({+ capturePhotoForResultInternal(+ { bitmap -> applyManualControls(); onSaved(bitmap) },+ { applyManualControls(); onError() }+ )+ }, ContextCompat.getMainExecutor(app))+ } catch (e: IllegalStateException) {+ Log.status("CameraViewModel", "Failed to set still exposure for IMAGE_CAPTURE", e)+ capturePhotoForResultInternal(onSaved, onError)+ } catch (e: IllegalArgumentException) {+ Log.status("CameraViewModel", "Failed to set still exposure for IMAGE_CAPTURE", e)+ capturePhotoForResultInternal(onSaved, onError)+ }+}++internal fun CameraViewModel.capturePhotoForResultInternal(onSaved: (Bitmap?) -> Unit, onError: () -> Unit) { val capture = imageCapture ?: return onError() if (isCapturingMutable.value) return isCapturingMutable.value = true
camera/src/test/java/com/vayunmathur/camera/domain/PreviewExposurePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewExposurePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewExposurePolicyTest.ktnew file mode 100644index 0000000000..4d6b33c9d1--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewExposurePolicyTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class PreviewExposurePolicyTest {++ private fun split(stillNanos: Long, stillIso: Int, isoMax: Int? = null) =+ PreviewExposurePolicy.split(stillNanos, stillIso, isoMax)++ @Test+ fun shortExposureIsNotSplit() {+ val split = split(16_666_667L, 400) // 1/60s+ assertEquals(16_666_667L, split.previewNanos)+ assertEquals(400, split.previewIso)+ assertEquals(16_666_667L, split.stillNanos)+ assertEquals(400, split.stillIso)+ assertFalse(split.stillOverrideRequired)+ }++ @Test+ fun capBoundaryIsNotSplit() {+ val split = split(PreviewExposurePolicy.PREVIEW_MAX_EXPOSURE_NANOS, 800)+ assertFalse(split.stillOverrideRequired)+ assertEquals(33_333_333L, split.previewNanos)+ }++ @Test+ fun oneSecondExposureCapsPreviewAtThirtyFpsAndBoostsIso() {+ val split = split(1_000_000_000L, 100)+ assertEquals(33_333_333L, split.previewNanos)+ // 1s / (1/30s) = 30x gain: ISO 100 -> 3000 for equal preview brightness.+ assertEquals(3000, split.previewIso)+ assertEquals(1_000_000_000L, split.stillNanos)+ assertEquals(100, split.stillIso)+ assertTrue(split.stillOverrideRequired)+ assertEquals(30.0, PreviewExposurePolicy.maxFps(split.previewNanos), 0.01)+ assertEquals(1.0, PreviewExposurePolicy.maxFps(split.stillNanos), 0.001)+ }++ @Test+ fun fourSecondExposureBoostClampsToSensorCeiling() {+ val split = split(4_000_000_000L, 400, isoMax = 12_800)+ assertEquals(33_333_333L, split.previewNanos)+ assertEquals(12_800, split.previewIso) // unclamped would be 48_000+ assertEquals(4_000_000_000L, split.stillNanos)+ assertEquals(400, split.stillIso)+ assertTrue(split.stillOverrideRequired)+ }++ @Test+ fun nightSingleExposureQuarterSecondSplits() {+ val split = split(250_000_000L, 1600)+ assertEquals(33_333_333L, split.previewNanos)+ assertEquals(12_000, split.previewIso) // 7.5x gain+ assertTrue(split.stillOverrideRequired)+ }++ @Test+ fun previewIsoNeverDropsBelowStillIso() {+ // Just over the cap: gain ~1.0x must not round the preview ISO down.+ val split = split(34_000_000L, 101)+ assertTrue(split.previewIso >= 101)+ }++ @Test+ fun maxFpsOfNonPositiveExposureIsUnbounded() {+ assertEquals(Double.POSITIVE_INFINITY, PreviewExposurePolicy.maxFps(0L))+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/ManualPreviewExposureTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/ManualPreviewExposureTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/ManualPreviewExposureTest.ktnew file mode 100644index 0000000000..3bdab1303c--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/ManualPreviewExposureTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.camera.platform++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/**+ * Controller-level split between the live preview exposure and the still exposure:+ * which values each use-case stream effectively gets for a given manual setting.+ * The repeating (preview+analysis) request only ever receives the preview half via+ * applyManualControls(); the still half is locked transiently at capture time.+ */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ManualPreviewExposureTest {++ private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ private fun vm() = CameraViewModel(context.applicationContext as android.app.Application)++ private fun stopIndex(label: String): Int =+ CameraViewModel.EXPOSURE_TIME_STOPS.indexOfFirst { it.label == label }++ @Test fun autoExposureHasNoSplitAndNeedsNoOverride() {+ val viewModel = vm()+ viewModel.setExposureTimeIndex(0)+ viewModel.setManualIsoIndex(0)+ assertNull(viewModel.currentExposureSplit())+ assertFalse(viewModel.stillExposureOverrideRequired())+ // Unbound camera: pushing the (cleared) controls must not throw.+ viewModel.applyManualControls()+ }++ @Test fun shortManualShutterAppliesIdenticallyToPreviewAndStill() {+ val viewModel = vm()+ viewModel.isoStopsMutable.value = listOf(100, 200, 400, 800)+ viewModel.setExposureTimeIndex(stopIndex("1/60s"))+ viewModel.setManualIsoIndex(3) // ISO 400+ val split = assertNotNull(viewModel.currentExposureSplit())+ assertEquals(16_666_667L, split.stillNanos)+ assertEquals(400, split.stillIso)+ assertEquals(split.stillNanos, split.previewNanos)+ assertEquals(split.stillIso, split.previewIso)+ assertFalse(viewModel.stillExposureOverrideRequired())+ }++ @Test fun longManualShutterCapsPreviewButKeepsStill() {+ val viewModel = vm()+ viewModel.isoStopsMutable.value = listOf(100, 200, 400, 800, 1600, 3200)+ viewModel.setExposureTimeIndex(stopIndex("4s"))+ viewModel.setManualIsoIndex(2) // ISO 200+ val split = assertNotNull(viewModel.currentExposureSplit())+ assertEquals(4_000_000_000L, split.stillNanos)+ assertEquals(200, split.stillIso)+ assertEquals(33_333_333L, split.previewNanos)+ // 120x gain clamped to the highest known stop.+ assertEquals(3200, split.previewIso)+ assertTrue(viewModel.stillExposureOverrideRequired())+ // Unbound camera: the capped preview push must not throw.+ viewModel.applyManualControls()+ }++ @Test fun oneSecondShutterPreviewRunsThirtyFpsWhileStillRunsOne() {+ val viewModel = vm()+ viewModel.isoStopsMutable.value = listOf(50, 100, 200, 400, 800, 1600, 3200, 6400, 12800)+ viewModel.setExposureTimeIndex(stopIndex("1s"))+ viewModel.setManualIsoIndex(2) // ISO 100+ val split = assertNotNull(viewModel.currentExposureSplit())+ assertEquals(3000, split.previewIso)+ assertEquals(+ 30.0,+ com.vayunmathur.camera.domain.PreviewExposurePolicy.maxFps(split.previewNanos),+ 0.01+ )+ assertEquals(+ 1.0,+ com.vayunmathur.camera.domain.PreviewExposurePolicy.maxFps(split.stillNanos),+ 0.001+ )+ }++ @Test fun halfManualIsoOnlySeedsShutterFromLastAe() {+ val viewModel = vm()+ viewModel.isoStopsMutable.value = listOf(100, 200, 400)+ viewModel.lastAeExposureNanos = 8_000_000L // 1/125s converged+ viewModel.setExposureTimeIndex(0)+ viewModel.setManualIsoIndex(2) // ISO 200, shutter auto-seeded+ val split = assertNotNull(viewModel.currentExposureSplit())+ assertEquals(8_000_000L, split.stillNanos)+ assertEquals(200, split.stillIso)+ assertFalse(viewModel.stillExposureOverrideRequired())+ }+}