Modern Apps git

← Modern-Apps.git

camera: night extension via Camera2 ExtensionSession (Phase 6)

Commit
43966b0de4192c4d3459331ba2af62e8e555a4c3
Author
Vayun Mathur <[email protected]>
When
2026-11-21 19:41 UTC (14 days ago)
Parents
77d41f7
The vendor NIGHT extension gets a Camera2 path:
Camera2ExtensionProbe mirrors the CameraX availability
contract from extension characteristics (per-lens NIGHT +
preview/JPEG sizes, latency exposed but never gating), the
driver seam configures a real ExtensionSessionConfiguration
and fails rather than substituting a normal session, and
stills save through the Phase-4a glue. The 7-day failure
cache is shared with the CameraX path (not forked) so a bad
device is learned once. Night engagement on this path uses
the existing luma hysteresis - Camera2 has no night-mode
indicator - and the extension-strength indicator hides
instead of faking a value. Policy: Camera2 extension only
with gate + probe + clear cache, else CameraX, else our own
burst.

Verified: 98 camera2 tests, full suite 725 green. The glue
hook isn't composed into the live preview yet - owning the
surface at night-engagement and the GrapheneOS async-failure
shape are device work, stated in the change.

Diff

camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.ktnew file mode 100644index 0000000000..cd7dc0c396--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt@@ -0,0 +1,159 @@+package com.vayunmathur.camera.platform++import android.hardware.camera2.CameraManager+import androidx.lifecycle.viewModelScope+import com.vayunmathur.camera.data.setLastCaptureUri+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.platform.camera2.Camera2ExtensionProbe+import com.vayunmathur.camera.platform.camera2.Camera2ExtensionSession+import com.vayunmathur.camera.platform.camera2.CapturedStill+import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade+import com.vayunmathur.camera.platform.camera2.ExtensionsEngineInput+import com.vayunmathur.camera.platform.camera2.ExtensionsEnginePolicy+import com.vayunmathur.camera.platform.camera2.NightCamera2Gate+import com.vayunmathur.camera.platform.camera2.NightEngine+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Camera2 migration Phase 6: NIGHT-extension glue between the gated+ * [Camera2ExtensionSession] and the existing night routing.+ *+ * Decision order (see [ExtensionsEnginePolicy]): Camera2 extension only+ * when the gate is on, the [Camera2ExtensionProbe] passes for the current+ * lens, and the failure cache is clear; else the CameraX extension; else+ * the own burst — the last two exactly as before this phase.+ *+ * Failure-cache reuse, not a fork: the persisted 7-day cache lives in+ * `CameraNightMode.kt` (`night_ext_failed_at`, [nightExtFailedRecently] /+ * [recordNightExtensionFailure]). This glue reads that store for every+ * decision and records Camera2 bind/capture failures into that same store,+ * so a GrapheneOS-style async extension failure suppresses both engines+ * for the same TTL as a CameraX failure does today.+ *+ * Detection: there is no Camera2 `getNightModeIndicator()` equivalent, so+ * engagement on this path is the existing luma hysteresis (PhotoAnalyzer+ * average-Y → `onLuminance`, which only skips when a CameraX indicator was+ * observed). This glue never observes an indicator; the moon affordance+ * and `nightModeActive` therefore behave identically whichever engine+ * will serve the capture.+ *+ * Strength UI: there is no Camera2 strength flow, so a Camera2 decision+ * clears the strength value and the screen state hides the indicator on+ * this path ([ExtensionsEnginePolicy.showsExtensionStrength]) — it is+ * never synthesised from the probe's latency estimate.+ */++/** Registers the live gated Camera2 extension session (null when it leaves composition). */+internal fun CameraViewModel.registerCamera2ExtensionSession(session: Camera2ExtensionSession?) {+    activeCamera2ExtensionSession = session+    camera2NightSessionActiveMutable.value = session != null+    if (session != null) {+        // No Camera2 strength flow: never carry a CameraX strength value over.+        extensionStrengthMutable.value = null+    }+}++/** The Camera2 night decision for one lens snapshot; pure but for logging. */+internal fun CameraViewModel.camera2NightDecision(+    facade: CharacteristicsFacade,+): NightEngine {+    val probe = Camera2ExtensionProbe.probeNight(facade.snapshot)+    val input = ExtensionsEngineInput(+        camera2GateOn = NightCamera2Gate.ENABLED && camera2NightEnabledMutable.value,+        mode = cameraModeMutable.value,+        camera2ProbeOk = probe.usable,+        failureCacheClear = !nightExtFailedRecently(),+        cameraXExtensionUsable = nightExtensionUsableMutable.value,+    )+    val engine = ExtensionsEnginePolicy.select(input)+    Log.debug(+        "Camera2Night",+        "Camera2 night decision: engine=$engine probe=$probe " ++            "camera2Reason=${ExtensionsEnginePolicy.camera2ExclusionReason(input) ?: "none"}",+    )+    return engine+}++/**+ * Attempts the night shutter on the Camera2 extension session. Returns+ * true when Camera2 took the shot (the caller must not also route it to+ * CameraX/custom); false means the existing routing decides, for a policy+ * reason or because no gated extension session is live. The caller has+ * already claimed the in-flight flag; every outcome here clears it (the+ * fallback paths re-claim it themselves).+ */+internal fun CameraViewModel.tryCaptureCamera2NightExtension(): Boolean {+    val session = activeCamera2ExtensionSession ?: return false+    val probe = session.currentProbe()+    val input = ExtensionsEngineInput(+        camera2GateOn = NightCamera2Gate.ENABLED && camera2NightEnabledMutable.value,+        mode = cameraModeMutable.value,+        camera2ProbeOk = probe?.usable == true && session.hasJpegOutput,+        failureCacheClear = !nightExtFailedRecently(),+        cameraXExtensionUsable = nightExtensionUsableMutable.value,+    )+    if (!ExtensionsEnginePolicy.usesCamera2Extension(input)) return false++    // Hide, never fake, the strength indicator on this path.+    extensionStrengthMutable.value = null+    session.setFlashSetting(+        when (flashModeMutable.value) {+            FlashMode.ON -> com.vayunmathur.camera.domain.FlashSetting.ON+            FlashMode.AUTO -> com.vayunmathur.camera.domain.FlashSetting.AUTO+            FlashMode.OFF -> com.vayunmathur.camera.domain.FlashSetting.OFF+        },+    )+    val mirrored = mirrorCaptures+    emitShutterFeedback()+    session.capture(+        mirrored = mirrored,+        callback = object : Camera2ExtensionSession.StillCallback {+            override fun onStillCaptured(still: CapturedStill) {+                viewModelScope.launch {+                    val uri = withContext(Dispatchers.IO) {+                        runCatching { saveCamera2Still(still) }+                            .onFailure { Log.error("Camera2Night", "save failed", it) }+                            .getOrNull()+                    }+                    isCapturingMutable.value = false+                    if (uri != null) setLastCaptureUri(uri)+                }+            }++            override fun onStillFailed(message: String) {+                // Same failure store as CameraX bind/async failures: one+                // bad extender suppresses both engines for the 7-day TTL.+                Log.status("Camera2Night", "extension capture failed: $message (caching failure)")+                recordNightExtensionFailure()+                isCapturingMutable.value = false+            }+        },+    )+    return true+}++/**+ * Evaluates (and logs) the Camera2 night decision for the current lens+ * when the runtime gate is on; a no-op otherwise. Never routes a capture+ * itself — used by bind-time logging/diagnostics, mirroring+ * `evaluateCamera2SloMoDecision`.+ */+internal fun CameraViewModel.evaluateCamera2NightDecision() {+    if (!camera2NightEnabledMutable.value) return+    try {+        val lensId = selectedLensMutable.value?.logicalCameraId+            ?: availableLensesMutable.value+                .firstOrNull { it.facing == LensFacing.BACK }+                ?.logicalCameraId+            ?: return+        val manager = app.getSystemService(CameraManager::class.java) ?: return+        camera2NightDecision(CharacteristicsFacade.fromCameraManager(manager, lensId))+    } catch (e: IllegalStateException) {+        Log.status("Camera2Night", "Camera2 night decision failed; staying on existing routing", e)+    } catch (e: IllegalArgumentException) {+        Log.status("Camera2Night", "Camera2 night decision failed; staying on existing routing", e)+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.ktindex 8c61dbf299..5446011a2e 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -104,8 +104,12 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean {     return true } -/** Saves one Camera2 still through the shared routing. Blocking: call off main. */-private fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? {+/**+ * Saves one Camera2 still through the shared routing. Blocking: call off+ * main. Shared with the Phase-6 NIGHT extension glue so an extension JPEG+ * lands through exactly this Phase-4a path (stamp/AVIF/MediaStore).+ */+internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? {     val rotation = still.metadata.rotationDegrees     if (photoFormatMutable.value == PhotoFormat.AVIF) {         val bitmap = BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size)
camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.ktindex 9840008e60..ab5a0ada12 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.kt@@ -94,6 +94,9 @@ fun CameraViewModel.onLuminance(avg: Float) {     // getNightModeIndicator() is authoritative when the device supports it — skip the luminance     // heuristic so the two don't fight. This luma path is only the fallback for devices without     // the indicator.+    // Phase 6: the indicator is a CameraX-only signal (there is no Camera2 equivalent), so on+    // the Camera2 path it is never observed (nightIndicatorSupported stays false) and this luma+    // hysteresis is the engagement trigger; see Camera2ExtensionProbe's detection contract.     if (nightIndicatorSupported) return     val beforeLow = lowLightDetectedMutable.value     val beforeOff = nightModeOverriddenOffMutable.value
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 9f39db0548..64faba781a 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -465,6 +465,10 @@ internal fun CameraViewModel.assembleAndSaveMotionPhoto(request: MotionSaveReque  * bind (GrapheneOS/Pixel) goes straight to the working custom path instead of failing.  */ internal fun CameraViewModel.captureNightPhoto() {+    // Phase 6: a gated, probed, cache-clear Camera2 extension session takes+    // the shot first (ExtensionsEnginePolicy). With the gate off (default)+    // this is one null/policy check and routing below is unchanged.+    if (tryCaptureCamera2NightExtension()) return     viewModelScope.launch {         if (nightExtensionUsableMutable.value) {             captureNightPhotoExtension()
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 36964ba011..61feb08424 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -185,6 +185,34 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {         camera2SloMoEnabledMutable.value = enabled     } +    /**+     * Gate for the Camera2 NIGHT-extension path (Phase 6). Default OFF —+     * night stays on CameraX extension / own burst and the Camera2 decision+     * in `Camera2NightGlue` is not evaluated. In-memory only;+     * `ExtensionsEnginePolicy` further requires a passing probe and a clear+     * failure cache.+     */+    internal val camera2NightEnabledMutable = MutableStateFlow(false)+    val camera2NightEnabled = camera2NightEnabledMutable.asStateFlow()++    /** Turns the Camera2 night gate on/off (PHOTO only; see ExtensionsEnginePolicy). */+    fun setCamera2NightEnabled(enabled: Boolean) {+        camera2NightEnabledMutable.value = enabled+    }++    /**+     * The live Camera2 NIGHT extension session while one is bound+     * (Phase 6), registered by its owner; null otherwise. The night glue+     * reads it synchronously — it is only ever set/cleared on the main+     * thread from composition effects, like [activeCamera2Session].+     */+    internal var activeCamera2ExtensionSession:+        com.vayunmathur.camera.platform.camera2.Camera2ExtensionSession? = null++    /** True while a Camera2 extension session is registered (strength UI hides). */+    internal val camera2NightSessionActiveMutable = MutableStateFlow(false)+    val camera2NightSessionActive = camera2NightSessionActiveMutable.asStateFlow()+     /**      * The live Camera2 session while the gated preview is composed      * (Phase 4a stills), registered by `Camera2Preview`; null otherwise.
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.ktindex 711a747fc5..bd94367b01 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt@@ -6,6 +6,8 @@ import android.graphics.Rect import android.hardware.camera2.CameraCaptureSession import android.hardware.camera2.CameraConstrainedHighSpeedCaptureSession import android.hardware.camera2.CameraDevice+import android.hardware.camera2.CameraExtensionSession+import android.hardware.camera2.params.ExtensionSessionConfiguration import android.hardware.camera2.CameraManager import android.hardware.camera2.CaptureRequest import android.hardware.camera2.CaptureResult@@ -67,6 +69,21 @@ interface DeviceHandle {         callback.onConfigureFailed()     } +    /**+     * Creates an extension session (Phase 6) for [extensionMode]+     * (`CameraExtensionCharacteristics.EXTENSION_*`) over [surfaces]+     * (preview first, JPEG still second). The default fails the configure:+     * silently substituting a regular session would take a plain still and+     * call it a vendor night shot.+     */+    fun createExtensionCaptureSession(+        extensionMode: Int,+        surfaces: List<Surface>,+        callback: CaptureSessionCallback,+    ) {+        callback.onConfigureFailed()+    }+     fun close() } @@ -325,9 +342,89 @@ private class AndroidDeviceHandle(         }     } +    override fun createExtensionCaptureSession(+        extensionMode: Int,+        surfaces: List<Surface>,+        callback: CaptureSessionCallback,+    ) {+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {+            callback.onConfigureFailed()+            return+        }+        val stateCallback = object : CameraExtensionSession.StateCallback() {+            override fun onConfigured(session: CameraExtensionSession) =+                callback.onConfigured(AndroidExtensionSessionHandle(device, session, handler))++            override fun onConfigureFailed(session: CameraExtensionSession) =+                callback.onConfigureFailed()++            override fun onClosed(session: CameraExtensionSession) = callback.onClosed()+        }+        val outputs = surfaces.map { OutputConfiguration(it) }+        val config = ExtensionSessionConfiguration(+            extensionMode,+            outputs,+            { command -> handler.post(command) },+            stateCallback,+        )+        runCatching { device.createExtensionSession(config) }+            .onFailure { callback.onConfigureFailed() }+    }+     override fun close() = device.close() } +/** Real extension-session handle over a `CameraExtensionSession` (API 31+). */+private class AndroidExtensionSessionHandle(+    private val device: CameraDevice,+    private val session: CameraExtensionSession,+    private val handler: Handler,+) : CaptureSessionHandle {++    private val executor = java.util.concurrent.Executor { command -> handler.post(command) }++    override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {+        val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)+        builder.applyPreviewParams(params, target)+        session.setRepeatingRequest(builder.build(), executor, NoOpExtensionCallback)+    }++    override fun captureStill(+        params: ResolvedStillParams,+        stillTarget: Surface,+        callback: StillResultCallback,+    ) {+        val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)+        builder.applyStillParams(params, stillTarget)+        session.capture(+            builder.build(),+            executor,+            object : CameraExtensionSession.ExtensionCaptureCallback() {+                override fun onCaptureResultAvailable(+                    session: CameraExtensionSession,+                    request: CaptureRequest,+                    result: TotalCaptureResult,+                ) {+                    callback.onCompleted(result.toRawStillMetadata())+                }++                override fun onCaptureFailed(+                    session: CameraExtensionSession,+                    request: CaptureRequest,+                ) {+                    callback.onFailed("extension capture failed")+                }+            },+        )+    }++    override fun close() {+        runCatching { session.close() }+    }++    private object NoOpExtensionCallback : CameraExtensionSession.ExtensionCaptureCallback()+}+ private class AndroidCaptureSessionHandle(     private val device: CameraDevice,     private val session: CameraCaptureSession,
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionProbe.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionProbe.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionProbe.ktnew file mode 100644index 0000000000..18e5045e49--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionProbe.kt@@ -0,0 +1,126 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraExtensionCharacteristics+import android.util.Range++/**+ * Camera2 migration Phase 6: NIGHT availability probe over the Phase-0+ * facade snapshot, mirroring the CameraX probe's contract in+ * `CameraNightMode.kt` (`isNightExtensionAvailable`):+ *+ * 1. Per-lens availability — CameraX asks+ *    `ExtensionsManager.isExtensionAvailable(selector, NIGHT)` for the+ *    selected lens; here the snapshot's `supportedExtensions` for *this*+ *    lens either contains `EXTENSION_NIGHT` or it does not. No other lens's+ *    support leaks in, and no trial bind is attempted.+ * 2. Session-config support — CameraX asks+ *    `cameraInfo.isSessionConfigSupported(Preview + ImageCapture NIGHT)`;+ *    the Camera2 equivalent of that exact config is an+ *    `ExtensionSessionConfiguration(EXTENSION_NIGHT, preview + still)`+ *    whose output sizes the extension advertises. Support therefore+ *    requires at least one advertised preview (`SurfaceTexture`) size+ *    *and* at least one advertised JPEG still size for NIGHT. A mode that+ *    is listed but advertises no usable pair is *not* supported — the+ *    session would fail configure, which is precisely what the CameraX+ *    query exists to avoid.+ *+ * The estimated capture latency rides along for expectations/logging; it+ * never gates support (the HAL may legitimately report no estimate).+ *+ * Failure-cache contract (unchanged, not forked): this probe does *not*+ * consult the persisted failure cache. Exactly as today, the caller checks+ * `nightExtFailedRecently()` first (7-day TTL, `night_ext_failed_at` in+ * `CameraNightMode.kt`) and only probes when it is clear; a real bind or+ * async failure on either engine records into that same store via+ * `recordNightExtensionFailure()`. See [ExtensionsEnginePolicy].+ *+ * Detection contract: CameraX's `getNightModeIndicator()` has no Camera2+ * equivalent. On the Camera2 path night *engagement* is therefore driven+ * by the existing luma hysteresis (`PhotoAnalyzer` average-Y fed into+ * `CameraViewModel.onLuminance`, engage < 40 / disengage > 55 over 4+ * frames), never by an indicator. The indicator remains observed only on+ * CameraX-bound cameras; a Camera2 session must not observe it (it would+ * report UNKNOWN/NOT_RECOMMENDED and fight the hysteresis — the same+ * reason the CameraX extension camera is not observed today).+ */++/** Outcome of probing one extension mode on one lens snapshot. */+data class ExtensionProbeResult(+    val mode: Int,+    /** The mode appears in this lens's `supportedExtensions`. */+    val available: Boolean,+    /** A preview+still `ExtensionSessionConfiguration` can be built. */+    val sessionConfigSupported: Boolean,+    /** Deterministically selected preview size, or null when unsupported. */+    val previewSize: FrameSize?,+    /** Deterministically selected JPEG still size, or null when unsupported. */+    val stillSize: FrameSize?,+    /** Estimated capture latency (millis) for [stillSize], when reported. */+    val estimatedCaptureLatencyRangeMillis: Range<Long>?,+    /** Why the mode is unusable, or null when it is usable. */+    val rejectionReason: String?,+) {+    /** True only when both contract halves pass. */+    val usable: Boolean get() = rejectionReason == null+}++object Camera2ExtensionProbe {++    /** The only extension mode Phase 6 routes. */+    const val NIGHT_MODE: Int = CameraExtensionCharacteristics.EXTENSION_NIGHT++    /** Probes [mode] on [snapshot]; pure and deterministic. */+    fun probe(snapshot: LensCharacteristicsSnapshot, mode: Int): ExtensionProbeResult {+        if (!snapshot.hasExtension(mode)) {+            return ExtensionProbeResult(+                mode = mode,+                available = false,+                sessionConfigSupported = false,+                previewSize = null,+                stillSize = null,+                estimatedCaptureLatencyRangeMillis = null,+                rejectionReason = "extension $mode not in supportedExtensions for camera ${snapshot.cameraId}",+            )+        }+        val support = snapshot.extensionSupportFor(mode)+        val previewSizes = support?.previewSizes.orEmpty().map { FrameSize.from(it) }.distinct()+        val jpegSizes = support?.jpegSizes.orEmpty().map { FrameSize.from(it) }.distinct()+        if (previewSizes.isEmpty() || jpegSizes.isEmpty()) {+            return ExtensionProbeResult(+                mode = mode,+                available = true,+                sessionConfigSupported = false,+                previewSize = null,+                stillSize = null,+                estimatedCaptureLatencyRangeMillis = null,+                rejectionReason = "extension $mode advertises no preview+JPEG size pair " ++                    "(preview=${previewSizes.size}, jpeg=${jpegSizes.size})",+            )+        }+        // Still: largest advertised JPEG (extension stills are the saved+        // image; CameraX's ImageCapture likewise takes the max still size).+        val still = jpegSizes.maxWithOrNull(+            compareBy({ it.area }, { it.width }, { it.height }),+        )+        // Preview: largest advertised preview size; the session re-selects+        // against the actual surface size at open time.+        val preview = previewSizes.maxWithOrNull(+            compareBy({ it.area }, { it.width }, { it.height }),+        )+        return ExtensionProbeResult(+            mode = mode,+            available = true,+            sessionConfigSupported = true,+            previewSize = preview,+            stillSize = still,+            estimatedCaptureLatencyRangeMillis = still?.let { selected ->+                support?.estimatedLatencyFor(selected.toSize())+            },+            rejectionReason = null,+        )+    }++    /** Probes `EXTENSION_NIGHT` on [snapshot]. */+    fun probeNight(snapshot: LensCharacteristicsSnapshot): ExtensionProbeResult =+        probe(snapshot, NIGHT_MODE)+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.ktnew file mode 100644index 0000000000..ff0047a606--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt@@ -0,0 +1,381 @@+package com.vayunmathur.camera.platform.camera2++import android.view.Surface++/**+ * Camera2 migration Phase 6: NIGHT extension session core.+ *+ * Opens a `CameraDevice` through the Phase-2 driver seam, configures an+ * `ExtensionSessionConfiguration(EXTENSION_NIGHT, preview + still)` session+ * (never a regular session — the seam fails configure instead, see+ * [DeviceHandle.createExtensionCaptureSession]), streams a TEMPLATE_PREVIEW+ * repeating request, and takes stills whose JPEG bytes pair with their+ * `CaptureResult` metadata into a [CapturedStill] — the exact shape the+ * Phase-4a save glue (`Camera2StillCapture`) already consumes.+ *+ * Up-front honesty: [open] probes the snapshot with+ * [Camera2ExtensionProbe] before touching the device; a lens without a+ * usable preview+JPEG pair fails via [Listener.onError] and the device is+ * never opened. A configure failure likewise reports an error and produces+ * no still — callers fall back through [ExtensionsEnginePolicy] rather than+ * receiving a plain capture mislabelled as a night shot.+ *+ * Night engagement on this path is *not* decided here: there is no Camera2+ * `getNightModeIndicator()` equivalent, so the ViewModel's luma hysteresis+ * (PhotoAnalyzer → `onLuminance`) decides when night is active, exactly as+ * documented in [Camera2ExtensionProbe]. This session only serves a night+ * capture once that decision has been made.+ *+ * Threading and teardown mirror [Camera2Session]: every public method+ * posts onto the executor, driver callbacks are generation-checked through+ * [SessionStateMachine], and [close] is idempotent and terminal.+ */+class Camera2ExtensionSession(+    private val driver: Camera2Driver,+    private val executor: Camera2Executor,+    private val snapshot: LensCharacteristicsSnapshot,+    private val stateMachine: SessionStateMachine = SessionStateMachine(),+    private val listener: Listener? = null,+) {++    /** Session lifecycle notifications; all fire on the executor thread. */+    interface Listener {+        fun onStateChanged(state: SessionState) {}+        fun onError(message: String) {}+        fun onStreaming(probe: ExtensionProbeResult) {}+    }++    /** One-shot still outcome; fires on the executor thread. */+    interface StillCallback {+        fun onStillCaptured(still: CapturedStill)+        fun onStillFailed(message: String)+    }++    val state: SessionState get() = stateMachine.state++    private var device: DeviceHandle? = null+    private var captureSession: CaptureSessionHandle? = null+    private var previewSurface: Surface? = null+    private var previewSize: FrameSize? = null+    private var stillOutput: StillOutput? = null+    private var stillSize: FrameSize? = null+    private var probeResult: ExtensionProbeResult? = null+    private var pendingStill: PendingStill? = null+    private var displayRotationDegrees: Int = 0+    private var controls: Camera2ControlState = Camera2ControlState.DEFAULT++    private class PendingStill(+        val params: ResolvedStillParams,+        val callback: StillCallback,+        var rawMetadata: RawStillMetadata? = null,+        var jpegBytes: ByteArray? = null,+        var jpegWidth: Int = 0,+        var jpegHeight: Int = 0,+    )++    /** The probe outcome decided at [open], or null before a successful open. */+    fun currentProbe(): ExtensionProbeResult? = probeResult++    /** The JPEG still size configured at [open], or null when unavailable. */+    fun currentStillSize(): FrameSize? = stillSize++    /** True when a JPEG output exists on the extension session. */+    val hasJpegOutput: Boolean get() = stillOutput != null++    /** Applies the user's still-flash setting, keeping other controls. */+    fun setFlashSetting(setting: com.vayunmathur.camera.domain.FlashSetting) {+        executor.execute {+            controls = controls.copy(flashSetting = setting)+            issueRepeatingRequest()+        }+    }++    /** Records the display rotation still orientations are computed from. */+    fun setDisplayRotationDegrees(degrees: Int) {+        executor.execute { displayRotationDegrees = degrees }+    }++    /**+     * Opens [cameraId] as a NIGHT extension session on [surface]. The probe+     * runs first; an unusable lens reports [Listener.onError] and never+     * opens the device. No-op unless CLOSED.+     */+    fun open(cameraId: String, surface: Surface, requestedSize: FrameSize) {+        executor.execute {+            if (stateMachine.state != SessionState.CLOSED) return@execute+            val probe = Camera2ExtensionProbe.probeNight(snapshot)+            probeResult = probe+            if (!probe.usable) {+                reportError("Camera2 NIGHT extension unusable for camera $cameraId: ${probe.rejectionReason}")+                return@execute+            }+            val previewSizes = snapshot.extensionSupportFor(probe.mode)?.previewSizes+                .orEmpty().map { FrameSize.from(it) }.distinct()+            val selected = StreamSelection.selectPreviewSize(requestedSize, previewSizes)+            if (selected == null) {+                reportError("no extension preview sizes for camera $cameraId")+                return@execute+            }+            previewSurface = surface+            previewSize = selected+            if (transition(SessionEvent.OPEN_REQUESTED) !is TransitionResult.Applied) {+                return@execute+            }+            val gen = stateMachine.generation+            runCatching {+                driver.openCamera(cameraId, DeviceCallbackImpl(gen))+            }.onFailure {+                dispatch(gen, SessionEvent.ERROR_OCCURRED)+                reportError("openCamera failed for $cameraId: ${it.message}")+            }+        }+    }++    /**+     * Takes one extension still: issues `TEMPLATE_STILL_CAPTURE` carrying+     * the session's current control state plus flash resolution, and+     * delivers the JPEG bytes with mapped metadata once both halves+     * arrive. Only one still may be in flight; misuse fails via+     * [StillCallback.onStillFailed] without touching the HAL.+     */+    fun capture(+        callback: StillCallback,+        displayRotationDegrees: Int? = null,+        mirrored: Boolean = false,+    ) {+        executor.execute {+            val session = captureSession+            val output = stillOutput+            when {+                stateMachine.state != SessionState.STREAMING || session == null ->+                    callback.onStillFailed("extension still capture requires a streaming session")+                output == null ->+                    callback.onStillFailed("no JPEG output on this extension session")+                pendingStill != null ->+                    callback.onStillFailed("an extension still capture is already in flight")+                else -> {+                    val params = StillCapturePlanner.resolve(+                        state = controls,+                        snapshot = snapshot,+                        displayRotationDegrees = displayRotationDegrees+                            ?: [email protected],+                        mirrored = mirrored,+                    )+                    val pending = PendingStill(params, callback)+                    pendingStill = pending+                    runCatching {+                        session.captureStill(params, output.surface, object : StillResultCallback {+                            override fun onCompleted(metadata: RawStillMetadata) {+                                onStillResult(pending, metadata)+                            }++                            override fun onFailed(message: String) {+                                failPending(pending, message)+                            }+                        })+                    }.onFailure { failPending(pending, "captureStill failed: ${it.message}") }+                }+            }+        }+    }++    /** Tears the session down; idempotent and terminal. */+    fun close() {+        executor.execute {+            if (stateMachine.state == SessionState.CLOSED) return@execute+            val gen = stateMachine.beginTeardown()+            pendingStill?.let { pending ->+                pendingStill = null+                runCatching { pending.callback.onStillFailed("session closed during capture") }+            }+            runCatching { captureSession?.close() }+            captureSession = null+            runCatching { stillOutput?.close() }+            stillOutput = null+            stillSize = null+            runCatching { device?.close() }+            device = null+            previewSurface = null+            dispatch(gen, SessionEvent.DEVICE_CLOSED)+            if (stateMachine.state == SessionState.CLOSING) {+                stateMachine.completeTeardown()+            }+            notifyState()+        }+    }++    // -- internals (executor thread only) ------------------------------------++    private fun onStillResult(pending: PendingStill, metadata: RawStillMetadata) {+        try {+            executor.execute {+                if (pendingStill !== pending) return@execute+                pending.rawMetadata = metadata+                deliverPendingIfReady(pending)+            }+        } catch (e: java.util.concurrent.RejectedExecutionException) {+        }+    }++    private fun onJpegAvailable(bytes: ByteArray, width: Int, height: Int) {+        try {+            executor.execute {+                val pending = pendingStill ?: return@execute+                pending.jpegBytes = bytes+                pending.jpegWidth = width+                pending.jpegHeight = height+                deliverPendingIfReady(pending)+            }+        } catch (e: java.util.concurrent.RejectedExecutionException) {+        }+    }++    private fun deliverPendingIfReady(pending: PendingStill) {+        val raw = pending.rawMetadata ?: return+        val bytes = pending.jpegBytes ?: return+        pendingStill = null+        pending.callback.onStillCaptured(+            CapturedStill(+                jpegBytes = bytes,+                jpegWidth = pending.jpegWidth,+                jpegHeight = pending.jpegHeight,+                metadata = StillMetadataMapper.map(+                    raw, pending.params.jpegOrientationDegrees, pending.params.mirrored,+                ),+            ),+        )+    }++    private fun failPending(pending: PendingStill, message: String) {+        try {+            executor.execute {+                if (pendingStill !== pending) return@execute+                pendingStill = null+                pending.callback.onStillFailed(message)+            }+        } catch (e: java.util.concurrent.RejectedExecutionException) {+        }+    }++    private fun issueRepeatingRequest() {+        val session = captureSession ?: return+        val surface = previewSurface ?: return+        if (stateMachine.state != SessionState.STREAMING) return+        val params = Camera2Controls.resolve(controls, snapshot)+        runCatching { session.setRepeatingPreview(params, surface) }+            .onFailure { reportError("setRepeatingPreview failed: ${it.message}") }+    }++    private fun configureSession(opened: DeviceHandle, gen: Long) {+        val surface = previewSurface ?: return+        val probe = probeResult ?: return+        if (transition(SessionEvent.CONFIGURE_REQUESTED) !is TransitionResult.Applied) return+        val jpegSize = probe.stillSize+        val output = jpegSize?.let { size ->+            runCatching { driver.createStillOutput(size) }.getOrNull()?.also { created ->+                created.setListener(JpegImageListener { bytes, width, height, _ ->+                    onJpegAvailable(bytes, width, height)+                })+            }+        }+        stillOutput = output+        stillSize = if (output != null) jpegSize else null+        if (output == null) {+            dispatch(gen, SessionEvent.CONFIGURE_FAILED)+            reportError("no JPEG still output for Camera2 NIGHT extension session")+            return+        }+        val surfaces = listOf(surface, output.surface)+        runCatching {+            opened.createExtensionCaptureSession(+                probe.mode,+                surfaces,+                SessionCallbackImpl(gen),+            )+        }.onFailure {+            dispatch(gen, SessionEvent.CONFIGURE_FAILED)+            reportError("createExtensionCaptureSession failed: ${it.message}")+        }+    }++    private fun transition(event: SessionEvent): TransitionResult {+        val result = stateMachine.transition(event)+        if (result is TransitionResult.Applied) notifyState()+        return result+    }++    private fun dispatch(gen: Long, event: SessionEvent): TransitionResult {+        val result = stateMachine.dispatch(gen, event)+        if (result is TransitionResult.Applied) notifyState()+        return result+    }++    private fun notifyState() {+        listener?.onStateChanged(stateMachine.state)+    }++    private fun reportError(message: String) {+        listener?.onError(message)+    }++    private inner class DeviceCallbackImpl(+        private val gen: Long,+    ) : DeviceCallback {+        override fun onOpened(device: DeviceHandle) {+            if (!stateMachine.isCurrent(gen)) {+                runCatching { device.close() }+                return+            }+            if (dispatch(gen, SessionEvent.DEVICE_OPENED) !is TransitionResult.Applied) {+                runCatching { device.close() }+                return+            }+            [email protected] = device+            configureSession(device, gen)+        }++        override fun onClosed() {+            dispatch(gen, SessionEvent.DEVICE_CLOSED)+        }++        override fun onDisconnected() {+            if (!stateMachine.isCurrent(gen)) return+            dispatch(gen, SessionEvent.ERROR_OCCURRED)+            reportError("camera disconnected")+        }++        override fun onError(errorCode: Int) {+            if (!stateMachine.isCurrent(gen)) return+            dispatch(gen, SessionEvent.ERROR_OCCURRED)+            reportError("camera open error $errorCode")+        }+    }++    private inner class SessionCallbackImpl(+        private val gen: Long,+    ) : CaptureSessionCallback {+        override fun onConfigured(session: CaptureSessionHandle) {+            if (!stateMachine.isCurrent(gen)) {+                runCatching { session.close() }+                return+            }+            if (dispatch(gen, SessionEvent.SESSION_CONFIGURED) !is TransitionResult.Applied) {+                runCatching { session.close() }+                return+            }+            captureSession = session+            issueRepeatingRequest()+            probeResult?.let { listener?.onStreaming(it) }+        }++        override fun onConfigureFailed() {+            if (!stateMachine.isCurrent(gen)) return+            dispatch(gen, SessionEvent.CONFIGURE_FAILED)+            reportError("extension capture session configure failed")+        }++        override fun onClosed() {+            // Session close follows device teardown; device callback drives CLOSED.+        }+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.ktindex 676b95a4e0..461e10fd5a 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt@@ -71,6 +71,25 @@ data class StreamConfigSummary(     } } +/**+ * Pure-data summary of one extension mode's advertised support, read once+ * from `CameraExtensionCharacteristics` (API 31+). [jpegSizes] /+ * [previewSizes] are the `getExtensionSupportedSizes` lists for the JPEG+ * still output and the `SurfaceTexture` preview output — the two outputs an+ * `ExtensionSessionConfiguration` for this mode would carry. Latency is the+ * `getEstimatedCaptureLatencyRangeMillis` range per JPEG size (millis, null+ * entries omitted): an estimate for UI expectations, never a support gate.+ */+data class ExtensionModeSupport(+    val mode: Int,+    val jpegSizes: List<Size> = emptyList(),+    val previewSizes: List<Size> = emptyList(),+    val estimatedCaptureLatencyRangeMillisByJpegSize: Map<Size, Range<Long>> = emptyMap(),+) {+    fun estimatedLatencyFor(jpegSize: Size): Range<Long>? =+        estimatedCaptureLatencyRangeMillisByJpegSize[jpegSize]+}+ /** Immutable per-lens capability snapshot. Pure data; safe to pass across threads. */ data class LensCharacteristicsSnapshot(     val cameraId: String,@@ -92,6 +111,14 @@ data class LensCharacteristicsSnapshot(     val availableCapabilities: Set<Int>,     /** Extension modes (`CameraExtensionCharacteristics.EXTENSION_*`), empty pre-API 31. */     val availableExtensionModes: List<Int>,+    /**+     * Per-extension advertised sizes + estimated capture latency, keyed by+     * extension mode. An entry exists for every mode in+     * [availableExtensionModes] when built from the real characteristics;+     * fake-built snapshots may carry modes without an entry (probe then+     * reports no session-config support, never a guessed yes).+     */+    val extensionSupport: Map<Int, ExtensionModeSupport> = emptyMap(),     val focalLengthsMm: List<Float>,     val colorFilterArrangement: Int?,     /** `SENSOR_INFO_ACTIVE_ARRAY_SIZE` width in pixels; 0 when unreadable. */@@ -152,6 +179,9 @@ data class LensCharacteristicsSnapshot(         get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO in             availableCapabilities     fun hasExtension(mode: Int): Boolean = mode in availableExtensionModes++    /** Advertised support for [mode], or null when never probed for it. */+    fun extensionSupportFor(mode: Int): ExtensionModeSupport? = extensionSupport[mode] }  /**@@ -200,6 +230,7 @@ class CharacteristicsFacade private constructor(             surfaceTextureSizes: List<Size> = emptyList(),             highSpeedVideoSizes: List<Size> = emptyList(),             highSpeedFpsRangesBySize: Map<Size, List<Range<Int>>> = emptyMap(),+            extensionSupport: Map<Int, ExtensionModeSupport> = emptyMap(),         ): CharacteristicsFacade = fromSnapshot(             LensCharacteristicsSnapshot(                 cameraId = cameraId,@@ -230,6 +261,7 @@ class CharacteristicsFacade private constructor(                 supportsZoomRatioKey = supportsZoomRatioKey,                 highSpeedVideoSizes = highSpeedVideoSizes,                 highSpeedFpsRangesBySize = highSpeedFpsRangesBySize,+                extensionSupport = extensionSupport,             ),         ) @@ -238,6 +270,7 @@ class CharacteristicsFacade private constructor(             cameraId: String,             chars: CameraCharacteristics,             availableExtensionModes: List<Int> = emptyList(),+            extensionSupport: Map<Int, ExtensionModeSupport> = emptyMap(),         ): CharacteristicsFacade {             fun <T> get(key: CameraCharacteristics.Key<T>): T? =                 runCatching { chars.get(key) }.getOrNull()@@ -314,6 +347,7 @@ class CharacteristicsFacade private constructor(                     supportsZoomRatioKey = zoomRatioRange != null,                     highSpeedVideoSizes = highSpeedSizes,                     highSpeedFpsRangesBySize = highSpeedRanges,+                    extensionSupport = extensionSupport,                 ),             )         }@@ -325,14 +359,36 @@ class CharacteristicsFacade private constructor(          */         fun fromCameraManager(manager: CameraManager, cameraId: String): CharacteristicsFacade {             val chars = manager.getCameraCharacteristics(cameraId)-            val extensions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+            var extensions: List<Int> = emptyList()+            var support: Map<Int, ExtensionModeSupport> = emptyMap()+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {                 runCatching {-                    manager.getCameraExtensionCharacteristics(cameraId).supportedExtensions-                }.getOrDefault(emptyList())-            } else {-                emptyList()+                    val extChars = manager.getCameraExtensionCharacteristics(cameraId)+                    extensions = extChars.supportedExtensions+                    support = extensions.associateWith { mode ->+                        val jpegSizes = runCatching {+                            extChars.getExtensionSupportedSizes(mode, ImageFormat.JPEG)+                        }.getOrDefault(emptyList())+                        val previewSizes = runCatching {+                            extChars.getExtensionSupportedSizes(+                                mode, android.graphics.SurfaceTexture::class.java,+                            )+                        }.getOrDefault(emptyList())+                        val latency = jpegSizes.mapNotNull { size ->+                            runCatching {+                                extChars.getEstimatedCaptureLatencyRangeMillis(+                                    mode, size, ImageFormat.JPEG,+                                )+                            }.getOrNull()?.let { size to it }+                        }.toMap()+                        ExtensionModeSupport(mode, jpegSizes, previewSizes, latency)+                    }+                }.onFailure {+                    extensions = emptyList()+                    support = emptyMap()+                }             }-            return fromCharacteristics(cameraId, chars, extensions)+            return fromCharacteristics(cameraId, chars, extensions, support)         }     } }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/ExtensionsEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/ExtensionsEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/ExtensionsEnginePolicy.ktnew file mode 100644index 0000000000..76186b2a72--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/ExtensionsEnginePolicy.kt@@ -0,0 +1,92 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.platform.CameraMode++/** Which engine produces a night still. */+enum class NightEngine {+    /** Camera2 `CameraExtensionSession` with `EXTENSION_NIGHT` (Phase 6). */+    CAMERA2_EXTENSION,++    /** CameraX Extensions NIGHT (the long-standing live path). */+    CAMERAX_EXTENSION,++    /** Our own burst + Rust merge (`captureNightPhotoCustom`, unchanged). */+    OWN_BURST,+}++/**+ * Gate for the Camera2 NIGHT-extension path. Default OFF in two independent+ * places, mirroring [SloMoCamera2Gate]: this compile-time master switch and+ * the ViewModel's runtime flow. Either being off keeps every night capture+ * on today's routing (CameraX extension, else own burst).+ */+object NightCamera2Gate {+    const val ENABLED: Boolean = false+}++/** Inputs to the night-engine selection rule. */+data class ExtensionsEngineInput(+    /** The Phase-6 gate (master switch AND runtime flow). Default OFF. */+    val camera2GateOn: Boolean,+    val mode: CameraMode,+    /** [Camera2ExtensionProbe] result for this lens (probe ok = usable). */+    val camera2ProbeOk: Boolean = false,+    /**+     * The persisted failure cache is clear (`!nightExtFailedRecently()` —+     * the same 7-day `night_ext_failed_at` store both engines record into;+     * see `CameraNightMode.kt`). A recent bind/async failure on *either*+     * engine suppresses *both* extensions, exactly as today.+     */+    val failureCacheClear: Boolean = true,+    /** CameraX NIGHT probe result (`nightExtensionUsable`, cache-gated). */+    val cameraXExtensionUsable: Boolean = false,+)++/**+ * Explicit selection rule for night captures, mirroring+ * [StillEnginePolicy]/[SloMoEnginePolicy]:+ *+ * 1. Camera2 extension only when the gate is on, the mode is PHOTO, the+ *    Camera2 probe passes, and the failure cache is clear.+ * 2. Else the CameraX extension when it is usable (its usable flag is+ *    already failure-cache gated by `refreshNightExtensionUsable`, and the+ *    explicit cache check here keeps a Camera2-recorded failure from+ *    immediately retrying through CameraX within the same decision).+ * 3. Else our own burst, unchanged.+ *+ * Extension strength UI: CameraX surfaces a live processing strength+ * (`CameraExtensionsInfo.getExtensionStrength()`); there is no Camera2+ * equivalent and no strength flow on the extension session, so the+ * indicator is shown only on the CameraX-extension path — never faked+ * from latency or frame counts on Camera2 (see [showsExtensionStrength]).+ */+object ExtensionsEnginePolicy {++    fun select(input: ExtensionsEngineInput): NightEngine = when {+        !input.failureCacheClear -> NightEngine.OWN_BURST+        input.camera2GateOn && input.mode == CameraMode.PHOTO && input.camera2ProbeOk ->+            NightEngine.CAMERA2_EXTENSION+        input.cameraXExtensionUsable -> NightEngine.CAMERAX_EXTENSION+        else -> NightEngine.OWN_BURST+    }++    fun usesCamera2Extension(input: ExtensionsEngineInput): Boolean =+        select(input) == NightEngine.CAMERA2_EXTENSION++    /** Why Camera2 did not take this capture, or null when it did. */+    fun camera2ExclusionReason(input: ExtensionsEngineInput): String? = when {+        !input.failureCacheClear -> "night extension failure cache still warm (7-day TTL)"+        !input.camera2GateOn -> "camera2 night gate off"+        input.mode != CameraMode.PHOTO -> "mode ${input.mode} is not PHOTO"+        !input.camera2ProbeOk -> "Camera2 NIGHT extension probe failed for this lens"+        else -> null+    }++    /**+     * True only when the live strength indicator may be shown: a strength+     * value exists *and* the serving engine is the CameraX extension. On+     * the Camera2 path the indicator is hidden (no equivalent flow).+     */+    fun showsExtensionStrength(engine: NightEngine, strength: Int?): Boolean =+        engine == NightEngine.CAMERAX_EXTENSION && strength != null+}
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex dec5bcf253..283758978f 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -311,7 +311,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(         nightModeActive = state.nightModeActive,         onToggleNightOverride = { viewModel.toggleNightModeOverride() },         iconRotation = animatedRotation,-        extensionStrength = state.extensionStrength,+        extensionStrength = state.visibleExtensionStrength,         photoSessionActive = state.photoSessionActive,         analysisStreamActive = state.analysisStreamActive,     )
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex ff4bd3b49b..11e6f3d856 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -98,6 +98,8 @@ import com.vayunmathur.camera.platform.BokehAnalyzer     val sessionBindRetry: Int = 0,     /** Camera2 preview gate (default OFF); policy-gated to PHOTO in the getter below. */     val camera2PreviewEnabled: Boolean = false,+    /** Phase 6: a Camera2 NIGHT extension session is live (strength hides). */+    val camera2NightSessionActive: Boolean = false, ) {     var activeSetting by activeSettingState     var maskBitmap by maskBitmapState@@ -131,6 +133,30 @@ import com.vayunmathur.camera.platform.BokehAnalyzer             camera2PreviewEnabled, cameraMode,         ) +    /**+     * Strength indicator value to show, or null to hide it. There is no+     * Camera2 strength flow, so on the Camera2 night path the indicator is+     * hidden rather than faked; only the CameraX extension shows it.+     */+    val visibleExtensionStrength: Int?+        get() {+            // A strength value only ever exists on a CameraX extension bind;+            // the policy hides it whenever the serving engine is Camera2.+            val engine = if (camera2NightSessionActive) {+                com.vayunmathur.camera.platform.camera2.NightEngine.CAMERA2_EXTENSION+            } else {+                com.vayunmathur.camera.platform.camera2.NightEngine.CAMERAX_EXTENSION+            }+            return if (+                com.vayunmathur.camera.platform.camera2.ExtensionsEnginePolicy+                    .showsExtensionStrength(engine, extensionStrength)+            ) {+                extensionStrength+            } else {+                null+            }+        }+     val previewAspectRatio get() = when {         // The still crop only exists on the photo sessions (PHOTO/PORTRAIT ImageCapture).         // Video/HFR/pano never crop to it, so letterboxing their preview to it lies about@@ -207,6 +233,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen     val nightExtAvailable by viewModel.nightExtensionUsable.collectAsState()     val surfaceRequest by viewModel.surfaceRequest.collectAsState()     val camera2PreviewEnabled by viewModel.camera2PreviewEnabled.collectAsState()+    val camera2NightSessionActive by viewModel.camera2NightSessionActive.collectAsState()     val sessionBindFailed by viewModel.sessionBindFailed.collectAsState()     val sessionBindRetry by viewModel.sessionBindRetry.collectAsState()     val availableZoomLevels by viewModel.availableZoomLevels.collectAsState()@@ -235,7 +262,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen         isoStops, longExposureProgress, longExposureRemaining, lowLightDetected,         nightModeActive, extensionStrength, sloMoSupported, highSpeedActive,         photoSessionActive, analysisStreamActive, nightExtAvailable, surfaceRequest,-        camera2PreviewEnabled,+        camera2PreviewEnabled, camera2NightSessionActive,         sessionBindFailed, sessionBindRetry,         availableZoomLevels, galleryBitmap, panoSweeping, panoStitching, panoDots,         panoCurrentAngle, panoDirection, panoPitch,@@ -302,6 +329,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen             sessionBindFailed = sessionBindFailed,             sessionBindRetry = sessionBindRetry,             camera2PreviewEnabled = camera2PreviewEnabled,+            camera2NightSessionActive = camera2NightSessionActive,         )     } }
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionProbeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionProbeTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionProbeTest.ktnew file mode 100644index 0000000000..af7692d92f--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionProbeTest.kt@@ -0,0 +1,153 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.hardware.camera2.CameraExtensionCharacteristics+import android.hardware.camera2.CameraMetadata+import android.util.Range+import android.util.Size+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Phase-6 probe tests: mapping from fake extension characteristics into the+ * per-lens availability + session-config contract that mirrors the CameraX+ * probe (`isExtensionAvailable` + `isSessionConfigSupported(Preview ++ * ImageCapture)`).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Camera2ExtensionProbeTest {++    private val night = CameraExtensionCharacteristics.EXTENSION_NIGHT+    private val hdr = CameraExtensionCharacteristics.EXTENSION_HDR++    private fun snapshot(+        modes: List<Int> = listOf(night),+        support: Map<Int, ExtensionModeSupport> = mapOf(+            night to ExtensionModeSupport(+                mode = night,+                jpegSizes = listOf(Size(1920, 1080), Size(4032, 3024)),+                previewSizes = listOf(Size(1280, 720), Size(1920, 1080)),+                estimatedCaptureLatencyRangeMillisByJpegSize = mapOf(+                    Size(4032, 3024) to Range(800L, 1500L),+                    Size(1920, 1080) to Range(300L, 700L),+                ),+            ),+        ),+    ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+        cameraId = "0",+        lensFacingRaw = CameraMetadata.LENS_FACING_BACK,+        sizesByFormat = mapOf(ImageFormat.JPEG to listOf(Size(4032, 3024))),+        availableExtensionModes = modes,+        extensionSupport = support,+    ).snapshot++    @Test fun nightUsableWhenModeAndSizePairAdvertised() {+        val result = Camera2ExtensionProbe.probeNight(snapshot())+        assertTrue(result.available)+        assertTrue(result.sessionConfigSupported)+        assertTrue(result.usable)+        assertNull(result.rejectionReason)+        // Largest JPEG is the still; largest preview is the preview selection.+        assertEquals(FrameSize(4032, 3024), result.stillSize)+        assertEquals(FrameSize(1920, 1080), result.previewSize)+        // Latency follows the selected still size, never gates support.+        assertEquals(Range(800L, 1500L), result.estimatedCaptureLatencyRangeMillis)+    }++    @Test fun modeAbsentFromSupportedExtensionsIsUnavailable() {+        val result = Camera2ExtensionProbe.probeNight(snapshot(modes = listOf(hdr)))+        assertFalse(result.available)+        assertFalse(result.sessionConfigSupported)+        assertFalse(result.usable)+        assertTrue(result.rejectionReason!!.contains("not in supportedExtensions"))+    }++    @Test fun listedModeWithoutProbedSupportIsNotSessionSupported() {+        // Mode listed, but no sizes were ever read for it: probe must not guess.+        val result = Camera2ExtensionProbe.probeNight(snapshot(support = emptyMap()))+        assertTrue(result.available)+        assertFalse(result.sessionConfigSupported)+        assertFalse(result.usable)+    }++    @Test fun missingPreviewOrJpegPairIsNotSessionSupported() {+        val noJpeg = Camera2ExtensionProbe.probeNight(+            snapshot(+                support = mapOf(+                    night to ExtensionModeSupport(+                        mode = night,+                        jpegSizes = emptyList(),+                        previewSizes = listOf(Size(1280, 720)),+                    ),+                ),+            ),+        )+        assertFalse(noJpeg.sessionConfigSupported)+        val noPreview = Camera2ExtensionProbe.probeNight(+            snapshot(+                support = mapOf(+                    night to ExtensionModeSupport(+                        mode = night,+                        jpegSizes = listOf(Size(4032, 3024)),+                        previewSizes = emptyList(),+                    ),+                ),+            ),+        )+        assertFalse(noPreview.sessionConfigSupported)+    }++    @Test fun probeIsPerModeAndPerLensSnapshot() {+        // HDR support must not make NIGHT usable, and vice versa.+        val snap = snapshot(+            modes = listOf(night, hdr),+            support = mapOf(+                hdr to ExtensionModeSupport(+                    mode = hdr,+                    jpegSizes = listOf(Size(4032, 3024)),+                    previewSizes = listOf(Size(1920, 1080)),+                ),+            ),+        )+        assertFalse(Camera2ExtensionProbe.probeNight(snap).usable)+        assertTrue(Camera2ExtensionProbe.probe(snap, hdr).usable)+        assertEquals(night, Camera2ExtensionProbe.NIGHT_MODE)+    }++    @Test fun missingLatencyEstimateDoesNotGateSupport() {+        val result = Camera2ExtensionProbe.probeNight(+            snapshot(+                support = mapOf(+                    night to ExtensionModeSupport(+                        mode = night,+                        jpegSizes = listOf(Size(4032, 3024)),+                        previewSizes = listOf(Size(1920, 1080)),+                    ),+                ),+            ),+        )+        assertTrue(result.usable)+        assertNull(result.estimatedCaptureLatencyRangeMillis)+    }++    @Test fun facadeSnapshotCarriesExtensionSupportEntry() {+        val snap = snapshot()+        assertTrue(snap.hasExtension(night))+        assertEquals(+            listOf(Size(1920, 1080), Size(4032, 3024)),+            snap.extensionSupportFor(night)?.jpegSizes,+        )+        assertEquals(+            Range(300L, 700L),+            snap.extensionSupportFor(night)?.estimatedLatencyFor(Size(1920, 1080)),+        )+        assertNull(snap.extensionSupportFor(hdr))+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.ktnew file mode 100644index 0000000000..2b3d04f7e4--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExtensionSessionTest.kt@@ -0,0 +1,289 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraExtensionCharacteristics+import android.hardware.camera2.CameraMetadata+import android.util.Range+import android.util.Size+import android.view.Surface+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.mockito.Mockito.mock+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Phase-6 extension-session tests over driver fakes: the extension-session+ * request construction (EXTENSION_NIGHT, preview+still surfaces, never a+ * regular session), JPEG delivery into the Phase-4a [CapturedStill] shape,+ * up-front probe rejection, configure failure, the seam's fail-don't-+ * substitute default, and stale-generation drops.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Camera2ExtensionSessionTest {++    private val night = CameraExtensionCharacteristics.EXTENSION_NIGHT++    private class FakeExtensionHandle : CaptureSessionHandle {+        val repeating = mutableListOf<ResolvedRequestParams>()+        val stills = mutableListOf<Pair<ResolvedStillParams, Surface>>()+        var closed = false+        override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {+            repeating += params+        }+        override fun captureStill(+            params: ResolvedStillParams,+            stillTarget: Surface,+            callback: StillResultCallback,+        ) {+            stills += params to stillTarget+            callback.onCompleted(+                RawStillMetadata(sensorTimestampNs = 99L, iso = 3200, exposureTimeNs = 33_000_000L),+            )+        }+        override fun close() { closed = true }+    }++    private class FakeStillOutput(+        override val surface: Surface = mock(Surface::class.java),+    ) : StillOutput {+        private var listener: JpegImageListener? = null+        var closed = false+        override fun setListener(listener: JpegImageListener?) { this.listener = listener }+        fun emitJpeg(bytes: ByteArray, width: Int, height: Int) =+            listener?.onJpeg(bytes, width, height, 123L)+        override fun close() { closed = true }+    }++    private open class FakeDeviceHandle(+        override val cameraId: String = "0",+        val sessionHandle: FakeExtensionHandle = FakeExtensionHandle(),+        private val failConfigure: Boolean = false,+    ) : DeviceHandle {+        var regularSessionRequested = false+        var extensionMode: Int? = null+        var extensionSurfaces: List<Surface>? = null+        var closed = false+        override fun createCaptureSession(+            surfaces: List<Surface>,+            callback: CaptureSessionCallback,+        ) {+            regularSessionRequested = true+            callback.onConfigured(sessionHandle)+        }+        override fun createExtensionCaptureSession(+            extensionMode: Int,+            surfaces: List<Surface>,+            callback: CaptureSessionCallback,+        ) {+            this.extensionMode = extensionMode+            extensionSurfaces = surfaces+            if (failConfigure) callback.onConfigureFailed() else callback.onConfigured(sessionHandle)+        }+        override fun close() { closed = true }+    }++    /** Device that does not override the extension seam: must fail, not substitute. */+    private class RegularOnlyDevice(override val cameraId: String = "0") : DeviceHandle {+        var regularSessionRequested = false+        override fun createCaptureSession(+            surfaces: List<Surface>,+            callback: CaptureSessionCallback,+        ) {+            regularSessionRequested = true+            callback.onConfigured(FakeExtensionHandle())+        }+        override fun close() {}+    }++    private class FakeDriver(+        val device: DeviceHandle = FakeDeviceHandle(),+        val stillOutput: FakeStillOutput = FakeStillOutput(),+    ) : Camera2Driver {+        var openedCameraId: String? = null+        var stillSizeRequested: FrameSize? = null+        override fun openCamera(cameraId: String, callback: DeviceCallback) {+            openedCameraId = cameraId+            callback.onOpened(device)+        }+        override fun createStillOutput(size: FrameSize): StillOutput? {+            stillSizeRequested = size+            return stillOutput+        }+    }++    private class RecordingListener : Camera2ExtensionSession.Listener {+        val errors = mutableListOf<String>()+        val streaming = mutableListOf<ExtensionProbeResult>()+        override fun onError(message: String) { errors += message }+        override fun onStreaming(probe: ExtensionProbeResult) { streaming += probe }+    }++    private fun snapshot(+        modes: List<Int> = listOf(night),+        support: Map<Int, ExtensionModeSupport> = mapOf(+            night to ExtensionModeSupport(+                mode = night,+                jpegSizes = listOf(Size(4032, 3024), Size(1920, 1080)),+                previewSizes = listOf(Size(1920, 1080), Size(1280, 720)),+                estimatedCaptureLatencyRangeMillisByJpegSize = mapOf(+                    Size(4032, 3024) to Range(800L, 1500L),+                ),+            ),+        ),+    ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+        cameraId = "0",+        lensFacingRaw = CameraMetadata.LENS_FACING_BACK,+        hasFlashUnit = true,+        availableExtensionModes = modes,+        extensionSupport = support,+        activeArrayWidth = 4032,+        activeArrayHeight = 3024,+        sensorOrientationDegrees = 90,+    ).snapshot++    private fun Camera2Executor.drain() {+        val latch = CountDownLatch(1)+        execute { latch.countDown() }+        assertTrue(latch.await(5, TimeUnit.SECONDS), "executor did not drain")+    }++    @Test fun openConfiguresExtensionSessionAndCaptureDeliversJpegStill() {+        val executor = Camera2Executor("ExtensionSessionTest-seq")+        try {+            val device = FakeDeviceHandle()+            val driver = FakeDriver(device)+            val listener = RecordingListener()+            val session = Camera2ExtensionSession(driver, executor, snapshot(), listener = listener)+            val preview = mock(Surface::class.java)++            session.open("0", preview, FrameSize(1280, 720))+            executor.drain()++            assertEquals("0", driver.openedCameraId)+            assertEquals(SessionState.STREAMING, session.state)+            // Extension seam with NIGHT + [preview, still]; regular never used.+            assertTrue(!device.regularSessionRequested)+            assertEquals(night, device.extensionMode)+            assertEquals(listOf(preview, driver.stillOutput.surface), device.extensionSurfaces)+            assertEquals(FrameSize(4032, 3024), driver.stillSizeRequested)+            assertEquals(FrameSize(4032, 3024), session.currentStillSize())+            assertTrue(session.hasJpegOutput)+            assertEquals(Range(800L, 1500L), listener.streaming.single().estimatedCaptureLatencyRangeMillis)+            assertEquals(1, device.sessionHandle.repeating.size)++            // Capture: request construction carries still fields; JPEG + metadata pair up.+            val captured = mutableListOf<CapturedStill>()+            val failed = mutableListOf<String>()+            session.capture(object : Camera2ExtensionSession.StillCallback {+                override fun onStillCaptured(still: CapturedStill) { captured += still }+                override fun onStillFailed(message: String) { failed += message }+            })+            executor.drain()+            assertEquals(1, device.sessionHandle.stills.size)+            assertEquals(driver.stillOutput.surface, device.sessionHandle.stills.single().second)+            // JPEG arrives after the result metadata (either order must pair).+            driver.stillOutput.emitJpeg(byteArrayOf(1, 2, 3), 4032, 3024)+            executor.drain()+            assertTrue(failed.isEmpty())+            val still = captured.single()+            assertTrue(still.jpegBytes.contentEquals(byteArrayOf(1, 2, 3)))+            assertEquals(4032, still.jpegWidth)+            assertEquals(3200, still.metadata.iso)+            assertEquals(90, still.metadata.rotationDegrees)++            session.close()+            executor.drain()+            assertEquals(SessionState.CLOSED, session.state)+            assertTrue(device.sessionHandle.closed)+            assertTrue(device.closed)+        } finally {+            executor.shutdown()+        }+    }++    @Test fun unusableProbeFailsBeforeOpeningDevice() {+        val executor = Camera2Executor("ExtensionSessionTest-noprobe")+        try {+            val driver = FakeDriver()+            val listener = RecordingListener()+            val session = Camera2ExtensionSession(+                driver, executor, snapshot(modes = emptyList(), support = emptyMap()),+                listener = listener,+            )+            session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+            executor.drain()+            assertEquals(null, driver.openedCameraId)+            assertEquals(SessionState.CLOSED, session.state)+            assertTrue(listener.errors.single().contains("unusable"))+        } finally {+            executor.shutdown()+        }+    }++    @Test fun configureFailureReportsErrorAndNeverStreams() {+        val executor = Camera2Executor("ExtensionSessionTest-cfgfail")+        try {+            val driver = FakeDriver(FakeDeviceHandle(failConfigure = true))+            val listener = RecordingListener()+            val session = Camera2ExtensionSession(driver, executor, snapshot(), listener = listener)+            session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+            executor.drain()+            assertEquals(SessionState.OPEN, session.state)+            assertTrue(listener.errors.any { it.contains("configure failed") })+            assertTrue(listener.streaming.isEmpty())+        } finally {+            executor.shutdown()+        }+    }++    @Test fun defaultExtensionSeamFailsRatherThanSubstitutingRegularSession() {+        val executor = Camera2Executor("ExtensionSessionTest-defaultfail")+        try {+            val device = RegularOnlyDevice()+            val driver = FakeDriver(device)+            val listener = RecordingListener()+            val session = Camera2ExtensionSession(driver, executor, snapshot(), listener = listener)+            session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+            executor.drain()+            assertTrue(!device.regularSessionRequested)+            assertEquals(SessionState.OPEN, session.state)+            assertTrue(listener.errors.any { it.contains("configure failed") })+        } finally {+            executor.shutdown()+        }+    }++    @Test fun staleOpenCompletionIsDroppedAndDeviceClosed() {+        val executor = Camera2Executor("ExtensionSessionTest-stale")+        try {+            var pending: DeviceCallback? = null+            val driver = object : Camera2Driver {+                override fun openCamera(cameraId: String, callback: DeviceCallback) {+                    pending = callback+                }+                override fun createStillOutput(size: FrameSize): StillOutput? = FakeStillOutput()+            }+            val session = Camera2ExtensionSession(driver, executor, snapshot())+            session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+            executor.drain()+            assertEquals(SessionState.OPENING, session.state)+            session.close()+            executor.drain()+            assertEquals(SessionState.CLOSED, session.state)++            val late = FakeDeviceHandle()+            pending!!.onOpened(late)+            executor.drain()+            assertEquals(SessionState.CLOSED, session.state)+            assertTrue(late.closed, "stale device must be closed")+            assertEquals(null, late.extensionSurfaces)+        } finally {+            executor.shutdown()+        }+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/ExtensionsEnginePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ExtensionsEnginePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ExtensionsEnginePolicyTest.ktnew file mode 100644index 0000000000..14015f3eb7--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ExtensionsEnginePolicyTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.platform.CameraMode+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Test++/**+ * Phase-6 policy matrix: Camera2 extension only when gate on + probe ok ++ * failure-cache clear; else CameraX extension; else own burst. Pure JVM —+ * the policy carries no Android types beyond CameraMode.+ */+class ExtensionsEnginePolicyTest {++    private fun input(+        gate: Boolean = true,+        mode: CameraMode = CameraMode.PHOTO,+        probeOk: Boolean = true,+        cacheClear: Boolean = true,+        cameraXUsable: Boolean = true,+    ) = ExtensionsEngineInput(+        camera2GateOn = gate,+        mode = mode,+        camera2ProbeOk = probeOk,+        failureCacheClear = cacheClear,+        cameraXExtensionUsable = cameraXUsable,+    )++    @Test fun gateOffByDefaultConstant() {+        assertFalse(NightCamera2Gate.ENABLED)+    }++    @Test fun camera2WinsWhenGateProbeAndCacheAllPass() {+        val chosen = input()+        assertEquals(NightEngine.CAMERA2_EXTENSION, ExtensionsEnginePolicy.select(chosen))+        assertTrue(ExtensionsEnginePolicy.usesCamera2Extension(chosen))+        assertNull(ExtensionsEnginePolicy.camera2ExclusionReason(chosen))+    }++    @Test fun gateOffFallsToCameraXExtension() {+        assertEquals(+            NightEngine.CAMERAX_EXTENSION,+            ExtensionsEnginePolicy.select(input(gate = false)),+        )+        assertTrue(+            ExtensionsEnginePolicy.camera2ExclusionReason(input(gate = false))!!+                .contains("gate off"),+        )+    }++    @Test fun probeFailureFallsToCameraXExtension() {+        assertEquals(+            NightEngine.CAMERAX_EXTENSION,+            ExtensionsEnginePolicy.select(input(probeOk = false)),+        )+    }++    @Test fun nonPhotoModeFallsToCameraXExtension() {+        assertEquals(+            NightEngine.CAMERAX_EXTENSION,+            ExtensionsEnginePolicy.select(input(mode = CameraMode.VIDEO)),+        )+    }++    @Test fun noExtensionAnywhereFallsToOwnBurst() {+        assertEquals(+            NightEngine.OWN_BURST,+            ExtensionsEnginePolicy.select(+                input(gate = false, probeOk = false, cameraXUsable = false),+            ),+        )+        assertEquals(+            NightEngine.OWN_BURST,+            ExtensionsEnginePolicy.select(input(cameraXUsable = false, probeOk = false)),+        )+    }++    @Test fun warmFailureCacheSuppressesBothExtensions() {+        // A recorded failure (either engine, same store) makes at most one+        // attempt per TTL: even with gate+probe green and CameraX reporting+        // usable in isolation, the decision is the own burst.+        val warm = input(cacheClear = false)+        assertEquals(NightEngine.OWN_BURST, ExtensionsEnginePolicy.select(warm))+        assertFalse(ExtensionsEnginePolicy.usesCamera2Extension(warm))+        assertTrue(+            ExtensionsEnginePolicy.camera2ExclusionReason(warm)!!.contains("failure cache"),+        )+        // Cache check precedes the gate check: reason stays the cache.+        assertTrue(+            ExtensionsEnginePolicy.camera2ExclusionReason(input(gate = false, cacheClear = false))!!+                .contains("failure cache"),+        )+    }++    @Test fun strengthShownOnlyOnCameraXExtension() {+        assertTrue(ExtensionsEnginePolicy.showsExtensionStrength(NightEngine.CAMERAX_EXTENSION, 42))+        assertFalse(ExtensionsEnginePolicy.showsExtensionStrength(NightEngine.CAMERA2_EXTENSION, 42))+        assertFalse(ExtensionsEnginePolicy.showsExtensionStrength(NightEngine.OWN_BURST, 42))+        assertFalse(ExtensionsEnginePolicy.showsExtensionStrength(NightEngine.CAMERAX_EXTENSION, null))+        assertFalse(ExtensionsEnginePolicy.showsExtensionStrength(NightEngine.CAMERA2_EXTENSION, null))+    }+}