Modern Apps git

← Modern-Apps.git

camera: Camera2 slo-mo core behind gates (Phase 5)

Commit
77d41f7d022551d06957eed51008bb1ababd8cb2
Author
Vayun Mathur <[email protected]>
When
2026-11-21 19:31 UTC (14 days ago)
Parents
a100c38
Constrained high-speed capture on the Camera2 seam:
characteristics snapshot carries HFR sizes/ranges, the
planner only accepts exact fixed ranges at the highest fps
(no normalised variable ranges), and the request is a
TEMPLATE_RECORD pinned to that range. CameraX writes no
proprietary slo-mo atom - slow motion is capture-rate vs
playback-rate in the track timing - so the Camera2 encoder
plan mirrors it (KEY_CAPTURE_RATE 120/240, muxed at 30) with
a testable muxer-side timestamp stretch as the equivalent.
Both gates stay off (master flag and recordingEngineReady),
so CameraX slo-mo is untouched until the Phase-1 engine
coupling and an ffprobe-on-device check prove the encoder
honours capture rate.

Verified: camera compiles, 78 camera2 tests pass incl. 16 new
planner/policy/session tests.

Diff

camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.ktnew file mode 100644index 0000000000..9412e03933--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt@@ -0,0 +1,119 @@+package com.vayunmathur.camera.platform++import android.hardware.camera2.CameraManager+import android.media.MediaFormat+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade+import com.vayunmathur.camera.platform.camera2.HighSpeedPlanner+import com.vayunmathur.camera.platform.camera2.HighSpeedSelection+import com.vayunmathur.camera.platform.camera2.SloMoCamera2Gate+import com.vayunmathur.camera.platform.camera2.SloMoEngine+import com.vayunmathur.camera.platform.camera2.SloMoEngineInput+import com.vayunmathur.camera.platform.camera2.SloMoEnginePolicy+import com.vayunmathur.library.log.Log++/**+ * Camera2 migration Phase 5: slo-mo glue between the gated Camera2+ * high-speed session and the existing CameraX slo-mo path.+ *+ * The decision is evaluated only when a gate is on — with both gates off+ * (the default) this file costs one boolean check and SLOW_MO runs exactly+ * as before. When the runtime gate is on, the lens snapshot, planner+ * selection and AVC encoder probe are assembled and [SloMoEnginePolicy]+ * decides; the reason is logged either way. Today the policy always keeps+ * recording on CameraX because `recordingEngineReady` is false: the+ * constrained session (`Camera2HighSpeedSession`) is not yet coupled to+ * the Phase-1 codec/muxer engine and the output has not been+ * device-verified. Flipping the gate therefore changes logging, never the+ * recording path, until that coupling lands.+ */++/** Encoder mime the Phase-1 engine would record slo-mo with. */+private const val SLOMO_ENCODER_MIME = MediaFormat.MIMETYPE_VIDEO_AVC++/**+ * The Phase-1 engine configuration for [selection]: its size, playback+ * rate as the encoder frame rate, and capture rate as `KEY_CAPTURE_RATE`.+ * Building this config does not route any recording — the engine still+ * opens its own (regular) device, so the policy's+ * `recordingEngineReady` stays false until it can be driven by+ * `Camera2HighSpeedSession`'s constrained session.+ */+internal fun HighSpeedSelection.toCustomRecordingConfig(): CustomRecordingConfig =+    CustomRecordingConfig(+        width = size.width,+        height = size.height,+        fps = playbackFps,+        captureFps = captureFps,+        videoMime = SLOMO_ENCODER_MIME,+    )++/** The Camera2 slo-mo decision for one lens snapshot; pure but for logging. */+internal fun CameraViewModel.camera2SloMoDecision(+    facade: CharacteristicsFacade,+    encoderSupportsCaptureRate: Boolean,+): SloMoEngine {+    val snapshot = facade.snapshot+    val selection = HighSpeedPlanner.select(snapshot)+    val input = SloMoEngineInput(+        camera2Enabled = SloMoCamera2Gate.ENABLED && camera2SloMoEnabledMutable.value,+        mode = cameraModeMutable.value,+        lensFacing = snapshot.lensFacing,+        hasConstrainedHighSpeed = snapshot.supportsConstrainedHighSpeedVideo,+        hasSelection = selection != null,+        encoderSupportsCaptureRate = encoderSupportsCaptureRate,+        recordingEngineReady = false,+    )+    val reason = SloMoEnginePolicy.exclusionReason(input)+    Log.debug(+        "SloMo",+        "Camera2 slo-mo decision: engine=${SloMoEnginePolicy.select(input)} " ++            "selection=$selection reason=${reason ?: "none"}",+    )+    return SloMoEnginePolicy.select(input)+}++/**+ * True when some AVC encoder can run at [selection]'s capture rate at its+ * size — the encoder-at-HFR half of the Phase-5 decision. Bitrate is not+ * probed here (the Phase-1 controller owns it); size + frame rate are.+ */+internal fun encoderSupportsSloMoCaptureRate(selection: HighSpeedSelection): Boolean =+    CodecSupport.supportsVideoFrameRate(+        SLOMO_ENCODER_MIME,+        selection.size.width,+        selection.size.height,+        selection.captureFps,+    )++/**+ * Evaluates (and logs) the Camera2 slo-mo decision for the requested back+ * lens when the runtime gate is on; a no-op otherwise. Never routes a+ * recording itself — the CameraX setup that follows remains the live path+ * while the policy excludes Camera2 (see the file doc).+ */+internal fun CameraViewModel.evaluateCamera2SloMoDecision() {+    if (!camera2SloMoEnabledMutable.value) return+    try {+        val lensId = selectedLensMutable.value+            ?.takeIf { it.facing == LensFacing.BACK }+            ?.logicalCameraId+            ?: availableLensesMutable.value+                .firstOrNull { it.facing == LensFacing.BACK }+                ?.logicalCameraId+            ?: return+        val manager = app.getSystemService(CameraManager::class.java) ?: return+        val facade = CharacteristicsFacade.fromCameraManager(manager, lensId)+        val selection = HighSpeedPlanner.select(facade.snapshot)+        camera2SloMoDecision(+            facade,+            encoderSupportsCaptureRate = selection?.let {+                encoderSupportsSloMoCaptureRate(it)+            } ?: false,+        )+    } catch (e: IllegalStateException) {+        Log.status("SloMo", "Camera2 slo-mo decision failed; staying on CameraX", e)+    } catch (e: IllegalArgumentException) {+        Log.status("SloMo", "Camera2 slo-mo decision failed; staying on CameraX", e)+    }+}
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 a5e1d588f3..3ad5297620 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -57,6 +57,13 @@ data class CustomRecordingConfig(     val width: Int,     val height: Int,     val fps: Int = 30,+    /**+     * Rate frames are captured at, when it differs from the playback+     * [fps] (Phase-5 slo-mo: 120/240 captured, 30 played back). Equal to+     * [fps] for normal recording; the encoder is then configured with+     * `KEY_CAPTURE_RATE = captureFps`, `KEY_FRAME_RATE = fps`.+     */+    val captureFps: Int = fps,     val videoMime: String = MediaFormat.MIMETYPE_VIDEO_AVC,     val audioSampleRate: Int = 48_000,     val audioBitrateBps: Int = 128_000,@@ -217,6 +224,11 @@ class Camera2VideoRecordingEngine(                 )                 setInteger(MediaFormat.KEY_BIT_RATE, controller.currentBitrateBps)                 setInteger(MediaFormat.KEY_FRAME_RATE, config.fps)+                // Slo-mo (Phase 5): capture faster than playback so the+                // encoder stretches sample timestamps into a slow MP4.+                if (config.captureFps != config.fps) {+                    setInteger(MediaFormat.KEY_CAPTURE_RATE, config.captureFps)+                }                 setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, config.iFrameIntervalSec)             }         videoCodec = MediaCodec.createEncoderByType(config.videoMime).apply {@@ -303,7 +315,7 @@ class Camera2VideoRecordingEngine(                                 addTarget(reader.surface)                                 set(                                     CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,-                                    android.util.Range(config.fps, config.fps)+                                    android.util.Range(config.captureFps, config.captureFps)                                 )                             }.build()                             try {
camera/src/main/java/com/vayunmathur/camera/platform/CameraSloMoSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSloMoSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSloMoSession.ktindex dc9c48ee74..b3c3d3735a 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSloMoSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSloMoSession.kt@@ -32,6 +32,11 @@ import com.vayunmathur.camera.platform.refreshCapabilities  *   only touches the HFR Recorder built here.  */ suspend fun CameraViewModel.setupHighSpeedSession(): Boolean {+    // Phase 5: evaluate/log the Camera2 slo-mo decision when its gate is+    // on. It never routes the recording today (SloMoEnginePolicy keeps+    // CameraX while the recording engine is uncoupled/unverified), so the+    // CameraX setup below is unchanged in every configuration.+    evaluateCamera2SloMoDecision()     return try {         val session = prepareHighSpeedSession() ?: return false         if (!bindHfrLadder(session)) return false
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 ecd6840bd1..36964ba011 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -170,6 +170,21 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {         camera2PreviewEnabledMutable.value = enabled     } +    /**+     * Gate for the Camera2 slo-mo path (Phase 5). Default OFF — SLOW_MO+     * stays on the CameraX high-speed session and the Camera2 decision in+     * `Camera2SloMoGlue` is not even evaluated. In-memory only;+     * `SloMoEnginePolicy` further requires a constrained-HFR lens, a+     * capable encoder and a coupled, device-verified recording engine.+     */+    internal val camera2SloMoEnabledMutable = MutableStateFlow(false)+    val camera2SloMoEnabled = camera2SloMoEnabledMutable.asStateFlow()++    /** Turns the Camera2 slo-mo gate on/off (SLOW_MO only; see SloMoEnginePolicy). */+    fun setCamera2SloMoEnabled(enabled: Boolean) {+        camera2SloMoEnabledMutable.value = enabled+    }+     /**      * 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/CodecSupport.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.ktindex 1b0618a653..10f30059db 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt@@ -77,6 +77,34 @@ object CodecSupport {         false     } +    /**+     * True when some encoder for [mimeType] supports [fps] at+     * [width]x[height], ignoring bitrate. Used by the Phase-5 slo-mo+     * decision: an encoder that cannot take 120/240 fps input at the+     * high-speed size cannot record slo-mo, whatever its bitrate range.+     */+    fun supportsVideoFrameRate(+        mimeType: String,+        width: Int,+        height: Int,+        fps: Int,+    ): Boolean = try {+        val list = android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS)+        list.codecInfos.any { info ->+            if (!info.isEncoder) return@any false+            val caps = try {+                info.getCapabilitiesForType(mimeType)+            } catch (_: IllegalArgumentException) {+                return@any false+            }+            val video = caps.videoCapabilities ?: return@any false+            video.isSizeSupported(width, height) &&+                video.getSupportedFrameRatesFor(width, height).contains(fps.toDouble())+        }+    } catch (_: Exception) {+        false+    }+     /**      * Default recording codec (issue #757): HEVC when the Recorder supports it, else AVC.      * AV1 hardware encoders stall on several devices, so AV1 stays opt-in via Settings.
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 11a2a927c6..711a747fc5 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@@ -4,6 +4,7 @@ import android.annotation.SuppressLint import android.content.Context import android.graphics.Rect import android.hardware.camera2.CameraCaptureSession+import android.hardware.camera2.CameraConstrainedHighSpeedCaptureSession import android.hardware.camera2.CameraDevice import android.hardware.camera2.CameraManager import android.hardware.camera2.CaptureRequest@@ -52,6 +53,20 @@ interface CaptureSessionCallback { interface DeviceHandle {     val cameraId: String     fun createCaptureSession(surfaces: List<Surface>, callback: CaptureSessionCallback)++    /**+     * Creates a constrained high-speed session (Phase 5) over [surfaces],+     * which must be a combination the HAL advertised for high speed. The+     * default fails the configure: silently substituting a regular session+     * would record realtime video and call it slo-mo.+     */+    fun createConstrainedHighSpeedCaptureSession(+        surfaces: List<Surface>,+        callback: CaptureSessionCallback,+    ) {+        callback.onConfigureFailed()+    }+     fun close() } @@ -73,6 +88,18 @@ interface CaptureSessionHandle {      * carries the `CaptureResult` metadata for the same frame.      */     fun captureStill(params: ResolvedStillParams, stillTarget: Surface, callback: StillResultCallback)++    /**+     * Issues [params] as the TEMPLATE_RECORD repeating burst on [targets]+     * (encoder surface first, preview second) of a constrained high-speed+     * session. Only valid on a session created via+     * [DeviceHandle.createConstrainedHighSpeedCaptureSession]; the default+     * throws rather than issuing a regular repeating request at HFR.+     */+    fun setRepeatingHighSpeed(params: ResolvedHighSpeedParams, targets: List<Surface>) {+        throw IllegalStateException("not a constrained high-speed session")+    }+     fun close() } @@ -167,6 +194,20 @@ internal fun CaptureRequest.Builder.applyStillParams(     } } +/** Applies resolved high-speed fields onto a TEMPLATE_RECORD builder. */+internal fun CaptureRequest.Builder.applyHighSpeedParams(+    params: ResolvedHighSpeedParams,+    targets: List<Surface>,+) {+    targets.forEach { addTarget(it) }+    set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO)+    set(CaptureRequest.CONTROL_AF_MODE, params.afMode)+    set(CaptureRequest.CONTROL_AE_MODE, params.aeMode)+    // Exact fixed range: no AE wandering to a lower rate mid-recording.+    set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, params.aeTargetFpsRange)+    set(CaptureRequest.FLASH_MODE, params.flashMode)+}+ /** Extracts the pure metadata shape from a completed capture result. */ internal fun TotalCaptureResult.toRawStillMetadata(): RawStillMetadata = RawStillMetadata(     sensorTimestampNs = get(CaptureResult.SENSOR_TIMESTAMP),@@ -256,6 +297,34 @@ private class AndroidDeviceHandle(         }     } +    override fun createConstrainedHighSpeedCaptureSession(+        surfaces: List<Surface>,+        callback: CaptureSessionCallback,+    ) {+        val stateCallback = object : CameraCaptureSession.StateCallback() {+            override fun onConfigured(session: CameraCaptureSession) =+                callback.onConfigured(AndroidCaptureSessionHandle(device, session, handler))++            override fun onConfigureFailed(session: CameraCaptureSession) =+                callback.onConfigureFailed()++            override fun onClosed(session: CameraCaptureSession) = callback.onClosed()+        }+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {+            val outputs = surfaces.map { OutputConfiguration(it) }+            val config = SessionConfiguration(+                SessionConfiguration.SESSION_HIGH_SPEED,+                outputs,+                { command -> handler.post(command) },+                stateCallback,+            )+            device.createCaptureSession(config)+        } else {+            @Suppress("DEPRECATION")+            device.createConstrainedHighSpeedCaptureSession(surfaces, stateCallback, handler)+        }+    }+     override fun close() = device.close() } @@ -271,6 +340,17 @@ private class AndroidCaptureSessionHandle(         session.setRepeatingRequest(builder.build(), null, handler)     } +    override fun setRepeatingHighSpeed(params: ResolvedHighSpeedParams, targets: List<Surface>) {+        val highSpeed = session as? CameraConstrainedHighSpeedCaptureSession+            ?: throw IllegalStateException("not a constrained high-speed session")+        val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD)+        builder.applyHighSpeedParams(params, targets)+        // High-speed sessions only accept requests batched via the+        // high-speed request list, issued as a repeating burst.+        val requests = highSpeed.createHighSpeedRequestList(builder.build())+        highSpeed.setRepeatingBurst(requests, null, handler)+    }+     override fun captureStill(         params: ResolvedStillParams,         stillTarget: Surface,
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.ktnew file mode 100644index 0000000000..2c0289fa0e--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt@@ -0,0 +1,214 @@+package com.vayunmathur.camera.platform.camera2++import android.view.Surface++/**+ * Camera2 migration Phase 5: constrained high-speed session core.+ *+ * Opens a `CameraDevice` through the Phase-2 driver seam, configures a+ * constrained high-speed capture session over an encoder surface plus a+ * preview surface, and streams a `TEMPLATE_RECORD` repeating burst pinned+ * to the selection's exact FPS range (see [HighSpeedPlanner]).+ *+ * This class owns the camera/session only — not the codec or muxer. The+ * caller supplies the encoder surface (the Phase-1 engine's MediaCodec+ * input, configured from [HighSpeedSelection.encoderPlan]) and keeps+ * ownership of it; coupling that engine to this session is the remaining+ * live-path work, so [SloMoEnginePolicy] keeps recording on CameraX until+ * it is done and device-verified.+ *+ * 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 Camera2HighSpeedSession(+    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(selection: HighSpeedSelection) {}+    }++    val state: SessionState get() = stateMachine.state++    private var device: DeviceHandle? = null+    private var captureSession: CaptureSessionHandle? = null+    private var selection: HighSpeedSelection? = null++    /**+     * Opens [cameraId] for slo-mo: [encoderSurface] receives the HFR frames+     * for the codec, [previewSurface] the viewfinder. The operating point+     * is re-selected from the snapshot here (never trusted from the+     * caller); when the lens offers no honest point, [Listener.onError]+     * fires and the device is never opened.+     */+    fun open(cameraId: String, encoderSurface: Surface, previewSurface: Surface) {+        executor.execute {+            if (stateMachine.state != SessionState.CLOSED) return@execute+            val selected = HighSpeedPlanner.select(snapshot)+            if (selected == null) {+                reportError("no constrained high-speed slo-mo point for camera $cameraId")+                return@execute+            }+            selection = selected+            if (transition(SessionEvent.OPEN_REQUESTED) !is TransitionResult.Applied) {+                return@execute+            }+            val gen = stateMachine.generation+            runCatching {+                driver.openCamera(cameraId, DeviceCallbackImpl(gen, encoderSurface, previewSurface))+            }.onFailure {+                dispatch(gen, SessionEvent.ERROR_OCCURRED)+                reportError("openCamera failed for $cameraId: ${it.message}")+            }+        }+    }++    /** The operating point chosen at [open], or null before a successful open. */+    fun currentSelection(): HighSpeedSelection? = selection++    /**+     * Tears the session down: bumps the generation first (so callbacks+     * already in flight go stale), then closes the capture session and the+     * device. Idempotent. The encoder/preview surfaces are caller-owned+     * and are not released here.+     */+    fun close() {+        executor.execute {+            if (stateMachine.state == SessionState.CLOSED) return@execute+            val gen = stateMachine.beginTeardown()+            runCatching { captureSession?.close() }+            captureSession = null+            runCatching { device?.close() }+            device = null+            dispatch(gen, SessionEvent.DEVICE_CLOSED)+            if (stateMachine.state == SessionState.CLOSING) {+                stateMachine.completeTeardown()+            }+            notifyState()+        }+    }++    // -- internals (executor thread only) ------------------------------------++    private fun configureSession(+        opened: DeviceHandle,+        gen: Long,+        encoderSurface: Surface,+        previewSurface: Surface,+    ) {+        if (transition(SessionEvent.CONFIGURE_REQUESTED) !is TransitionResult.Applied) return+        runCatching {+            opened.createConstrainedHighSpeedCaptureSession(+                listOf(encoderSurface, previewSurface),+                SessionCallbackImpl(gen, encoderSurface, previewSurface),+            )+        }.onFailure {+            dispatch(gen, SessionEvent.CONFIGURE_FAILED)+            reportError("createConstrainedHighSpeedCaptureSession failed: ${it.message}")+        }+    }++    private fun issueRepeatingRequest(encoderSurface: Surface, previewSurface: Surface) {+        val session = captureSession ?: return+        val selected = selection ?: return+        if (stateMachine.state != SessionState.STREAMING) return+        val params = HighSpeedPlanner.resolveRequest(selected)+        runCatching {+            session.setRepeatingHighSpeed(params, listOf(encoderSurface, previewSurface))+        }.onFailure { reportError("setRepeatingHighSpeed 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,+        private val encoderSurface: Surface,+        private val previewSurface: Surface,+    ) : 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, encoderSurface, previewSurface)+        }++        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,+        private val encoderSurface: Surface,+        private val previewSurface: Surface,+    ) : 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(encoderSurface, previewSurface)+            selection?.let { listener?.onStreaming(it) }+        }++        override fun onConfigureFailed() {+            if (!stateMachine.isCurrent(gen)) return+            dispatch(gen, SessionEvent.CONFIGURE_FAILED)+            reportError("constrained high-speed session configure failed")+        }++        override fun onClosed() {+            // Session close follows device teardown; the device callback+            // drives the machine to 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 a0b166188d..676b95a4e0 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@@ -112,6 +112,19 @@ data class LensCharacteristicsSnapshot(      */     val maxAfRegions: Int = 0,     val maxAeRegions: Int = 0,+    /**+     * Sizes legal for a constrained high-speed session+     * (`StreamConfigurationMap.getHighSpeedVideoSizes`); empty when the lens+     * advertises none. Phase 5 (slo-mo) selects the encoder/preview size+     * exclusively from this list — a regular stream size is not a substitute.+     */+    val highSpeedVideoSizes: List<Size> = emptyList(),+    /**+     * Advertised FPS ranges keyed by high-speed size+     * (`getHighSpeedVideoFpsRangesFor`). Only fixed ranges (lower == upper)+     * are usable for a pinned slo-mo request; see `HighSpeedPlanner`.+     */+    val highSpeedFpsRangesBySize: Map<Size, List<Range<Int>>> = emptyMap(),     /**      * True when `CONTROL_ZOOM_RATIO_RANGE` itself was reported, i.e. the      * request key `CONTROL_ZOOM_RATIO` is honoured. False when [zoomRatioRange]@@ -134,6 +147,10 @@ data class LensCharacteristicsSnapshot(             CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING in availableCapabilities     val supportsManualSensor: Boolean         get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR in availableCapabilities+    /** True when the HAL offers `CONSTRAINED_HIGH_SPEED_VIDEO` (Phase 5). */+    val supportsConstrainedHighSpeedVideo: Boolean+        get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO in+            availableCapabilities     fun hasExtension(mode: Int): Boolean = mode in availableExtensionModes } @@ -181,6 +198,8 @@ class CharacteristicsFacade private constructor(             maxAeRegions: Int = 0,             supportsZoomRatioKey: Boolean = zoomRatioRange != null,             surfaceTextureSizes: List<Size> = emptyList(),+            highSpeedVideoSizes: List<Size> = emptyList(),+            highSpeedFpsRangesBySize: Map<Size, List<Range<Int>>> = emptyMap(),         ): CharacteristicsFacade = fromSnapshot(             LensCharacteristicsSnapshot(                 cameraId = cameraId,@@ -209,6 +228,8 @@ class CharacteristicsFacade private constructor(                 maxAfRegions = maxAfRegions,                 maxAeRegions = maxAeRegions,                 supportsZoomRatioKey = supportsZoomRatioKey,+                highSpeedVideoSizes = highSpeedVideoSizes,+                highSpeedFpsRangesBySize = highSpeedFpsRangesBySize,             ),         ) @@ -244,6 +265,17 @@ class CharacteristicsFacade private constructor(             } else {                 emptySet()             }+            // Constrained-high-speed tables live on the same stream map but+            // are not part of the generic format summary: read them once here.+            val streamMap = get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)+            val highSpeedSizes = runCatching {+                streamMap?.highSpeedVideoSizes?.toList().orEmpty()+            }.getOrDefault(emptyList())+            val highSpeedRanges = highSpeedSizes.associateWith { size ->+                runCatching {+                    streamMap?.getHighSpeedVideoFpsRangesFor(size)?.toList().orEmpty()+                }.getOrDefault(emptyList())+            }             return fromSnapshot(                 LensCharacteristicsSnapshot(                     cameraId = cameraId,@@ -280,6 +312,8 @@ class CharacteristicsFacade private constructor(                     maxAfRegions = get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF) ?: 0,                     maxAeRegions = get(CameraCharacteristics.CONTROL_MAX_REGIONS_AE) ?: 0,                     supportsZoomRatioKey = zoomRatioRange != null,+                    highSpeedVideoSizes = highSpeedSizes,+                    highSpeedFpsRangesBySize = highSpeedRanges,                 ),             )         }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/HighSpeedCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/HighSpeedCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/HighSpeedCapture.ktnew file mode 100644index 0000000000..ee6094a4e2--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/HighSpeedCapture.kt@@ -0,0 +1,148 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraMetadata+import android.util.Range++/**+ * Camera2 migration Phase 5: slo-mo on a constrained high-speed session.+ *+ * Today SLOW_MO uses CameraX `HighSpeedVideoSessionConfig`+ * (`setSlowMotionEnabled(true)`, a pinned HFR range, `SLOMO_<ts>.mp4`, no+ * audio, saved through `saveVideoStaged`). The Camera2 equivalent is a+ * `ConstrainedHighSpeedCaptureSession` whose repeating `TEMPLATE_RECORD`+ * request is pinned to one exact FPS range and targets a MediaCodec encoder+ * surface (plus preview). This file is the pure half: it selects the+ * size/range from the facade snapshot and resolves the exact request and+ * encoder fields. No trial binds, no HAL iteration order leaks in.+ *+ * Slow-motion marking (the UI/container contract): CameraX writes no+ * proprietary slo-mo atom — the recorded MP4 *is* slow because its video+ * track timestamps/frame-rate play at normal speed while frames were+ * captured at HFR. The Camera2 encoder contract mirrors that with+ * `MediaFormat.KEY_CAPTURE_RATE = captureFps` and+ * `KEY_FRAME_RATE = playbackFps` (30): a conforming encoder stretches the+ * sample timestamps by capture/playback, so players need no extra+ * metadata. [HighSpeedSelection.stretchedPtsUs] is the same stretch, kept+ * pure so a muxer-side fallback can be tested without a codec. If a+ * device's encoder ignores `KEY_CAPTURE_RATE`, the file would be realtime+ * HFR, not slo-mo — that is a device-verification remainder, not something+ * a metadata flag can fix after the fact, and it keeps the gate off.+ *+ * Output decision: when the snapshot carries the constrained capability+ * plus a usable fixed range/size, the output is the encoder surface+ * ([HighSpeedOutput.ENCODER_SURFACE]). A stills-style YUV/JPEG burst was+ * rejected as the fallback: it has no container, no audio/timing contract+ * and cannot land through `saveVideoStaged` as an MP4, so presenting it as+ * slo-mo would be dishonest. Devices without a usable selection stay on+ * CameraX (`SloMoEnginePolicy`).+ */++/** Which output a high-speed session feeds. */+enum class HighSpeedOutput { ENCODER_SURFACE, NONE }++/** Encoder fields for one slo-mo recording (Phase-1 engine vocabulary). */+data class HighSpeedEncoderPlan(+    val width: Int,+    val height: Int,+    /** `MediaFormat.KEY_FRAME_RATE`: the rate the MP4 plays back at. */+    val frameRateFps: Int,+    /** `MediaFormat.KEY_CAPTURE_RATE`: the rate frames are captured at. */+    val captureRateFps: Int,+)++/** One selected slo-mo operating point. */+data class HighSpeedSelection(+    val size: FrameSize,+    /** Exact fixed range to pin (`lower == upper == captureFps`). */+    val fpsRange: Range<Int>,+    val captureFps: Int,+    val playbackFps: Int,+    val output: HighSpeedOutput,+) {+    /** How much slower than realtime playback is (4x at 120 -> 30). */+    val slowdownFactor: Float get() = captureFps.toFloat() / playbackFps.toFloat()++    val encoderPlan: HighSpeedEncoderPlan get() = HighSpeedEncoderPlan(+        width = size.width,+        height = size.height,+        frameRateFps = playbackFps,+        captureRateFps = captureFps,+    )++    /** Muxer-side timestamp stretch, if the encoder did not apply it. */+    fun stretchedPtsUs(realtimePtsUs: Long): Long =+        (realtimePtsUs.toDouble() * captureFps.toDouble() / playbackFps.toDouble()).toLong()+}++/**+ * Resolved `CaptureRequest` fields for the high-speed `TEMPLATE_RECORD`+ * repeating request. The FPS range is the whole point: it is exact and+ * fixed, so AE cannot wander to a lower rate mid-recording.+ */+data class ResolvedHighSpeedParams(+    /** `CONTROL_AE_TARGET_FPS_RANGE`; always `Range(fps, fps)`. */+    val aeTargetFpsRange: Range<Int>,+    val captureFps: Int,+    val playbackFps: Int,+    /** `CONTROL_AE_MODE` (`CameraMetadata.CONTROL_AE_MODE_*`). */+    val aeMode: Int,+    /** `CONTROL_AF_MODE` (`CameraMetadata.CONTROL_AF_MODE_*`). */+    val afMode: Int,+    /** `FLASH_MODE` (`CameraMetadata.FLASH_MODE_*`); slo-mo never flashes. */+    val flashMode: Int,+)++object HighSpeedPlanner {++    /** Playback rate of the slo-mo MP4, matching the CameraX contract. */+    const val PLAYBACK_FPS: Int = 30++    /** Minimum capture rate that counts as true slo-mo (mirrors CameraX HFR). */+    const val MIN_CAPTURE_FPS: Int = 60++    /**+     * Every usable (size, fixed range) candidate in the snapshot. A range+     * is usable only when it is already fixed (lower == upper) and at or+     * above [MIN_CAPTURE_FPS]: pinning a non-advertised fixed range risks+     * a HAL configure failure, so variable ranges are not normalised here.+     */+    fun candidates(snapshot: LensCharacteristicsSnapshot): List<HighSpeedSelection> {+        if (!snapshot.supportsConstrainedHighSpeedVideo) return emptyList()+        return snapshot.highSpeedVideoSizes.flatMap { size ->+            val frameSize = FrameSize.from(size)+            snapshot.highSpeedFpsRangesBySize[size].orEmpty()+                .filter { it.lower == it.upper && it.upper >= MIN_CAPTURE_FPS }+                .map { range ->+                    HighSpeedSelection(+                        size = frameSize,+                        fpsRange = Range(range.upper, range.upper),+                        captureFps = range.upper,+                        playbackFps = PLAYBACK_FPS,+                        output = HighSpeedOutput.ENCODER_SURFACE,+                    )+                }+        }+    }++    /**+     * The operating point to record at: highest capture fps first (240+     * over 120, as the CameraX ladder tries ranges highest-first), then+     * largest area, then width/height for determinism. Null when the lens+     * offers no honest slo-mo point — the caller stays on CameraX.+     */+    fun select(snapshot: LensCharacteristicsSnapshot): HighSpeedSelection? =+        candidates(snapshot).maxWithOrNull(+            compareBy({ it.captureFps }, { it.size.area }, { it.size.width }, { it.size.height }),+        )++    /** Resolves the pinned `TEMPLATE_RECORD` fields for [selection]. */+    fun resolveRequest(selection: HighSpeedSelection): ResolvedHighSpeedParams =+        ResolvedHighSpeedParams(+            aeTargetFpsRange = Range(selection.captureFps, selection.captureFps),+            captureFps = selection.captureFps,+            playbackFps = selection.playbackFps,+            aeMode = CameraMetadata.CONTROL_AE_MODE_ON,+            afMode = CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_VIDEO,+            flashMode = CameraMetadata.FLASH_MODE_OFF,+        )+}
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.ktnew file mode 100644index 0000000000..376fa4e64e--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt@@ -0,0 +1,72 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.platform.CameraMode++/** Which engine records SLOW_MO. */+enum class SloMoEngine { CAMERAX, CAMERA2 }++/**+ * Gate for the Camera2 slo-mo path. Default OFF in two independent places:+ * this constant (the compile-time master switch, like+ * `CustomRecordingGate`) and the ViewModel's runtime flow. Either being off+ * keeps every slo-mo recording on CameraX.+ */+object SloMoCamera2Gate {+    const val ENABLED: Boolean = false+}++/** Inputs to the slo-mo engine selection rule. */+data class SloMoEngineInput(+    /** The Phase-5 gate. Default OFF: CameraX remains the live path. */+    val camera2Enabled: Boolean,+    val mode: CameraMode,+    /** Slo-mo is back-only today (enforced by the mode switch and here). */+    val lensFacing: LensFacing?,+    /** `CONSTRAINED_HIGH_SPEED_VIDEO` in the facade snapshot. */+    val hasConstrainedHighSpeed: Boolean = false,+    /** [HighSpeedPlanner] found a fixed HFR size/range on this lens. */+    val hasSelection: Boolean = false,+    /**+     * Some encoder for the selected size can run at the capture rate+     * (probed from `MediaCodec` capabilities by the glue). An encoder that+     * cannot take 120/240 fps input cannot honestly record slo-mo.+     */+    val encoderSupportsCaptureRate: Boolean = false,+    /**+     * The constrained session is coupled to a recording engine (codec ++     * muxer) end to end. False today: `Camera2HighSpeedSession` can stream+     * to an encoder surface, but the Phase-1 engine still opens its own+     * device, so no live recording may be routed here yet. Device+     * verification (encoder honouring `KEY_CAPTURE_RATE`, ffprobe of the+     * output) is also outstanding — see the Phase-5 report.+     */+    val recordingEngineReady: Boolean = false,+)++/**+ * Explicit selection rule for slo-mo, mirroring [StillEnginePolicy]:+ * Camera2 records only when the gate is on *and* every honest-support+ * condition holds. Anything else stays on the CameraX high-speed session,+ * exactly as today.+ */+object SloMoEnginePolicy {++    fun select(input: SloMoEngineInput): SloMoEngine =+        if (exclusionReason(input) == null) SloMoEngine.CAMERA2 else SloMoEngine.CAMERAX++    fun usesCamera2(input: SloMoEngineInput): Boolean = select(input) == SloMoEngine.CAMERA2++    /** Why [input] cannot use Camera2, or null when it can. */+    fun exclusionReason(input: SloMoEngineInput): String? = when {+        !input.camera2Enabled -> "camera2 slo-mo gate off"+        input.mode != CameraMode.SLOW_MO -> "mode ${input.mode} is not SLOW_MO"+        input.lensFacing == LensFacing.FRONT -> "slo-mo is back-camera only"+        !input.hasConstrainedHighSpeed -> "no CONSTRAINED_HIGH_SPEED_VIDEO capability"+        !input.hasSelection -> "no fixed HFR size/range for slo-mo"+        !input.encoderSupportsCaptureRate -> "no encoder supports the capture rate at the selected size"+        !input.recordingEngineReady ->+            "Camera2 slo-mo recording engine not coupled/device-verified yet"+        else -> null+    }+}
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.ktnew file mode 100644index 0000000000..26bbce4c15--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSessionTest.kt@@ -0,0 +1,202 @@+package com.vayunmathur.camera.platform.camera2++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-5 session tests over a fake driver: the constrained-session+ * configure sequence, the pinned repeating request, up-front rejection when+ * the lens has no slo-mo point, and stale-generation drops.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Camera2HighSpeedSessionTest {++    private class FakeHighSpeedHandle : CaptureSessionHandle {+        val highSpeedRequests = mutableListOf<Pair<ResolvedHighSpeedParams, List<Surface>>>()+        var closed = false+        override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}+        override fun captureStill(+            params: ResolvedStillParams,+            stillTarget: Surface,+            callback: StillResultCallback,+        ) {+            callback.onFailed("unused")+        }+        override fun setRepeatingHighSpeed(params: ResolvedHighSpeedParams, targets: List<Surface>) {+            highSpeedRequests += params to targets+        }+        override fun close() { closed = true }+    }++    private class FakeDeviceHandle(+        override val cameraId: String = "0",+        val sessionHandle: FakeHighSpeedHandle = FakeHighSpeedHandle(),+        private val failConfigure: Boolean = false,+    ) : DeviceHandle {+        var constrainedSurfaces: List<Surface>? = null+        var regularSessionRequested = false+        var closed = false+        override fun createCaptureSession(+            surfaces: List<Surface>,+            callback: CaptureSessionCallback,+        ) {+            regularSessionRequested = true+            callback.onConfigured(sessionHandle)+        }+        override fun createConstrainedHighSpeedCaptureSession(+            surfaces: List<Surface>,+            callback: CaptureSessionCallback,+        ) {+            constrainedSurfaces = surfaces+            if (failConfigure) callback.onConfigureFailed() else callback.onConfigured(sessionHandle)+        }+        override fun close() { closed = true }+    }++    private class FakeDriver(+        val device: FakeDeviceHandle = FakeDeviceHandle(),+    ) : Camera2Driver {+        var openedCameraId: String? = null+        override fun openCamera(cameraId: String, callback: DeviceCallback) {+            openedCameraId = cameraId+            callback.onOpened(device)+        }+        override fun createStillOutput(size: FrameSize): StillOutput? = null+    }++    private class RecordingListener : Camera2HighSpeedSession.Listener {+        val errors = mutableListOf<String>()+        val streaming = mutableListOf<HighSpeedSelection>()+        override fun onError(message: String) { errors += message }+        override fun onStreaming(selection: HighSpeedSelection) { streaming += selection }+    }++    private fun snapshot(+        ranges: Map<Size, List<Range<Int>>> = mapOf(+            Size(1280, 720) to listOf(Range(240, 240)),+        ),+    ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+        cameraId = "0",+        lensFacingRaw = CameraMetadata.LENS_FACING_BACK,+        availableCapabilities = setOf(+            CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO,+        ),+        highSpeedVideoSizes = ranges.keys.toList(),+        highSpeedFpsRangesBySize = ranges,+    ).snapshot++    private fun Camera2Executor.drain() {+        val latch = CountDownLatch(1)+        execute { latch.countDown() }+        assertTrue(latch.await(5, TimeUnit.SECONDS), "executor did not drain")+    }++    @Test fun openConfiguresConstrainedSessionAndPinsFixedRange() {+        val executor = Camera2Executor("HighSpeedSessionTest-seq")+        try {+            val driver = FakeDriver()+            val listener = RecordingListener()+            val session = Camera2HighSpeedSession(driver, executor, snapshot(), listener = listener)+            val encoder = mock(Surface::class.java)+            val preview = mock(Surface::class.java)++            session.open("0", encoder, preview)+            executor.drain()++            assertEquals("0", driver.openedCameraId)+            assertEquals(SessionState.STREAMING, session.state)+            // Constrained seam used, regular session never requested, and the+            // encoder surface is the first target.+            assertTrue(!driver.device.regularSessionRequested)+            assertEquals(listOf(encoder, preview), driver.device.constrainedSurfaces)+            val (params, targets) = driver.device.sessionHandle.highSpeedRequests.single()+            assertEquals(listOf(encoder, preview), targets)+            assertEquals(Range(240, 240), params.aeTargetFpsRange)+            assertEquals(240, session.currentSelection()?.captureFps)+            assertEquals(240, listener.streaming.single().captureFps)++            session.close()+            executor.drain()+            assertEquals(SessionState.CLOSED, session.state)+            assertTrue(driver.device.sessionHandle.closed)+            assertTrue(driver.device.closed)+        } finally {+            executor.shutdown()+        }+    }++    @Test fun noSloMoPointFailsBeforeOpeningDevice() {+        val executor = Camera2Executor("HighSpeedSessionTest-none")+        try {+            val driver = FakeDriver()+            val listener = RecordingListener()+            val session = Camera2HighSpeedSession(+                driver, executor, snapshot(ranges = emptyMap()), listener = listener,+            )+            session.open("0", mock(Surface::class.java), mock(Surface::class.java))+            executor.drain()+            assertEquals(null, driver.openedCameraId)+            assertEquals(SessionState.CLOSED, session.state)+            assertTrue(listener.errors.single().contains("no constrained high-speed"))+        } finally {+            executor.shutdown()+        }+    }++    @Test fun configureFailureReportsErrorAndStaysOpen() {+        val executor = Camera2Executor("HighSpeedSessionTest-cfgfail")+        try {+            val driver = FakeDriver(FakeDeviceHandle(failConfigure = true))+            val listener = RecordingListener()+            val session = Camera2HighSpeedSession(driver, executor, snapshot(), listener = listener)+            session.open("0", mock(Surface::class.java), mock(Surface::class.java))+            executor.drain()+            assertEquals(SessionState.OPEN, session.state)+            assertTrue(listener.errors.any { it.contains("configure failed") })+            assertTrue(listener.streaming.isEmpty())+        } finally {+            executor.shutdown()+        }+    }++    @Test fun staleOpenCompletionIsDroppedAndDeviceClosed() {+        val executor = Camera2Executor("HighSpeedSessionTest-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? = null+            }+            val session = Camera2HighSpeedSession(driver, executor, snapshot())+            session.open("0", mock(Surface::class.java), mock(Surface::class.java))+            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.constrainedSurfaces)+        } finally {+            executor.shutdown()+        }+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.ktnew file mode 100644index 0000000000..64d09f62e7--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.kt@@ -0,0 +1,144 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraMetadata+import android.util.Range+import com.vayunmathur.camera.platform.toCustomRecordingConfig+import android.util.Size+import kotlin.test.assertEquals+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-5 planner tests over fake characteristics: size/range selection,+ * the fixed-FPS request resolution, and the encoder/timestamp contract.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class HighSpeedCaptureTest {++    private fun snapshot(+        capabilities: Set<Int> = setOf(+            CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO,+        ),+        sizes: List<Size> = listOf(Size(1920, 1080), Size(1280, 720)),+        ranges: Map<Size, List<Range<Int>>> = mapOf(+            Size(1920, 1080) to listOf(Range(120, 120), Range(60, 60)),+            Size(1280, 720) to listOf(Range(240, 240), Range(120, 120)),+        ),+    ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+        cameraId = "0",+        lensFacingRaw = CameraMetadata.LENS_FACING_BACK,+        availableCapabilities = capabilities,+        highSpeedVideoSizes = sizes,+        highSpeedFpsRangesBySize = ranges,+    ).snapshot++    @Test fun facadeSnapshotCarriesHighSpeedTables() {+        val s = snapshot()+        assertTrue(s.supportsConstrainedHighSpeedVideo)+        assertEquals(listOf(Size(1920, 1080), Size(1280, 720)), s.highSpeedVideoSizes)+        assertEquals(+            listOf(Range(240, 240), Range(120, 120)),+            s.highSpeedFpsRangesBySize[Size(1280, 720)],+        )+    }++    @Test fun selectsHighestFpsThenLargestSize() {+        val selected = HighSpeedPlanner.select(snapshot())+        assertEquals(240, selected?.captureFps)+        assertEquals(FrameSize(1280, 720), selected?.size)++        // Without a 240 point, 120 at the larger size wins over 120 small.+        val no240 = snapshot(+            ranges = mapOf(+                Size(1920, 1080) to listOf(Range(120, 120)),+                Size(1280, 720) to listOf(Range(120, 120), Range(60, 60)),+            ),+        )+        val selected120 = HighSpeedPlanner.select(no240)+        assertEquals(120, selected120?.captureFps)+        assertEquals(FrameSize(1920, 1080), selected120?.size)+    }++    @Test fun selectionIsDeterministicRegardlessOfAdvertisedOrder() {+        val shuffled = snapshot(+            sizes = listOf(Size(1280, 720), Size(1920, 1080)),+            ranges = mapOf(+                Size(1280, 720) to listOf(Range(120, 120), Range(240, 240)),+                Size(1920, 1080) to listOf(Range(60, 60), Range(120, 120)),+            ),+        )+        assertEquals(HighSpeedPlanner.select(snapshot()), HighSpeedPlanner.select(shuffled))+    }++    @Test fun noCapabilityOrNoFixedRangeMeansNoSelection() {+        assertNull(+            HighSpeedPlanner.select(snapshot(capabilities = emptySet())),+            "without CONSTRAINED_HIGH_SPEED_VIDEO there is no slo-mo point",+        )+        assertNull(+            HighSpeedPlanner.select(+                snapshot(ranges = mapOf(Size(1920, 1080) to listOf(Range(30, 120)))),+            ),+            "a variable range must not be normalised into a pinned one",+        )+        assertNull(+            HighSpeedPlanner.select(+                snapshot(ranges = mapOf(Size(1920, 1080) to listOf(Range(30, 30)))),+            ),+            "30 fps is not slo-mo",+        )+        assertNull(HighSpeedPlanner.select(snapshot(sizes = emptyList(), ranges = emptyMap())))+    }++    @Test fun requestIsTemplateRecordShapedAndFixedRange() {+        val selection = HighSpeedPlanner.select(snapshot())!!+        val params = HighSpeedPlanner.resolveRequest(selection)+        // Exact fixed range: lower == upper == capture fps, no AE wandering.+        assertEquals(Range(240, 240), params.aeTargetFpsRange)+        assertEquals(params.aeTargetFpsRange.lower, params.aeTargetFpsRange.upper)+        assertEquals(240, params.captureFps)+        assertEquals(HighSpeedPlanner.PLAYBACK_FPS, params.playbackFps)+        assertEquals(CameraMetadata.CONTROL_AE_MODE_ON, params.aeMode)+        assertEquals(CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_VIDEO, params.afMode)+        assertEquals(CameraMetadata.FLASH_MODE_OFF, params.flashMode)+    }++    @Test fun encoderPlanAndTimestampStretchMatchPlaybackContract() {+        val selection = HighSpeedPlanner.select(snapshot())!!+        assertEquals(HighSpeedOutput.ENCODER_SURFACE, selection.output)+        val plan = selection.encoderPlan+        assertEquals(1280, plan.width)+        assertEquals(720, plan.height)+        // Captured at 240, played at 30: KEY_CAPTURE_RATE vs KEY_FRAME_RATE.+        assertEquals(240, plan.captureRateFps)+        assertEquals(30, plan.frameRateFps)+        assertEquals(8f, selection.slowdownFactor)+        // Two realtime seconds become sixteen seconds of playback.+        assertEquals(16_000_000L, selection.stretchedPtsUs(2_000_000L))+        assertEquals(0L, selection.stretchedPtsUs(0L))+    }++    @Test fun selectionMapsOntoPhase1EncoderConfig() {+        val selection = HighSpeedPlanner.select(snapshot())!!+        val config = selection.toCustomRecordingConfig()+        assertEquals(1280, config.width)+        assertEquals(720, config.height)+        assertEquals(30, config.fps)+        assertEquals(240, config.captureFps)+        assertEquals(android.media.MediaFormat.MIMETYPE_VIDEO_AVC, config.videoMime)+    }++    @Test fun sixtyFpsIsTheSlowestHonestPoint() {+        val only60 = snapshot(+            ranges = mapOf(Size(1280, 720) to listOf(Range(60, 60))),+        )+        val selection = HighSpeedPlanner.select(only60)+        assertEquals(60, selection?.captureFps)+        assertEquals(2f, selection?.slowdownFactor)+    }+}
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.ktnew file mode 100644index 0000000000..aba967cf3e--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.domain.LensFacing+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-5 gating: Camera2 slo-mo only when every honest condition holds. */+class SloMoEnginePolicyTest {++    private fun readyInput(+        camera2Enabled: Boolean = true,+        mode: CameraMode = CameraMode.SLOW_MO,+        lensFacing: LensFacing? = LensFacing.BACK,+        hasConstrainedHighSpeed: Boolean = true,+        hasSelection: Boolean = true,+        encoderSupportsCaptureRate: Boolean = true,+        recordingEngineReady: Boolean = true,+    ) = SloMoEngineInput(+        camera2Enabled = camera2Enabled,+        mode = mode,+        lensFacing = lensFacing,+        hasConstrainedHighSpeed = hasConstrainedHighSpeed,+        hasSelection = hasSelection,+        encoderSupportsCaptureRate = encoderSupportsCaptureRate,+        recordingEngineReady = recordingEngineReady,+    )++    @Test fun gateOffAlwaysCameraX() {+        assertEquals(SloMoEngine.CAMERAX, SloMoEnginePolicy.select(readyInput(camera2Enabled = false)))+        assertTrue(SloMoEnginePolicy.exclusionReason(readyInput(camera2Enabled = false))!!.contains("gate off"))+    }++    @Test fun masterGateConstantIsOff() {+        assertFalse(SloMoCamera2Gate.ENABLED, "Phase 5 ships with the gate off (device unverified)")+    }++    @Test fun allConditionsMetSelectsCamera2() {+        val input = readyInput()+        assertEquals(SloMoEngine.CAMERA2, SloMoEnginePolicy.select(input))+        assertTrue(SloMoEnginePolicy.usesCamera2(input))+        assertNull(SloMoEnginePolicy.exclusionReason(input))+    }++    @Test fun everyMissingConditionStaysOnCameraX() {+        val cases = listOf(+            readyInput(mode = CameraMode.VIDEO) to "not SLOW_MO",+            readyInput(lensFacing = LensFacing.FRONT) to "back-camera only",+            readyInput(hasConstrainedHighSpeed = false) to "CONSTRAINED_HIGH_SPEED_VIDEO",+            readyInput(hasSelection = false) to "no fixed HFR",+            readyInput(encoderSupportsCaptureRate = false) to "no encoder supports",+            readyInput(recordingEngineReady = false) to "not coupled/device-verified",+        )+        for ((input, fragment) in cases) {+            assertEquals(SloMoEngine.CAMERAX, SloMoEnginePolicy.select(input), fragment)+            assertFalse(SloMoEnginePolicy.usesCamera2(input), fragment)+            assertTrue(+                SloMoEnginePolicy.exclusionReason(input)!!.contains(fragment),+                "reason for $fragment",+            )+        }+    }++    @Test fun gateOffReasonWinsOverOtherExclusions() {+        // The gate is reported first so a disabled path never looks like a+        // device-capability failure in logs.+        val input = readyInput(camera2Enabled = false, hasConstrainedHighSpeed = false)+        assertTrue(SloMoEnginePolicy.exclusionReason(input)!!.contains("gate off"))+    }+}