Modern Apps git

← Modern-Apps.git

camera: adaptive bitrate - scene-aware up front, Camera2 path for live control

Commit
b3853f8da11d1a2b30adb106e87be5092c063a4e
Author
Vayun Mathur <[email protected]>
When
2026-11-21 17:08 UTC (14 days ago)
Parents
934d35c
Bitrate was a fixed ladder. A scene-motion estimator (frame
differences over the analysis stream) now classifies static/
moderate/high-motion at record start: static scenes record at
~50-60% of the rung, high motion at the rung plus a probed
+25% where the encoder supports it, never below a 40% floor;
low storage or thermal pressure steps the rung down and says
so ('Lower bitrate: low storage'). The CameraX decision is
consumed once before prepareRecording - no stop/restart
tricks mid-take.

For during-recording adaptation, a Camera2-first engine now
exists behind a disabled gate: own CameraDevice/session over
encoder+preview+analysis surfaces, MediaCodec bitrate
re-targeted live every 2s with hysteresis and slew limits,
AudioRecord->AAC->muxer, and MediaExtractor read-back
validation that deletes invalid output rather than handing
back corrupt files. It stays OFF until device verification
(preview handoff and EOS hardening listed in the change);
HLG/stabilization/AV1 stay on the CameraX path honestly.

Verified: adaptive policy matrix + estimator tests pass;
camera suite green for affected classes.

Diff

camera/src/main/java/com/vayunmathur/camera/domain/AdaptiveVideoBitrate.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/AdaptiveVideoBitrate.kt b/camera/src/main/java/com/vayunmathur/camera/domain/AdaptiveVideoBitrate.ktnew file mode 100644index 0000000000..038ef0f895--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/AdaptiveVideoBitrate.kt@@ -0,0 +1,218 @@+package com.vayunmathur.camera.domain++import kotlin.math.roundToInt++/** How much the preview scene is moving, from the analysis stream (see [SceneMotionEstimator]). */+enum class SceneMotion { STATIC, MODERATE, HIGH_MOTION }++/**+ * One rung of the video bitrate ladder. This is the single source for the values the+ * Recorder is built with (UHD 48 / FHD 25 / HD 12 / SD 6 Mbps at 30 fps); the platform+ * layer maps CameraX qualities onto these tiers so the policy stays CameraX-free.+ */+enum class VideoQualityTier(val baseBitrateBps: Int, val width: Int, val height: Int) {+    UHD(48_000_000, 3840, 2160),+    FHD(25_000_000, 1920, 1080),+    HD(12_000_000, 1280, 720),+    SD(6_000_000, 720, 480);++    /** Next lower rung; SD has none and stays SD. */+    fun lower(): VideoQualityTier = when (this) {+        UHD -> FHD+        FHD -> HD+        HD -> SD+        SD -> SD+    }+}++/** Thermal pressure as the policy needs it; the platform maps PowerManager onto this. */+enum class ThermalPressure { NORMAL, SEVERE, UNKNOWN }++/** Why a decision was forced below the scene's natural bitrate. */+enum class AdaptiveReduction { LOW_STORAGE, THERMAL }++/**+ * Everything [AdaptiveVideoBitratePolicy] decides from, snapshotted before a recording.+ *+ * @property motion latest scene classification, or null when the estimator has no+ *   samples yet (recording pressed before the analysis stream warmed up). Null is+ *   treated as "no evidence to save bits": the rung is used as-is.+ * @property freeStorageBytes bytes free where the recording is staged, or null when+ *   the probe failed. Null never forces a reduction.+ * @property boostAllowed the encoder probe confirmed the boosted bitrate is inside+ *   the chosen codec's supported range at this tier's resolution/frame rate.+ */+data class AdaptiveBitrateInput(+    val baseTier: VideoQualityTier,+    val motion: SceneMotion?,+    val freeStorageBytes: Long?,+    val thermal: ThermalPressure,+    val boostAllowed: Boolean,+)++/**+ * The bitrate to build the Recorder with, plus why.+ *+ * @property effectiveTier rung after storage/thermal step-downs. Only the bitrate+ *   steps down; the recorded resolution (QualitySelector) never changes here.+ * @property reductions forced step-downs that were applied (empty for scene-only cuts).+ */+data class AdaptiveBitrateDecision(+    val bitrateBps: Int,+    val baseTier: VideoQualityTier,+    val effectiveTier: VideoQualityTier,+    val motion: SceneMotion?,+    val reductions: Set<AdaptiveReduction>,+    val boosted: Boolean,+) {+    /** True when storage/thermal actually lowered the bitrate below the base rung. */+    val forcedReduction: Boolean+        get() = reductions.isNotEmpty() && bitrateBps < baseTier.baseBitrateBps+}++/**+ * Pure adaptive-bitrate policy: scene motion scales the rung, storage/thermal step+ * the rung down, and a quality floor keeps any combination from starving the encoder.+ *+ * Deliberately has no notion of changing a bitrate mid-recording: CameraX fixes the+ * Recorder's target bitrate when the Recorder is built, so a decision is only ever+ * consumed before `prepareRecording`.+ */+object AdaptiveVideoBitratePolicy {+    /** Below this much free space the policy steps down one rung (~500 MB). */+    const val LOW_STORAGE_THRESHOLD_BYTES: Long = 500L * 1024 * 1024++    const val STATIC_FACTOR: Double = 0.55+    const val MODERATE_FACTOR: Double = 0.80+    const val HIGH_MOTION_FACTOR: Double = 1.0+    const val HIGH_MOTION_BOOST_FACTOR: Double = 1.25++    /** No decision may fall below this fraction of its effective rung. */+    const val QUALITY_FLOOR_FRACTION: Double = 0.40++    fun decide(input: AdaptiveBitrateInput): AdaptiveBitrateDecision {+        var tier = input.baseTier+        val reductions = linkedSetOf<AdaptiveReduction>()+        val free = input.freeStorageBytes+        if (free != null && free < LOW_STORAGE_THRESHOLD_BYTES) {+            tier = tier.lower()+            reductions += AdaptiveReduction.LOW_STORAGE+        }+        if (input.thermal == ThermalPressure.SEVERE) {+            tier = tier.lower()+            reductions += AdaptiveReduction.THERMAL+        }+        val steppedDown = tier != input.baseTier++        // A boost is a quality spend; never spend while storage/thermal forced a cut.+        val boosted = input.motion == SceneMotion.HIGH_MOTION && !steppedDown &&+            input.boostAllowed &&+            (input.baseTier == VideoQualityTier.UHD || input.baseTier == VideoQualityTier.FHD)+        val factor = when {+            boosted -> HIGH_MOTION_BOOST_FACTOR+            input.motion == SceneMotion.STATIC -> STATIC_FACTOR+            input.motion == SceneMotion.MODERATE -> MODERATE_FACTOR+            else -> HIGH_MOTION_FACTOR // HIGH_MOTION, or unknown: rung as-is+        }+        val floor = (tier.baseBitrateBps * QUALITY_FLOOR_FRACTION).roundToInt()+        val bitrate = maxOf((tier.baseBitrateBps * factor).roundToInt(), floor)+        return AdaptiveBitrateDecision(+            bitrateBps = bitrate,+            baseTier = input.baseTier,+            effectiveTier = tier,+            motion = input.motion,+            reductions = reductions,+            boosted = boosted,+        )+    }+}++/**+ * One analysis frame reduced to the two numbers the classifier needs, on the+ * 0-255 luminance scale.+ *+ * @property meanAbsDiff mean per-sample absolute difference against the previous frame.+ * @property meanGradient mean absolute horizontal neighbour difference within this+ *   frame (detail/texture). Detail alone is not motion: it only re-weights a real diff.+ */+data class FrameDiffSample(val meanAbsDiff: Double, val meanGradient: Double)++/** Frame-difference math over downsampled luminance grids. Pure and allocation-light. */+object SceneMotionMath {+    /** Diff at/above which (after detail weighting) a scene counts as high motion. */+    const val HIGH_MOTION_THRESHOLD: Double = 9.0++    /** Diff below which (after detail weighting) a scene counts as static. */+    const val STATIC_THRESHOLD: Double = 2.5++    /**+     * Reduces two same-sized luminance grids (row-major, [gridWidth] samples per row)+     * to a [FrameDiffSample]. Returns null for empty or mismatched grids.+     */+    fun sample(previous: FloatArray, current: FloatArray, gridWidth: Int): FrameDiffSample? {+        if (previous.size != current.size || current.isEmpty() || gridWidth <= 0) return null+        var diffSum = 0.0+        var gradientSum = 0.0+        var gradientCount = 0+        for (i in current.indices) {+            diffSum += kotlin.math.abs(current[i] - previous[i])+            if (i % gridWidth != 0) {+                gradientSum += kotlin.math.abs(current[i] - current[i - 1])+                gradientCount+++            }+        }+        val gradient = if (gradientCount > 0) gradientSum / gradientCount else 0.0+        return FrameDiffSample(meanAbsDiff = diffSum / current.size, meanGradient = gradient)+    }++    /**+     * Classifies a smoothed diff. The gradient re-weights by at most +/-15%: a detailed+     * static scene (high gradient, ~zero diff) stays static, while the same camera+     * movement over texture counts for slightly more than over a flat wall.+     */+    fun classify(smoothedDiff: Double, smoothedGradient: Double): SceneMotion {+        val detailWeight = 0.85 + 0.30 * (smoothedGradient / 64.0).coerceIn(0.0, 1.0)+        val effective = smoothedDiff * detailWeight+        return when {+            effective < STATIC_THRESHOLD -> SceneMotion.STATIC+            effective < HIGH_MOTION_THRESHOLD -> SceneMotion.MODERATE+            else -> SceneMotion.HIGH_MOTION+        }+    }+}++/**+ * Smooths recent [FrameDiffSample]s (simple mean over the window) and classifies the+ * scene. Stateful but pure: feed it synthetic samples to test the math end to end.+ */+class SceneMotionEstimator(private val windowSize: Int = DEFAULT_WINDOW_SIZE) {+    private val samples = ArrayDeque<FrameDiffSample>()++    /** Latest classification, or null before the first sample. */+    var lastClassification: SceneMotion? = null+        private set++    val sampleCount: Int get() = samples.size++    fun add(sample: FrameDiffSample): SceneMotion {+        samples.addLast(sample)+        while (samples.size > windowSize) samples.removeFirst()+        val meanDiff = samples.sumOf { it.meanAbsDiff } / samples.size+        val meanGradient = samples.sumOf { it.meanGradient } / samples.size+        return SceneMotionMath.classify(meanDiff, meanGradient).also { lastClassification = it }+    }++    /** Frame-grid convenience over [SceneMotionMath.sample]; null when no sample could be taken. */+    fun addFrame(previous: FloatArray, current: FloatArray, gridWidth: Int): SceneMotion? =+        SceneMotionMath.sample(previous, current, gridWidth)?.let { add(it) }++    fun reset() {+        samples.clear()+        lastClassification = null+    }++    companion object {+        /** ~2.4 s of samples at the analyzer's ~5 Hz cadence: long enough to ride out a pan blip. */+        const val DEFAULT_WINDOW_SIZE: Int = 12+    }+}
camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.kt b/camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.ktnew file mode 100644index 0000000000..f081d0b9c5--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.kt@@ -0,0 +1,138 @@+package com.vayunmathur.camera.domain++import kotlin.math.roundToInt++/** Which recording pipeline a recording should use. */+enum class RecordingPath { CAMERAX_RECORDER, CUSTOM_CAMERA2 }++/**+ * Inputs to the recording-path selection rule.+ *+ * @property customPathEnabled the (default-off) gate for the Camera2/MediaCodec path.+ * @property liveAdaptationWanted live, during-recording bitrate changes are wanted.+ * @property hlgRequested 10-bit HLG output is wanted (vendor HDR semantics).+ * @property stabilizationRequested a vendor/CameraX stabilization mode is wanted.+ * @property codecAv1Requested AV1 output is wanted (custom path is AVC/HEVC only).+ * @property analysisBound the motion-analysis stream bound (live changes need it).+ */+data class RecordingPathInput(+    val customPathEnabled: Boolean,+    val liveAdaptationWanted: Boolean,+    val hlgRequested: Boolean,+    val stabilizationRequested: Boolean,+    val codecAv1Requested: Boolean,+    val analysisBound: Boolean,+)++/**+ * Explicit selection rule for the two recording pipelines.+ *+ * The custom Camera2/MediaCodec path exists for one thing CameraX cannot do:+ * re-targeting the encoder mid-recording. It is selected only when that is+ * actually wanted *and* everything the recording asked for is something the+ * custom path can honestly provide. Vendor stabilization modes and HLG are+ * CameraX/HAL semantics the custom path cannot reproduce, AV1 encoding is not+ * attempted there, and without the analysis stream there is no motion signal+ * to adapt from — in all of those cases the CameraX Recorder path is used and+ * adaptation happens at the pre-recording decision only.+ */+object RecordingPathPolicy {+    fun select(input: RecordingPathInput): RecordingPath = when {+        !input.customPathEnabled -> RecordingPath.CAMERAX_RECORDER+        !input.liveAdaptationWanted -> RecordingPath.CAMERAX_RECORDER+        input.hlgRequested -> RecordingPath.CAMERAX_RECORDER+        input.stabilizationRequested -> RecordingPath.CAMERAX_RECORDER+        input.codecAv1Requested -> RecordingPath.CAMERAX_RECORDER+        !input.analysisBound -> RecordingPath.CAMERAX_RECORDER+        else -> RecordingPath.CUSTOM_CAMERA2+    }+}++/**+ * During-recording bitrate control, driven by the same policy numbers as the+ * pre-recording decision: the recording starts at the decision's bitrate, and+ * live motion re-evaluations move within [floorBps]..[ceilingBps].+ *+ * The ceiling never exceeds the pre-recording decision's intent: when storage+ * or thermal forced the rung down, live motion may not spend that back; when+ * nothing was forced, the ceiling is the (possibly boosted) base rung.+ *+ * Anti-oscillation: a candidate must (a) differ from the current bitrate by at+ * least [MIN_RELATIVE_CHANGE], (b) win [REQUIRED_CONSECUTIVE_WINS] consecutive+ * evaluations, and (c) arrive at least [evaluateIntervalMs] after the last+ * applied change. Applied changes are slew-limited to [MAX_SLEW_FRACTION] of+ * the current bitrate per step, so the encoder ramps instead of jumping.+ *+ * Pure and clock-injected: tests drive it with synthetic motion/time.+ */+class LiveBitrateController(+    private val decision: AdaptiveBitrateDecision,+    private val evaluateIntervalMs: Long = DEFAULT_EVALUATE_INTERVAL_MS,+) {+    /** Bitrate the encoder should be at now (starts at the pre-record decision). */+    var currentBitrateBps: Int = decision.bitrateBps+        private set++    private var lastChangeAtMs: Long? = null+    private var pendingCandidateBps: Int? = null+    private var pendingWins: Int = 0++    val floorBps: Int = (decision.effectiveTier.baseBitrateBps *+        AdaptiveVideoBitratePolicy.QUALITY_FLOOR_FRACTION).roundToInt()++    val ceilingBps: Int = if (decision.reductions.isEmpty()) {+        maxOf(decision.baseTier.baseBitrateBps, decision.bitrateBps)+    } else {+        decision.bitrateBps+    }++    /** Candidate bitrate for [motion] under the recording's floor/ceiling. */+    fun candidateFor(motion: SceneMotion?): Int {+        val factor = when (motion) {+            SceneMotion.STATIC -> AdaptiveVideoBitratePolicy.STATIC_FACTOR+            SceneMotion.MODERATE -> AdaptiveVideoBitratePolicy.MODERATE_FACTOR+            else -> AdaptiveVideoBitratePolicy.HIGH_MOTION_FACTOR+        }+        val raw = (decision.effectiveTier.baseBitrateBps * factor).roundToInt()+        return raw.coerceIn(floorBps, ceilingBps)+    }++    /**+     * One evaluation tick (the recorder calls this every ~[evaluateIntervalMs]).+     * Returns the new target bitrate to apply to the encoder, or null to hold.+     */+    fun evaluate(motion: SceneMotion?, nowMs: Long): Int? {+        val candidate = candidateFor(motion)+        if (candidate == pendingCandidateBps) {+            pendingWins+++        } else {+            pendingCandidateBps = candidate+            pendingWins = 1+        }+        val lastChange = lastChangeAtMs+        if (lastChange != null && nowMs - lastChange < evaluateIntervalMs) return null+        if (pendingWins < REQUIRED_CONSECUTIVE_WINS) return null+        val delta = kotlin.math.abs(candidate - currentBitrateBps).toDouble()+        if (delta < currentBitrateBps * MIN_RELATIVE_CHANGE) return null++        val maxStep = (currentBitrateBps * MAX_SLEW_FRACTION).roundToInt()+        val next = if (candidate > currentBitrateBps) {+            minOf(candidate, currentBitrateBps + maxStep)+        } else {+            maxOf(candidate, currentBitrateBps - maxStep)+        }+        if (next == currentBitrateBps) return null+        currentBitrateBps = next+        lastChangeAtMs = nowMs+        pendingCandidateBps = null+        pendingWins = 0+        return next+    }++    companion object {+        const val DEFAULT_EVALUATE_INTERVAL_MS: Long = 2_000L+        const val REQUIRED_CONSECUTIVE_WINS: Int = 2+        const val MIN_RELATIVE_CHANGE: Double = 0.10+        const val MAX_SLEW_FRACTION: Double = 0.25+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.ktnew file mode 100644index 0000000000..b452d8d79a--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.kt@@ -0,0 +1,141 @@+package com.vayunmathur.camera.platform++import android.media.MediaFormat+import android.os.Build+import android.os.PowerManager+import android.os.StatFs+import com.vayunmathur.camera.domain.AdaptiveBitrateDecision+import com.vayunmathur.camera.domain.AdaptiveBitrateInput+import com.vayunmathur.camera.domain.AdaptiveVideoBitratePolicy+import com.vayunmathur.camera.domain.FrameDiffSample+import com.vayunmathur.camera.domain.ThermalPressure+import com.vayunmathur.camera.domain.VideoQualityTier+import com.vayunmathur.library.log.Log+import kotlin.math.roundToInt++/** Frame rate the ladder/boost probe is sized at (the video session's fixed rate). */+internal const val VIDEO_BITRATE_PROBE_FPS = 30++/** Feeds one analyzer sample into the estimator and publishes the classification. */+internal fun CameraViewModel.onSceneMotionSample(sample: FrameDiffSample) {+    val classification = sceneMotionEstimator.add(sample)+    if (classification != sceneMotionMutable.value) {+        sceneMotionMutable.value = classification+        Log.dev("VideoMotion", "scene motion=$classification samples=${sceneMotionEstimator.sampleCount}")+    }+}++/** Bytes free where recordings are staged (the cache dir), or null when the probe fails. */+internal fun CameraViewModel.probeFreeStorageBytes(): Long? = try {+    StatFs(app.cacheDir.absolutePath).availableBytes+} catch (e: IllegalArgumentException) {+    Log.status("AdaptiveBitrate", "StatFs probe failed", e)+    null+} catch (e: IllegalStateException) {+    Log.status("AdaptiveBitrate", "StatFs probe failed", e)+    null+}++/**+ * Thermal pressure from PowerManager: SEVERE only at THERMAL_STATUS_SEVERE or worse+ * (API 30+). Older devices, or any probe failure, report UNKNOWN, which the policy+ * treats as no evidence — it never forces a reduction.+ */+internal fun CameraViewModel.probeThermalPressure(): ThermalPressure {+    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return ThermalPressure.UNKNOWN+    return try {+        val power = app.getSystemService(PowerManager::class.java) ?: return ThermalPressure.UNKNOWN+        if (power.currentThermalStatus >= PowerManager.THERMAL_STATUS_SEVERE) {+            ThermalPressure.SEVERE+        } else {+            ThermalPressure.NORMAL+        }+    } catch (e: IllegalStateException) {+        Log.status("AdaptiveBitrate", "Thermal status probe failed", e)+        ThermalPressure.UNKNOWN+    } catch (e: IllegalArgumentException) {+        Log.status("AdaptiveBitrate", "Thermal status probe failed", e)+        ThermalPressure.UNKNOWN+    } catch (e: SecurityException) {+        Log.status("AdaptiveBitrate", "Thermal status probe failed", e)+        ThermalPressure.UNKNOWN+    }+}++/**+ * The adaptive decision for [baseTier] from live probes: the estimator's latest+ * classification, free storage, thermal status, and (only when a boost could+ * apply) the encoder range probe for the codec the Recorder will be built with.+ */+internal fun CameraViewModel.computeAdaptiveBitrateDecision(+    baseTier: VideoQualityTier,+    useAv1: Boolean,+    useHevc: Boolean,+): AdaptiveBitrateDecision {+    val boostedBps = (baseTier.baseBitrateBps *+        AdaptiveVideoBitratePolicy.HIGH_MOTION_BOOST_FACTOR).roundToInt()+    val mime = when {+        useAv1 -> MediaFormat.MIMETYPE_VIDEO_AV1+        useHevc -> MediaFormat.MIMETYPE_VIDEO_HEVC+        else -> MediaFormat.MIMETYPE_VIDEO_AVC+    }+    val boostAllowed = CodecSupport.supportsVideoBitrate(+        mime, baseTier.width, baseTier.height, VIDEO_BITRATE_PROBE_FPS, boostedBps+    )+    val decision = AdaptiveVideoBitratePolicy.decide(+        AdaptiveBitrateInput(+            baseTier = baseTier,+            motion = sceneMotionEstimator.lastClassification,+            freeStorageBytes = probeFreeStorageBytes(),+            thermal = probeThermalPressure(),+            boostAllowed = boostAllowed,+        )+    )+    lastAdaptiveBitrateDecision = decision+    Log.debug(+        "AdaptiveBitrate",+        "tier=${decision.baseTier}->${decision.effectiveTier} motion=${decision.motion} " ++            "bitrate=${decision.bitrateBps} reductions=${decision.reductions} boosted=${decision.boosted}"+    )+    return decision+}++/**+ * Builds the recording engine for [path] behind the [VideoRecordingEngine]+ * boundary. The CameraX engine adapts the existing session plumbing (its+ * finalization keeps flowing through VideoRecordEvent); the Camera2 engine is+ * constructed only when the selection rule picks it, and owns its own+ * device/session from that point. Record-start selection itself lives in+ * [recordingPathFor]; nothing constructs the Camera2 engine while the gate is off.+ */+internal fun CameraViewModel.createVideoRecordingEngine(+    path: com.vayunmathur.camera.domain.RecordingPath,+    config: CustomRecordingConfig,+    controller: com.vayunmathur.camera.domain.LiveBitrateController,+): VideoRecordingEngine = when (path) {+    com.vayunmathur.camera.domain.RecordingPath.CUSTOM_CAMERA2 -> Camera2VideoRecordingEngine(+        context = app,+        config = config,+        controller = controller,+        motionSupplier = { sceneMotionEstimator.lastClassification },+        onMotionSample = { sample -> onSceneMotionSample(sample) },+        onError = { e -> Log.error("Camera2Recorder", "Camera2 recording engine error", e) },+    )+    com.vayunmathur.camera.domain.RecordingPath.CAMERAX_RECORDER -> CameraXVideoRecordingEngine(+        startImpl = { startRecording() },+        stopImpl = {+            currentRecording?.stop()+            currentRecording = null+            stopRecordingTimer()+        },+    )+}++/** CameraX quality -> pure ladder tier; unknown quality keeps the FHD rung (as before). */+internal fun tierForQuality(quality: androidx.camera.video.Quality?): VideoQualityTier = when (quality) {+    androidx.camera.video.Quality.UHD -> VideoQualityTier.UHD+    androidx.camera.video.Quality.FHD -> VideoQualityTier.FHD+    androidx.camera.video.Quality.HD -> VideoQualityTier.HD+    androidx.camera.video.Quality.SD -> VideoQualityTier.SD+    else -> VideoQualityTier.FHD+}
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.ktnew file mode 100644index 0000000000..a5e1d588f3--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -0,0 +1,528 @@+package com.vayunmathur.camera.platform++import android.annotation.SuppressLint+import android.content.Context+import android.hardware.camera2.CameraCaptureSession+import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraDevice+import android.hardware.camera2.CameraManager+import android.hardware.camera2.CaptureRequest+import android.media.AudioFormat+import android.media.AudioRecord+import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaExtractor+import android.media.MediaFormat+import android.media.MediaMuxer+import android.media.MediaRecorder+import android.os.Bundle+import android.os.Handler+import android.os.HandlerThread+import android.view.Surface+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.library.log.Log+import java.io.File+import java.nio.ByteBuffer++/**+ * Gate for the custom recording path. Default OFF: every recording uses the+ * CameraX Recorder until this path has been device-verified end to end+ * (see the verification note on [Camera2VideoRecordingEngine]).+ */+object CustomRecordingGate {+    const val ENABLED: Boolean = false+}++/** Selection inputs for the currently bound session, via [RecordingPathPolicy]. */+internal fun CameraViewModel.recordingPathFor(+    liveAdaptationWanted: Boolean,+    hlgBound: Boolean,+    stabilizationBound: Boolean,+): RecordingPath = RecordingPathPolicy.select(+    com.vayunmathur.camera.domain.RecordingPathInput(+        customPathEnabled = CustomRecordingGate.ENABLED,+        liveAdaptationWanted = liveAdaptationWanted,+        hlgRequested = hlgBound,+        stabilizationRequested = stabilizationBound,+        codecAv1Requested = recordingWithAv1,+        analysisBound = analysisStreamActiveMutable.value,+    )+)++/** Configuration for one custom-path recording. AVC/HEVC video + AAC audio only. */+data class CustomRecordingConfig(+    val width: Int,+    val height: Int,+    val fps: Int = 30,+    val videoMime: String = MediaFormat.MIMETYPE_VIDEO_AVC,+    val audioSampleRate: Int = 48_000,+    val audioBitrateBps: Int = 128_000,+    val iFrameIntervalSec: Int = 1,+)++/** Read-back summary of a finished file (see [Camera2VideoRecordingEngine.validateOutput]). */+data class CustomRecordingValidation(+    val readable: Boolean,+    val trackCount: Int,+    val hasVideoTrack: Boolean,+    val durationUs: Long,+)++/**+ * Custom recording path: Camera2 capture session feeding a MediaCodec encoder+ * input surface (plus the caller's preview surface), AudioRecord feeding an+ * audio MediaCodec, and a MediaMuxer writing the MP4. It exists for the one+ * thing the CameraX Recorder cannot do: re-targeting the encoder mid-recording+ * via `MediaCodec.setParameters(KEY_BITRATE)`, driven here by a+ * [LiveBitrateController] over the same motion estimator as the CameraX path.+ *+ * Ownership contract: this recorder opens the camera device itself, so the+ * CameraX session must be torn down before [start] and rebuilt after [stop].+ * It supports SDR AVC/HEVC + AAC only — no HLG, no vendor stabilization/EIS+ * semantics, no AV1; [RecordingPathPolicy] keeps those recordings on CameraX.+ *+ * VERIFICATION STATUS: compile-checked and unit-tested at the policy/controller+ * level only. It has NOT been device-verified: before [CustomRecordingGate] is+ * ever flipped, a device run must record on this path and validate the output+ * with [validateOutput] (plus external ffprobe) — an unverified muxer/encoder+ * path must never be the only copy of a user's recording.+ */+class Camera2VideoRecordingEngine(+    private val context: Context,+    private val config: CustomRecordingConfig,+    private val controller: LiveBitrateController,+    private val motionSupplier: () -> SceneMotion?,+    private val onMotionSample: (com.vayunmathur.camera.domain.FrameDiffSample) -> Unit,+    private val onError: (Exception) -> Unit,+) : VideoRecordingEngine {+    override val path: RecordingPath = RecordingPath.CUSTOM_CAMERA2++    private var cameraThread: HandlerThread? = null+    private var cameraHandler: Handler? = null+    private var cameraDevice: CameraDevice? = null+    private var captureSession: CameraCaptureSession? = null+    private var analysisReader: android.media.ImageReader? = null+    private var ownedPreviewTexture: android.graphics.SurfaceTexture? = null+    private var ownedPreviewSurface: Surface? = null+    private var outcomeCallback: ((VideoRecordingOutcome) -> Unit)? = null+    private var previousGrid: FloatArray? = null+    private var previousGridWidth = 0+    private var lastAnalysisAtMs = 0L++    /** The engine-owned preview surface (for a TextureView to render), once started. */+    fun ownedPreviewSurface(): Surface? = ownedPreviewSurface++    override fun start(request: VideoRecordingRequest, onFinalized: (VideoRecordingOutcome) -> Unit) {+        val cameraId = request.cameraId+        if (cameraId == null) {+            onFinalized(+                VideoRecordingOutcome(+                    request.outputFile,+                    IllegalArgumentException("Camera2 engine requires a cameraId")+                )+            )+            return+        }+        outcomeCallback = onFinalized+        start(request.outputFile, cameraId, request.previewSurface)+    }++    private var videoCodec: MediaCodec? = null+    private var audioCodec: MediaCodec? = null+    private var audioRecord: AudioRecord? = null+    private var muxer: MediaMuxer? = null++    @Volatile private var muxerStarted = false+    private var videoTrackIndex = -1+    private var audioTrackIndex = -1++    @Volatile private var running = false+    private var drainThread: Thread? = null+    private var audioThread: Thread? = null+    private var adaptationThread: Thread? = null+    private var outputFile: File? = null++    /** Opens the camera + encoders and starts recording into [outputFile]. */+    @SuppressLint("MissingPermission")+    fun start(outputFile: File, cameraId: String, previewSurface: Surface?) {+        check(!running) { "Camera2VideoRecordingEngine already running" }+        this.outputFile = outputFile+        try {+            setupEncoders(outputFile)+            openCamera(cameraId, previewSurface)+            running = true+            startDrainThread()+            startAudioThread()+            startAdaptationThread()+        } catch (e: Exception) {+            releaseAll()+            throw e+        }+    }++    /** Stops capture, drains the encoders, and finishes the muxed file. */+    override fun stop() {+        if (!running) return+        running = false+        try {+            captureSession?.stopRepeating()+            captureSession?.close()+            cameraDevice?.close()+            try {+                videoCodec?.signalEndOfInputStream()+            } catch (_: IllegalStateException) {+            }+            audioRecord?.stop()+            drainThread?.join(DRAIN_JOIN_TIMEOUT_MS)+            audioThread?.join(DRAIN_JOIN_TIMEOUT_MS)+            adaptationThread?.interrupt()+            if (muxerStarted) muxer?.stop()+        } catch (e: IllegalStateException) {+            Log.error("Camera2Recorder", "stop() failed", e)+        } finally {+            releaseAll()+            // Never hand back a corrupt file: read it back, and on failure+            // delete it and report an error outcome instead of an output.+            val file = outputFile+            val callback = outcomeCallback+            outcomeCallback = null+            if (file != null && callback != null) {+                val validation = validateOutput(file)+                if (validation.readable) {+                    callback(VideoRecordingOutcome(file))+                } else {+                    file.delete()+                    callback(+                        VideoRecordingOutcome(+                            file,+                            IllegalStateException(+                                "Custom-path output failed read-back validation: $validation"+                            )+                        )+                    )+                }+            }+        }+    }++    private fun setupEncoders(outputFile: File) {+        val videoFormat = MediaFormat.createVideoFormat(config.videoMime, config.width, config.height)+            .apply {+                setInteger(+                    MediaFormat.KEY_COLOR_FORMAT,+                    MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface+                )+                setInteger(MediaFormat.KEY_BIT_RATE, controller.currentBitrateBps)+                setInteger(MediaFormat.KEY_FRAME_RATE, config.fps)+                setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, config.iFrameIntervalSec)+            }+        videoCodec = MediaCodec.createEncoderByType(config.videoMime).apply {+            configure(videoFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+        }++        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)+    }++    @SuppressLint("MissingPermission")+    private fun openCamera(cameraId: String, previewSurface: Surface?) {+        cameraThread = HandlerThread("Camera2RecorderCamera").apply { start() }+        cameraHandler = Handler(cameraThread!!.looper)+        val manager = context.getSystemService(CameraManager::class.java)+        val encoderSurface = videoCodec!!.createInputSurface()+        videoCodec!!.start()+        // Preview surface: the caller's when given, else an engine-owned+        // SurfaceTexture surface (exposed via ownedPreviewSurface() for a+        // TextureView to render once the UI migrates off CameraX preview).+        val effectivePreview = previewSurface ?: run {+            val texture = android.graphics.SurfaceTexture(PREVIEW_TEXTURE_ID).apply {+                setDefaultBufferSize(config.width, config.height)+            }+            ownedPreviewTexture = texture+            Surface(texture).also { ownedPreviewSurface = it }+        }+        // Analysis surface: same motion signal as the CameraX path, from an+        // ImageReader feeding the shared estimator through onMotionSample.+        val reader = android.media.ImageReader.newInstance(+            ANALYSIS_WIDTH, ANALYSIS_HEIGHT, android.graphics.ImageFormat.YUV_420_888, ANALYSIS_MAX_IMAGES+        )+        analysisReader = reader+        reader.setOnImageAvailableListener({ r ->+            val nowMs = android.os.SystemClock.elapsedRealtime()+            if (nowMs - lastAnalysisAtMs < VIDEO_MOTION_SAMPLE_INTERVAL_MS) {+                runCatching { r.acquireLatestImage()?.close() }+                return@setOnImageAvailableListener+            }+            lastAnalysisAtMs = nowMs+            val image = try {+                r.acquireLatestImage()+            } catch (_: IllegalStateException) {+                null+            } ?: return@setOnImageAvailableListener+            try {+                val plane = image.planes.firstOrNull() ?: return@setOnImageAvailableListener+                val (grid, gridWidth) = sampleYPlaneGrid(+                    plane.buffer, plane.rowStride, plane.pixelStride, image.width, image.height+                ) ?: return@setOnImageAvailableListener+                val previous = previousGrid+                previousGrid = grid+                if (previous != null && previous.size == grid.size && previousGridWidth == gridWidth) {+                    com.vayunmathur.camera.domain.SceneMotionMath+                        .sample(previous, grid, gridWidth)+                        ?.let { onMotionSample(it) }+                }+                previousGridWidth = gridWidth+            } finally {+                image.close()+            }+        }, cameraHandler)+        manager.openCamera(cameraId, object : CameraDevice.StateCallback() {+            override fun onOpened(device: CameraDevice) {+                cameraDevice = device+                try {+                    val surfaces = listOfNotNull(encoderSurface, effectivePreview, reader.surface)+                    device.createCaptureSession(surfaces, object : CameraCaptureSession.StateCallback() {+                        override fun onConfigured(session: CameraCaptureSession) {+                            captureSession = session+                            val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {+                                addTarget(encoderSurface)+                                addTarget(effectivePreview)+                                addTarget(reader.surface)+                                set(+                                    CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,+                                    android.util.Range(config.fps, config.fps)+                                )+                            }.build()+                            try {+                                session.setRepeatingRequest(request, null, cameraHandler)+                            } catch (e: IllegalStateException) {+                                onError(e)+                            }+                        }++                        override fun onConfigureFailed(session: CameraCaptureSession) {+                            onError(IllegalStateException("Custom recorder capture session failed to configure"))+                        }+                    }, cameraHandler)+                } catch (e: IllegalStateException) {+                    onError(e)+                } catch (e: IllegalArgumentException) {+                    onError(e)+                }+            }++            override fun onDisconnected(device: CameraDevice) {+                device.close()+                cameraDevice = null+            }++            override fun onError(device: CameraDevice, error: Int) {+                device.close()+                cameraDevice = null+                onError(IllegalStateException("Custom recorder camera error $error"))+            }+        }, cameraHandler)+        // Facing check kept explicit: callers pick the id, but a front camera+        // would need mirroring this path does not do.+        val facing = manager.getCameraCharacteristics(cameraId)+            .get(CameraCharacteristics.LENS_FACING)+        Log.debug("Camera2Recorder", "opening camera $cameraId facing=$facing")+    }++    /** Muxer drain: video + audio codec outputs, started once both formats are known. */+    private fun startDrainThread() {+        drainThread = Thread({+            val bufferInfo = MediaCodec.BufferInfo()+            while (running || muxerStarted) {+                drainCodec(videoCodec, isVideo = true, bufferInfo)+                drainCodec(audioCodec, isVideo = false, bufferInfo)+                if (!running && drainedBoth()) break+                Thread.sleep(DRAIN_POLL_MS)+            }+        }, "Camera2RecorderDrain").apply { start() }+    }++    private fun drainedBoth(): Boolean = !running // simplified end condition; see stop()++    private fun drainCodec(codec: MediaCodec?, isVideo: Boolean, info: MediaCodec.BufferInfo) {+        codec ?: return+        while (true) {+            val index = try {+                codec.dequeueOutputBuffer(info, 0)+            } catch (_: IllegalStateException) {+                return+            }+            when {+                index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {+                    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) {+                        m.start()+                        muxerStarted = true+                    }+                }+                index == MediaCodec.INFO_TRY_AGAIN_LATER -> return+                index >= 0 -> {+                    if (muxerStarted && info.size > 0) {+                        val buffer: ByteBuffer = codec.getOutputBuffer(index) ?: continue+                        buffer.position(info.offset)+                        buffer.limit(info.offset + info.size)+                        muxer?.writeSampleData(if (isVideo) videoTrackIndex else audioTrackIndex, buffer, info)+                    }+                    codec.releaseOutputBuffer(index, false)+                    if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return+                }+                else -> return+            }+        }+    }++    /** AudioRecord (mono) -> audio encoder input buffers, with codec timestamps. */+    private fun startAudioThread() {+        val minBuffer = AudioRecord.getMinBufferSize(+            config.audioSampleRate,+            AudioFormat.CHANNEL_IN_MONO,+            AudioFormat.ENCODING_PCM_16BIT+        )+        if (minBuffer <= 0) {+            Log.error("Camera2Recorder", "AudioRecord min buffer unavailable: $minBuffer")+            return+        }+        @SuppressLint("MissingPermission")+        val record = AudioRecord(+            MediaRecorder.AudioSource.CAMCORDER,+            config.audioSampleRate,+            AudioFormat.CHANNEL_IN_MONO,+            AudioFormat.ENCODING_PCM_16BIT,+            maxOf(minBuffer, AUDIO_MAX_INPUT_BYTES)+        )+        audioRecord = record+        record.startRecording()+        audioThread = Thread({+            val chunk = ByteArray(AUDIO_CHUNK_BYTES)+            var presentationUs = 0L+            val codec = audioCodec ?: return@Thread+            while (running) {+                val read = record.read(chunk, 0, chunk.size)+                if (read <= 0) continue+                val inputIndex = try {+                    codec.dequeueInputBuffer(AUDIO_DEQUEUE_TIMEOUT_US)+                } catch (_: IllegalStateException) {+                    break+                }+                if (inputIndex < 0) continue+                val input = codec.getInputBuffer(inputIndex) ?: continue+                input.clear()+                input.put(chunk, 0, minOf(read, input.remaining()))+                val flags = if (!running) MediaCodec.BUFFER_FLAG_END_OF_STREAM else 0+                codec.queueInputBuffer(inputIndex, 0, minOf(read, AUDIO_CHUNK_BYTES), presentationUs, flags)+                presentationUs += read.toLong() * 1_000_000L / (config.audioSampleRate * AUDIO_BYTES_PER_SAMPLE)+            }+        }, "Camera2RecorderAudio").apply { start() }+    }++    /** Every 2 s: ask the controller, apply via encoder parameters when it moves. */+    private fun startAdaptationThread() {+        adaptationThread = Thread({+            var tickMs = 0L+            while (running) {+                Thread.sleep(LiveBitrateController.DEFAULT_EVALUATE_INTERVAL_MS)+                tickMs += LiveBitrateController.DEFAULT_EVALUATE_INTERVAL_MS+                val target = controller.evaluate(motionSupplier(), tickMs) ?: continue+                try {+                    videoCodec?.setParameters(Bundle().apply {+                        putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, target)+                    })+                    Log.debug("Camera2Recorder", "live bitrate -> $target")+                } catch (e: IllegalStateException) {+                    Log.error("Camera2Recorder", "setParameters(KEY_BITRATE) failed", e)+                }+            }+        }, "Camera2RecorderAdapt").apply { start() }+    }++    private fun releaseAll() {+        try { analysisReader?.close() } catch (_: Exception) {}+        try { ownedPreviewSurface?.release() } catch (_: Exception) {}+        try { ownedPreviewTexture?.release() } catch (_: Exception) {}+        analysisReader = null+        ownedPreviewSurface = null+        ownedPreviewTexture = null+        previousGrid = null+        try { audioRecord?.release() } catch (_: Exception) {}+        try { audioCodec?.stop() } catch (_: Exception) {}+        try { audioCodec?.release() } catch (_: Exception) {}+        try { videoCodec?.stop() } catch (_: Exception) {}+        try { videoCodec?.release() } catch (_: Exception) {}+        try { muxer?.release() } catch (_: Exception) {}+        try { cameraThread?.quitSafely() } catch (_: Exception) {}+        audioRecord = null+        audioCodec = null+        videoCodec = null+        muxer = null+        muxerStarted = false+        videoTrackIndex = -1+        audioTrackIndex = -1+    }++    companion object {+        private const val PREVIEW_TEXTURE_ID = 1+        private const val ANALYSIS_WIDTH = 640+        private const val ANALYSIS_HEIGHT = 480+        private const val ANALYSIS_MAX_IMAGES = 3+        private const val AUDIO_MAX_INPUT_BYTES = 16_384+        private const val AUDIO_CHUNK_BYTES = 4_096+        private const val AUDIO_BYTES_PER_SAMPLE = 2 // PCM16 mono+        private const val AUDIO_DEQUEUE_TIMEOUT_US = 10_000L+        private const val DRAIN_POLL_MS = 5L+        private const val DRAIN_JOIN_TIMEOUT_MS = 2_000L++        /**+         * Read-back validation for a finished custom-path file: the extractor+         * must open it, find a video track, and report a positive duration.+         * Device-only (android.media is stubbed in unit tests) — callers run+         * this after [stop] before treating the file as the user's recording.+         */+        fun validateOutput(file: File): CustomRecordingValidation {+            val extractor = MediaExtractor()+            return try {+                extractor.setDataSource(file.absolutePath)+                var hasVideo = false+                var durationUs = 0L+                for (i in 0 until extractor.trackCount) {+                    val format = extractor.getTrackFormat(i)+                    val mime = format.getString(MediaFormat.KEY_MIME) ?: continue+                    if (mime.startsWith("video/")) hasVideo = true+                    if (format.containsKey(MediaFormat.KEY_DURATION)) {+                        durationUs = maxOf(durationUs, format.getLong(MediaFormat.KEY_DURATION))+                    }+                }+                CustomRecordingValidation(+                    readable = extractor.trackCount > 0 && hasVideo && durationUs > 0,+                    trackCount = extractor.trackCount,+                    hasVideoTrack = hasVideo,+                    durationUs = durationUs,+                )+            } catch (e: Exception) {+                Log.error("Camera2Recorder", "validateOutput failed for ${file.name}", e)+                CustomRecordingValidation(false, 0, false, 0L)+            } finally {+                extractor.release()+            }+        }+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.ktindex b827842cf4..3e4973a910 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt@@ -126,6 +126,8 @@ fun CameraViewModel.teardownSession() {     imageCapture = null     imageAnalysis = null     videoCapture = null+    boundVideoBitrateBps = null+    boundVideoQualityTier = null     highSpeedVideoCapture = null     cameraProvider = null     photoSessionActiveMutable.value = false
camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.ktindex 68b92a6a7f..3d748f2951 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -56,6 +56,9 @@ fun CameraViewModel.toggleHighSpeedRecording() { private const val COUNTDOWN_TICK_MS = 1000L private const val TIMELAPSE_SPEED_FACTOR = 8f +/** Settle pause between teardown and rebind for an adaptive-bitrate record press. */+private const val ADAPTIVE_REBIND_SETTLE_MS = 40L+ @android.annotation.SuppressLint("MissingPermission") internal fun CameraViewModel.startHighSpeedRecording() {     if (isRecordingMutable.value) return@@ -132,9 +135,81 @@ fun CameraViewModel.toggleRecording() {  @android.annotation.SuppressLint("MissingPermission") internal fun CameraViewModel.startRecording() {+    startRecording(allowAdaptiveRebind = true)+}++/**+ * Starts a recording, consuming the adaptive-bitrate decision first.+ *+ * CameraX fixes the Recorder's target bitrate when the Recorder is built (at+ * session bind), and there is no API to re-target it afterwards — so when the+ * scene estimate / storage / thermal probes have moved since the bind, the+ * honest move is one rebind *before* `prepareRecording`, never a stop/restart+ * mid-recording. The re-decision after that rebind converges (same probes,+ * same scene), so at most one rebind happens per press.+ */[email protected]("MissingPermission")+private fun CameraViewModel.startRecording(allowAdaptiveRebind: Boolean) {     if (isRecordingMutable.value) return+    if (adaptiveBitrateRebindInFlight) return     val capture = videoCapture ?: return +    val tier = boundVideoQualityTier+    val boundBitrate = boundVideoBitrateBps+    if (tier != null && boundBitrate != null) {+        val decision = computeAdaptiveBitrateDecision(+            tier, useAv1 = recordingWithAv1, useHevc = recordingWithHevc+        )+        if (decision.bitrateBps != boundBitrate) {+            if (!allowAdaptiveRebind) {+                // Already rebound once for this press and the probes still+                // disagree (e.g. the quality probe moved): record at the+                // bound bitrate rather than rebinding in a loop.+                Log.status(+                    "AdaptiveBitrate",+                    "Decision ${decision.bitrateBps} != bound $boundBitrate after rebind; recording as bound"+                )+            } else {+                adaptiveBitrateRebindInFlight = true+                viewModelScope.launch {+                    try {+                        val ok = runSessionBindWithRetry {+                            teardownSession()+                            delay(ADAPTIVE_REBIND_SETTLE_MS)+                            setupVideoSession()+                        }+                        if (!ok) {+                            Log.error(+                                "AdaptiveBitrate",+                                "Adaptive rebind failed; recording not started"+                            )+                            // Surface the same bind-error UI (with manual retry)+                            // the session effect uses after its retries.+                            sessionBindFailedMutable.value = true+                        }+                    } finally {+                        adaptiveBitrateRebindInFlight = false+                    }+                    if (videoCapture != null && !isRecordingMutable.value) {+                        startRecording(allowAdaptiveRebind = false)+                    }+                }+                return+            }+        } else if (decision.forcedReduction) {+            // The one user-visible adaptive note, and only for a forced cut:+            // scene-only savings stay silent by design.+            val noteRes = if (+                com.vayunmathur.camera.domain.AdaptiveReduction.LOW_STORAGE in decision.reductions+            ) {+                com.vayunmathur.camera.R.string.lower_bitrate_low_storage+            } else {+                com.vayunmathur.camera.R.string.lower_bitrate_thermal+            }+            com.vayunmathur.library.util.AppMessages.show(app.getString(noteRes))+        }+    }+     val timestamp = MediaStoreSaver.timestamp()     val recordingMode = cameraModeMutable.value     val displayName = "${recordingPrefix(recordingMode)}_$timestamp"
camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.ktindex 6f6934b12f..c2fc69dee3 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt@@ -36,12 +36,6 @@ suspend fun CameraViewModel.setupVideoSession(): Boolean {     } } -/** Explicit video bitrate ladder, bits per second. */-private const val VIDEO_BITRATE_UHD_BPS = 48_000_000-private const val VIDEO_BITRATE_FHD_BPS = 25_000_000-private const val VIDEO_BITRATE_HD_BPS = 12_000_000-private const val VIDEO_BITRATE_SD_BPS = 6_000_000- /** Explicit recording audio: 128 kbps stereo, for AAC and Opus alike. */ private const val AUDIO_BITRATE_BPS = 128_000 private const val AUDIO_CHANNEL_COUNT = 2@@ -55,13 +49,8 @@ private const val AUDIO_CHANNEL_COUNT = 2  * Unknown/unprobeable quality falls back to the FHD rung: high enough for  * HD/FHD, low enough that UHD-only encoder ranges are not required.  */-internal fun videoBitRateForQuality(quality: Quality?): Int = when (quality) {-    Quality.UHD -> VIDEO_BITRATE_UHD_BPS-    Quality.FHD -> VIDEO_BITRATE_FHD_BPS-    Quality.HD -> VIDEO_BITRATE_HD_BPS-    Quality.SD -> VIDEO_BITRATE_SD_BPS-    else -> VIDEO_BITRATE_FHD_BPS-}+internal fun videoBitRateForQuality(quality: Quality?): Int =+    tierForQuality(quality).baseBitrateBps  /** Codec/quality choices resolved off the camera info. */ internal data class VideoChoices(@@ -72,7 +61,7 @@ internal data class VideoChoices(     val bestFpsRange: android.util.Range<Int>?,     val stabilizationMode: Int?,     val qualitySelector: QualitySelector,-    val videoEncodingBitRate: Int = VIDEO_BITRATE_FHD_BPS,+    val videoEncodingBitRate: Int = com.vayunmathur.camera.domain.VideoQualityTier.FHD.baseBitrateBps,     val audioEncodingBitRate: Int = AUDIO_BITRATE_BPS,     val audioChannelCount: Int = AUDIO_CHANNEL_COUNT )@@ -91,6 +80,13 @@ internal suspend fun CameraViewModel.prepareVideoSession(): VideoSessionPrep {     val provider = ProcessCameraProvider.awaitInstance(app)     cameraProvider = provider     provider.unbindAll()+    // A fresh video entry starts the scene estimate from scratch (the first+    // samples land within ~400 ms; until then the policy uses the rung as-is).+    // A record-start adaptive rebind keeps the estimate it just decided from.+    if (!adaptiveBitrateRebindInFlight) {+        sceneMotionEstimator.reset()+        sceneMotionMutable.value = null+    }      ensureLensesEnumerated(provider)     val videoLens = selectedLensMutable.value@@ -146,10 +142,16 @@ internal fun CameraViewModel.resolveVideoChoices(cameraInfo: androidx.camera.cor     // the encoder default. The Recorder is built inside each bind rung, so a     // device that rejects these encoding options fails that rung and the     // existing bind ladder (HDR/snapshot x lens) walks on.-    val videoEncodingBitRate = videoBitRateForQuality(-        highestSupportedVideoQuality(cameraInfo, hlgSupported)-    )-    Log.debug("VideoSession", "Video encoding bitrate=$videoEncodingBitRate")+    // Adaptive: the static ladder rung for the highest supported quality, scaled+    // by the scene estimate + storage/thermal probes. This is a bind-time snapshot+    // (the Recorder is built below and cannot be re-targeted afterwards); the+    // record path re-decides and rebinds once before prepareRecording when the+    // scene/probes moved since this bind. See AdaptiveVideoBitratePolicy.+    val baseTier = tierForQuality(highestSupportedVideoQuality(cameraInfo, hlgSupported))+    boundVideoQualityTier = baseTier+    val videoEncodingBitRate = computeAdaptiveBitrateDecision(baseTier, useAv1, useHevc).bitrateBps+    boundVideoBitrateBps = videoEncodingBitRate+    Log.debug("VideoSession", "Video encoding bitrate=$videoEncodingBitRate tier=$baseTier")     return VideoChoices(         useAv1, useHevc, useOpus, hlgSupported, bestFpsRange, stabilizationMode,         qualitySelector, videoEncodingBitRate = videoEncodingBitRate@@ -192,13 +194,27 @@ internal fun CameraViewModel.bindVideoLadder(session: VideoSessionPrep) {     var bound: Camera? = null     var videoBoundLensId: String? = null     var lastError: Exception? = null-    for ((hlg, snapshot) in videoAttempts(session.choices.hlgSupported)) {-        val rung = tryVideoRungSet(session, hlg, snapshot)-        lastError = rung.lastError ?: lastError-        if (rung.bound != null) {-            videoBoundLensId = rung.lensId-            bound = rung.bound-            break+    // The motion-analysis stream is an extra use case some devices cannot host+    // alongside Preview+VideoCapture(+snapshot). Try the full ladder with it+    // first; if every rung fails, walk the same ladder without it — video then+    // records at the rung as-is (no scene samples), exactly the pre-adaptive+    // behaviour, instead of losing the video session entirely.+    for (includeAnalysis in listOf(true, false)) {+        for ((hlg, snapshot) in videoAttempts(session.choices.hlgSupported)) {+            val rung = tryVideoRungSet(session, hlg, snapshot, includeAnalysis)+            lastError = rung.lastError ?: lastError+            if (rung.bound != null) {+                videoBoundLensId = rung.lensId+                bound = rung.bound+                break+            }+        }+        if (bound != null) break+        if (includeAnalysis) {+            Log.status(+                "VideoSession",+                "Video bind with motion analysis failed on every rung; retrying without analysis"+            )         }     }     boundCamera = bound ?: throw (lastError ?: IllegalStateException("Video session bind failed"))@@ -228,7 +244,8 @@ internal data class VideoRungResult( internal fun CameraViewModel.tryVideoRungSet(     session: VideoSessionPrep,     hlg: Boolean,-    snapshot: Boolean+    snapshot: Boolean,+    includeAnalysis: Boolean = true ): VideoRungResult {     val lensOrdered = buildList {         if (session.videoLens != null) add(session.videoLens)@@ -238,7 +255,7 @@ internal fun CameraViewModel.tryVideoRungSet(     }     var lastError: Exception? = null     for (candidate in lensOrdered) {-        if (tryVideoRung(session, candidate, hlg, snapshot)) {+        if (tryVideoRung(session, candidate, hlg, snapshot, includeAnalysis)) {             return VideoRungResult(boundCamera, candidate?.logicalCameraId, lastError)         } else {             lastError = videoLastError@@ -255,7 +272,8 @@ internal fun CameraViewModel.tryVideoRung(     session: VideoSessionPrep,     candidate: com.vayunmathur.camera.domain.PhysicalLens?,     hlg: Boolean,-    snapshot: Boolean+    snapshot: Boolean,+    includeAnalysis: Boolean = true ): Boolean {     return try {         session.provider.unbindAll()@@ -263,7 +281,8 @@ internal fun CameraViewModel.tryVideoRung(             session,             lensSelector(lensFacingMutable.value, candidate),             hlg,-            snapshot+            snapshot,+            includeAnalysis         )         true     } catch (e: IllegalStateException) {@@ -292,29 +311,61 @@ internal fun CameraViewModel.bindVideoUseCases(     session: VideoSessionPrep,     lensSelector: CameraSelector,     hlg: Boolean,-    snapshot: Boolean+    snapshot: Boolean,+    includeAnalysis: Boolean = true ): Camera {-    val choices = session.choices     val dynamicRange = if (hlg) androidx.camera.core.DynamicRange.HLG_10_BIT         else androidx.camera.core.DynamicRange.SDR     val preview = buildVideoPreview(session, dynamicRange)     val capture = buildVideoCapture(session, dynamicRange)-    return if (snapshot) {+    // Motion-analysis stream for the adaptive-bitrate scene estimate. The+    // analyzer is attached directly (not via desiredAnalyzer): the photo+    // stream's PhotoAnalyzer must never land on this stream.+    val analysis = if (includeAnalysis) buildVideoAnalysis() else null+    imageAnalysis = analysis+    val still = if (snapshot) {         // Extra ImageCapture use case enables taking a still while recording (SDR JPEG).         // Crop matches the still aspect ratio like the photo session, or snapshots         // always save full-frame while the preview shows cropped.-        val still = ImageCapture.Builder()+        ImageCapture.Builder()             .setFlashMode(ImageCapture.FLASH_MODE_OFF)             .build()-        imageCapture = still-        still.setCropAspectRatio(currentCropAspectRatio())-        bindSession(session.provider, session.owner, lensSelector, preview, capture, still)+            .also {+                imageCapture = it+                it.setCropAspectRatio(currentCropAspectRatio())+            }     } else {         imageCapture = null-        bindSession(session.provider, session.owner, lensSelector, preview, capture)+        null     }+    val useCases = listOfNotNull(preview, capture, still, analysis).toTypedArray()+    return bindSession(session.provider, session.owner, lensSelector, *useCases) } +/** Capped, cheap analysis stream (640x480 target) carrying only the motion estimate. */+internal fun CameraViewModel.buildVideoAnalysis(): androidx.camera.core.ImageAnalysis {+    val analysis = androidx.camera.core.ImageAnalysis.Builder()+        .setBackpressureStrategy(androidx.camera.core.ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+        .setResolutionSelector(+            androidx.camera.core.resolutionselector.ResolutionSelector.Builder()+                .setResolutionStrategy(+                    androidx.camera.core.resolutionselector.ResolutionStrategy(+                        android.util.Size(VIDEO_ANALYSIS_WIDTH, VIDEO_ANALYSIS_HEIGHT),+                        androidx.camera.core.resolutionselector.ResolutionStrategy+                            .FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER+                    )+                )+                .build()+        )+        .build()+    analysis.setAnalyzer(analysisExecutor, VideoMotionAnalyzer { onSceneMotionSample(it) })+    return analysis+}++/** Target resolution for the video motion-analysis stream. */+private const val VIDEO_ANALYSIS_WIDTH = 640+private const val VIDEO_ANALYSIS_HEIGHT = 480+ /** Builds the video preview with the shared dynamic range + capture options. */ internal fun CameraViewModel.buildVideoPreview(     session: VideoSessionPrep,@@ -370,6 +421,7 @@ internal fun CameraViewModel.buildVideoCapture( /** Records snapshot support and marks the video session active. */ internal suspend fun CameraViewModel.finishVideoSession() {     videoSnapshotSupportedMutable.value = imageCapture != null+    analysisStreamActiveMutable.value = imageAnalysis != null     boundCamera?.let { refreshCapabilities(it, boundLensIdField) }     videoSessionActiveMutable.value = true }
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 e23ac88b6f..ece694ea74 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -625,6 +625,30 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     var recordingWithHevc: Boolean = false         internal set +    // --- Adaptive video bitrate (pre-recording only; see AdaptiveVideoBitratePolicy) ---++    /** Smoothed scene-motion estimate fed by the video session's VideoMotionAnalyzer. */+    internal val sceneMotionEstimator =+        com.vayunmathur.camera.domain.SceneMotionEstimator()++    /** Latest scene classification while previewing in a video mode; null until sampled. */+    internal val sceneMotionMutable =+        MutableStateFlow<com.vayunmathur.camera.domain.SceneMotion?>(null)+    val sceneMotion = sceneMotionMutable.asStateFlow()++    /** Last adaptive decision made (bind time or record start); kept for tests/debug. */+    internal var lastAdaptiveBitrateDecision:+        com.vayunmathur.camera.domain.AdaptiveBitrateDecision? = null++    /** Bitrate the bound Recorder was actually built with; null outside a video session. */+    internal var boundVideoBitrateBps: Int? = null++    /** Ladder tier the bound video session resolved to. */+    internal var boundVideoQualityTier: com.vayunmathur.camera.domain.VideoQualityTier? = null++    /** True while a record press is rebinding the video session for a new bitrate. */+    internal var adaptiveBitrateRebindInFlight: Boolean = false+     fun setSloMoFps(fps: Int) {         sloMoFps = fps     }
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 a6c259c6d5..1b0618a653 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt@@ -47,6 +47,36 @@ object CodecSupport {         supportsAudio(MediaFormat.MIMETYPE_AUDIO_OPUS)     } +    /**+     * True when some encoder for [mimeType] supports [bitrateBps] at+     * [width]x[height]@[fps]. Used to gate the adaptive high-motion boost: the+     * Recorder accepts any target bitrate, but requesting one outside the+     * encoder's range only buys macro-blocking (or a failed configure).+     */+    fun supportsVideoBitrate(+        mimeType: String,+        width: Int,+        height: Int,+        fps: Int,+        bitrateBps: 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()) &&+                video.bitrateRange.contains(bitrateBps)+        }+    } 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/VideoMotionAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/VideoMotionAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/platform/VideoMotionAnalyzer.ktnew file mode 100644index 0000000000..8751ad5524--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/VideoMotionAnalyzer.kt@@ -0,0 +1,122 @@+package com.vayunmathur.camera.platform++import android.os.SystemClock+import androidx.annotation.OptIn+import androidx.camera.core.ExperimentalGetImage+import androidx.camera.core.ImageAnalysis+import androidx.camera.core.ImageProxy+import com.vayunmathur.camera.domain.FrameDiffSample+import com.vayunmathur.camera.domain.SceneMotionMath+import com.vayunmathur.library.log.Log++/** Minimum gap between motion samples: ~5 Hz is plenty for a scene classification. */+internal const val VIDEO_MOTION_SAMPLE_INTERVAL_MS = 200L++/** Longest side of the luminance grid the frame difference runs over (~9k samples). */+internal const val VIDEO_MOTION_GRID_MAX_SIDE = 96++/**+ * Cheapest motion signal for the video preview: frame-difference over a heavily+ * downsampled Y-plane grid, reusing the PhotoAnalyzer pattern (read plane 0 once,+ * stride it, close the proxy on every path).+ *+ * VIDEO mode binds no analyzer today, so this is a new dedicated ImageAnalysis+ * stream for the video session (the photo stream's PhotoAnalyzer is not reused:+ * it also pays for ZXing and Motion-Photo bitmap copies). Only a grid vs the+ * previous kept grid is compared — no bitmaps, no per-frame allocation beyond+ * the two grids — and sampling is capped at ~5 Hz on the shared analysis thread.+ *+ * Emits [FrameDiffSample]s; the [SceneMotionEstimator] smoothing/classification+ * lives in the ViewModel so it survives analyzer re-creation across binds.+ */+class VideoMotionAnalyzer(+    private val onSample: (FrameDiffSample) -> Unit,+) : ImageAnalysis.Analyzer {+    private var lastSampleAtMs = 0L+    private var previousGrid: FloatArray? = null+    private var previousGridWidth = 0++    @OptIn(ExperimentalGetImage::class)+    override fun analyze(imageProxy: ImageProxy) {+        try {+            val nowMs = SystemClock.elapsedRealtime()+            if (nowMs - lastSampleAtMs < VIDEO_MOTION_SAMPLE_INTERVAL_MS) return+            lastSampleAtMs = nowMs+            val (grid, gridWidth) = readLuminanceGrid(imageProxy) ?: return+            val previous = previousGrid+            previousGrid = grid+            if (previous == null || previous.size != grid.size || previousGridWidth != gridWidth) {+                previousGridWidth = gridWidth+                return // first frame of a (re)bind: no diff to take yet+            }+            previousGridWidth = gridWidth+            SceneMotionMath.sample(previous, grid, gridWidth)?.let { sample ->+                try {+                    onSample(sample)+                } catch (e: IllegalStateException) {+                    Log.error("VideoMotion", "onSample callback threw", e)+                } catch (e: IllegalArgumentException) {+                    Log.error("VideoMotion", "onSample callback threw", e)+                }+            }+        } catch (e: IllegalStateException) {+            Log.error("VideoMotion", "VideoMotionAnalyzer analyze() threw", e)+        } catch (e: IllegalArgumentException) {+            Log.error("VideoMotion", "VideoMotionAnalyzer analyze() threw", e)+        } finally {+            try {+                imageProxy.close()+            } catch (e: IllegalStateException) {+                Log.error("VideoMotion", "imageProxy.close() threw – pipeline stall risk", e)+            }+        }+    }++    /**+     * Downsamples plane 0 (Y) to a grid of at most [VIDEO_MOTION_GRID_MAX_SIDE]+     * samples per side. Returns the grid and its width, or null when unreadable.+     */+    @OptIn(ExperimentalGetImage::class)+    private fun readLuminanceGrid(imageProxy: ImageProxy): Pair<FloatArray, Int>? {+        val plane = imageProxy.planes.firstOrNull() ?: return null+        return sampleYPlaneGrid(+            plane.buffer.duplicate(), plane.rowStride, plane.pixelStride,+            imageProxy.width, imageProxy.height,+        )+    }+}++/**+ * Downsamples a Y plane to a grid of at most [VIDEO_MOTION_GRID_MAX_SIDE] samples+ * per side. Shared by the CameraX [VideoMotionAnalyzer] and the Camera2 custom+ * path's ImageReader analysis surface, so both pipelines feed the estimator the+ * same signal. Returns the grid and its width, or null when unreadable.+ */+internal fun sampleYPlaneGrid(+    buffer: java.nio.ByteBuffer,+    rowStride: Int,+    pixelStride: Int,+    width: Int,+    height: Int,+): Pair<FloatArray, Int>? {+    if (width <= 0 || height <= 0) return null+    val strideX = maxOf(1, width / VIDEO_MOTION_GRID_MAX_SIDE)+    val strideY = maxOf(1, height / VIDEO_MOTION_GRID_MAX_SIDE)+    val gridWidth = (width + strideX - 1) / strideX+    val gridHeight = (height + strideY - 1) / strideY+    val grid = FloatArray(gridWidth * gridHeight)+    var out = 0+    var y = 0+    while (y < height) {+        val rowStart = y * rowStride+        var x = 0+        while (x < width) {+            val index = rowStart + x * pixelStride+            if (index >= buffer.limit()) return null+            grid[out++] = (buffer.get(index).toInt() and 0xFF).toFloat()+            x += strideX+        }+        y += strideY+    }+    return grid to gridWidth+}
camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.ktnew file mode 100644index 0000000000..9d13a518a9--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/VideoRecordingEngine.kt@@ -0,0 +1,71 @@+package com.vayunmathur.camera.platform++import android.view.Surface+import com.vayunmathur.camera.domain.RecordingPath+import java.io.File++/**+ * Clean boundary between the two video recording pipelines, so a recording+ * request looks the same whichever engine serves it — and so the stills+ * migration can later follow the same shape (one request in, one outcome out,+ * engine-specific surfaces/sessions hidden behind the implementation).+ *+ * - [Camera2VideoRecordingEngine]: Camera2-first. Owns the CameraDevice,+ *   CaptureSession and request, with preview + encoder + analysis surfaces.+ *   The only engine that can re-target the encoder mid-recording.+ * - [CameraXVideoRecordingEngine]: the existing CameraX Recorder path. It is+ *   the degraded fallback for everything the Camera2 path cannot honestly+ *   provide (HLG, vendor stabilization, AV1, a failed Camera2 open, or the+ *   gate being off) — its bitrate is fixed when its Recorder is built and is+ *   adapted only before `prepareRecording`.+ */+interface VideoRecordingEngine {+    val path: RecordingPath++    /**+     * Starts recording. Camera2 implementations require [request.cameraId]+     * and take ownership of the camera device (any CameraX session must be+     * torn down first); [request.previewSurface] is where preview frames go+     * (Camera2 may supply its own owned surface when null).+     */+    fun start(request: VideoRecordingRequest, onFinalized: (VideoRecordingOutcome) -> Unit)++    /** Stops and finalizes; the outcome arrives via the [start] callback. */+    fun stop()+}++/** One recording, engine-agnostic. */+data class VideoRecordingRequest(+    val outputFile: File,+    val cameraId: String? = null,+    val previewSurface: Surface? = null,+    val audioEnabled: Boolean = true,+)++/**+ * A finished (or failed) recording. [error] != null means [outputFile] must+ * not be saved (implementations delete corrupt output before reporting).+ */+data class VideoRecordingOutcome(+    val outputFile: File,+    val error: Exception? = null,+)++/**+ * CameraX Recorder engine: delegates to the existing session/record plumbing.+ * The lambdas keep this adapter free of CameraX session state of its own.+ */+class CameraXVideoRecordingEngine(+    private val startImpl: (VideoRecordingRequest) -> Unit,+    private val stopImpl: () -> Unit,+) : VideoRecordingEngine {+    override val path: RecordingPath = RecordingPath.CAMERAX_RECORDER++    override fun start(request: VideoRecordingRequest, onFinalized: (VideoRecordingOutcome) -> Unit) {+        // Finalization for this engine is reported by the caller's existing+        // VideoRecordEvent plumbing; the adapter only drives start/stop.+        startImpl(request)+    }++    override fun stop() = stopImpl()+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Executor.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Executor.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Executor.ktnew file mode 100644index 0000000000..b7d3f013da--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Executor.kt@@ -0,0 +1,66 @@+package com.vayunmathur.camera.platform.camera2++import android.os.Handler+import android.os.HandlerThread+import android.os.Looper+import java.util.concurrent.Executor+import java.util.concurrent.RejectedExecutionException++/**+ * Camera2 migration Phase 0: single-threaded background executor for Camera2+ * callbacks, plus a main-thread poster.+ *+ * Ownership: whoever constructs this owns it and must call [shutdown] exactly+ * when the owning session/screen is destroyed. The executor is single-use —+ * after [shutdown] it never restarts; construct a new one for a new session.+ * Work submitted after shutdown is rejected, never silently queued.+ */+class Camera2Executor(+    threadName: String = DEFAULT_THREAD_NAME,+) : Executor, AutoCloseable {++    private val thread = HandlerThread(threadName).apply { start() }+    private val handler = Handler(thread.looper)+    private val mainHandler = Handler(Looper.getMainLooper())++    @Volatile+    var isShutdown: Boolean = false+        private set++    val looper: Looper get() = thread.looper++    fun isOnCameraThread(): Boolean = Looper.myLooper() == thread.looper++    override fun execute(command: Runnable) {+        if (isShutdown || !handler.post(command)) {+            throw RejectedExecutionException("Camera2Executor is shut down")+        }+    }++    /** Posts to the main thread; returns false (and drops the task) after shutdown. */+    fun postMain(task: Runnable): Boolean = !isShutdown && mainHandler.post(task)++    /**+     * Deterministic shutdown: stops accepting work, quits safely (already-queued+     * tasks run to completion), then joins the thread for up to [timeoutMs].+     * Idempotent. Returns true when the thread actually terminated.+     */+    fun shutdown(timeoutMs: Long = DEFAULT_SHUTDOWN_TIMEOUT_MS): Boolean {+        if (isShutdown) return !thread.isAlive+        isShutdown = true+        thread.quitSafely()+        if (timeoutMs > 0 && Thread.currentThread() !== thread) {+            runCatching { thread.join(timeoutMs) }+        }+        return !thread.isAlive+    }++    override fun close() {+        shutdown()+    }++    companion object {+        const val DEFAULT_THREAD_NAME = "Camera2Executor"+        const val DEFAULT_SHUTDOWN_TIMEOUT_MS = 2_000L+    }+}
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.ktnew file mode 100644index 0000000000..0c9144276d--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt@@ -0,0 +1,239 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraManager+import android.hardware.camera2.CameraMetadata+import android.hardware.camera2.params.StreamConfigurationMap+import android.os.Build+import android.util.Range+import android.util.Size+import com.vayunmathur.camera.domain.LensFacing++/**+ * Camera2 migration Phase 0: cached, pure-data snapshot of everything the+ * existing CameraX-era probes compute ad hoc per bind (see `LensSelector.kt`,+ * `CameraManualControls.readManualControlRanges`,+ * `CameraSessions.highestFpsRange` / `preferredStabilizationMode`,+ * `CameraNightCapture.computeNightExposure`,+ * `CameraPhotoSessionSetup.isJpegRReprocessable`).+ *+ * All [CameraCharacteristics] reads happen once, at construction; accessors+ * never touch the HAL / binder again. The snapshot types are plain data so+ * they can be built from fake maps in unit tests without a device.+ */++/** Summary of one output format in a [StreamConfigurationMap]. */+data class FormatSummary(+    val format: Int,+    val sizes: List<Size>,+) {+    val maxSize: Size? get() = sizes.maxWithOrNull(compareBy({ it.width * it.height }, { it.width }))+    val sizeCount: Int get() = sizes.size+}++/** Pure-data summary of a stream configuration map (never holds the map itself). */+data class StreamConfigSummary(+    val formats: Map<Int, FormatSummary>,+) {+    fun sizesFor(format: Int): List<Size> = formats[format]?.sizes.orEmpty()+    fun maxSizeFor(format: Int): Size? = formats[format]?.maxSize+    val supportsRawSensor: Boolean get() = ImageFormat.RAW_SENSOR in formats++    companion object {+        val EMPTY = StreamConfigSummary(emptyMap())++        /** Builds a summary from plain sizes — the fake-map entry point for tests. */+        fun fromSizes(sizesByFormat: Map<Int, List<Size>>): StreamConfigSummary =+            StreamConfigSummary(sizesByFormat.mapValues { (format, sizes) -> FormatSummary(format, sizes) })++        fun fromMap(map: StreamConfigurationMap?): StreamConfigSummary {+            if (map == null) return EMPTY+            val byFormat = map.outputFormats.associateWith { format ->+                runCatching { map.getOutputSizes(format)?.toList().orEmpty() }.getOrDefault(emptyList())+            }+            return fromSizes(byFormat)+        }+    }+}++/** Immutable per-lens capability snapshot. Pure data; safe to pass across threads. */+data class LensCharacteristicsSnapshot(+    val cameraId: String,+    /** Raw `LENS_FACING` value (`CameraMetadata.LENS_FACING_*`), or null when unreadable. */+    val lensFacingRaw: Int?,+    val physicalCameraIds: Set<String>,+    val isLogicalMultiCamera: Boolean,+    val zoomRatioRange: Range<Float>?,+    val hasFlashUnit: Boolean,+    val exposureTimeRangeNs: Range<Long>?,+    val sensitivityRange: Range<Int>?,+    /** Exposure-compensation range converted to EV steps; null when unreadable. */+    val exposureCompensationEvRange: Range<Float>?,+    val videoStabilizationModes: List<Int>,+    val opticalStabilizationModes: List<Int>,+    val aeTargetFpsRanges: List<Range<Int>>,+    val streamConfig: StreamConfigSummary,+    val hardwareLevel: Int?,+    val availableCapabilities: Set<Int>,+    /** Extension modes (`CameraExtensionCharacteristics.EXTENSION_*`), empty pre-API 31. */+    val availableExtensionModes: List<Int>,+    val focalLengthsMm: List<Float>,+    val colorFilterArrangement: Int?,+) {+    val lensFacing: LensFacing? = when (lensFacingRaw) {+        CameraMetadata.LENS_FACING_BACK -> LensFacing.BACK+        CameraMetadata.LENS_FACING_FRONT -> LensFacing.FRONT+        else -> null+    }+    val minZoomRatio: Float get() = zoomRatioRange?.lower ?: 1f+    val maxZoomRatio: Float get() = zoomRatioRange?.upper ?: 1f+    val supportsRaw: Boolean+        get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_RAW in availableCapabilities+    val supportsReprocess: Boolean+        get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING in availableCapabilities ||+            CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING in availableCapabilities+    val supportsManualSensor: Boolean+        get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR in availableCapabilities+    fun hasExtension(mode: Int): Boolean = mode in availableExtensionModes+}++/**+ * Facade over [CameraManager]/[CameraCharacteristics] for one lens.+ *+ * Ownership: construct once per lens (construction performs the only IPC),+ * read [snapshot] freely afterwards, discard on lens switch — there is no+ * refresh API by design.+ */+class CharacteristicsFacade private constructor(+    val snapshot: LensCharacteristicsSnapshot,+) {+    val cameraId: String get() = snapshot.cameraId++    companion object {+        /** Builds a facade from an already-materialised snapshot (tests / fakes). */+        fun fromSnapshot(snapshot: LensCharacteristicsSnapshot): CharacteristicsFacade =+            CharacteristicsFacade(snapshot)++        /** Builds a facade from plain format sizes plus scalar fields (tests / fakes). */+        fun fromFakeMap(+            cameraId: String,+            lensFacingRaw: Int? = null,+            physicalCameraIds: Set<String> = emptySet(),+            zoomRatioRange: Range<Float>? = null,+            hasFlashUnit: Boolean = false,+            exposureTimeRangeNs: Range<Long>? = null,+            sensitivityRange: Range<Int>? = null,+            exposureCompensationEvRange: Range<Float>? = null,+            videoStabilizationModes: List<Int> = emptyList(),+            opticalStabilizationModes: List<Int> = emptyList(),+            aeTargetFpsRanges: List<Range<Int>> = emptyList(),+            sizesByFormat: Map<Int, List<Size>> = emptyMap(),+            hardwareLevel: Int? = null,+            availableCapabilities: Set<Int> = emptySet(),+            availableExtensionModes: List<Int> = emptyList(),+            focalLengthsMm: List<Float> = emptyList(),+            colorFilterArrangement: Int? = null,+        ): CharacteristicsFacade = fromSnapshot(+            LensCharacteristicsSnapshot(+                cameraId = cameraId,+                lensFacingRaw = lensFacingRaw,+                physicalCameraIds = physicalCameraIds,+                isLogicalMultiCamera =+                    CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA in availableCapabilities,+                zoomRatioRange = zoomRatioRange,+                hasFlashUnit = hasFlashUnit,+                exposureTimeRangeNs = exposureTimeRangeNs,+                sensitivityRange = sensitivityRange,+                exposureCompensationEvRange = exposureCompensationEvRange,+                videoStabilizationModes = videoStabilizationModes,+                opticalStabilizationModes = opticalStabilizationModes,+                aeTargetFpsRanges = aeTargetFpsRanges,+                streamConfig = StreamConfigSummary.fromSizes(sizesByFormat),+                hardwareLevel = hardwareLevel,+                availableCapabilities = availableCapabilities,+                availableExtensionModes = availableExtensionModes,+                focalLengthsMm = focalLengthsMm,+                colorFilterArrangement = colorFilterArrangement,+            ),+        )++        /** Reads every field from [chars] exactly once. Never throws on a missing key. */+        fun fromCharacteristics(+            cameraId: String,+            chars: CameraCharacteristics,+            availableExtensionModes: List<Int> = emptyList(),+        ): CharacteristicsFacade {+            fun <T> get(key: CameraCharacteristics.Key<T>): T? =+                runCatching { chars.get(key) }.getOrNull()++            val capabilities = get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES)+                ?.toSet().orEmpty()+            val zoomRange = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+                get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE)+            } else {+                null+            } ?: get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM)+                ?.let { max -> Range(1f, max) }+            val compensationRange = get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE)+            val compensationStep = get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP)+            val evRange = if (compensationRange != null && compensationStep != null) {+                val step = compensationStep.toFloat()+                Range(compensationRange.lower * step, compensationRange.upper * step)+            } else {+                null+            }+            val physicalIds = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {+                runCatching { chars.physicalCameraIds }.getOrDefault(emptySet())+            } else {+                emptySet()+            }+            return fromSnapshot(+                LensCharacteristicsSnapshot(+                    cameraId = cameraId,+                    lensFacingRaw = get(CameraCharacteristics.LENS_FACING),+                    physicalCameraIds = physicalIds,+                    isLogicalMultiCamera =+                        CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA in capabilities,+                    zoomRatioRange = zoomRange,+                    hasFlashUnit = get(CameraCharacteristics.FLASH_INFO_AVAILABLE) ?: false,+                    exposureTimeRangeNs = get(CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE),+                    sensitivityRange = get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE),+                    exposureCompensationEvRange = evRange,+                    videoStabilizationModes =+                        get(CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES)?.toList().orEmpty(),+                    opticalStabilizationModes =+                        get(CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION)?.toList().orEmpty(),+                    aeTargetFpsRanges =+                        get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)?.toList().orEmpty(),+                    streamConfig = StreamConfigSummary.fromMap(+                        get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP),+                    ),+                    hardwareLevel = get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL),+                    availableCapabilities = capabilities,+                    availableExtensionModes = availableExtensionModes,+                    focalLengthsMm =+                        get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)?.toList().orEmpty(),+                    colorFilterArrangement = get(CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT),+                ),+            )+        }++        /**+         * Full entry point: characteristics + extension availability for [cameraId].+         * Extension probing (`getCameraExtensionCharacteristics`, API 31+) degrades+         * to an empty list on older releases or on any HAL failure.+         */+        fun fromCameraManager(manager: CameraManager, cameraId: String): CharacteristicsFacade {+            val chars = manager.getCameraCharacteristics(cameraId)+            val extensions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+                runCatching {+                    manager.getCameraExtensionCharacteristics(cameraId).availableExtensionModes+                }.getOrDefault(emptyList())+            } else {+                emptyList()+            }+            return fromCharacteristics(cameraId, chars, extensions)+        }+    }+}
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex b1e57cfa3e..6141c28f3a 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -58,6 +58,10 @@     <string name="setting_applies_after_recording">Saved — applies after this recording</string>     <!-- Messenger note when a mode/lens switch is tapped mid-recording and blocked -->     <string name="switch_blocked_while_recording">Stop the recording first to switch</string>+    <!-- One-line note at record start when low storage forced a lower recording bitrate -->+    <string name="lower_bitrate_low_storage">Lower bitrate: low storage</string>+    <!-- One-line note at record start when thermal throttling forced a lower recording bitrate -->+    <string name="lower_bitrate_thermal">Lower bitrate: device is warm</string>      <!-- Video codec settings (SettingsPage) -->     <!-- SettingsPage: section header for video codec selection -->
camera/src/test/java/com/vayunmathur/camera/domain/AdaptiveVideoBitratePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/AdaptiveVideoBitratePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/AdaptiveVideoBitratePolicyTest.ktnew file mode 100644index 0000000000..4f0c75478c--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/AdaptiveVideoBitratePolicyTest.kt@@ -0,0 +1,191 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class AdaptiveVideoBitratePolicyTest {++    private val plenty = AdaptiveVideoBitratePolicy.LOW_STORAGE_THRESHOLD_BYTES * 4+    private val low = AdaptiveVideoBitratePolicy.LOW_STORAGE_THRESHOLD_BYTES - 1++    private fun decide(+        tier: VideoQualityTier,+        motion: SceneMotion?,+        free: Long? = plenty,+        thermal: ThermalPressure = ThermalPressure.NORMAL,+        boost: Boolean = false,+    ) = AdaptiveVideoBitratePolicy.decide(+        AdaptiveBitrateInput(tier, motion, free, thermal, boost)+    )++    // -- Scene scaling on each rung, no forced reductions --------------------++    @Test+    fun staticScalesToFiftyFivePercent() {+        assertEquals(26_400_000, decide(VideoQualityTier.UHD, SceneMotion.STATIC).bitrateBps)+        assertEquals(13_750_000, decide(VideoQualityTier.FHD, SceneMotion.STATIC).bitrateBps)+        assertEquals(6_600_000, decide(VideoQualityTier.HD, SceneMotion.STATIC).bitrateBps)+        assertEquals(3_300_000, decide(VideoQualityTier.SD, SceneMotion.STATIC).bitrateBps)+    }++    @Test+    fun moderateScalesToEightyPercent() {+        assertEquals(38_400_000, decide(VideoQualityTier.UHD, SceneMotion.MODERATE).bitrateBps)+        assertEquals(20_000_000, decide(VideoQualityTier.FHD, SceneMotion.MODERATE).bitrateBps)+        assertEquals(9_600_000, decide(VideoQualityTier.HD, SceneMotion.MODERATE).bitrateBps)+        assertEquals(4_800_000, decide(VideoQualityTier.SD, SceneMotion.MODERATE).bitrateBps)+    }++    @Test+    fun highMotionUsesRungAsIsWithoutBoostProbe() {+        for (tier in VideoQualityTier.entries) {+            val d = decide(tier, SceneMotion.HIGH_MOTION, boost = false)+            assertEquals(tier.baseBitrateBps, d.bitrateBps, "tier=$tier")+            assertFalse(d.boosted)+        }+    }++    @Test+    fun unknownMotionUsesRungAsIs() {+        // No estimator samples yet must never silently cut quality.+        for (tier in VideoQualityTier.entries) {+            assertEquals(tier.baseBitrateBps, decide(tier, motion = null).bitrateBps, "tier=$tier")+        }+    }++    @Test+    fun highMotionBoostsUhdAndFhdByTwentyFivePercentWhenProbeAllows() {+        assertEquals(60_000_000, decide(VideoQualityTier.UHD, SceneMotion.HIGH_MOTION, boost = true).bitrateBps)+        assertEquals(31_250_000, decide(VideoQualityTier.FHD, SceneMotion.HIGH_MOTION, boost = true).bitrateBps)+        assertTrue(decide(VideoQualityTier.UHD, SceneMotion.HIGH_MOTION, boost = true).boosted)+    }++    @Test+    fun highMotionNeverBoostsHdOrSd() {+        assertEquals(12_000_000, decide(VideoQualityTier.HD, SceneMotion.HIGH_MOTION, boost = true).bitrateBps)+        assertEquals(6_000_000, decide(VideoQualityTier.SD, SceneMotion.HIGH_MOTION, boost = true).bitrateBps)+    }++    // -- Forced step-downs ----------------------------------------------------++    @Test+    fun lowStorageStepsDownOneTier() {+        val d = decide(VideoQualityTier.UHD, SceneMotion.HIGH_MOTION, free = low)+        assertEquals(VideoQualityTier.FHD, d.effectiveTier)+        assertEquals(25_000_000, d.bitrateBps)+        assertEquals(setOf(AdaptiveReduction.LOW_STORAGE), d.reductions)+        assertTrue(d.forcedReduction)+    }++    @Test+    fun severeThermalStepsDownOneTier() {+        val d = decide(VideoQualityTier.FHD, SceneMotion.MODERATE, thermal = ThermalPressure.SEVERE)+        assertEquals(VideoQualityTier.HD, d.effectiveTier)+        assertEquals(9_600_000, d.bitrateBps) // HD rung at the moderate factor+        assertEquals(setOf(AdaptiveReduction.THERMAL), d.reductions)+        assertTrue(d.forcedReduction)+    }++    @Test+    fun storageAndThermalStackToTwoTiers() {+        val d = decide(+            VideoQualityTier.UHD, SceneMotion.HIGH_MOTION,+            free = low, thermal = ThermalPressure.SEVERE, boost = true,+        )+        assertEquals(VideoQualityTier.HD, d.effectiveTier)+        assertEquals(12_000_000, d.bitrateBps)+        assertEquals(+            setOf(AdaptiveReduction.LOW_STORAGE, AdaptiveReduction.THERMAL), d.reductions+        )+        assertFalse(d.boosted, "no quality spend while forced down")+    }++    @Test+    fun sceneFactorAppliesToTheSteppedDownRung() {+        // UHD static + low storage: FHD rung x 0.55, not UHD x 0.55 capped down.+        val d = decide(VideoQualityTier.UHD, SceneMotion.STATIC, free = low)+        assertEquals(VideoQualityTier.FHD, d.effectiveTier)+        assertEquals(13_750_000, d.bitrateBps)+    }++    @Test+    fun sdCannotStepDownFurtherButReductionIsRecorded() {+        val d = decide(+            VideoQualityTier.SD, SceneMotion.HIGH_MOTION,+            free = low, thermal = ThermalPressure.SEVERE,+        )+        assertEquals(VideoQualityTier.SD, d.effectiveTier)+        assertEquals(6_000_000, d.bitrateBps)+        assertEquals(+            setOf(AdaptiveReduction.LOW_STORAGE, AdaptiveReduction.THERMAL), d.reductions+        )+        assertFalse(d.forcedReduction, "bitrate did not actually drop below the SD rung")+    }++    @Test+    fun storageThresholdIsExclusiveAndUnknownProbesNeverForce() {+        val atThreshold = decide(+            VideoQualityTier.UHD, SceneMotion.HIGH_MOTION,+            free = AdaptiveVideoBitratePolicy.LOW_STORAGE_THRESHOLD_BYTES,+        )+        assertEquals(VideoQualityTier.UHD, atThreshold.effectiveTier)+        val unknown = decide(+            VideoQualityTier.UHD, SceneMotion.HIGH_MOTION,+            free = null, thermal = ThermalPressure.UNKNOWN,+        )+        assertEquals(48_000_000, unknown.bitrateBps)+        assertTrue(unknown.reductions.isEmpty())+    }++    @Test+    fun boostIsSuppressedByAStepDown() {+        val d = decide(+            VideoQualityTier.UHD, SceneMotion.HIGH_MOTION,+            thermal = ThermalPressure.SEVERE, boost = true,+        )+        assertEquals(VideoQualityTier.FHD, d.effectiveTier)+        assertEquals(25_000_000, d.bitrateBps)+        assertFalse(d.boosted)+    }++    // -- Whole-matrix properties ----------------------------------------------++    @Test+    fun matrixNeverBreachesFloorOrExceedsBoostedRung() {+        val frees = listOf(plenty, low, null)+        val thermals = ThermalPressure.entries+        for (tier in VideoQualityTier.entries) for (motion in listOf<SceneMotion?>(+            SceneMotion.STATIC, SceneMotion.MODERATE, SceneMotion.HIGH_MOTION, null+        )) for (free in frees) for (thermal in thermals) for (boost in listOf(false, true)) {+            val d = decide(tier, motion, free, thermal, boost)+            val floor = (d.effectiveTier.baseBitrateBps *+                AdaptiveVideoBitratePolicy.QUALITY_FLOOR_FRACTION).toInt()+            assertTrue(+                d.bitrateBps >= floor,+                "below floor: tier=$tier motion=$motion free=$free thermal=$thermal -> $d"+            )+            assertTrue(+                d.bitrateBps <= (tier.baseBitrateBps *+                    AdaptiveVideoBitratePolicy.HIGH_MOTION_BOOST_FACTOR).toInt(),+                "above boosted base rung: tier=$tier motion=$motion free=$free thermal=$thermal -> $d"+            )+            // A step-down may never raise the bitrate above the base rung either.+            if (d.effectiveTier != tier) {+                assertTrue(d.bitrateBps <= tier.baseBitrateBps, "step-down raised bitrate: $d")+            }+        }+    }++    @Test+    fun ladderValuesAreTheStaticLadder() {+        // Guards the single source the Recorder ladder is built from.+        assertEquals(48_000_000, VideoQualityTier.UHD.baseBitrateBps)+        assertEquals(25_000_000, VideoQualityTier.FHD.baseBitrateBps)+        assertEquals(12_000_000, VideoQualityTier.HD.baseBitrateBps)+        assertEquals(6_000_000, VideoQualityTier.SD.baseBitrateBps)+        assertEquals(VideoQualityTier.FHD, VideoQualityTier.UHD.lower())+        assertEquals(VideoQualityTier.SD, VideoQualityTier.SD.lower())+    }+}
camera/src/test/java/com/vayunmathur/camera/domain/LiveBitrateControllerTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/LiveBitrateControllerTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/LiveBitrateControllerTest.ktnew file mode 100644index 0000000000..97a216d053--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/LiveBitrateControllerTest.kt@@ -0,0 +1,166 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class LiveBitrateControllerTest {++    private fun decision(+        tier: VideoQualityTier = VideoQualityTier.UHD,+        motion: SceneMotion? = SceneMotion.HIGH_MOTION,+        free: Long? = AdaptiveVideoBitratePolicy.LOW_STORAGE_THRESHOLD_BYTES * 4,+        thermal: ThermalPressure = ThermalPressure.NORMAL,+        boost: Boolean = false,+    ) = AdaptiveVideoBitratePolicy.decide(AdaptiveBitrateInput(tier, motion, free, thermal, boost))++    private fun controller(+        d: AdaptiveBitrateDecision = decision(),+        intervalMs: Long = 2_000L,+    ) = LiveBitrateController(d, intervalMs)++    /** Exactly the two consecutive evaluations a change needs; returns the applied bitrate. */+    private fun drive(+        c: LiveBitrateController,+        motion: SceneMotion?,+        startMs: Long,+    ): Int? {+        c.evaluate(motion, startMs)+        return c.evaluate(motion, startMs + 1_000L)+    }++    @Test+    fun startsAtThePreRecordingDecision() {+        val d = decision(motion = SceneMotion.STATIC)+        assertEquals(26_400_000, controller(d).currentBitrateBps)+    }++    @Test+    fun boundsFollowTheDecision() {+        val boosted = controller(decision(boost = true))+        assertEquals(60_000_000, boosted.ceilingBps)+        assertEquals(19_200_000, boosted.floorBps)++        // Forced down (storage): live motion may not spend the rung back.+        val forced = controller(+            decision(free = AdaptiveVideoBitratePolicy.LOW_STORAGE_THRESHOLD_BYTES - 1)+        )+        assertEquals(VideoQualityTier.FHD, forcedFloorTier(forced))+        assertEquals(25_000_000, forced.ceilingBps)+        assertEquals(10_000_000, forced.floorBps)+    }++    private fun forcedFloorTier(c: LiveBitrateController) =+        VideoQualityTier.entries.first { (it.baseBitrateBps * 0.40).toInt() == c.floorBps }++    @Test+    fun sustainedStaticSceneRampsDownInSlewLimitedSteps() {+        val c = controller() // starts at UHD 48 Mbps+        // One winning candidate needs 2 consecutive evaluations; each applied+        // step moves at most 25% toward it: 48 -> 36 -> 27 -> 26.4 (candidate).+        assertEquals(36_000_000, drive(c, SceneMotion.STATIC, 0L))+        assertEquals(27_000_000, drive(c, SceneMotion.STATIC, 10_000L))+        // The exact candidate (26.4M) is now within 10% of current: the+        // anti-churn threshold deliberately holds at 27M instead of micro-stepping.+        assertEquals(null, drive(c, SceneMotion.STATIC, 20_000L))+        assertEquals(27_000_000, c.currentBitrateBps)+    }++    @Test+    fun aSingleEvaluationNeverChangesAnything() {+        val c = controller()+        assertNull(c.evaluate(SceneMotion.STATIC, 0L))+        assertEquals(48_000_000, c.currentBitrateBps)+    }++    @Test+    fun alternatingMotionDoesNotOscillate() {+        val c = controller()+        var applied = 0+        for (i in 0 until 40) {+            val motion = if (i % 2 == 0) SceneMotion.STATIC else SceneMotion.HIGH_MOTION+            if (c.evaluate(motion, i * 1_000L) != null) applied+++        }+        assertEquals(0, applied, "alternating candidates never win twice in a row")+        assertEquals(48_000_000, c.currentBitrateBps)+    }++    @Test+    fun evaluationsInsideTheIntervalAreHeld() {+        val c = controller()+        // Win the first change at t=1000 (second consecutive evaluation).+        assertNull(c.evaluate(SceneMotion.STATIC, 0L))+        assertEquals(36_000_000, c.evaluate(SceneMotion.STATIC, 1_000L))+        // A reversal inside the 2 s hold is ignored even with two wins.+        assertNull(c.evaluate(SceneMotion.HIGH_MOTION, 1_500L))+        assertNull(c.evaluate(SceneMotion.HIGH_MOTION, 2_000L))+        assertEquals(36_000_000, c.currentBitrateBps)+    }++    @Test+    fun smallCandidateDifferencesAreIgnored() {+        // Moderate (38.4M) -> static candidate is a >10% move, but a controller+        // already at the moderate bitrate sees high-motion (48M) as +25%: applied.+        // Here: HD high (12M) with a moderate candidate (9.6M) is a 20% move: applied.+        val c = controller(decision(tier = VideoQualityTier.HD))+        assertEquals(12_000_000, c.currentBitrateBps)+        val applied = drive(c, SceneMotion.MODERATE, 0L)+        assertEquals(9_600_000, applied)+    }++    @Test+    fun candidatesClampToFloorAndCeiling() {+        val forced = decision(+            tier = VideoQualityTier.UHD,+            free = AdaptiveVideoBitratePolicy.LOW_STORAGE_THRESHOLD_BYTES - 1,+        )+        val c = controller(forced) // effective FHD, starts 25M+        assertEquals(25_000_000, c.candidateFor(SceneMotion.HIGH_MOTION)) // ceiling+        assertEquals(13_750_000, c.candidateFor(SceneMotion.STATIC)) // FHD x 0.55, above floor+        assertEquals(25_000_000, c.candidateFor(null)) // unknown motion: ceiling-wards, no cut+    }++    // -- Recording-path selection ---------------------------------------------++    private val customFriendly = RecordingPathInput(+        customPathEnabled = true,+        liveAdaptationWanted = true,+        hlgRequested = false,+        stabilizationRequested = false,+        codecAv1Requested = false,+        analysisBound = true,+    )++    @Test+    fun customPathOnlyWhenEverythingAligns() {+        assertEquals(RecordingPath.CUSTOM_CAMERA2, RecordingPathPolicy.select(customFriendly))+    }++    @Test+    fun cameraXFALLBACKS() {+        assertEquals(+            RecordingPath.CAMERAX_RECORDER,+            RecordingPathPolicy.select(customFriendly.copy(customPathEnabled = false))+        )+        assertEquals(+            RecordingPath.CAMERAX_RECORDER,+            RecordingPathPolicy.select(customFriendly.copy(liveAdaptationWanted = false))+        )+        assertEquals(+            RecordingPath.CAMERAX_RECORDER,+            RecordingPathPolicy.select(customFriendly.copy(hlgRequested = true))+        )+        assertEquals(+            RecordingPath.CAMERAX_RECORDER,+            RecordingPathPolicy.select(customFriendly.copy(stabilizationRequested = true))+        )+        assertEquals(+            RecordingPath.CAMERAX_RECORDER,+            RecordingPathPolicy.select(customFriendly.copy(codecAv1Requested = true))+        )+        assertEquals(+            RecordingPath.CAMERAX_RECORDER,+            RecordingPathPolicy.select(customFriendly.copy(analysisBound = false))+        )+    }+}
camera/src/test/java/com/vayunmathur/camera/domain/SceneMotionEstimatorTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/SceneMotionEstimatorTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/SceneMotionEstimatorTest.ktnew file mode 100644index 0000000000..16491eb014--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/SceneMotionEstimatorTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class SceneMotionEstimatorTest {++    private val w = 8+    private val h = 6++    /** Flat grid at [value]. */+    private fun flat(value: Float) = FloatArray(w * h) { value }++    /** Checkerboard of [a]/[b]: maximum detail, zero motion when repeated. */+    private fun checker(a: Float, b: Float) =+        FloatArray(w * h) { i -> if ((i % w + i / w) % 2 == 0) a else b }++    @Test+    fun identicalFramesAreStaticEvenWhenHighlyDetailed() {+        val est = SceneMotionEstimator()+        // A repeated checkerboard has a huge gradient but zero diff: detail is not motion.+        repeat(4) {+            assertEquals(SceneMotion.STATIC, est.addFrame(checker(0f, 255f), checker(0f, 255f), w))+        }+    }++    @Test+    fun sampleMathOnFlatFrames() {+        val s = SceneMotionMath.sample(flat(100f), flat(110f), w)+        assertEquals(10.0, s!!.meanAbsDiff)+        assertEquals(0.0, s.meanGradient)+        assertNull(SceneMotionMath.sample(flat(0f), FloatArray(3), w))+        assertNull(SceneMotionMath.sample(flat(0f), flat(0f), 0))+    }++    @Test+    fun smallBrightnessDriftIsStatic() {+        val est = SceneMotionEstimator()+        repeat(3) { assertEquals(SceneMotion.STATIC, est.addFrame(flat(100f), flat(101f), w)) }+    }++    @Test+    fun moderateShiftIsModerate() {+        val est = SceneMotionEstimator()+        // +5 luminance everywhere on a flat scene: effective 5 x 0.85 = 4.25.+        repeat(3) { assertEquals(SceneMotion.MODERATE, est.addFrame(flat(100f), flat(105f), w)) }+    }++    @Test+    fun largeShiftIsHighMotion() {+        val est = SceneMotionEstimator()+        repeat(3) { assertEquals(SceneMotion.HIGH_MOTION, est.addFrame(flat(50f), flat(90f), w)) }+    }++    @Test+    fun detailWeightsTheSameDiffUpwards() {+        // Same mean diff (10) reads higher over texture than over a flat wall.+        val flatClass = SceneMotionMath.classify(10.0, 0.0)+        val texturedClass = SceneMotionMath.classify(10.0, 255.0)+        assertEquals(SceneMotion.MODERATE, flatClass) // 10 x 0.85 = 8.5+        assertEquals(SceneMotion.HIGH_MOTION, texturedClass) // 10 x 1.15 = 11.5+        // ...but detail with (near-)zero diff can never fake motion.+        assertEquals(SceneMotion.STATIC, SceneMotionMath.classify(0.0, 255.0))+        assertEquals(SceneMotion.STATIC, SceneMotionMath.classify(2.0, 255.0)) // 2.3 < 2.5+    }++    @Test+    fun windowSmoothsASingleFrameSpike() {+        val est = SceneMotionEstimator(windowSize = 4)+        repeat(3) { est.add(FrameDiffSample(0.0, 0.0)) }+        // One violent frame in four: mean diff 10 -> effective 8.5, not high motion.+        assertEquals(SceneMotion.MODERATE, est.add(FrameDiffSample(40.0, 0.0)))+        assertEquals(SceneMotion.MODERATE, est.lastClassification)+    }++    @Test+    fun sustainedMotionTakesOverTheWindow() {+        val est = SceneMotionEstimator(windowSize = 2)+        est.add(FrameDiffSample(0.0, 0.0))+        est.add(FrameDiffSample(0.0, 0.0))+        assertEquals(SceneMotion.STATIC, est.lastClassification)+        est.add(FrameDiffSample(30.0, 0.0))+        assertEquals(SceneMotion.HIGH_MOTION, est.add(FrameDiffSample(30.0, 0.0)))+    }++    @Test+    fun noSamplesMeansNoClassification() {+        val est = SceneMotionEstimator()+        assertNull(est.lastClassification)+        assertEquals(0, est.sampleCount)+        est.add(FrameDiffSample(0.0, 0.0))+        est.reset()+        assertNull(est.lastClassification)+        assertEquals(0, est.sampleCount)+    }+}