Modern Apps git

← Modern-Apps.git

camera: advance Camera2 holdouts without fake-enabling any

Commit
795425497bc63f91b60520c8b8ad0908adce3350
Author
Vayun Mathur <[email protected]>
When
2026-11-23 01:10 UTC (13 days ago)
Parents
16f2d62
Non-PHOTO preview: not extended - selecting Camera2
preview unbinds CameraX entirely, so every non-PHOTO mode
would show a viewfinder with a dead shutter/recorder.
PreviewEnginePolicy now carries an executable per-mode
exclusionReason, test-pinned, so a preview-only flip can't
masquerade as progress.

Slo-mo: two of the seven documented blockers closed
(codec-first encoder-surface handoff; no-audio muxer mode)
plus stop-before-EOS ordering. Bitmap analysis: honest
YUV->ARGB conversion (BT.601, stride/orientation aware)
with the live feed blocked on documented metadata gaps.

recordingEngineReady stays false everywhere it was;
CameraX holdouts unchanged in behavior. Verified: 317
camera2/domain tests green, compile green.

Diff

camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.ktindex d07470afd9..25a6e244f1 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt@@ -39,6 +39,38 @@ data class AnalysisSourceInput(  *  * Everything else (night-hysteresis luma, video motion grid) is plane-only  * and may move once the flag is enabled for that session.+ *+ * Bitmap-conversion assessment (2026-11-22): the conversion itself now+ * exists and is honest — `Yuv420ToArgb` (pure, stride-aware, BT.601+ * limited range) plus `AnalysisFrame.toBitmapFromPlanes()` produce the+ * same sensor-oriented bitmap `ImageProxy.toBitmap()` hands these+ * consumers, with rotation carried separately exactly as today. What+ * still blocks feeding `segment(Bitmap)`/`offerFrame` from Camera2, in+ * order:+ *+ * 1. No rotation/crop metadata on the Camera2 frame. `AnalysisFrame`+ *    carries planes + timestamp only; CameraX consumers read+ *    `imageInfo.rotationDegrees` (BokehAnalyzer's orient-to-display,+ *    PanoramaEngine's per-frame upright, MotionPhotoEncoder's clip+ *    rotation) and, on the night path, `ImageProxy.cropRect`. Deriving+ *    the Camera2 equivalent needs sensor orientation + display rotation+ *    + facing at the analysis source (the still path's+ *    `StillCapturePlanner.jpegRotationDegrees` is the back-lens half of+ *    that formula; the front-lens analysis formula is unproven), and no+ *    crop is ever applied to the Camera2 analysis stream.+ * 2. The bitmap sessions never compose a Camera2 session. Portrait,+ *    panorama and Motion-Photo (PHOTO with its excluded still routes)+ *    bind CameraX sessions; under `PreviewEnginePolicy` a Camera2+ *    preview would unbind the CameraX capture those modes still need.+ *    The analysis source cannot move before the preview/capture does.+ * 3. No perf win from the move alone: `segment(Bitmap)` still needs a+ *    converted bitmap per frame, so Camera2 would pay the same+ *    conversion `toBitmap()` pays today. The win is a single camera+ *    session, not a cheaper frame — worth having only after (1)-(2).+ *+ * Until (1) and (2) land, `needsBitmapFrame` keeps the session on+ * CameraX; do not relax this policy on the strength of the conversion+ * alone.  */ object AnalysisSourcePolicy {     /** Master policy flag: default on (per-session exclusions still apply). */
camera/src/main/java/com/vayunmathur/camera/domain/Yuv420ToArgb.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/Yuv420ToArgb.kt b/camera/src/main/java/com/vayunmathur/camera/domain/Yuv420ToArgb.ktnew file mode 100644index 0000000000..c02551e413--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/Yuv420ToArgb.kt@@ -0,0 +1,78 @@+package com.vayunmathur.camera.domain++import kotlin.math.roundToInt++/**+ * Pure YUV_420_888 -> ARGB conversion: the sensor-oriented pixel math a+ * Camera2 analysis frame needs to feed a `Bitmap` consumer+ * (`SelfieSegmenter.segment(Bitmap)`, `PanoramaEngine.offerFrame(Bitmap)`,+ * Motion-Photo frame copies), which CameraX frames get from+ * `ImageProxy.toBitmap()`.+ *+ * Semantics, deliberately identical to that path's contract:+ * - BT.601 limited range (Y 16-235, chroma centred on 128), the same+ *   colour science `YuvImage`/CameraX apply to these planes.+ * - Strides honoured exactly: every sample goes through+ *   `rowStride`/`pixelStride`, so HAL row padding and semi-planar+ *   (pixelStride 2) chroma are never mistaken for pixels.+ * - Sensor orientation preserved: the output is the unrotated sensor+ *   frame, exactly as `toBitmap()` hands it to the consumers above.+ *   Rotation is carried separately by the caller (as the CameraX paths+ *   carry `imageInfo.rotationDegrees`); this conversion neither knows+ *   nor invents it, and it applies no crop.+ *+ * Returns null when the planes cannot describe a full frame (fewer than+ * three planes, non-positive size, or a plane too short for its strides):+ * a partial bitmap would silently corrupt a mask/stitch, so the caller+ * drops the frame instead.+ */+object Yuv420ToArgb {++    /** Converts [planes] (Y, U, V in format order) to row-major ARGB ints. */+    fun convert(planes: List<PlaneView>, width: Int, height: Int): IntArray? {+        if (planes.size < 3 || width <= 0 || height <= 0) return null+        val yPlane = planes[0]+        val uPlane = planes[1]+        val vPlane = planes[2]+        if (!readable(yPlane, width, height)) return null+        val chromaWidth = (width + 1) / 2+        val chromaHeight = (height + 1) / 2+        if (!readable(uPlane, chromaWidth, chromaHeight)) return null+        if (!readable(vPlane, chromaWidth, chromaHeight)) return null++        val out = IntArray(width * height)+        var offset = 0+        for (row in 0 until height) {+            val chromaRow = row / 2+            for (col in 0 until width) {+                val y = sample(yPlane, col, row)+                val u = sample(uPlane, col / 2, chromaRow)+                val v = sample(vPlane, col / 2, chromaRow)+                out[offset++] = argb(y, u, v)+            }+        }+        return out+    }++    private fun sample(plane: PlaneView, x: Int, y: Int): Int {+        val buffer = plane.buffer.duplicate()+        return buffer.get(y * plane.rowStride + x * plane.pixelStride).toInt() and 0xFF+    }++    private fun readable(plane: PlaneView, width: Int, height: Int): Boolean {+        if (plane.rowStride <= 0 || plane.pixelStride <= 0) return false+        val last = (height - 1).toLong() * plane.rowStride ++            (width - 1).toLong() * plane.pixelStride+        return last < plane.buffer.limit()+    }++    private fun argb(y: Int, u: Int, v: Int): Int {+        val yScaled = 1.164f * (y - 16)+        val uCentred = u - 128+        val vCentred = v - 128+        val r = (yScaled + 1.596f * vCentred).roundToInt().coerceIn(0, 255)+        val g = (yScaled - 0.813f * vCentred - 0.391f * uCentred).roundToInt().coerceIn(0, 255)+        val b = (yScaled + 2.018f * uCentred).roundToInt().coerceIn(0, 255)+        return (0xFF shl 24) or (r shl 16) or (g shl 8) or b+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.ktindex 25ce256deb..4903650126 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt@@ -12,12 +12,13 @@ import com.vayunmathur.camera.platform.camera2.AnalysisConsumer  * The consumer is luma-only by construction: it feeds each frame's Y plane  * to [PhotoAnalyzer.onYPlane] (luma stats via the Rust plane-stats work in  * `StitchNative.lumaStats`, Kotlin fallback identical), which drives the- * night hysteresis through [onLuminance]. QR decode and bitmap frame- * copies deliberately have no plane entry point (see- * [AnalysisSourcePolicy]): sessions needing them — QR, PORTRAIT,- * PANORAMA/PHOTOSPHERE, Motion-Photo frame copies — stay on the CameraX- * ImageAnalysis path, exactly as before. Those session types never compose- * the Camera2 preview, so they never reach this glue.+ * night hysteresis through [onLuminance]. QR decode has no plane entry+ * point here, and bitmap frame copies — although a conversion now exists+ * (`AnalysisFrame.toBitmapFromPlanes`) — are not fed from this glue: the+ * frame carries no rotation/crop metadata and those sessions never+ * compose a Camera2 session (see [AnalysisSourcePolicy]). Sessions+ * needing them — QR, PORTRAIT, PANORAMA/PHOTOSPHERE, Motion-Photo frame+ * copies — stay on the CameraX ImageAnalysis path, exactly as before.  */ internal fun CameraViewModel.camera2AnalysisConsumer(): AnalysisConsumer {     val analyzer = PhotoAnalyzer(
camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.ktindex 3ad5297620..399f4557e5 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -23,6 +23,8 @@ import com.vayunmathur.camera.domain.LiveBitrateController import com.vayunmathur.camera.domain.RecordingPath import com.vayunmathur.camera.domain.RecordingPathPolicy import com.vayunmathur.camera.domain.SceneMotion+import com.vayunmathur.camera.platform.camera2.EncoderSurfaceHandoff+import com.vayunmathur.camera.platform.camera2.MuxerStartPolicy import com.vayunmathur.library.log.Log import java.io.File import java.nio.ByteBuffer@@ -68,6 +70,12 @@ data class CustomRecordingConfig(     val audioSampleRate: Int = 48_000,     val audioBitrateBps: Int = 128_000,     val iFrameIntervalSec: Int = 1,+    /**+     * False records video only (slo-mo's contract, SloMoEnginePolicy+     * piece 5): no AudioRecord/AAC codec is created and the muxer starts+     * on the video track alone ([MuxerStartPolicy]).+     */+    val audioEnabled: Boolean = true, )  /** Read-back summary of a finished file (see [Camera2VideoRecordingEngine.validateOutput]). */@@ -137,6 +145,9 @@ class Camera2VideoRecordingEngine(         start(request.outputFile, cameraId, request.previewSurface)     } +    private val encoderHandoff = EncoderSurfaceHandoff()+    private var preparedEncoderSurface: Surface? = null+     private var videoCodec: MediaCodec? = null     private var audioCodec: MediaCodec? = null     private var audioRecord: AudioRecord? = null@@ -180,6 +191,7 @@ class Camera2VideoRecordingEngine(             cameraDevice?.close()             try {                 videoCodec?.signalEndOfInputStream()+                encoderHandoff.markEosSignalled()             } catch (_: IllegalStateException) {             }             audioRecord?.stop()@@ -215,7 +227,32 @@ class Camera2VideoRecordingEngine(         }     } -    private fun setupEncoders(outputFile: File) {+    /**+     * Codec-first split (SloMoEnginePolicy piece 1): configures the video+     * codec and exposes its input surface *before* any camera is opened,+     * so a caller-owned session (e.g. the constrained high-speed session)+     * can list the surface as a configure-time target. Idempotent; [start]+     * reuses the prepared surface instead of creating one in `openCamera`.+     * Returns null when the codec cannot be configured.+     */+    fun prepareEncoderSurface(): Surface? {+        preparedEncoderSurface?.let { return it }+        return try {+            if (videoCodec == null) configureVideoCodec()+            val surface = videoCodec!!.createInputSurface()+            encoderHandoff.markSurfaceExposed()+            preparedEncoderSurface = surface+            surface+        } catch (e: IllegalStateException) {+            Log.error("Camera2Recorder", "prepareEncoderSurface failed", e)+            null+        }+    }++    /** The surface exposed by [prepareEncoderSurface], or null before it. */+    fun preparedEncoderSurface(): Surface? = preparedEncoderSurface++    private fun configureVideoCodec() {         val videoFormat = MediaFormat.createVideoFormat(config.videoMime, config.width, config.height)             .apply {                 setInteger(@@ -234,17 +271,23 @@ class Camera2VideoRecordingEngine(         videoCodec = MediaCodec.createEncoderByType(config.videoMime).apply {             configure(videoFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)         }+        encoderHandoff.markCodecConfigured()+    } -        val audioFormat = MediaFormat.createAudioFormat(-            MediaFormat.MIMETYPE_AUDIO_AAC, config.audioSampleRate, 1-        ).apply {-            setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)-            setInteger(MediaFormat.KEY_BIT_RATE, config.audioBitrateBps)-            setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, AUDIO_MAX_INPUT_BYTES)-        }-        audioCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC).apply {-            configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)-            start()+    private fun setupEncoders(outputFile: File) {+        if (videoCodec == null) configureVideoCodec()+        if (config.audioEnabled) {+            val audioFormat = MediaFormat.createAudioFormat(+                MediaFormat.MIMETYPE_AUDIO_AAC, config.audioSampleRate, 1+            ).apply {+                setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)+                setInteger(MediaFormat.KEY_BIT_RATE, config.audioBitrateBps)+                setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, AUDIO_MAX_INPUT_BYTES)+            }+            audioCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC).apply {+                configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+                start()+            }         }         muxer = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)     }@@ -254,7 +297,8 @@ class Camera2VideoRecordingEngine(         cameraThread = HandlerThread("Camera2RecorderCamera").apply { start() }         cameraHandler = Handler(cameraThread!!.looper)         val manager = context.getSystemService(CameraManager::class.java)-        val encoderSurface = videoCodec!!.createInputSurface()+        val encoderSurface = preparedEncoderSurface ?: prepareEncoderSurface()+            ?: throw IllegalStateException("encoder input surface unavailable")         videoCodec!!.start()         // Preview surface: the caller's when given, else an engine-owned         // SurfaceTexture surface (exposed via ownedPreviewSurface() for a@@ -309,6 +353,7 @@ class Camera2VideoRecordingEngine(                     device.createCaptureSession(surfaces, object : CameraCaptureSession.StateCallback() {                         override fun onConfigured(session: CameraCaptureSession) {                             captureSession = session+                            encoderHandoff.markSessionStreaming()                             val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {                                 addTarget(encoderSurface)                                 addTarget(effectivePreview)@@ -382,7 +427,13 @@ class Camera2VideoRecordingEngine(                     val format = codec.outputFormat                     val m = muxer ?: return                     if (isVideo) videoTrackIndex = m.addTrack(format) else audioTrackIndex = m.addTrack(format)-                    if (videoTrackIndex >= 0 && audioTrackIndex >= 0 && !muxerStarted) {+                    if (+                        !muxerStarted && MuxerStartPolicy.shouldStart(+                            hasVideoTrack = videoTrackIndex >= 0,+                            hasAudioTrack = audioTrackIndex >= 0,+                            audioEnabled = config.audioEnabled,+                        )+                    ) {                         m.start()                         muxerStarted = true                     }@@ -405,6 +456,7 @@ class Camera2VideoRecordingEngine(      /** AudioRecord (mono) -> audio encoder input buffers, with codec timestamps. */     private fun startAudioThread() {+        if (!config.audioEnabled) return         val minBuffer = AudioRecord.getMinBufferSize(             config.audioSampleRate,             AudioFormat.CHANNEL_IN_MONO,@@ -481,6 +533,9 @@ class Camera2VideoRecordingEngine(         try { videoCodec?.stop() } catch (_: Exception) {}         try { videoCodec?.release() } catch (_: Exception) {}         try { muxer?.release() } catch (_: Exception) {}+        try { preparedEncoderSurface?.release() } catch (_: Exception) {}+        preparedEncoderSurface = null+        encoderHandoff.markReleased()         try { cameraThread?.quitSafely() } catch (_: Exception) {}         audioRecord = null         audioCodec = null
camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.ktindex 29f74a4571..078b77aa21 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt@@ -15,8 +15,10 @@ import java.util.concurrent.atomic.AtomicLong /**  * One analysis frame as plane views. The buffers are borrowed: they are only  * valid until [close], consumers must read them synchronously during the- * delivery call and retain nothing. There is deliberately no bitmap accessor- * on this path — no `ImageProxy.toBitmap()` equivalent exists here.+ * delivery call and retain nothing. A sensor-oriented bitmap is available+ * via [toBitmapFromPlanes]; there is no rotation/crop metadata on this+ * frame (see that function), which is what still keeps bitmap consumers+ * on CameraX (see `AnalysisSourcePolicy`).  */ interface AnalysisFrame : AutoCloseable {     val width: Int@@ -35,6 +37,28 @@ fun interface AnalysisConsumer {     fun onFrame(frame: AnalysisFrame) } +/**+ * Converts this frame to a sensor-oriented `Bitmap` via the pure+ * [com.vayunmathur.camera.domain.Yuv420ToArgb] math (BT.601 limited+ * range, strides honoured, no rotation, no crop — the same orientation+ * contract `ImageProxy.toBitmap()` hands the bitmap consumers). Must be+ * called synchronously while the frame is open; the caller owns the+ * returned bitmap. Null when the planes cannot describe a full frame.+ *+ * This makes the conversion available; it does not by itself move a+ * bitmap consumer to Camera2: the frame carries no `rotationDegrees` or+ * `cropRect` (CameraX supplies both on `ImageProxy`), and the sessions+ * needing bitmaps do not compose a Camera2 session today — see+ * `AnalysisSourcePolicy`.+ */+fun AnalysisFrame.toBitmapFromPlanes(): android.graphics.Bitmap? {+    val argb = com.vayunmathur.camera.domain.Yuv420ToArgb.convert(planes, width, height)+        ?: return null+    return android.graphics.Bitmap.createBitmap(+        argb, width, height, android.graphics.Bitmap.Config.ARGB_8888,+    )+}+ /**  * Testable handle over a YUV analysis output (an `ImageReader` in the real  * driver). The session adds [surface] as a capture-session output alongside
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 a7430a7c5b..3740a87358 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@@ -167,6 +167,13 @@ interface CaptureSessionHandle {         throw IllegalStateException("not a constrained high-speed session")     } +    /**+     * Stops the repeating/burst request without closing the session, so a+     * recording boundary can signal encoder EOS before teardown. The+     * default is a no-op for handles that never stream a repeating request.+     */+    fun stopRepeating() {}+     fun close() } @@ -711,6 +718,10 @@ private class AndroidCaptureSessionHandle(         )     } +    override fun stopRepeating() {+        runCatching { session.stopRepeating() }+    }+     override fun close() {         runCatching { imageWriter?.close() }         imageWriter = null
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.ktindex 2c0289fa0e..6941780a5c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt@@ -74,6 +74,23 @@ class Camera2HighSpeedSession(     /** The operating point chosen at [open], or null before a successful open. */     fun currentSelection(): HighSpeedSelection? = selection +    /**+     * Recording stop boundary (SloMoEnginePolicy piece 3): stops the+     * repeating high-speed request first, and only then invokes+     * [eosSignal], so no frame can enter the encoder after EOS. The+     * session and device stay open and the caller-owned encoder/preview+     * surfaces are never closed here; [close] remains the teardown.+     * A no-op unless streaming.+     */+    fun stopRecording(eosSignal: () -> Unit) {+        executor.execute {+            if (stateMachine.state != SessionState.STREAMING) return@execute+            runCatching { captureSession?.stopRepeating() }+                .onFailure { reportError("stopRepeating failed: ${it.message}") }+            eosSignal()+        }+    }+     /**      * Tears the session down: bumps the generation first (so callbacks      * already in flight go stale), then closes the capture session and the
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.ktindex 094ec2221f..c90e234af8 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt@@ -28,17 +28,69 @@ data class PreviewEngineInput(  * PHOTO stills on that preview (see `StillEnginePolicy` for which shots  * still stay on CameraX), so every other mode stays on CameraX even with  * the gate on.+ *+ * Per-mode assessment (2026-11-22, CameraX-holdout reduction): extending+ * preview alone is only coherent when the mode's capture/analysis also+ * lives on the Camera2 session. When Camera2 preview is selected the+ * CameraX session is NOT bound at all (`CameraScreenEffects` tears it+ * down and skips the bind), so a mode whose capture needs a bound CameraX+ * use case would show a viewfinder with a dead shutter/recorder:+ *+ * - PHOTO: coherent and live. Plain stills are served by the Camera2+ *   session itself ([StillEnginePolicy]); its excluded shots fall back+ *   per-shot only because the session already owns the camera.+ * - PORTRAIT: blocked. The capture is a processed CameraX still (bokeh+ *   bake) and the preview mask comes from a CameraX `ImageAnalysis`+ *   bitmap segmenter. Camera2 has neither a portrait still route nor+ *   (yet) a bitmap analysis feed for that session; see+ *   `AnalysisSourcePolicy`.+ * - PANORAMA / PHOTOSPHERE: blocked. Capture is analysis bitmap frames+ *   (`PanoramaEngine.offerFrame(Bitmap)`) from CameraX `ImageAnalysis`;+ *   there is no bound CameraX analysis stream under a Camera2 preview.+ * - VIDEO / TIMELAPSE / CINEMATIC: blocked. Recording is the CameraX+ *   Recorder (`videoCapture` bound by the video session;+ *   `startRecording` silently no-ops when it is null), and the Camera2+ *   recording engine is not device-verified (`CustomRecordingGate`).+ *   An idle-only Camera2 preview would need a record-press rebind to+ *   CameraX (teardown, settle, video-session bind, then start) that does+ *   not exist today; showing Camera2 preview until the press and then+ *   going black for the rebind is a worse, unverified trade, not a+ *   reduction. Revisit only with that rebind implemented end to end.+ * - SLOW_MO: blocked. Preview, capture and recording are one CameraX+ *   high-speed session. The Camera2 constrained session exists but its+ *   recording coupling is incomplete (see `SloMoEnginePolicy`), and it+ *   has no preview-only surface to show before a recording exists.+ *+ * Adding a mode to [supportedModes] therefore requires, in the same+ * change, its capture/analysis route on the Camera2 session (or a+ * verified capture-time rebind); a preview-only flip is a split-brain+ * regression, not progress.  */ object PreviewEnginePolicy {      /** Modes the Camera2 preview engine supports today (PHOTO first). */     val supportedModes: Set<CameraMode> = setOf(CameraMode.PHOTO) -    fun select(input: PreviewEngineInput): PreviewEngine = when {-        !input.camera2Enabled -> PreviewEngine.CAMERAX-        input.fallbackLatched -> PreviewEngine.CAMERAX-        input.mode !in supportedModes -> PreviewEngine.CAMERAX-        else -> PreviewEngine.CAMERA2+    fun select(input: PreviewEngineInput): PreviewEngine =+        if (exclusionReason(input) == null) PreviewEngine.CAMERA2 else PreviewEngine.CAMERAX++    /** Why [input] cannot use Camera2 preview, or null when it can. */+    fun exclusionReason(input: PreviewEngineInput): String? = when {+        !input.camera2Enabled -> "camera2 preview gate off"+        input.fallbackLatched -> "camera2 bind failure latched for this session"+        input.mode == CameraMode.PHOTO -> null+        input.mode == CameraMode.PORTRAIT ->+            "PORTRAIT capture and bitmap segmentation stay on CameraX; " ++                "a Camera2 preview would leave neither bound"+        input.mode == CameraMode.PANORAMA || input.mode == CameraMode.PHOTOSPHERE ->+            "panorama capture needs CameraX analysis bitmap frames; " ++                "a Camera2 preview would leave no analysis stream bound"+        input.mode == CameraMode.SLOW_MO ->+            "slo-mo preview is part of the CameraX high-speed session; " ++                "the Camera2 constrained session has no preview-only surface"+        else ->+            "video-mode recording stays on the CameraX Recorder; " ++                "a Camera2 preview would leave no Recorder bound to record into"     }      /** True when [mode] should render through the Camera2 preview engine. */
camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.ktindex c94044ac65..145ba8dd2e 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt@@ -36,56 +36,54 @@ data class SloMoEngineInput(     val encoderSupportsCaptureRate: Boolean = false,     /**      * The constrained session is coupled to a recording engine (codec +-     * muxer) end to end. False today — assessed 2026-11-22: coupling+     * muxer) end to end. False today — coupling      * `Camera2HighSpeedSession` to `Camera2VideoRecordingEngine` is NOT-     * mechanical. The exact missing pieces, in dependency order:+     * mechanical. The seven pieces, in dependency order, with status+     * after the structural work of 2026-11-22 (see+     * [SloMoRecordingReadiness], whose per-piece flags mirror this list):      *-     * 1. Encoder-surface handoff. The engine creates its codec input-     *    surface internally in `openCamera()` (`videoCodec.createInputSurface()`-     *    after `setupEncoders`) and never exposes it before the camera is-     *    opened. The high-speed session needs that surface *before* open,-     *    as a configure-time session target. Missing: a codec-first split-     *    of the engine (configure codec -> expose input surface -> start-     *    drain/muxer separately from camera open).-     * 2. Device/session ownership. Both classes open the same cameraId:-     *    the engine owns a private `CameraDevice`/`HandlerThread` and a-     *    *regular* capture session; the high-speed session owns the device-     *    through the driver seam and a *constrained* session-     *    (`SESSION_HIGH_SPEED` + `createHighSpeedRequestList`). The-     *    engine's regular `TEMPLATE_RECORD` request with a pinned FPS-     *    range cannot deliver 120/240 fps and must not be substituted.-     *    Missing: an engine variant that accepts an externally-owned-     *    session (or extracts the codec/muxer/drain core both can share).-     * 3. Recording lifecycle. `Camera2HighSpeedSession` has open/close-     *    only — no start/stop-recording boundary, no EOS/drain-     *    coordination with a codec. The engine's `stop()` assumes it owns-     *    session+device+codec. Missing: start/stop semantics on the-     *    high-speed session that signal EOS to the external codec and-     *    only then close, without closing caller-owned surfaces.-     * 4. Preview surface in SLOW_MO. `PreviewEnginePolicy` serves PHOTO-     *    only; SLOW_MO preview is a CameraX `surfaceRequest`. There is no-     *    Camera2 slo-mo preview composable/bridge to supply the-     *    high-speed session's preview target (mirroring `Camera2Preview`).-     * 5. Audio/muxer contract. CameraX slo-mo records *no* audio; the-     *    engine always starts `AudioRecord`+AAC and its muxer only starts-     *    once *both* tracks appear. Missing: a no-audio mode (muxer starts-     *    on the video track alone) for the slo-mo configuration.-     * 6. Timestamp verification. The muxer writes encoder `BufferInfo`-     *    PTS as-is; the pure `HighSpeedSelection.stretchedPtsUs` fallback-     *    is not wired into the drain path, and `validateOutput` does not-     *    check frame rate / stretched duration. Missing: either proof a-     *    device encoder honours `KEY_CAPTURE_RATE`, or muxer-side PTS-     *    stretching, plus read-back checks (and external ffprobe) that-     *    the output is slow, not realtime HFR.-     * 7. Save-path glue + fallback. `setupHighSpeedSession` /-     *    recording start-stop plumbing expects an engine that opens the-     *    camera itself (`VideoRecordingEngine.start`). Missing: glue that-     *    tears CameraX down, builds engine+high-speed session together,-     *    routes the file through `saveVideoStaged`, and on any failure-     *    rebinds the CameraX HFR ladder (fallback-latch philosophy) —-     *    plus the device verification in (6) before this flag may flip.+     * 1. Encoder-surface handoff. DONE (structural): the engine is now+     *    codec-first — `prepareEncoderSurface()` configures the video+     *    codec and exposes its input surface before any camera open, and+     *    `start` reuses it; the ordering itself is the pure, tested+     *    [EncoderSurfaceHandoff] phase machine.+     * 2. Device/session ownership. OPEN: both classes still open the same+     *    cameraId — the engine owns a private device and a *regular*+     *    session; the high-speed session owns the device through the+     *    driver seam and a *constrained* session. The engine's regular+     *    `TEMPLATE_RECORD` request cannot deliver 120/240 fps and must+     *    not be substituted. Still missing: extracting the codec/muxer/+     *    drain core so it can run under an externally-owned session.+     * 3. Recording lifecycle. PARTIAL: `Camera2HighSpeedSession` now has+     *    a stop boundary ([Camera2HighSpeedSession.stopRecording]) that+     *    stops the repeating request before signalling EOS and never+     *    closes caller-owned surfaces. Still missing: the shared core+     *    from (2) for the EOS signal to land on, and start semantics.+     * 4. Preview surface in SLOW_MO. OPEN: there is no Camera2 slo-mo+     *    preview composable/bridge to supply the high-speed session's+     *    preview target (mirroring `Camera2Preview`); see also+     *    [PreviewEnginePolicy]'s SLOW_MO exclusion.+     * 5. Audio/muxer contract. DONE (structural): the engine takes a+     *    no-audio configuration (`audioEnabled = false`, CameraX slo-mo's+     *    contract) — no AudioRecord/AAC is created and the muxer starts+     *    on the video track alone via the tested [MuxerStartPolicy].+     * 6. Timestamp verification. OPEN: the muxer writes encoder PTS+     *    as-is; `stretchedPtsUs` is not wired into the drain path and+     *    `validateOutput` checks neither frame rate nor stretched+     *    duration. Needs device proof an encoder honours+     *    `KEY_CAPTURE_RATE` (or muxer-side stretching) plus read-back+     *    and external ffprobe checks that output is slow, not realtime.+     * 7. Save-path glue + fallback. OPEN: glue that tears CameraX down,+     *    builds engine+high-speed session together, routes the file+     *    through `saveVideoStaged`, and on failure rebinds the CameraX+     *    HFR ladder — plus the device verification in (6) before this+     *    flag may flip. Callers should pass+     *    [SloMoRecordingReadiness.recordingEngineReady] (false today).      *-     * Until (1)-(7) land, no live recording may be routed here.+     * Until (2), (4), (6) and (7) land, no live recording may be routed+     * here: with pieces 1/3/5 in place the remaining work is the shared+     * drain core, the preview bridge, and device verification — in that+     * order.      */     val recordingEngineReady: Boolean = false, )
camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.ktnew file mode 100644index 0000000000..0fed89e90e--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.kt@@ -0,0 +1,106 @@+package com.vayunmathur.camera.platform.camera2++/**+ * Pure structural core for coupling the constrained high-speed session to+ * a recording engine (SloMoEnginePolicy pieces 1, 3 and 5). No Android+ * types: the ordering rules are unit-testable without a codec or HAL.+ *+ * Nothing here routes a live recording. [SloMoRecordingReadiness] keeps+ * `recordingEngineReady` false until every documented piece closes and a+ * device run verifies the output (piece 6).+ */++/** Ordered phases of one encoder-surface handoff (piece 1). */+enum class EncoderSurfacePhase {+    IDLE,+    CODEC_CONFIGURED,+    SURFACE_EXPOSED,+    SESSION_STREAMING,+    EOS_SIGNALLED,+    RELEASED,+}++/**+ * Enforces the codec-first ordering the high-speed coupling needs: the+ * codec is configured and its input surface exposed *before* any camera+ * session may list that surface as a configure-time target; EOS may only+ * be signalled after streaming; release is terminal. Illegal transitions+ * are rejected (return false), never reordered silently.+ */+class EncoderSurfaceHandoff {+    var phase: EncoderSurfacePhase = EncoderSurfacePhase.IDLE+        private set++    private fun advance(to: EncoderSurfacePhase, allowedFrom: Set<EncoderSurfacePhase>): Boolean {+        if (phase !in allowedFrom) return false+        phase = to+        return true+    }++    fun markCodecConfigured(): Boolean =+        advance(EncoderSurfacePhase.CODEC_CONFIGURED, setOf(EncoderSurfacePhase.IDLE))++    fun markSurfaceExposed(): Boolean = advance(+        EncoderSurfacePhase.SURFACE_EXPOSED, setOf(EncoderSurfacePhase.CODEC_CONFIGURED),+    )++    fun markSessionStreaming(): Boolean = advance(+        EncoderSurfacePhase.SESSION_STREAMING, setOf(EncoderSurfacePhase.SURFACE_EXPOSED),+    )++    fun markEosSignalled(): Boolean = advance(+        EncoderSurfacePhase.EOS_SIGNALLED, setOf(EncoderSurfacePhase.SESSION_STREAMING),+    )++    fun markReleased(): Boolean {+        if (phase == EncoderSurfacePhase.RELEASED) return false+        phase = EncoderSurfacePhase.RELEASED+        return true+    }+}++/**+ * When a muxer may start (piece 5): on the video track alone when the+ * configuration records no audio (CameraX slo-mo's contract), otherwise+ * only once both tracks are known, exactly as the normal engine behaves.+ */+object MuxerStartPolicy {+    fun shouldStart(hasVideoTrack: Boolean, hasAudioTrack: Boolean, audioEnabled: Boolean): Boolean =+        hasVideoTrack && (!audioEnabled || hasAudioTrack)+}++/**+ * Readiness of SloMoEnginePolicy's seven documented pieces after the+ * structural work of 2026-11-22. Only pieces closed in code may read+ * true; [recordingEngineReady] is their conjunction, so it stays false+ * (and slo-mo stays on CameraX) until the rest land *and* a device run+ * verifies stretched timestamps / slow duration (piece 6).+ */+object SloMoRecordingReadiness {+    /** 1. Codec-first split; surface exposed before camera open. */+    const val ENCODER_SURFACE_HANDOFF_READY: Boolean = true++    /** 2. Codec/muxer/drain core shared by engine and high-speed session. */+    const val SHARED_CODEC_CORE_READY: Boolean = false++    /** 3. Stop boundary on the high-speed session: stop repeating, then EOS, no caller-surface close. */+    const val SESSION_RECORDING_BOUNDARY_READY: Boolean = true++    /** 4. Camera2 slo-mo preview composable/bridge. */+    const val SLO_MO_PREVIEW_READY: Boolean = false++    /** 5. No-audio muxer mode (muxer starts on the video track alone). */+    const val NO_AUDIO_MUXER_READY: Boolean = true++    /** 6. Timestamp stretching proof + read-back frame-rate/duration checks. */+    const val TIMESTAMP_VERIFICATION_READY: Boolean = false++    /** 7. Save-path glue (engine + session together, staged save, CameraX fallback latch). */+    const val SAVE_PATH_GLUE_READY: Boolean = false++    /** True only when every piece above is ready; feeds SloMoEngineInput.recordingEngineReady. */+    val recordingEngineReady: Boolean+        get() = ENCODER_SURFACE_HANDOFF_READY && SHARED_CODEC_CORE_READY &&+            SESSION_RECORDING_BOUNDARY_READY && SLO_MO_PREVIEW_READY &&+            NO_AUDIO_MUXER_READY && TIMESTAMP_VERIFICATION_READY && SAVE_PATH_GLUE_READY+}
camera/src/test/java/com/vayunmathur/camera/domain/Yuv420ToArgbTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/Yuv420ToArgbTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/Yuv420ToArgbTest.ktnew file mode 100644index 0000000000..93a0896033--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/Yuv420ToArgbTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.camera.domain++import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class Yuv420ToArgbTest {++    private fun plane(bytes: ByteArray, rowStride: Int, pixelStride: Int, w: Int, h: Int) =+        PlaneView(ByteBuffer.wrap(bytes), rowStride, pixelStride, w, h)++    /** One-colour frame: constant Y plus one chroma sample per 2x2 block. */+    private fun solidFrame(width: Int, height: Int, y: Int, u: Int, v: Int): List<PlaneView> {+        val yPlane = plane(ByteArray(width * height) { y.toByte() }, width, 1, width, height)+        val cw = (width + 1) / 2+        val ch = (height + 1) / 2+        val uPlane = plane(ByteArray(cw * ch) { u.toByte() }, cw, 1, width, height)+        val vPlane = plane(ByteArray(cw * ch) { v.toByte() }, cw, 1, width, height)+        return listOf(yPlane, uPlane, vPlane)+    }++    private fun red(argb: Int) = (argb shr 16) and 0xFF+    private fun green(argb: Int) = (argb shr 8) and 0xFF+    private fun blue(argb: Int) = argb and 0xFF++    @Test fun blackAndWhiteEndpoints() {+        val black = Yuv420ToArgb.convert(solidFrame(2, 2, y = 16, u = 128, v = 128), 2, 2)!!+        assertTrue(black.all { it == 0xFF000000.toInt() })+        val white = Yuv420ToArgb.convert(solidFrame(2, 2, y = 235, u = 128, v = 128), 2, 2)!!+        assertTrue(white.all { it == 0xFFFFFFFF.toInt() })+    }++    @Test fun neutralGreyIsNeutral() {+        val grey = Yuv420ToArgb.convert(solidFrame(4, 2, y = 128, u = 128, v = 128), 4, 2)!!.first()+        assertEquals(red(grey), green(grey))+        assertEquals(green(grey), blue(grey))+        assertTrue(red(grey) in 128..134, "mid grey should land near 130, got ${red(grey)}")+    }++    @Test fun chromaMovesColourInTheRightDirection() {+        // High V pushes red, high U pushes blue (BT.601 limited range).+        val redish = Yuv420ToArgb.convert(solidFrame(2, 2, y = 128, u = 128, v = 255), 2, 2)!!.first()+        assertTrue(red(redish) > green(redish) && red(redish) > blue(redish))+        val blueish = Yuv420ToArgb.convert(solidFrame(2, 2, y = 128, u = 255, v = 128), 2, 2)!!.first()+        assertTrue(blue(blueish) > red(blueish) && blue(blueish) > green(blueish))+    }++    @Test fun rowPaddingIsNotMistakenForPixels() {+        // 2-wide frame in 4-wide rows: bytes beyond column 1 are padding.+        val paddedY = plane(+            ByteArray(8) { if (it % 4 < 2) 16.toByte() else 99.toByte() }, rowStride = 4, pixelStride = 1, w = 2, h = 2,+        )+        val chroma = plane(ByteArray(1) { 128.toByte() }, rowStride = 1, pixelStride = 1, w = 2, h = 2)+        val out = Yuv420ToArgb.convert(listOf(paddedY, chroma, chroma), 2, 2)!!+        assertTrue(out.all { it == 0xFF000000.toInt() }, "padding must not leak into pixels")+    }++    @Test fun semiPlanarChromaPixelStrideIsHonoured() {+        // Chroma stored interleaved (pixelStride 2): sample 0 at byte 0, junk at byte 1.+        val yPlane = plane(ByteArray(4) { 16 }, rowStride = 2, pixelStride = 1, w = 2, h = 2)+        val uPlane = plane(byteArrayOf(128.toByte(), 0), rowStride = 2, pixelStride = 2, w = 2, h = 2)+        val vPlane = plane(byteArrayOf(128.toByte(), 0), rowStride = 2, pixelStride = 2, w = 2, h = 2)+        val out = Yuv420ToArgb.convert(listOf(yPlane, uPlane, vPlane), 2, 2)!!+        assertTrue(out.all { it == 0xFF000000.toInt() })+    }++    @Test fun invalidPlanesReturnNull() {+        assertNull(Yuv420ToArgb.convert(emptyList(), 2, 2))+        assertNull(Yuv420ToArgb.convert(solidFrame(2, 2, 16, 128, 128), 0, 2))+        val shortY = plane(ByteArray(2), rowStride = 2, pixelStride = 1, w = 2, h = 2)+        val chroma = plane(ByteArray(1) { 128.toByte() }, rowStride = 1, pixelStride = 1, w = 2, h = 2)+        assertNull(Yuv420ToArgb.convert(listOf(shortY, chroma, chroma), 2, 2))+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.ktindex 26bbce4c15..c3e2f6629e 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt@@ -25,7 +25,11 @@ class Camera2HighSpeedSessionTest {      private class FakeHighSpeedHandle : CaptureSessionHandle {         val highSpeedRequests = mutableListOf<Pair<ResolvedHighSpeedParams, List<Surface>>>()+        val events = mutableListOf<String>()         var closed = false+        override fun stopRepeating() {+            events += "stopRepeating"+        }         override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}         override fun captureStill(             params: ResolvedStillParams,@@ -137,6 +141,35 @@ class Camera2HighSpeedSessionTest {         }     } +    @Test fun stopRecordingStopsRepeatingBeforeEosAndKeepsDeviceOpen() {+        val executor = Camera2Executor("HighSpeedSessionTest-eos")+        try {+            val driver = FakeDriver()+            val session = Camera2HighSpeedSession(driver, executor, snapshot())+            session.open("0", mock(Surface::class.java), mock(Surface::class.java))+            executor.drain()+            assertEquals(SessionState.STREAMING, session.state)++            session.stopRecording {+                driver.device.sessionHandle.events += "eos"+            }+            executor.drain()++            // Order is the contract: no frame may enter the encoder after EOS.+            assertEquals(listOf("stopRepeating", "eos"), driver.device.sessionHandle.events)+            // The boundary is not teardown: session/device stay open for close().+            assertEquals(SessionState.STREAMING, session.state)+            assertTrue(!driver.device.closed)+            assertTrue(!driver.device.sessionHandle.closed)++            session.close()+            executor.drain()+            assertEquals(SessionState.CLOSED, session.state)+        } finally {+            executor.shutdown()+        }+    }+     @Test fun noSloMoPointFailsBeforeOpeningDevice() {         val executor = Camera2Executor("HighSpeedSessionTest-none")         try {
camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.ktindex 7fe561ef34..a1849d484d 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.kt@@ -38,6 +38,43 @@ class PreviewEnginePolicyTest {         assertEquals(setOf(CameraMode.PHOTO), PreviewEnginePolicy.supportedModes)     } +    @Test fun photoHasNoExclusionWhenGateOnAndUnlatched() {+        assertEquals(+            null,+            PreviewEnginePolicy.exclusionReason(PreviewEngineInput(true, CameraMode.PHOTO)),+        )+    }++    @Test fun everyNonPhotoModeNamesItsCaptureBlocker() {+        // Preview alone is split-brain for these modes: selecting Camera2+        // preview unbinds the CameraX session their capture/analysis needs.+        val blockers = mapOf(+            CameraMode.PORTRAIT to "PORTRAIT capture",+            CameraMode.PANORAMA to "analysis bitmap",+            CameraMode.PHOTOSPHERE to "analysis bitmap",+            CameraMode.VIDEO to "CameraX Recorder",+            CameraMode.TIMELAPSE to "CameraX Recorder",+            CameraMode.CINEMATIC to "CameraX Recorder",+            CameraMode.SLOW_MO to "high-speed",+        )+        for ((mode, fragment) in blockers) {+            val reason = PreviewEnginePolicy.exclusionReason(PreviewEngineInput(true, mode))+            assertTrue(reason!!.contains(fragment), "$mode reason must name its blocker: $reason")+        }+    }++    @Test fun gateAndLatchReasonsWinOverModeBlockers() {+        assertTrue(+            PreviewEnginePolicy.exclusionReason(PreviewEngineInput(false, CameraMode.VIDEO))!!+                .contains("gate off"),+        )+        assertTrue(+            PreviewEnginePolicy.exclusionReason(+                PreviewEngineInput(true, CameraMode.VIDEO, fallbackLatched = true),+            )!!.contains("latched"),+        )+    }+     @Test fun ringGatesDefaultOn() {         assertTrue(ReprocessRingGate.ENABLED)         assertTrue(RawRingGate.ENABLED)
camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.ktindex 51a4a68a4c..e122a449ad 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt@@ -67,6 +67,15 @@ class SloMoEnginePolicyTest {         }     } +    @Test fun liveReadinessFlagStillKeepsRecordingOnCameraX() {+        // Pieces 1/3/5 are structural-done, 2/4/6/7 are open, so the flag+        // callers should feed the policy must still select CameraX.+        assertEquals(+            SloMoEngine.CAMERAX,+            SloMoEnginePolicy.select(readyInput(recordingEngineReady = SloMoRecordingReadiness.recordingEngineReady)),+        )+    }+     @Test fun gateOffReasonWinsOverOtherExclusions() {         // The gate is reported first so a disabled path never looks like a         // device-capability failure in logs.
camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.ktnew file mode 100644index 0000000000..84d712390e--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.kt@@ -0,0 +1,50 @@+package com.vayunmathur.camera.platform.camera2++import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Structural pieces 1/3/5 ordering rules, plus the readiness gate. */+class SloMoRecordingCoreTest {++    @Test fun handoffRequiresCodecBeforeSurfaceBeforeStreamingBeforeEos() {+        val handoff = EncoderSurfaceHandoff()+        assertFalse(handoff.markSurfaceExposed(), "surface before codec must be rejected")+        assertFalse(handoff.markSessionStreaming())+        assertFalse(handoff.markEosSignalled())+        assertTrue(handoff.markCodecConfigured())+        assertFalse(handoff.markCodecConfigured(), "codec configure is not repeatable")+        assertFalse(handoff.markEosSignalled(), "EOS before streaming must be rejected")+        assertTrue(handoff.markSurfaceExposed())+        assertTrue(handoff.markSessionStreaming())+        assertTrue(handoff.markEosSignalled())+        assertFalse(handoff.markSurfaceExposed(), "no re-expose after EOS")+    }++    @Test fun handoffReleaseIsTerminal() {+        val handoff = EncoderSurfaceHandoff()+        assertTrue(handoff.markReleased())+        assertFalse(handoff.markReleased())+        assertFalse(handoff.markCodecConfigured())+    }++    @Test fun muxerStartsOnVideoAloneOnlyWhenNoAudio() {+        assertTrue(MuxerStartPolicy.shouldStart(true, false, audioEnabled = false))+        assertFalse(MuxerStartPolicy.shouldStart(true, false, audioEnabled = true))+        assertTrue(MuxerStartPolicy.shouldStart(true, true, audioEnabled = true))+        assertFalse(MuxerStartPolicy.shouldStart(false, true, audioEnabled = false))+    }++    @Test fun readinessKeepsRecordingOnCameraXUntilEveryPieceCloses() {+        assertTrue(SloMoRecordingReadiness.ENCODER_SURFACE_HANDOFF_READY)+        assertTrue(SloMoRecordingReadiness.SESSION_RECORDING_BOUNDARY_READY)+        assertTrue(SloMoRecordingReadiness.NO_AUDIO_MUXER_READY)+        assertFalse(SloMoRecordingReadiness.SHARED_CODEC_CORE_READY)+        assertFalse(SloMoRecordingReadiness.SLO_MO_PREVIEW_READY)+        assertFalse(SloMoRecordingReadiness.TIMESTAMP_VERIFICATION_READY)+        assertFalse(SloMoRecordingReadiness.SAVE_PATH_GLUE_READY)+        // The conjunction is the flag callers feed the policy; it must not+        // flip while any piece above is open.+        assertFalse(SloMoRecordingReadiness.recordingEngineReady)+    }+}