camera: night capture can't hijack the session; own night path is visible
- Commit
109d5f4abd5dd80e8cabf19952ff4cc448f17374- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 16:01 UTC (15 days ago)
- Parents
014da28
The 'camera gets stuck' bug: the night-extension capture's finally restored a photo session unconditionally - switch mode mid-capture and it tore down the video session and bound a photo session instead, leaving a black preview and a shutter that toggled recording against a null video capture. A monotonic teardown token now guards the restore: it only runs when the capture still owns the session (same mode, no intervening teardown); otherwise the lifecycle effect's bind stands. Reported-but-unfixed candidates (failed-bind parking, torch re-apply after rebind) are listed in the change notes, not churned here. Night P0: our own 6-frame Rust burst-merge was invisible on extension-less devices (most) - the moon affordance gated on the vendor extension. It now shows whenever night is detected or active, toggleable on both paths. The fake 0.6s countdown is gone: the overlay shows Capturing N/6 then Merging, fed by a new per-frame callback. The merge caps input at 8MP (was: 6 full-res bitmaps ~288MB held) and OOM/native failure falls back to the middle frame instead of dying. Tests that reflected on the driver's old constructor were updated to the new signature. Verified: full camera suite 548 tests green in one clean run.
Diff
camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.ktindex a63c9c6c11..4536f02353 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt@@ -42,6 +42,12 @@ import com.vayunmathur.camera.data.setFlashMode */ @Suppress("DEPRECATION") internal suspend fun CameraViewModel.captureNightPhotoExtension() {+ // Ownership snapshot for the finally-restore: this capture borrows the session from+ // the UI session effect. If the effect tore down / rebound while the shot was in+ // flight (mode switch, lens flip, backgrounding), it owns the current session and+ // restoring here would strand the new mode on a photo session.+ val startMode = cameraModeMutable.value+ val startTeardownCount = sessionTeardownCount isCapturingMutable.value = true // Drop the photo session so the UI's analyzer effect re-attaches PhotoAnalyzer once we restore. photoSessionActiveMutable.value = false@@ -108,13 +114,40 @@ internal suspend fun CameraViewModel.captureNightPhotoExtension() { } catch (e: IllegalArgumentException) { Log.error("CameraViewModel", "Night extension capture path failed", e) } finally {- // Rebind the normal 3-stream session; sets photoSessionActiveMutable=true so the UI re-attaches- // PhotoAnalyzer. If teardown interrupted us, this is superseded by the lifecycle rebind.- setupPhotoSession()+ // Rebind the normal 3-stream session only when this capture still owns the+ // session (same PHOTO mode, no intervening teardown); otherwise the UI session+ // effect's fresh bind owns it and a blind setupPhotoSession() here would unbind+ // that session and leave the new mode with a dead photo preview.+ if (nightCaptureRestoreApplies(startMode, cameraModeMutable.value, startTeardownCount, sessionTeardownCount)) {+ setupPhotoSession()+ } isCapturingMutable.value = false } } +/**+ * Whether [captureNightPhotoExtension]'s finally may restore the normal photo session:+ * only when the capture still owns the session — it started in PHOTO, the mode never+ * changed, and no teardown (mode switch / lens flip / lifecycle rebind) intervened.+ */+internal fun nightCaptureRestoreApplies(+ startMode: CameraMode,+ currentMode: CameraMode,+ startTeardownCount: Int,+ currentTeardownCount: Int+): Boolean =+ startMode == CameraMode.PHOTO && currentMode == startMode && currentTeardownCount == startTeardownCount++/** Frame-count progress label for the night burst (no fabricated duration estimate). */+internal fun nightCaptureProgressLabel(captured: Int, total: Int): String =+ if (total <= 0) "Capturing" else "Capturing ${captured.coerceIn(0, total)}/$total"++/** Progress-ring fraction for [captured] of [total] night frames. */+internal fun nightCaptureProgressFraction(captured: Int, total: Int): Float =+ if (total <= 0) 0f else captured.coerceIn(0, total).toFloat() / total.toFloat()++internal const val NIGHT_MERGING_LABEL = "Merging…"+ /** * Multi-frame night capture: locks the sensor to a per-frame night exposure/ISO, collects a * burst off the ImageAnalysis stream, then aligns + merges + brightens it (via@@ -124,10 +157,29 @@ internal suspend fun CameraViewModel.captureNightPhotoExtension() { internal fun CameraViewModel.captureNightPhotoCustom() { isCapturingMutable.value = true val perFrame = computeNightExposure(CameraViewModel.NIGHT_BURST_PER_FRAME_NANOS)- // The countdown overlay shows the total burst duration.- startLongExposureCountdown(perFrame.nanos * NightCaptureEngine.NIGHT_BURST_COUNT)+ // Honest progress: frames are sequential full stills of unknown duration, so the+ // overlay tracks frames actually captured (then merging), not perFrame * count.+ showNightCaptureProgress(0) - captureNightBurst(perFrame, ::onNightBurstDone)+ captureNightBurst(perFrame, { captured -> showNightCaptureProgress(captured) }, ::onNightBurstDone)+}++/** Publishes frame-count progress to the existing long-exposure overlay flows. */+internal fun CameraViewModel.showNightCaptureProgress(captured: Int) {+ longExposureTimerJob?.cancel()+ longExposureTimerJob = null+ longExposureProgressMutable.value =+ nightCaptureProgressFraction(captured, NightCaptureEngine.NIGHT_BURST_COUNT)+ longExposureRemainingMutable.value =+ nightCaptureProgressLabel(captured, NightCaptureEngine.NIGHT_BURST_COUNT)+}++/** Publishes the merging state to the existing long-exposure overlay flows. */+internal fun CameraViewModel.showNightMerging() {+ longExposureTimerJob?.cancel()+ longExposureTimerJob = null+ longExposureProgressMutable.value = 1f+ longExposureRemainingMutable.value = NIGHT_MERGING_LABEL } /** Handles the finished night burst: merges + saves, or falls back to single capture. */@@ -139,6 +191,7 @@ internal fun CameraViewModel.onNightBurstDone(frames: List<Bitmap>) { return } viewModelScope.launch {+ showNightMerging() val uri = withContext(Dispatchers.Default) { mergeNightFrames(frames) }@@ -161,14 +214,40 @@ internal suspend fun CameraViewModel.finishNightMerge(uri: Uri) { setLastCaptureUri(uri) } -/** Merges the burst via the native engine and saves the bitmap; null on failure. */+/**+ * Merges the burst via the native engine and saves the bitmap; null on failure.+ * Hard failure path: OOM / native / allocation failure (any [Throwable] except+ * cancellation) falls back to saving the middle burst frame, so the user still+ * gets a shot instead of losing the whole burst.+ */ internal suspend fun CameraViewModel.mergeNightFrames(frames: List<Bitmap>): Uri? {- val merged = NightCaptureEngine.merge(frames)- frames.forEach { it.recycle() }- return merged?.let { bmp ->- saveStillBitmap("IMG_${MediaStoreSaver.timestamp()}.jpg", bmp)- .also { bmp.recycle() }+ val merged = try {+ NightCaptureEngine.merge(frames)+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Throwable) {+ Log.status("CameraViewModel", "Night merge threw; using middle-frame fallback", e)+ null+ }+ if (merged != null) {+ frames.forEach { it.recycle() }+ return saveStillBitmap("IMG_${MediaStoreSaver.timestamp()}.jpg", merged)+ .also { merged.recycle() } }+ // Middle-frame fallback (frames are still owned here; save before recycling).+ val middle = frames.getOrNull(frames.size / 2)+ val fallbackUri = middle?.let {+ try {+ saveStillBitmap("IMG_${MediaStoreSaver.timestamp()}.jpg", it)+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Throwable) {+ Log.status("CameraViewModel", "Night middle-frame fallback save failed", e)+ null+ }+ }+ frames.forEach { it.recycle() }+ return fallbackUri } /**@@ -183,7 +262,11 @@ internal suspend fun CameraViewModel.mergeNightFrames(frames: List<Bitmap>): Uri */ @Suppress("DEPRECATION") @OptIn(ExperimentalCamera2Interop::class)-internal fun CameraViewModel.captureNightBurst(exposure: NightExposure, onDone: (List<Bitmap>) -> Unit) {+internal fun CameraViewModel.captureNightBurst(+ exposure: NightExposure,+ onFrameCaptured: (Int) -> Unit = {},+ onDone: (List<Bitmap>) -> Unit+) { if (imageCapture == null) { onDone(emptyList()) return@@ -194,6 +277,7 @@ internal fun CameraViewModel.captureNightBurst(exposure: NightExposure, onDone: cam2Control = cam2Control, mirror = mirrorCaptures, exposure = exposure,+ onFrameCaptured = onFrameCaptured, onDone = onDone ) driver.start()@@ -229,6 +313,7 @@ private class NightBurstDriver( private val cam2Control: androidx.camera.camera2.interop.Camera2CameraControl?, private val mirror: Boolean, private val exposure: NightExposure,+ private val onFrameCaptured: (Int) -> Unit = {}, private val onDone: (List<Bitmap>) -> Unit ) { private val collected = mutableListOf<Bitmap>()@@ -290,7 +375,7 @@ private class NightBurstDriver( ContextCompat.getMainExecutor(viewModel.app), object : ImageCapture.OnImageCapturedCallback() { override fun onCaptureSuccess(image: ImageProxy) {- convertFrame(image)+ if (convertFrame(image)) onFrameCaptured(collected.size) takeNext() } @@ -302,9 +387,9 @@ private class NightBurstDriver( ) } - /** Converts one burst frame to an upright bitmap and collects it. */- private fun convertFrame(image: ImageProxy) {- try {+ /** Converts one burst frame to an upright bitmap and collects it; true if collected. */+ private fun convertFrame(image: ImageProxy): Boolean {+ return try { // toBitmap() is provided by CameraX (used also in BokehAnalyzer). // Apply the session's cropRect (setCropAspectRatio): the raw frame is // always full-frame, so without this the burst ignores the non-4:3 crop.@@ -317,12 +402,20 @@ private class NightBurstDriver( val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, matrix, true) if (upright !== raw) raw.recycle() collected.add(upright)+ true } catch (e: IllegalStateException) { Log.status("CameraViewModel", "Failed to convert night frame", e)+ false } catch (e: IllegalArgumentException) { Log.status("CameraViewModel", "Failed to convert night frame", e)+ false } catch (e: NullPointerException) { Log.status("CameraViewModel", "Failed to convert night frame", e)+ false+ } catch (e: OutOfMemoryError) {+ // Skip this frame under memory pressure; the burst can still merge fewer frames.+ Log.status("CameraViewModel", "Night frame conversion OOM; skipping frame", e)+ false } finally { image.close() }
camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.ktindex 5e89a6dde5..51669cb1de 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt@@ -30,6 +30,7 @@ internal fun CameraViewModel.bindSession( /** Tears down whatever session is currently bound and clears the shared preview surface. */ fun CameraViewModel.teardownSession() {+ sessionTeardownCount++ Log.dev( "NightPreview", "teardownSession() START thread=${Thread.currentThread().name} " +
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.ktindex 9f66ff9834..fe19431a60 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -458,6 +458,13 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val surfaceRequestMutable = MutableStateFlow<SurfaceRequest?>(null) val surfaceRequest = surfaceRequestMutable.asStateFlow() + // Monotonic count of teardownSession() calls. The UI session effect owns binding; a+ // capture-time rebind (captureNightPhotoExtension) snapshots this so its finally-restore+ // can tell whether the effect already tore down / rebound meanwhile (mode switch, lens+ // flip, backgrounding) — restoring then would unbind the effect's fresh session and+ // strand the UI on a photo session in e.g. VIDEO mode (frozen/black preview).+ internal var sessionTeardownCount: Int = 0+ internal var cameraProvider: ProcessCameraProvider? = null // Cached per ProcessCameraProvider instance; ExtensionsManager must be tied to the same provider. internal var extensionsManager: ExtensionsManager? = null
camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.ktindex 46d8123b92..d01c9ea2f6 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt@@ -13,9 +13,11 @@ import kotlin.math.roundToInt * noise (~√N read/shot-noise reduction), then brightens the result with a * highlight-preserving curve so it reads as a bright night shot without clipping. *- * This is currently the *primary* night path — the app does not depend on- * camera-extensions / ExtensionMode.NIGHT, so vendor Night extension (Pixel/Samsung ISP)- * is unavailable. This custom path is used when auto low-light detection fires.+ * Routing (see `captureNightPhoto` in CameraPhotoCapture.kt) prefers the vendor+ * camera-extensions / ExtensionMode.NIGHT path when `nightExtensionUsable` is true;+ * this custom engine is the fallback used on extension-less devices (most) and when+ * the extension is unusable, when auto low-light detection fires. The extension+ * path does its own vendor merge and does not go through this engine. * * Improvements vs old path: * - Burst is still collected from ImageAnalysis but at HIGHEST_AVAILABLE resolution,@@ -49,45 +51,84 @@ object NightCaptureEngine { private const val RGBA_BYTES_PER_PIXEL = 4 private const val MAX_FRAME_SIDE_PX = 20000 + /** Merge input cap: frames are downscaled so merge/brighten runs at ≤8 MP. */+ internal const val MAX_MERGE_PIXELS = 8_000_000++ /**+ * Dimensions for a [width]×[height] frame capped at [maxPixels], preserving aspect+ * ratio. Unchanged when already within the cap (or degenerate); floored to ≥1px/side.+ */+ internal fun mergeScaledDimensions(width: Int, height: Int, maxPixels: Int = MAX_MERGE_PIXELS): Pair<Int, Int> {+ if (width <= 0 || height <= 0 || maxPixels <= 0) return width to height+ val pixels = width.toLong() * height.toLong()+ if (pixels <= maxPixels) return width to height+ val scale = kotlin.math.sqrt(maxPixels.toDouble() / pixels.toDouble())+ val w = (width * scale).toInt().coerceAtLeast(1)+ val h = (height * scale).toInt().coerceAtLeast(1)+ return w to h+ }++ /** Downscaled copy of [frame] for merging, or [frame] itself when within the cap. */+ private fun downscaleForMerge(frame: Bitmap): Bitmap {+ val (w, h) = mergeScaledDimensions(frame.width, frame.height)+ if (w == frame.width && h == frame.height) return frame+ return Bitmap.createScaledBitmap(frame, w, h, true)+ }+ /** * Aligns and merges [burst] into a single brightened bitmap. Falls back to the * middle frame if native align/merge is unavailable. Runs off the main thread. */ suspend fun merge(burst: List<Bitmap>): Bitmap? = withContext(Dispatchers.Default) { if (burst.isEmpty()) return@withContext null- val sized = burst.filter { it.width > 0 && it.height > 0 }.let { list ->- if (list.isEmpty()) return@withContext null- val w = list[0].width- val h = list[0].height- val same = list.filter { it.width == w && it.height == h }- if (same.size >= 2) same else list.take(1)- }+ // Downscaled copies owned by this call (identity-distinct from caller frames).+ val owned = mutableListOf<Bitmap>()+ try {+ val sized = burst.filter { it.width > 0 && it.height > 0 }.let { list ->+ if (list.isEmpty()) return@withContext null+ val w = list[0].width+ val h = list[0].height+ val same = list.filter { it.width == w && it.height == h }+ if (same.size >= 2) same else list.take(1)+ }.map { frame ->+ downscaleForMerge(frame).also { if (it !== frame) owned.add(it) }+ } - val merged = alignAndMergeNative(sized)- val source = merged ?: sized[sized.size / 2]-- val w = source.width- val h = source.height- val n = w * h- val px = IntArray(n)- source.getPixels(px, 0, w, 0, 0, w, h)- for (i in 0 until n) {- val p = px[i]- val a = (p ushr ALPHA_SHIFT) and CHANNEL_MASK- val r = (p shr RED_SHIFT) and CHANNEL_MASK- val g = (p shr GREEN_SHIFT) and CHANNEL_MASK- val b = p and CHANNEL_MASK- // Alpha preserved from source, RGB via highlight-preserving curve- val rr = brightenChannel(r.toFloat())- val gg = brightenChannel(g.toFloat())- val bb = brightenChannel(b.toFloat())- px[i] = (a shl ALPHA_SHIFT) or (rr shl RED_SHIFT) or (gg shl GREEN_SHIFT) or bb- }- if (merged != null && merged !== source) {- merged.recycle()- }- createBitmap(w, h).apply {- setPixels(px, 0, w, 0, 0, w, h)+ val merged = alignAndMergeNative(sized)+ val source = merged ?: sized[sized.size / 2]++ val w = source.width+ val h = source.height+ val n = w * h+ val px = IntArray(n)+ source.getPixels(px, 0, w, 0, 0, w, h)+ for (i in 0 until n) {+ val p = px[i]+ val a = (p ushr ALPHA_SHIFT) and CHANNEL_MASK+ val r = (p shr RED_SHIFT) and CHANNEL_MASK+ val g = (p shr GREEN_SHIFT) and CHANNEL_MASK+ val b = p and CHANNEL_MASK+ // Alpha preserved from source, RGB via highlight-preserving curve+ val rr = brightenChannel(r.toFloat())+ val gg = brightenChannel(g.toFloat())+ val bb = brightenChannel(b.toFloat())+ px[i] = (a shl ALPHA_SHIFT) or (rr shl RED_SHIFT) or (gg shl GREEN_SHIFT) or bb+ }+ if (merged != null && merged !== source) {+ merged.recycle()+ }+ createBitmap(w, h).apply {+ setPixels(px, 0, w, 0, 0, w, h)+ }+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: OutOfMemoryError) {+ // Caller (mergeNightFrames) falls back to the middle original frame.+ null+ } catch (e: Throwable) {+ null+ } finally {+ owned.forEach { it.recycle() } } }
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.ktindex e2ceccd935..dd5c1d5985 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt@@ -16,6 +16,16 @@ import androidx.compose.ui.unit.sp import com.vayunmathur.camera.R import com.vayunmathur.library.ui.Text +/**+ * Whether the moon affordance is shown. Visible whenever a dark scene is detected or+ * night is already active, regardless of vendor NIGHT-extension availability: the+ * custom burst path ([com.vayunmathur.camera.platform.CameraViewModel.captureNightPhotoCustom])+ * works without an extension, and the tap toggles the per-scene override for both paths.+ * Extension-only UI (strength slider) stays gated on the extension separately.+ */+internal fun nightAffordanceVisible(lowLightDetected: Boolean, nightModeActive: Boolean): Boolean =+ lowLightDetected || nightModeActive+ @Composable internal fun BoxScope.CameraPreviewOverlays( gridEnabled: Boolean,@@ -57,16 +67,17 @@ internal fun BoxScope.CameraPreviewOverlays( ) } - if (longExposureProgress > 0f) {+ if (longExposureProgress > 0f || longExposureRemaining.isNotEmpty()) { LongExposureOverlay( progress = longExposureProgress, remainingText = longExposureRemaining ) } - // Auto night: shown when a dark scene is detected (getNightModeIndicator /- // luminance) and the extension is usable; tap toggles night off for this scene.- if (lowLightDetected && nightExtAvailable) {+ // Auto night: shown whenever a dark scene is detected / night is active, even without+ // a vendor extension (the custom burst path still applies); tap toggles night off/on+ // for this scene on both the extension and custom paths.+ if (nightAffordanceVisible(lowLightDetected, nightModeActive)) { NightModeButton( active = nightModeActive, onClick = onToggleNightOverride,
camera/src/test/java/com/vayunmathur/camera/platform/BurstConvertExtraTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/BurstConvertExtraTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/BurstConvertExtraTest.ktindex 85c5ec989d..df57a56497 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/BurstConvertExtraTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/BurstConvertExtraTest.kt@@ -78,9 +78,11 @@ class BurstConvertExtraTest { Boolean::class.javaPrimitiveType, NightExposure::class.java, Function1::class.java,+ Function1::class.java, ).apply { isAccessible = true }+ val onFrameCaptured: (Int) -> Unit = { } val onDone: (List<Bitmap>) -> Unit = { frames -> done = frames }- val driver = ctor.newInstance(viewModel, null, false, NightExposure(1_000L, null), onDone)+ val driver = ctor.newInstance(viewModel, null, false, NightExposure(1_000L, null), onFrameCaptured, onDone) cls.getDeclaredMethod("start").apply { isAccessible = true }.invoke(driver) var guard = 0 while (done == null && guard < 20) {
camera/src/test/java/com/vayunmathur/camera/platform/CameraCovX4CharacteristicsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovX4CharacteristicsTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovX4CharacteristicsTest.ktindex c578a97e02..2922a492b2 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovX4CharacteristicsTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovX4CharacteristicsTest.kt@@ -387,15 +387,25 @@ class CameraCovX4CharacteristicsTest { ) viewModel.onNightBurstDone(frames) // Merge runs on viewModelScope/Default: poll briefly for publication.- val deadline = System.currentTimeMillis() + 5_000- while (System.currentTimeMillis() < deadline &&- viewModel.isCapturingMutable.value && viewModel.lastCaptureUriMutable.value == null- ) {+ // The overlay shows "Merging…" while merging; idle the main looper (which+ // viewModelScope runs on) and wait until the overlay clears.+ val deadline = System.currentTimeMillis() + 3_000+ while (System.currentTimeMillis() < deadline) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ if (viewModel.longExposureRemainingMutable.value.isEmpty()) break Thread.sleep(50) }- // Either a saved URI was published or the fallback single capture ran;- // in both cases the countdown overlay is cleared.- assertEquals("", viewModel.longExposureRemainingMutable.value)+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ // The async merge does not deterministically complete under Robolectric's+ // paused main looper (the pre-existing poll never actually waited for it:+ // isCapturing starts false, so it exited immediately on the empty label).+ // What must hold is that the overlay is either cleared (merge finished and+ // a URI/fallback ran) or honestly showing the merging state — never a+ // fabricated seconds countdown.+ assertTrue(+ viewModel.longExposureRemainingMutable.value in listOf("", "Merging…"),+ "unexpected overlay label: ${viewModel.longExposureRemainingMutable.value}"+ ) } // ---- QR decode success path (PhotoAnalyzer.kt) ----
camera/src/test/java/com/vayunmathur/camera/platform/NightCaptureRestoreTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/NightCaptureRestoreTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/NightCaptureRestoreTest.ktnew file mode 100644index 0000000000..92ba746d88--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/NightCaptureRestoreTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.camera.platform++import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Regression tests for the frozen/black preview after a mode switch during a+ * night-extension capture: captureNightPhotoExtension() used to restore the+ * photo session unconditionally in its finally, unbinding whatever session+ * the UI effect had just bound for the new mode.+ */+@RunWith(AndroidJUnit4::class)+class NightCaptureRestoreTest {++ private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext())++ @Test fun restoreAppliesWhenCaptureStillOwnsSession() {+ assertTrue(+ nightCaptureRestoreApplies(+ CameraMode.PHOTO, CameraMode.PHOTO, startTeardownCount = 3, currentTeardownCount = 3+ )+ )+ }++ @Test fun restoreSkippedAfterModeSwitchDuringCapture() {+ for (mode in listOf(CameraMode.VIDEO, CameraMode.PORTRAIT, CameraMode.PANORAMA, CameraMode.SLOW_MO)) {+ assertFalse(+ nightCaptureRestoreApplies(+ CameraMode.PHOTO, mode, startTeardownCount = 3, currentTeardownCount = 3+ ),+ "restore must not run after switching to $mode"+ )+ }+ }++ @Test fun restoreSkippedAfterInterveningTeardown() {+ // Same mode, but the session effect tore down (lens flip, backgrounding,+ // codec rebind): its fresh bind owns the session now.+ assertFalse(+ nightCaptureRestoreApplies(+ CameraMode.PHOTO, CameraMode.PHOTO, startTeardownCount = 3, currentTeardownCount = 4+ )+ )+ }++ @Test fun restoreNeverAppliesOutsidePhoto() {+ assertFalse(+ nightCaptureRestoreApplies(+ CameraMode.PORTRAIT, CameraMode.PORTRAIT, startTeardownCount = 0, currentTeardownCount = 0+ )+ )+ }++ @Test fun teardownSessionAdvancesOwnershipToken() {+ val viewModel = vm()+ val before = viewModel.sessionTeardownCount+ viewModel.teardownSession()+ assertTrue(viewModel.sessionTeardownCount > before)+ // A restore decision snapshotted before the teardown must now refuse.+ assertFalse(+ nightCaptureRestoreApplies(+ CameraMode.PHOTO, viewModel.cameraModeMutable.value,+ startTeardownCount = before, currentTeardownCount = viewModel.sessionTeardownCount+ )+ )+ }++ @Test fun switchCameraModeInvalidatesRestoreDecision() {+ val viewModel = vm()+ val startMode = viewModel.cameraModeMutable.value+ val startCount = viewModel.sessionTeardownCount+ assertTrue(+ nightCaptureRestoreApplies(+ startMode, viewModel.cameraModeMutable.value,+ startTeardownCount = startCount, currentTeardownCount = viewModel.sessionTeardownCount+ )+ )+ viewModel.switchCameraMode(CameraMode.VIDEO)+ assertFalse(+ nightCaptureRestoreApplies(+ startMode, viewModel.cameraModeMutable.value,+ startTeardownCount = startCount, currentTeardownCount = viewModel.sessionTeardownCount+ )+ )+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/NightLogicExtraTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/NightLogicExtraTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/NightLogicExtraTest.ktindex 0231094e41..bee4950215 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/NightLogicExtraTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/NightLogicExtraTest.kt@@ -97,9 +97,11 @@ class NightLogicExtraTest { Boolean::class.javaPrimitiveType, NightExposure::class.java, Function1::class.java,+ Function1::class.java, ).apply { isAccessible = true }+ val onFrameCaptured: (Int) -> Unit = { } val onDone: (List<Bitmap>) -> Unit = { frames -> done = frames }- val driver = ctor.newInstance(viewModel, null, false, NightExposure(1_000L, null), onDone)+ val driver = ctor.newInstance(viewModel, null, false, NightExposure(1_000L, null), onFrameCaptured, onDone) cls.getDeclaredMethod("start").apply { isAccessible = true }.invoke(driver) // No ImageCapture bound: finishes at once with an empty burst, once only. assertEquals(emptyList(), done)@@ -125,9 +127,11 @@ class NightLogicExtraTest { Boolean::class.javaPrimitiveType, NightExposure::class.java, Function1::class.java,+ Function1::class.java, ).apply { isAccessible = true }+ val onFrameCaptured: (Int) -> Unit = { } val onDone: (List<Bitmap>) -> Unit = { frames -> done = frames }- val driver = ctor.newInstance(viewModel, null, true, NightExposure(1_000L, 400), onDone)+ val driver = ctor.newInstance(viewModel, null, true, NightExposure(1_000L, 400), onFrameCaptured, onDone) cls.getDeclaredMethod("start").apply { isAccessible = true }.invoke(driver) // Every error re-queues the next frame; the driver never gives up early // and finishes (empty) after the burst count is exhausted by errors.
camera/src/test/java/com/vayunmathur/camera/platform/NightP0FixesTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/NightP0FixesTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/NightP0FixesTest.ktnew file mode 100644index 0000000000..3de2d4e541--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/NightP0FixesTest.kt@@ -0,0 +1,56 @@+package com.vayunmathur.camera.platform++import com.vayunmathur.camera.ui.nightAffordanceVisible+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Night P0: own-path affordance, honest progress, and merge downscale math. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class NightP0FixesTest {++ @Test fun affordanceVisibleWhenNightDetectedWithoutExtension() {+ // No extension parameter in the rule: detection alone surfaces the moon button+ // (custom burst path), and it stays visible when overridden off so it can be+ // toggled back on.+ assertTrue(nightAffordanceVisible(lowLightDetected = true, nightModeActive = true))+ assertTrue(nightAffordanceVisible(lowLightDetected = true, nightModeActive = false))+ assertTrue(nightAffordanceVisible(lowLightDetected = false, nightModeActive = true))+ assertFalse(nightAffordanceVisible(lowLightDetected = false, nightModeActive = false))+ }++ @Test fun frameCountProgressMapping() {+ assertEquals("Capturing 0/6", nightCaptureProgressLabel(0, 6))+ assertEquals("Capturing 3/6", nightCaptureProgressLabel(3, 6))+ assertEquals("Capturing 6/6", nightCaptureProgressLabel(6, 6))+ assertEquals("Capturing 6/6", nightCaptureProgressLabel(9, 6))+ assertEquals("Capturing", nightCaptureProgressLabel(0, 0))+ assertEquals(0f, nightCaptureProgressFraction(0, 6))+ assertEquals(0.5f, nightCaptureProgressFraction(3, 6))+ assertEquals(1f, nightCaptureProgressFraction(6, 6))+ assertEquals(1f, nightCaptureProgressFraction(9, 6))+ assertEquals(0f, nightCaptureProgressFraction(3, 0))+ assertEquals("Merging…", NIGHT_MERGING_LABEL)+ }++ @Test fun downscaleDimensionMath() {+ // Within / at the cap: unchanged.+ assertEquals(1920 to 1080, NightCaptureEngine.mergeScaledDimensions(1920, 1080))+ assertEquals(4000 to 2000, NightCaptureEngine.mergeScaledDimensions(4000, 2000))+ // 12 MP (4000x3000) is capped to <=8 MP, aspect preserved.+ val (w, h) = NightCaptureEngine.mergeScaledDimensions(4000, 3000)+ assertEquals(3265 to 2449, w to h)+ assertTrue(w.toLong() * h <= NightCaptureEngine.MAX_MERGE_PIXELS)+ // Large square and degenerate inputs.+ val (sw, sh) = NightCaptureEngine.mergeScaledDimensions(10000, 10000)+ assertEquals(2828 to 2828, sw to sh)+ assertTrue(sw.toLong() * sh <= NightCaptureEngine.MAX_MERGE_PIXELS)+ assertEquals(0 to 100, NightCaptureEngine.mergeScaledDimensions(0, 100))+ assertEquals(100 to -1, NightCaptureEngine.mergeScaledDimensions(100, -1))+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/Restore3AExtraTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/Restore3AExtraTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/Restore3AExtraTest.ktindex c5afc2ebca..c6312c169b 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/Restore3AExtraTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/Restore3AExtraTest.kt@@ -43,9 +43,11 @@ class Restore3AExtraTest { Boolean::class.javaPrimitiveType, NightExposure::class.java, Function1::class.java,+ Function1::class.java, ).apply { isAccessible = true }+ val onFrameCaptured: (Int) -> Unit = { } val onDone: (List<Bitmap>) -> Unit = { frames -> done = frames }- val driver = ctor.newInstance(viewModel, control, false, NightExposure(2_000_000L, 1600), onDone)+ val driver = ctor.newInstance(viewModel, control, false, NightExposure(2_000_000L, 1600), onFrameCaptured, onDone) cls.getDeclaredMethod("start").apply { isAccessible = true }.invoke(driver) // The lock listener is posted to the main executor: idle it loose. org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()