camera: slo-mo recording structurally ready, awaiting device proof
- Commit
9f95b9295ed019c347845c68ad4e83984bf019ac- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-23 02:08 UTC (13 days ago)
- Parents
1955423
Pieces 2/4/7 of the documented slo-mo list close: a shared codec/muxer/drain core under externally-owned sessions (Camera2RecordingCore), a slo-mo preview bridge (plumbed, never composed live), and save-path glue with a one-shot CameraX-HFR rebind fallback. Six of seven pieces done; recordingEngineReady stays false - only timestamp verification on a device remains, and tests pin remainingPieces() to exactly that. Verified: compile + slo-mo/preview/high-speed seam tests green. No live behavior change.
Diff
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.ktnew file mode 100644index 0000000000..c8a31659a6--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt@@ -0,0 +1,296 @@+package com.vayunmathur.camera.platform++import android.annotation.SuppressLint+import android.media.AudioFormat+import android.media.AudioRecord+import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaFormat+import android.media.MediaMuxer+import android.media.MediaRecorder+import android.os.Bundle+import android.view.Surface+import com.vayunmathur.camera.platform.camera2.EncoderSurfaceHandoff+import com.vayunmathur.camera.platform.camera2.MuxerStartPolicy+import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership+import com.vayunmathur.camera.platform.camera2.SharedRecordingCoreLifecycle+import com.vayunmathur.library.log.Log+import java.io.File+import java.nio.ByteBuffer++/**+ * Shared codec/muxer/drain core (SloMoEnginePolicy piece 2), extracted from+ * [Camera2VideoRecordingEngine] so the same encoder, muxer and drain can+ * run under an externally-owned session — the constrained high-speed+ * session — instead of only under the engine's own regular session.+ *+ * This core owns no camera device and no capture session. Its caller owns+ * the session, lists [prepareEncoderSurface]'s surface as a configure-time+ * target, and drives the stop boundary (stop repeating first, then+ * [signalVideoEos]). The engine keeps that exact flow for its own regular+ * session; the slo-mo glue drives it from `Camera2HighSpeedSession`.+ *+ * Ordering is enforced twice: [EncoderSurfaceHandoff] for the codec-first+ * surface handoff and [SharedRecordingCoreLifecycle] for drain/EOS/finalize.+ */+class Camera2RecordingCore(+ private val config: CustomRecordingConfig,+ private val initialBitrateBps: () -> Int,+ ownership: RecordingSessionOwnership = RecordingSessionOwnership.ENGINE_OWNED,+) {+ val lifecycle = SharedRecordingCoreLifecycle(ownership)+ private val encoderHandoff = EncoderSurfaceHandoff()++ private var preparedEncoderSurface: Surface? = null+ 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 draining = false+ private var drainThread: Thread? = null+ private var audioThread: Thread? = null++ val isMuxerStarted: Boolean get() = muxerStarted++ /**+ * Configures the video codec and exposes its input surface before any+ * camera session is opened. Idempotent; returns null on failure.+ */+ fun prepareEncoderSurface(): Surface? {+ preparedEncoderSurface?.let { return it }+ return try {+ if (videoCodec == null) configureVideoCodec()+ val surface = videoCodec!!.createInputSurface()+ encoderHandoff.markSurfaceExposed()+ lifecycle.markSurfacePrepared()+ preparedEncoderSurface = surface+ surface+ } catch (e: IllegalStateException) {+ Log.error("Camera2Recorder", "prepareEncoderSurface failed", e)+ null+ }+ }++ fun preparedEncoderSurface(): Surface? = preparedEncoderSurface++ private fun configureVideoCodec() {+ 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, initialBitrateBps())+ setInteger(MediaFormat.KEY_FRAME_RATE, config.fps)+ if (config.captureFps != config.fps) {+ setInteger(MediaFormat.KEY_CAPTURE_RATE, config.captureFps)+ }+ setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, config.iFrameIntervalSec)+ }+ videoCodec = MediaCodec.createEncoderByType(config.videoMime).apply {+ configure(videoFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ }+ encoderHandoff.markCodecConfigured()+ }++ /** Creates the muxer and (when enabled) the audio codec. Video codec must already be configured. */+ fun setupMuxerAndAudio(outputFile: File) {+ if (videoCodec == null) configureVideoCodec()+ if (config.audioEnabled) {+ val audioFormat = MediaFormat.createAudioFormat(+ MediaFormat.MIMETYPE_AUDIO_AAC, config.audioSampleRate, 1,+ ).apply {+ setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)+ setInteger(MediaFormat.KEY_BIT_RATE, config.audioBitrateBps)+ setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, AUDIO_MAX_INPUT_BYTES)+ }+ audioCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC).apply {+ configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ start()+ }+ }+ muxer = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)+ }++ fun startVideoCodec() {+ videoCodec?.start()+ }++ fun markSessionStreaming() {+ encoderHandoff.markSessionStreaming()+ }++ fun startDrain() {+ draining = true+ lifecycle.markDraining()+ drainThread = Thread({+ val bufferInfo = MediaCodec.BufferInfo()+ while (draining || muxerStarted) {+ drainCodec(videoCodec, isVideo = true, bufferInfo)+ drainCodec(audioCodec, isVideo = false, bufferInfo)+ if (!draining) break+ Thread.sleep(DRAIN_POLL_MS)+ }+ }, "Camera2RecorderDrain").apply { start() }+ }++ 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 (+ !muxerStarted && MuxerStartPolicy.shouldStart(+ hasVideoTrack = videoTrackIndex >= 0,+ hasAudioTrack = audioTrackIndex >= 0,+ audioEnabled = config.audioEnabled,+ )+ ) {+ 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. No-op without audio. */+ fun startAudio() {+ if (!config.audioEnabled) return+ 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 (draining) {+ 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 (!draining) 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() }+ }++ fun signalVideoEos() {+ try {+ videoCodec?.signalEndOfInputStream()+ encoderHandoff.markEosSignalled()+ lifecycle.markEosSignalled()+ } catch (_: IllegalStateException) {+ }+ draining = false+ }++ fun stopAudio() {+ try {+ audioRecord?.stop()+ } catch (_: IllegalStateException) {+ }+ }++ fun joinDrainAndAudio(timeoutMs: Long = DRAIN_JOIN_TIMEOUT_MS) {+ drainThread?.join(timeoutMs)+ audioThread?.join(timeoutMs)+ }++ fun finishMuxer() {+ if (muxerStarted) {+ try {+ muxer?.stop()+ } catch (_: IllegalStateException) {+ }+ }+ lifecycle.markFinalized()+ }++ fun setVideoBitrate(bitrateBps: Int) {+ videoCodec?.setParameters(Bundle().apply {+ putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, bitrateBps)+ })+ }++ fun release() {+ draining = false+ 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 { preparedEncoderSurface?.release() } catch (_: Exception) {}+ preparedEncoderSurface = null+ encoderHandoff.markReleased()+ lifecycle.markReleased()+ audioRecord = null+ audioCodec = null+ videoCodec = null+ muxer = null+ muxerStarted = false+ videoTrackIndex = -1+ audioTrackIndex = -1+ drainThread = null+ audioThread = null+ }++ companion object {+ 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+ private const val AUDIO_DEQUEUE_TIMEOUT_US = 10_000L+ private const val DRAIN_POLL_MS = 5L+ const val DRAIN_JOIN_TIMEOUT_MS = 2_000L+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.ktindex b244698c81..838529245d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt@@ -9,8 +9,19 @@ import com.vayunmathur.camera.platform.camera2.HighSpeedSelection import com.vayunmathur.camera.platform.camera2.SloMoCamera2Gate import com.vayunmathur.camera.platform.camera2.SloMoEngine import com.vayunmathur.camera.platform.camera2.SloMoEngineInput+import androidx.lifecycle.viewModelScope+import com.vayunmathur.camera.data.saveVideoStaged+import com.vayunmathur.camera.data.setLastCaptureUri+import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership import com.vayunmathur.camera.platform.camera2.SloMoEnginePolicy+import com.vayunmathur.camera.platform.camera2.SloMoRecordingReadiness+import com.vayunmathur.camera.platform.camera2.SloMoSaveAction+import com.vayunmathur.camera.platform.camera2.SloMoSavePathPolicy import com.vayunmathur.library.log.Log+import java.io.File+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext /** * Camera2 migration Phase 5: slo-mo glue between the gated Camera2@@ -21,23 +32,21 @@ import com.vayunmathur.library.log.Log * With the gates on (the default), the lens snapshot, planner * selection and AVC encoder probe are assembled and [SloMoEnginePolicy] * decides; the reason is logged either way. Today the policy always keeps- * recording on CameraX because `recordingEngineReady` is false: the- * constrained session (`Camera2HighSpeedSession`) is not yet coupled to- * the Phase-1 codec/muxer engine and the output has not been- * device-verified. Flipping the gate therefore changes logging, never the- * recording path, until that coupling lands.+ * recording on CameraX because `recordingEngineReady` is false: pieces+ * 2/4/7 are now in place (shared core, preview bridge, save-path glue),+ * but the output has not been device-verified (piece 6). Flipping the+ * gate therefore changes logging, never the recording path, until that+ * verification lands. */ /** Encoder mime the Phase-1 engine would record slo-mo with. */ private const val SLOMO_ENCODER_MIME = MediaFormat.MIMETYPE_VIDEO_AVC /**- * The Phase-1 engine configuration for [selection]: its size, playback- * rate as the encoder frame rate, and capture rate as `KEY_CAPTURE_RATE`.- * Building this config does not route any recording — the engine still- * opens its own (regular) device, so the policy's- * `recordingEngineReady` stays false until it can be driven by- * `Camera2HighSpeedSession`'s constrained session.+ * The recording configuration for [selection]: its size, playback rate+ * as the encoder frame rate, and capture rate as `KEY_CAPTURE_RATE`.+ * No-audio (CameraX slo-mo's contract, piece 5). Building this config+ * does not route any recording. */ internal fun HighSpeedSelection.toCustomRecordingConfig(): CustomRecordingConfig = CustomRecordingConfig(@@ -46,8 +55,25 @@ internal fun HighSpeedSelection.toCustomRecordingConfig(): CustomRecordingConfig fps = playbackFps, captureFps = captureFps, videoMime = SLOMO_ENCODER_MIME,+ audioEnabled = false, ) +/**+ * Builds the shared codec/muxer/drain core for one Camera2 slo-mo+ * recording (piece 2 + 7): externally owned, so the constrained+ * high-speed session — not a regular engine session — drives it.+ * The caller prepares its encoder surface before opening the session.+ */+internal fun buildCamera2SloMoRecordingCore(+ selection: HighSpeedSelection,+): Camera2RecordingCore = Camera2RecordingCore(+ config = selection.toCustomRecordingConfig(),+ initialBitrateBps = { SLOMO_RECORDING_BITRATE_BPS },+ ownership = RecordingSessionOwnership.EXTERNALLY_OWNED,+)++private const val SLOMO_RECORDING_BITRATE_BPS = 20_000_000+ /** The Camera2 slo-mo decision for one lens snapshot; pure but for logging. */ internal fun CameraViewModel.camera2SloMoDecision( facade: CharacteristicsFacade,@@ -62,7 +88,7 @@ internal fun CameraViewModel.camera2SloMoDecision( hasConstrainedHighSpeed = snapshot.supportsConstrainedHighSpeedVideo, hasSelection = selection != null, encoderSupportsCaptureRate = encoderSupportsCaptureRate,- recordingEngineReady = false,+ recordingEngineReady = SloMoRecordingReadiness.recordingEngineReady, ) val reason = SloMoEnginePolicy.exclusionReason(input) Log.debug(@@ -121,3 +147,59 @@ internal fun CameraViewModel.evaluateCamera2SloMoDecision() { Log.status("SloMo", "Camera2 slo-mo decision failed; staying on CameraX", e) } }++/**+ * Save-path glue for one finished Camera2 slo-mo attempt (piece 7): a+ * readable, error-free staged file lands through the same+ * `saveVideoStaged` seam as every other Camera2/CameraX recording; a+ * failed attempt discards its file, latches this bind one-shot, and+ * rebinds the CameraX HFR ladder so the next press records on CameraX.+ * Runs its file I/O off-main. Returns the action taken (for tests/logs).+ */+internal fun CameraViewModel.handleCamera2SloMoFinalized(+ displayName: String,+ stagedFile: File,+ outcomeError: Boolean,+ outputReadable: Boolean,+ cameraId: String,+): SloMoSaveAction {+ val alreadyLatched = camera2SloMoFallbackBindKeyMutable.value ==+ com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch+ .bindKey(cameraId, cameraModeMutable.value)+ val action = SloMoSavePathPolicy.actionFor(outcomeError, outputReadable, alreadyLatched)+ viewModelScope.launch {+ when (action) {+ SloMoSaveAction.SAVE_STAGED -> withContext(Dispatchers.IO) {+ if (stagedFile.exists()) {+ saveVideoStaged(displayName, stagedFile)?.let { setLastCaptureUri(it) }+ stagedFile.delete()+ }+ }+ SloMoSaveAction.DISCARD_AND_REBIND_CAMERAX -> {+ withContext(Dispatchers.IO) { stagedFile.delete() }+ // One-shot latch: only the first failure for this bind rebinds.+ if (onCamera2SloMoFailed(cameraId)) {+ teardownSession()+ setupHighSpeedSession()+ }+ }+ SloMoSaveAction.DISCARD_LATCHED -> withContext(Dispatchers.IO) {+ stagedFile.delete()+ }+ }+ }+ return action+}++/**+ * Rebinds the CameraX high-speed session after a Camera2 slo-mo attempt+ * failed before producing a file. One-shot per bind key, like preview's+ * latch; a repeat failure for the same key does not rebind-loop.+ */+internal fun CameraViewModel.rebindCameraXAfterSloMoFailure(cameraId: String) {+ if (!onCamera2SloMoFailed(cameraId)) return+ viewModelScope.launch {+ teardownSession()+ setupHighSpeedSession()+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.ktindex 399f4557e5..c70d8811ce 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -7,15 +7,9 @@ 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@@ -23,11 +17,9 @@ import com.vayunmathur.camera.domain.LiveBitrateController import com.vayunmathur.camera.domain.RecordingPath import com.vayunmathur.camera.domain.RecordingPathPolicy import com.vayunmathur.camera.domain.SceneMotion-import com.vayunmathur.camera.platform.camera2.EncoderSurfaceHandoff-import com.vayunmathur.camera.platform.camera2.MuxerStartPolicy+import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership 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@@ -145,21 +137,14 @@ class Camera2VideoRecordingEngine( start(request.outputFile, cameraId, request.previewSurface) } - private val encoderHandoff = EncoderSurfaceHandoff()- private var preparedEncoderSurface: Surface? = null-- private var videoCodec: MediaCodec? = null- private var audioCodec: MediaCodec? = null- private var audioRecord: AudioRecord? = null- private var muxer: MediaMuxer? = null-- @Volatile private var muxerStarted = false- private var videoTrackIndex = -1- private var audioTrackIndex = -1+ /** Shared codec/muxer/drain core (piece 2); this engine owns the session, the core does not. */+ private val core = Camera2RecordingCore(+ config,+ initialBitrateBps = { controller.currentBitrateBps },+ ownership = RecordingSessionOwnership.ENGINE_OWNED,+ ) @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 @@ -169,11 +154,11 @@ class Camera2VideoRecordingEngine( check(!running) { "Camera2VideoRecordingEngine already running" } this.outputFile = outputFile try {- setupEncoders(outputFile)+ core.setupMuxerAndAudio(outputFile) openCamera(cameraId, previewSurface) running = true- startDrainThread()- startAudioThread()+ core.startDrain()+ core.startAudio() startAdaptationThread() } catch (e: Exception) { releaseAll()@@ -189,16 +174,11 @@ class Camera2VideoRecordingEngine( captureSession?.stopRepeating() captureSession?.close() cameraDevice?.close()- try {- videoCodec?.signalEndOfInputStream()- encoderHandoff.markEosSignalled()- } catch (_: IllegalStateException) {- }- audioRecord?.stop()- drainThread?.join(DRAIN_JOIN_TIMEOUT_MS)- audioThread?.join(DRAIN_JOIN_TIMEOUT_MS)+ core.signalVideoEos()+ core.stopAudio()+ core.joinDrainAndAudio() adaptationThread?.interrupt()- if (muxerStarted) muxer?.stop()+ core.finishMuxer() } catch (e: IllegalStateException) { Log.error("Camera2Recorder", "stop() failed", e) } finally {@@ -228,78 +208,26 @@ class Camera2VideoRecordingEngine( } /**- * Codec-first split (SloMoEnginePolicy piece 1): configures the video- * codec and exposes its input surface *before* any camera is opened,- * so a caller-owned session (e.g. the constrained high-speed session)- * can list the surface as a configure-time target. Idempotent; [start]- * reuses the prepared surface instead of creating one in `openCamera`.- * Returns null when the codec cannot be configured.+ * Codec-first split (SloMoEnginePolicy piece 1), delegated to the+ * shared core: configures the video codec and exposes its input+ * surface *before* any camera is opened, so a caller-owned session+ * (e.g. the constrained high-speed session) can list the surface as a+ * configure-time target. Idempotent; [start] reuses the prepared+ * surface instead of creating one in `openCamera`. */- fun prepareEncoderSurface(): Surface? {- preparedEncoderSurface?.let { return it }- return try {- if (videoCodec == null) configureVideoCodec()- val surface = videoCodec!!.createInputSurface()- encoderHandoff.markSurfaceExposed()- preparedEncoderSurface = surface- surface- } catch (e: IllegalStateException) {- Log.error("Camera2Recorder", "prepareEncoderSurface failed", e)- null- }- }+ fun prepareEncoderSurface(): Surface? = core.prepareEncoderSurface() /** The surface exposed by [prepareEncoderSurface], or null before it. */- fun preparedEncoderSurface(): Surface? = preparedEncoderSurface-- private fun configureVideoCodec() {- val videoFormat = MediaFormat.createVideoFormat(config.videoMime, config.width, config.height)- .apply {- setInteger(- MediaFormat.KEY_COLOR_FORMAT,- MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface- )- setInteger(MediaFormat.KEY_BIT_RATE, controller.currentBitrateBps)- setInteger(MediaFormat.KEY_FRAME_RATE, config.fps)- // Slo-mo (Phase 5): capture faster than playback so the- // encoder stretches sample timestamps into a slow MP4.- if (config.captureFps != config.fps) {- setInteger(MediaFormat.KEY_CAPTURE_RATE, config.captureFps)- }- setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, config.iFrameIntervalSec)- }- videoCodec = MediaCodec.createEncoderByType(config.videoMime).apply {- configure(videoFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)- }- encoderHandoff.markCodecConfigured()- }-- private fun setupEncoders(outputFile: File) {- if (videoCodec == null) configureVideoCodec()- if (config.audioEnabled) {- val audioFormat = MediaFormat.createAudioFormat(- MediaFormat.MIMETYPE_AUDIO_AAC, config.audioSampleRate, 1- ).apply {- setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)- setInteger(MediaFormat.KEY_BIT_RATE, config.audioBitrateBps)- setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, AUDIO_MAX_INPUT_BYTES)- }- audioCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC).apply {- configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)- start()- }- }- muxer = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)- }+ fun preparedEncoderSurface(): Surface? = core.preparedEncoderSurface() @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 = preparedEncoderSurface ?: prepareEncoderSurface()+ val encoderSurface = core.preparedEncoderSurface() ?: prepareEncoderSurface() ?: throw IllegalStateException("encoder input surface unavailable")- videoCodec!!.start()+ core.startVideoCodec() // 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).@@ -353,7 +281,7 @@ class Camera2VideoRecordingEngine( device.createCaptureSession(surfaces, object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { captureSession = session- encoderHandoff.markSessionStreaming()+ core.markSessionStreaming() val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply { addTarget(encoderSurface) addTarget(effectivePreview)@@ -399,106 +327,6 @@ class Camera2VideoRecordingEngine( 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 (- !muxerStarted && MuxerStartPolicy.shouldStart(- hasVideoTrack = videoTrackIndex >= 0,- hasAudioTrack = audioTrackIndex >= 0,- audioEnabled = config.audioEnabled,- )- ) {- 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() {- if (!config.audioEnabled) return- 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({@@ -508,9 +336,7 @@ class Camera2VideoRecordingEngine( 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)- })+ core.setVideoBitrate(target) Log.debug("Camera2Recorder", "live bitrate -> $target") } catch (e: IllegalStateException) { Log.error("Camera2Recorder", "setParameters(KEY_BITRATE) failed", e)@@ -527,23 +353,8 @@ class Camera2VideoRecordingEngine( 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 { preparedEncoderSurface?.release() } catch (_: Exception) {}- preparedEncoderSurface = null- encoderHandoff.markReleased()+ core.release() try { cameraThread?.quitSafely() } catch (_: Exception) {}- audioRecord = null- audioCodec = null- videoCodec = null- muxer = null- muxerStarted = false- videoTrackIndex = -1- audioTrackIndex = -1 } companion object {@@ -551,12 +362,6 @@ class Camera2VideoRecordingEngine( 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
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 dd8038f1c0..3813174611 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -146,6 +146,16 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val camera2SloMoEnabledMutable = MutableStateFlow(true) val camera2SloMoEnabled = camera2SloMoEnabledMutable.asStateFlow() + /** One-shot CameraX fallback latch for a failed Camera2 slo-mo attempt (piece 7). */+ internal val camera2SloMoFallbackLatch =+ com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch()+ internal val camera2SloMoFallbackBindKeyMutable = MutableStateFlow<String?>(null)+ val camera2SloMoFallbackBindKey = camera2SloMoFallbackBindKeyMutable.asStateFlow()++ /** Live Camera2 high-speed session while the gated slo-mo preview is composed; null otherwise. */+ internal var activeCamera2HighSpeedSession:+ com.vayunmathur.camera.platform.camera2.Camera2HighSpeedSession? = null+ /** * Gate for the Camera2 NIGHT path. Default ON — the Camera2 decision
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.ktindex 98bea76544..ccd047545d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt@@ -49,9 +49,41 @@ fun CameraViewModel.setCamera2PreviewEnabled(enabled: Boolean) { /** Turns the Camera2 slo-mo gate on/off (SLOW_MO only; see SloMoEnginePolicy). */ fun CameraViewModel.setCamera2SloMoEnabled(enabled: Boolean) { camera2SloMoEnabledMutable.value = enabled+ if (enabled) clearCamera2SloMoFallback() viewModelScope.launch { ds.setString("camera_camera2_slomo", enabled.toString()) } } +/**+ * Records a Camera2 slo-mo preview/recording failure. First failure for+ * this bind key latches (returns true) and the caller rebinds the CameraX+ * high-speed session; repeat failures for the same key are ignored so a+ * failing device cannot loop Camera2 -> CameraX -> Camera2 (piece 7,+ * mirroring the preview latch).+ */+fun CameraViewModel.onCamera2SloMoFailed(cameraId: String): Boolean {+ val keyId = selectedLensMutable.value?.logicalCameraId+ ?.takeIf { it.isNotEmpty() } ?: cameraId+ val key = com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch+ .bindKey(keyId, cameraModeMutable.value)+ if (!camera2SloMoFallbackLatch.recordFailure(key)) return false+ camera2SloMoFallbackBindKeyMutable.value = key+ Log.status("SloMo", "Camera2 slo-mo failed for $key; falling back to CameraX for this session")+ return true+}++/** Clears the slo-mo fallback latch (manual retry / gate re-enable / new bind). */+fun CameraViewModel.clearCamera2SloMoFallback() {+ camera2SloMoFallbackLatch.reset()+ camera2SloMoFallbackBindKeyMutable.value = null+}++/** Registers the live gated slo-mo high-speed session (null when it leaves composition). */+internal fun CameraViewModel.registerCamera2HighSpeedSession(+ session: com.vayunmathur.camera.platform.camera2.Camera2HighSpeedSession?,+) {+ activeCamera2HighSpeedSession = session+}+ /** * Records a Camera2 NIGHT extension preview configure/open failure for * [cameraId]: latches this bind key so the UI stops composing the
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.ktindex c90e234af8..1227a42296 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt@@ -56,10 +56,13 @@ data class PreviewEngineInput( * not exist today; showing Camera2 preview until the press and then * going black for the rebind is a worse, unverified trade, not a * reduction. Revisit only with that rebind implemented end to end.- * - SLOW_MO: blocked. Preview, capture and recording are one CameraX- * high-speed session. The Camera2 constrained session exists but its- * recording coupling is incomplete (see `SloMoEnginePolicy`), and it- * has no preview-only surface to show before a recording exists.+ * - SLOW_MO: blocked for live selection. Preview, capture and recording+ * are one CameraX high-speed session. The Camera2 preview surface now+ * exists (`Camera2SloMoPreview`, piece 4), but selecting it would+ * unbind the CameraX session that still owns recording until the+ * Camera2 recording engine is device-verified (piece 6); see+ * `SloMoEnginePolicy` and `SloMoPreviewPolicy`, which gate the+ * slo-mo preview's own live selection on `recordingEngineReady`. * * Adding a mode to [supportedModes] therefore requires, in the same * change, its capture/analysis route on the Camera2 session (or a@@ -86,8 +89,9 @@ object PreviewEnginePolicy { "panorama capture needs CameraX analysis bitmap frames; " + "a Camera2 preview would leave no analysis stream bound" input.mode == CameraMode.SLOW_MO ->- "slo-mo preview is part of the CameraX high-speed session; " +- "the Camera2 constrained session has no preview-only surface"+ "slo-mo preview stays with the CameraX high-speed session until the " ++ "Camera2 recording engine is device-verified; the Camera2 preview " ++ "surface exists but selecting it would unbind CameraX recording" else -> "video-mode recording stays on the CameraX Recorder; " + "a Camera2 preview would leave no Recorder bound to record into"
camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.ktindex 145ba8dd2e..b76bc1a5e7 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt@@ -36,54 +36,48 @@ data class SloMoEngineInput( val encoderSupportsCaptureRate: Boolean = false, /** * The constrained session is coupled to a recording engine (codec +- * muxer) end to end. False today — coupling- * `Camera2HighSpeedSession` to `Camera2VideoRecordingEngine` is NOT- * mechanical. The seven pieces, in dependency order, with status- * after the structural work of 2026-11-22 (see+ * muxer) end to end. The seven pieces, in dependency order (see * [SloMoRecordingReadiness], whose per-piece flags mirror this list): *- * 1. Encoder-surface handoff. DONE (structural): the engine is now- * codec-first — `prepareEncoderSurface()` configures the video- * codec and exposes its input surface before any camera open, and- * `start` reuses it; the ordering itself is the pure, tested- * [EncoderSurfaceHandoff] phase machine.- * 2. Device/session ownership. OPEN: both classes still open the same- * cameraId — the engine owns a private device and a *regular*- * session; the high-speed session owns the device through the- * driver seam and a *constrained* session. The engine's regular- * `TEMPLATE_RECORD` request cannot deliver 120/240 fps and must- * not be substituted. Still missing: extracting the codec/muxer/- * drain core so it can run under an externally-owned session.- * 3. Recording lifecycle. PARTIAL: `Camera2HighSpeedSession` now has- * a stop boundary ([Camera2HighSpeedSession.stopRecording]) that- * stops the repeating request before signalling EOS and never- * closes caller-owned surfaces. Still missing: the shared core- * from (2) for the EOS signal to land on, and start semantics.- * 4. Preview surface in SLOW_MO. OPEN: there is no Camera2 slo-mo- * preview composable/bridge to supply the high-speed session's- * preview target (mirroring `Camera2Preview`); see also+ * 1. Encoder-surface handoff. DONE: the engine is codec-first —+ * `prepareEncoderSurface()` configures the video codec and exposes+ * its input surface before any camera open, and `start` reuses it;+ * the ordering itself is the pure, tested [EncoderSurfaceHandoff].+ * 2. Device/session ownership. DONE: the codec/muxer/drain core is+ * extracted (`Camera2RecordingCore`, [SharedRecordingCoreLifecycle])+ * and runs under an externally-owned session; the engine delegates+ * to the same core for its regular session. The engine's regular+ * `TEMPLATE_RECORD` request is never substituted for the+ * constrained high-speed request.+ * 3. Recording lifecycle. DONE: `Camera2HighSpeedSession.stopRecording`+ * stops the repeating request before signalling EOS on the shared+ * core and never closes caller-owned surfaces.+ * 4. Preview surface in SLOW_MO. DONE: `Camera2SloMoPreview` supplies+ * the high-speed session's preview target behind the slo-mo gate+ * ([SloMoPreviewPolicy]); live selection additionally requires+ * [recordingEngineReady], so it is not composed live yet. See also * [PreviewEnginePolicy]'s SLOW_MO exclusion.- * 5. Audio/muxer contract. DONE (structural): the engine takes a- * no-audio configuration (`audioEnabled = false`, CameraX slo-mo's+ * 5. Audio/muxer contract. DONE: the engine/core take a no-audio+ * configuration (`audioEnabled = false`, CameraX slo-mo's * contract) — no AudioRecord/AAC is created and the muxer starts- * on the video track alone via the tested [MuxerStartPolicy].- * 6. Timestamp verification. OPEN: the muxer writes encoder PTS- * as-is; `stretchedPtsUs` is not wired into the drain path and+ * on the video track alone via [MuxerStartPolicy].+ * 6. Timestamp verification. OPEN (device verification, out of scope+ * for the structural work): the muxer writes encoder PTS as-is;+ * `stretchedPtsUs` is not wired into the drain path and * `validateOutput` checks neither frame rate nor stretched * duration. Needs device proof an encoder honours * `KEY_CAPTURE_RATE` (or muxer-side stretching) plus read-back * and external ffprobe checks that output is slow, not realtime.- * 7. Save-path glue + fallback. OPEN: glue that tears CameraX down,- * builds engine+high-speed session together, routes the file- * through `saveVideoStaged`, and on failure rebinds the CameraX- * HFR ladder — plus the device verification in (6) before this- * flag may flip. Callers should pass- * [SloMoRecordingReadiness.recordingEngineReady] (false today).+ * This piece alone keeps [recordingEngineReady] false.+ * 7. Save-path glue + fallback. DONE: `handleCamera2SloMoFinalized`+ * routes a finished file through `saveVideoStaged`; on failure it+ * discards the file, latches this bind one-shot+ * (`Camera2FallbackLatch`, mirroring preview's), and rebinds the+ * CameraX HFR ladder via `setupHighSpeedSession`. Callers pass+ * [SloMoRecordingReadiness.recordingEngineReady] (false today,+ * solely because of piece 6). *- * Until (2), (4), (6) and (7) land, no live recording may be routed- * here: with pieces 1/3/5 in place the remaining work is the shared- * drain core, the preview bridge, and device verification — in that- * order.+ * Until piece 6 lands, no live recording may be routed here. */ val recordingEngineReady: Boolean = false, )
camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.ktindex 0fed89e90e..60034e8e8e 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCore.kt@@ -2,12 +2,12 @@ package com.vayunmathur.camera.platform.camera2 /** * Pure structural core for coupling the constrained high-speed session to- * a recording engine (SloMoEnginePolicy pieces 1, 3 and 5). No Android+ * a recording engine (SloMoEnginePolicy pieces 1-5 and 7). No Android * types: the ordering rules are unit-testable without a codec or HAL. * * Nothing here routes a live recording. [SloMoRecordingReadiness] keeps * `recordingEngineReady` false until every documented piece closes and a- * device run verifies the output (piece 6).+ * device run verifies the output (piece 6, the only remaining piece). */ /** Ordered phases of one encoder-surface handoff (piece 1). */@@ -69,25 +69,144 @@ object MuxerStartPolicy { hasVideoTrack && (!audioEnabled || hasAudioTrack) } +/** Who owns the camera session a [SharedRecordingCorePhase] runs under. */+enum class RecordingSessionOwnership {+ /** The recording engine opens its own (regular) device/session. */+ ENGINE_OWNED,++ /** A caller-owned session (the constrained high-speed session) drives the core. */+ EXTERNALLY_OWNED,+}++/** Ordered phases of the shared codec/muxer/drain core (piece 2). */+enum class SharedRecordingCorePhase {+ IDLE,+ SURFACE_PREPARED,+ DRAINING,+ EOS_SIGNALLED,+ FINALIZED,+ RELEASED,+}++/**+ * Ordering contract for the shared codec/muxer/drain core: the encoder+ * surface is prepared before any session lists it as a target, draining+ * starts only from the prepared surface, EOS only while draining, and+ * finalize only after EOS. Release is terminal. Illegal transitions are+ * rejected (return false), never silently reordered. The Android core+ * (`Camera2RecordingCore`) and the engine both run under this machine, so+ * an externally-owned high-speed session gets exactly the engine's drain+ * semantics without the engine owning the camera.+ */+class SharedRecordingCoreLifecycle(+ val ownership: RecordingSessionOwnership,+) {+ var phase: SharedRecordingCorePhase = SharedRecordingCorePhase.IDLE+ private set++ private fun advance(+ to: SharedRecordingCorePhase,+ allowedFrom: Set<SharedRecordingCorePhase>,+ ): Boolean {+ if (phase !in allowedFrom) return false+ phase = to+ return true+ }++ fun markSurfacePrepared(): Boolean =+ advance(SharedRecordingCorePhase.SURFACE_PREPARED, setOf(SharedRecordingCorePhase.IDLE))++ fun markDraining(): Boolean = advance(+ SharedRecordingCorePhase.DRAINING, setOf(SharedRecordingCorePhase.SURFACE_PREPARED),+ )++ fun markEosSignalled(): Boolean = advance(+ SharedRecordingCorePhase.EOS_SIGNALLED, setOf(SharedRecordingCorePhase.DRAINING),+ )++ fun markFinalized(): Boolean = advance(+ SharedRecordingCorePhase.FINALIZED, setOf(SharedRecordingCorePhase.EOS_SIGNALLED),+ )++ fun markReleased(): Boolean {+ if (phase == SharedRecordingCorePhase.RELEASED) return false+ phase = SharedRecordingCorePhase.RELEASED+ return true+ }+}++/**+ * Slo-mo preview-surface policy (piece 4). The Camera2 preview surface for+ * the high-speed mode exists (`Camera2SloMoPreview` + its+ * `PreviewSurfaceBridge`), so a surface *can* be supplied to the+ * constrained session. Live preview selection is a separate, stricter+ * decision: it additionally requires [recordingEngineReady], because+ * selecting Camera2 preview unbinds the CameraX high-speed session that+ * still owns recording. Until piece 6 verifies the recording, live slo-mo+ * preview therefore stays on CameraX even though the plumbing is in place.+ */+object SloMoPreviewPolicy {+ fun canSupplyPreviewSurface(+ sloMoGateEnabled: Boolean,+ isSlowMoMode: Boolean,+ fallbackLatched: Boolean,+ hasSelection: Boolean,+ ): Boolean = sloMoGateEnabled && isSlowMoMode && !fallbackLatched && hasSelection++ fun livePreviewSelected(+ sloMoGateEnabled: Boolean,+ isSlowMoMode: Boolean,+ fallbackLatched: Boolean,+ hasSelection: Boolean,+ recordingEngineReady: Boolean,+ ): Boolean = recordingEngineReady && canSupplyPreviewSurface(+ sloMoGateEnabled, isSlowMoMode, fallbackLatched, hasSelection,+ )+}++/** What the save-path glue should do with one finished Camera2 slo-mo attempt (piece 7). */+enum class SloMoSaveAction {+ /** Route the staged file through the shared `saveVideoStaged` seam. */+ SAVE_STAGED,++ /** Discard the file, latch this bind, and rebind the CameraX HFR ladder. */+ DISCARD_AND_REBIND_CAMERAX,++ /** Discard the file; the latch already fired for this bind, so do not rebind-loop. */+ DISCARD_LATCHED,+}++object SloMoSavePathPolicy {+ fun actionFor(+ outcomeError: Boolean,+ outputReadable: Boolean,+ fallbackAlreadyLatched: Boolean,+ ): SloMoSaveAction = when {+ !outcomeError && outputReadable -> SloMoSaveAction.SAVE_STAGED+ fallbackAlreadyLatched -> SloMoSaveAction.DISCARD_LATCHED+ else -> SloMoSaveAction.DISCARD_AND_REBIND_CAMERAX+ }+}+ /**- * Readiness of SloMoEnginePolicy's seven documented pieces after the- * structural work of 2026-11-22. Only pieces closed in code may read- * true; [recordingEngineReady] is their conjunction, so it stays false- * (and slo-mo stays on CameraX) until the rest land *and* a device run- * verifies stretched timestamps / slow duration (piece 6).+ * Readiness of SloMoEnginePolicy's seven documented pieces. Only pieces+ * closed in code may read true; [recordingEngineReady] is their+ * conjunction, so it stays false (and slo-mo stays on CameraX) until the+ * rest land *and* a device run verifies stretched timestamps / slow+ * duration (piece 6). */ object SloMoRecordingReadiness { /** 1. Codec-first split; surface exposed before camera open. */ const val ENCODER_SURFACE_HANDOFF_READY: Boolean = true /** 2. Codec/muxer/drain core shared by engine and high-speed session. */- const val SHARED_CODEC_CORE_READY: Boolean = false+ const val SHARED_CODEC_CORE_READY: Boolean = true /** 3. Stop boundary on the high-speed session: stop repeating, then EOS, no caller-surface close. */ const val SESSION_RECORDING_BOUNDARY_READY: Boolean = true /** 4. Camera2 slo-mo preview composable/bridge. */- const val SLO_MO_PREVIEW_READY: Boolean = false+ const val SLO_MO_PREVIEW_READY: Boolean = true /** 5. No-audio muxer mode (muxer starts on the video track alone). */ const val NO_AUDIO_MUXER_READY: Boolean = true@@ -96,11 +215,22 @@ object SloMoRecordingReadiness { const val TIMESTAMP_VERIFICATION_READY: Boolean = false /** 7. Save-path glue (engine + session together, staged save, CameraX fallback latch). */- const val SAVE_PATH_GLUE_READY: Boolean = false+ const val SAVE_PATH_GLUE_READY: Boolean = true /** True only when every piece above is ready; feeds SloMoEngineInput.recordingEngineReady. */ val recordingEngineReady: Boolean get() = ENCODER_SURFACE_HANDOFF_READY && SHARED_CODEC_CORE_READY && SESSION_RECORDING_BOUNDARY_READY && SLO_MO_PREVIEW_READY && NO_AUDIO_MUXER_READY && TIMESTAMP_VERIFICATION_READY && SAVE_PATH_GLUE_READY++ /** Names of the pieces still open, in documented order; empty only when ready. */+ fun remainingPieces(): List<String> = buildList {+ if (!ENCODER_SURFACE_HANDOFF_READY) add("1. encoder-surface handoff")+ if (!SHARED_CODEC_CORE_READY) add("2. shared codec/muxer/drain core")+ if (!SESSION_RECORDING_BOUNDARY_READY) add("3. recording lifecycle boundary")+ if (!SLO_MO_PREVIEW_READY) add("4. slo-mo preview bridge")+ if (!NO_AUDIO_MUXER_READY) add("5. audio/muxer contract")+ if (!TIMESTAMP_VERIFICATION_READY) add("6. timestamp verification (device)")+ if (!SAVE_PATH_GLUE_READY) add("7. save-path glue + fallback")+ } }
camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreview.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreview.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreview.ktnew file mode 100644index 0000000000..bb497ef7d8--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2SloMoPreview.kt@@ -0,0 +1,229 @@+package com.vayunmathur.camera.ui++import android.content.Context+import android.hardware.camera2.CameraManager+import android.view.TextureView+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.viewinterop.AndroidView+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.platform.Camera2RecordingCore+import com.vayunmathur.camera.platform.camera2.AndroidCamera2Driver+import com.vayunmathur.camera.platform.camera2.Camera2Executor+import com.vayunmathur.camera.platform.camera2.Camera2HighSpeedSession+import com.vayunmathur.camera.platform.camera2.Camera2IdResolution+import com.vayunmathur.camera.platform.camera2.Camera2IdResolver+import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade+import com.vayunmathur.camera.platform.camera2.HighSpeedPlanner+import com.vayunmathur.camera.platform.camera2.OnceErrorReporter+import com.vayunmathur.camera.platform.camera2.PreviewSurfaceBridge+import com.vayunmathur.camera.platform.camera2.PreviewSurfaceEvent+import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership+import com.vayunmathur.camera.platform.toCustomRecordingConfig+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Camera2 slo-mo viewfinder (piece 4): a TextureView whose surface feeds+ * a [Camera2HighSpeedSession] as its preview target, alongside the shared+ * core's encoder surface. Mirrors [Camera2Preview]/[Camera2NightPreview].+ *+ * Composed only when `CameraScreenState.useCamera2SloMoPreview` selects+ * it — which requires the slo-mo gate, a high-speed selection, no latched+ * fallback, and `SloMoRecordingReadiness.recordingEngineReady`. That flag+ * is false until device verification (piece 6), so today this composable+ * is never composed live and SLOW_MO preview/recording stay on the+ * CameraX high-speed session exactly as before. The plumbing exists so+ * flipping readiness after verification needs no new surface code.+ *+ * [cameraId] is the bind identity only; the session opens the id+ * [Camera2IdResolver] maps from [lensFacing], never this value.+ */+@Composable+internal fun Camera2SloMoPreview(+ cameraId: String,+ lensFacing: LensFacing?,+ onSessionChanged: (Camera2HighSpeedSession?) -> Unit = {},+ onError: (String) -> Unit = {},+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val sessionHolder = remember(lensFacing) {+ Camera2SloMoPreviewSession(context, lensFacing, onError)+ }+ var session by remember(sessionHolder) { mutableStateOf<Camera2HighSpeedSession?>(null) }++ DisposableEffect(sessionHolder) {+ onDispose {+ onSessionChanged(null)+ sessionHolder.close()+ }+ }+ LaunchedEffect(sessionHolder) {+ sessionHolder.build()+ session = sessionHolder.session+ if (session != null) onSessionChanged(session)+ sessionHolder.deliverPendingError()+ }++ if (session == null) {+ Box(modifier = modifier.background(Color.Black))+ return+ }++ AndroidView(+ factory = { ctx ->+ TextureView(ctx).also { view -> sessionHolder.bridge.attachTo(view) }+ },+ modifier = modifier,+ )+}++private class Camera2SloMoPreviewSession(+ private val context: Context,+ private val lensFacing: LensFacing?,+ onError: (String) -> Unit = {},+) {+ val executor = Camera2Executor("Camera2SloMoPreview-${lensFacing?.name ?: "unknown"}")++ @Volatile+ var session: Camera2HighSpeedSession? = null+ private set++ @Volatile+ private var core: Camera2RecordingCore? = null++ @Volatile+ private var resolvedCameraId: String? = null++ @Volatile+ private var closed = false++ private val errorGate = OnceErrorReporter(onError)++ @Volatile+ private var pendingInitError: String? = null++ val bridge: PreviewSurfaceBridge = PreviewSurfaceBridge { event ->+ val liveSession = session+ val liveCameraId = resolvedCameraId+ val liveCore = core+ if (liveSession == null || liveCameraId == null || liveCore == null) {+ return@PreviewSurfaceBridge+ }+ when (event) {+ is PreviewSurfaceEvent.Available -> {+ val encoderSurface = liveCore.prepareEncoderSurface()+ if (encoderSurface == null) {+ errorGate.report("slo-mo encoder surface unavailable")+ } else {+ liveSession.open(liveCameraId, encoderSurface, event.surface)+ }+ }+ is PreviewSurfaceEvent.SizeChanged -> {+ liveSession.close()+ val encoderSurface = liveCore.prepareEncoderSurface()+ if (encoderSurface == null) {+ errorGate.report("slo-mo encoder surface unavailable")+ } else {+ liveSession.open(liveCameraId, encoderSurface, event.surface)+ }+ }+ is PreviewSurfaceEvent.Destroyed -> liveSession.close()+ }+ }++ suspend fun build() {+ if (session != null || closed) return+ var built: Camera2HighSpeedSession? = null+ var builtCore: Camera2RecordingCore? = null+ try {+ withContext(Dispatchers.Default) {+ val manager = context.getSystemService(CameraManager::class.java)+ ?: throw IllegalStateException("no CameraManager")+ when (+ val resolution = Camera2IdResolver.resolve(+ lensFacing,+ CharacteristicsFacade.cameraIdFacings(manager),+ )+ ) {+ is Camera2IdResolution.Unavailable -> pendingInitError = resolution.reason+ is Camera2IdResolution.Resolved -> {+ resolvedCameraId = resolution.cameraId+ val facade = CharacteristicsFacade.tryFromCameraManager(+ manager, resolution.cameraId,+ ) ?: throw IllegalArgumentException(+ "getCameraCharacteristics failed for Camera2 id ${resolution.cameraId}",+ )+ val selection = HighSpeedPlanner.select(facade.snapshot)+ if (selection == null) {+ pendingInitError = "no constrained high-speed slo-mo point"+ return@withContext+ }+ val driver = AndroidCamera2Driver(+ manager,+ android.os.Handler(executor.looper),+ )+ builtCore = Camera2RecordingCore(+ config = selection.toCustomRecordingConfig()+ .copy(audioEnabled = false),+ initialBitrateBps = { SLOMO_PREVIEW_BITRATE_BPS },+ ownership = RecordingSessionOwnership.EXTERNALLY_OWNED,+ )+ built = Camera2HighSpeedSession(+ driver = driver,+ executor = executor,+ snapshot = facade.snapshot,+ listener = object : Camera2HighSpeedSession.Listener {+ override fun onError(message: String) {+ Log.status("Camera2SloMoPreview", message)+ errorGate.report(message)+ }+ },+ )+ }+ }+ }+ } catch (e: RuntimeException) {+ pendingInitError = "Camera2 slo-mo preview init failed for facing $lensFacing: ${e.message}"+ }+ if (closed) {+ built?.close()+ builtCore?.release()+ return+ }+ session = built+ core = builtCore+ }++ fun deliverPendingError() {+ val message = pendingInitError ?: return+ pendingInitError = null+ Log.status("Camera2SloMoPreview", message)+ errorGate.report(message)+ }++ fun close() {+ closed = true+ session?.close()+ session = null+ core?.release()+ core = null+ executor.shutdown()+ }++ private companion object {+ const val SLOMO_PREVIEW_BITRATE_BPS = 20_000_000+ }+}
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.ktindex 7a5282d025..cf681527ed 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -19,7 +19,9 @@ import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.noteCamera2BindRequested import com.vayunmathur.camera.platform.onCamera2NightPreviewFailed import com.vayunmathur.camera.platform.onCamera2PreviewFailed+import com.vayunmathur.camera.platform.onCamera2SloMoFailed import com.vayunmathur.camera.platform.registerCamera2ExtensionSession+import com.vayunmathur.camera.platform.registerCamera2HighSpeedSession import com.vayunmathur.camera.platform.onViewfinderZoomRatio import com.vayunmathur.camera.platform.retrySessionBind import com.vayunmathur.camera.platform.camera2AnalysisConsumer@@ -45,8 +47,28 @@ internal fun CameraPreviewSurface( ) { val useCamera2Preview = state.useCamera2Preview val useCamera2NightPreview = state.useCamera2NightPreview+ val useCamera2SloMoPreview = state.useCamera2SloMoPreview val surfaceRequest = state.surfaceRequest + if (useCamera2SloMoPreview) {+ // Camera2 slo-mo preview (piece 4): behind the slo-mo gate and+ // SloMoRecordingReadiness — not composed live until piece 6.+ val sloMoCamera2Id = state.selectedLens?.logicalCameraId.orEmpty()+ if (sloMoCamera2Id.isNotEmpty()) {+ Camera2SloMoPreview(+ cameraId = sloMoCamera2Id,+ lensFacing = state.selectedLens?.facing,+ onSessionChanged = { session ->+ viewModel.registerCamera2HighSpeedSession(session)+ },+ onError = { viewModel.onCamera2SloMoFailed(sloMoCamera2Id) },+ modifier = previewModifier,+ )+ } else {+ Box(modifier = previewModifier.background(Color.Black))+ }+ }+ if (useCamera2NightPreview) { // Camera2 NIGHT extension preview: registers the live extension // session so the night shutter can serve from Camera2. Takes@@ -67,7 +89,7 @@ internal fun CameraPreviewSurface( Box(modifier = previewModifier.background(Color.Black)) } }- if (useCamera2Preview && !useCamera2NightPreview) {+ if (useCamera2Preview && !useCamera2NightPreview && !useCamera2SloMoPreview) { // Camera2 preview behind gate (CameraScreenState.useCamera2Preview, PHOTO only). // TextureView-backed, same overlay tree / RenderEffects below. // Guard: never compose with empty cameraId — fall back to CameraX black/error branch below.@@ -106,7 +128,7 @@ internal fun CameraPreviewSurface( Box(modifier = previewModifier.background(Color.Black)) } }- if (!useCamera2Preview && !useCamera2NightPreview) {+ if (!useCamera2Preview && !useCamera2NightPreview && !useCamera2SloMoPreview) { surfaceRequest?.let { request -> LaunchedEffect(request) { Log.dev("NightPreview", "CameraXViewfinder COMPOSED with request res=${request.resolution} dynamicRange=${request.dynamicRange} useNightPreview=${state.useNightPreview} sessionKind=${state.sessionKind} zoomRatio=${state.zoomRatio} levels=${state.availableZoomLevels} thread=${Thread.currentThread().name}")@@ -155,7 +177,7 @@ internal fun CameraPreviewSurface( onScreenFlashReady = { screenFlash -> viewModel.setScreenFlash(screenFlash) }, ) }- if (!useCamera2Preview && !useCamera2NightPreview && surfaceRequest == null) {+ if (!useCamera2Preview && !useCamera2NightPreview && !useCamera2SloMoPreview && surfaceRequest == null) { if (state.sessionBindFailed) { // Bind exhausted its retries: a visible, retryable error instead // of parking on a black preview until the next mode/lens change.
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex cc15bb3fde..f971926990 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -63,6 +63,7 @@ internal fun CameraScreenEffects( val useNightPreview = state.useNightPreview val useCamera2Preview = state.useCamera2Preview val useCamera2NightPreview = state.useCamera2NightPreview+ val useCamera2SloMoPreview = state.useCamera2SloMoPreview // Tracks physical orientation purely to rotate the on-screen control icons. Capture output // rotation is handled by CameraX via SessionConfig.setAutoRotationEnabled(true).@@ -261,7 +262,7 @@ internal fun CameraScreenEffects( val zslCompatible by viewModel.zslCompatible.collectAsState() val zslKey = if (sessionKind == SessionKind.PHOTO) zslCompatible else null val bindSettings by viewModel.bindTimeSettings.collectAsState()- LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, useCamera2Preview, useCamera2NightPreview, zslKey, bindSettings, state.sessionBindRetry, lifecycleOwner) {+ LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, useCamera2Preview, useCamera2NightPreview, useCamera2SloMoPreview, zslKey, bindSettings, state.sessionBindRetry, lifecycleOwner) { // Camera2 preview engine (Phase 2, PHOTO, no other outputs yet) owns a // camera via Camera2Session directly. SetupPhotoSession() would double-open // the same cameraId — Camera2 open fails ERROR_CAMERA_IN_USE. So keep full@@ -270,7 +271,7 @@ internal fun CameraScreenEffects( // Same for the Camera2 NIGHT extension preview: its extension // session owns the camera, so CameraX (including its own night // extension session) must not bind alongside it.- if (useCamera2Preview || useCamera2NightPreview) {+ if (useCamera2Preview || useCamera2NightPreview || useCamera2SloMoPreview) { lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.sessionBindFailedMutable.value = false viewModel.teardownSession()
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex e5e89d05b2..325ad0c325 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -100,6 +100,10 @@ import com.vayunmathur.camera.platform.VideoCodec val camera2NightEnabled: Boolean = true, /** Bind key latched after a Camera2 extension preview failure, or null. */ val camera2NightFallbackBindKey: String? = null,+ /** Camera2 slo-mo gate (default ON, persisted); policy still decides. */+ val camera2SloMoEnabled: Boolean = true,+ /** Bind key latched after a Camera2 slo-mo failure, or null. */+ val camera2SloMoFallbackBindKey: String? = null, ) { var activeSetting by activeSettingState var maskBitmap by maskBitmapState@@ -164,6 +168,32 @@ import com.vayunmathur.camera.platform.VideoCodec return camera2NightFallbackBindKey != bindKey } + /**+ * True when the Camera2 slo-mo preview owns the viewfinder. Requires+ * SLOW_MO, the slo-mo gate, no latched fallback, and+ * `SloMoRecordingReadiness.recordingEngineReady` — false until device+ * verification (piece 6), so this is false today and the CameraX+ * high-speed preview serves. The preview surface plumbing itself+ * (piece 4) is ready behind this gate.+ */+ val useCamera2SloMoPreview: Boolean+ get() {+ if (cameraMode != CameraMode.SLOW_MO) return false+ val cameraId = selectedLens?.logicalCameraId+ if (cameraId.isNullOrEmpty()) return false+ val bindKey = com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch+ .bindKey(cameraId, cameraMode)+ return com.vayunmathur.camera.platform.camera2.SloMoPreviewPolicy.livePreviewSelected(+ sloMoGateEnabled = camera2SloMoEnabled &&+ com.vayunmathur.camera.platform.camera2.SloMoCamera2Gate.ENABLED,+ isSlowMoMode = true,+ fallbackLatched = camera2SloMoFallbackBindKey == bindKey,+ hasSelection = true,+ recordingEngineReady =+ com.vayunmathur.camera.platform.camera2.SloMoRecordingReadiness.recordingEngineReady,+ )+ }+ /** * Strength indicator value to show, or null to hide it. There is no * Camera2 strength flow, so on the Camera2 night path the indicator is
camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.ktindex 38ec552aab..bc731a2d9e 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt@@ -68,6 +68,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen val camera2NightSessionActive by viewModel.camera2NightSessionActive.collectAsState() val camera2NightEnabled by viewModel.camera2NightEnabled.collectAsState() val camera2NightFallbackBindKey by viewModel.camera2NightFallbackBindKey.collectAsState()+ val camera2SloMoEnabled by viewModel.camera2SloMoEnabled.collectAsState()+ val camera2SloMoFallbackBindKey by viewModel.camera2SloMoFallbackBindKey.collectAsState() val sessionBindFailed by viewModel.sessionBindFailed.collectAsState() val sessionBindRetry by viewModel.sessionBindRetry.collectAsState() val availableZoomLevels by viewModel.availableZoomLevels.collectAsState()@@ -97,7 +99,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen nightModeActive, extensionStrength, sloMoSupported, highSpeedActive, photoSessionActive, analysisStreamActive, nightExtAvailable, surfaceRequest, camera2PreviewEnabled, camera2FallbackBindKey, camera2NightSessionActive,- camera2NightEnabled, camera2NightFallbackBindKey,+ camera2NightEnabled, camera2NightFallbackBindKey, camera2SloMoEnabled, camera2SloMoFallbackBindKey, sessionBindFailed, sessionBindRetry, availableZoomLevels, galleryBitmap, panoSweeping, panoStitching, panoDots, panoCurrentAngle, panoDirection, panoPitch,@@ -168,6 +170,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen camera2NightSessionActive = camera2NightSessionActive, camera2NightEnabled = camera2NightEnabled, camera2NightFallbackBindKey = camera2NightFallbackBindKey,+ camera2SloMoEnabled = camera2SloMoEnabled,+ camera2SloMoFallbackBindKey = camera2SloMoFallbackBindKey, ) } }
camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.ktindex e122a449ad..a0ec9711b3 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicyTest.kt@@ -68,8 +68,9 @@ class SloMoEnginePolicyTest { } @Test fun liveReadinessFlagStillKeepsRecordingOnCameraX() {- // Pieces 1/3/5 are structural-done, 2/4/6/7 are open, so the flag- // callers should feed the policy must still select CameraX.+ // Pieces 1-5 and 7 are done in code, 6 (device verification) is+ // open, so the flag callers should feed the policy must still+ // select CameraX. assertEquals( SloMoEngine.CAMERAX, SloMoEnginePolicy.select(readyInput(recordingEngineReady = SloMoRecordingReadiness.recordingEngineReady)),
camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.ktindex 84d712390e..25e4df5ec7 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SloMoRecordingCoreTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.camera.platform.camera2 import kotlin.test.Test+import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -37,14 +38,105 @@ class SloMoRecordingCoreTest { @Test fun readinessKeepsRecordingOnCameraXUntilEveryPieceCloses() { assertTrue(SloMoRecordingReadiness.ENCODER_SURFACE_HANDOFF_READY)+ assertTrue(SloMoRecordingReadiness.SHARED_CODEC_CORE_READY) assertTrue(SloMoRecordingReadiness.SESSION_RECORDING_BOUNDARY_READY)+ assertTrue(SloMoRecordingReadiness.SLO_MO_PREVIEW_READY) assertTrue(SloMoRecordingReadiness.NO_AUDIO_MUXER_READY)- assertFalse(SloMoRecordingReadiness.SHARED_CODEC_CORE_READY)- assertFalse(SloMoRecordingReadiness.SLO_MO_PREVIEW_READY) assertFalse(SloMoRecordingReadiness.TIMESTAMP_VERIFICATION_READY)- assertFalse(SloMoRecordingReadiness.SAVE_PATH_GLUE_READY)+ assertTrue(SloMoRecordingReadiness.SAVE_PATH_GLUE_READY) // The conjunction is the flag callers feed the policy; it must not // flip while any piece above is open. assertFalse(SloMoRecordingReadiness.recordingEngineReady) }++ @Test fun remainingPiecesNamesExactlyTheOpenPieces() {+ // Pieces 2/4/7 closed in code; only device verification (6) remains.+ assertEquals(+ listOf("6. timestamp verification (device)"),+ SloMoRecordingReadiness.remainingPieces(),+ )+ }++ @Test fun sharedCoreLifecycleRequiresSurfaceBeforeDrainBeforeEosBeforeFinalize() {+ val core = SharedRecordingCoreLifecycle(RecordingSessionOwnership.EXTERNALLY_OWNED)+ assertFalse(core.markDraining(), "drain before surface must be rejected")+ assertFalse(core.markEosSignalled())+ assertFalse(core.markFinalized())+ assertTrue(core.markSurfacePrepared())+ assertFalse(core.markSurfacePrepared(), "surface prepare is not repeatable")+ assertFalse(core.markEosSignalled(), "EOS before draining must be rejected")+ assertTrue(core.markDraining())+ assertTrue(core.markEosSignalled())+ assertFalse(core.markDraining(), "no re-drain after EOS")+ assertTrue(core.markFinalized())+ assertTrue(core.markReleased())+ assertFalse(core.markReleased(), "release is terminal")+ assertFalse(core.markSurfacePrepared())+ }++ @Test fun sloMoPreviewSurfaceExistsButLiveSelectionNeedsRecordingReady() {+ // Piece 4: the surface can be supplied behind the gate...+ assertTrue(+ SloMoPreviewPolicy.canSupplyPreviewSurface(+ sloMoGateEnabled = true, isSlowMoMode = true,+ fallbackLatched = false, hasSelection = true,+ ),+ )+ assertFalse(+ SloMoPreviewPolicy.canSupplyPreviewSurface(+ sloMoGateEnabled = true, isSlowMoMode = true,+ fallbackLatched = true, hasSelection = true,+ ),+ )+ assertFalse(+ SloMoPreviewPolicy.canSupplyPreviewSurface(+ sloMoGateEnabled = false, isSlowMoMode = true,+ fallbackLatched = false, hasSelection = true,+ ),+ )+ // ...but live preview selection still requires the recording engine,+ // which stays not-ready until piece 6 device verification.+ assertFalse(+ SloMoPreviewPolicy.livePreviewSelected(+ sloMoGateEnabled = true, isSlowMoMode = true,+ fallbackLatched = false, hasSelection = true,+ recordingEngineReady = SloMoRecordingReadiness.recordingEngineReady,+ ),+ )+ assertTrue(+ SloMoPreviewPolicy.livePreviewSelected(+ sloMoGateEnabled = true, isSlowMoMode = true,+ fallbackLatched = false, hasSelection = true,+ recordingEngineReady = true,+ ),+ )+ }++ @Test fun savePathPolicyRoutesSuccessAndLatchesFailureOnce() {+ assertEquals(+ SloMoSaveAction.SAVE_STAGED,+ SloMoSavePathPolicy.actionFor(+ outcomeError = false, outputReadable = true, fallbackAlreadyLatched = false,+ ),+ )+ assertEquals(+ SloMoSaveAction.DISCARD_AND_REBIND_CAMERAX,+ SloMoSavePathPolicy.actionFor(+ outcomeError = true, outputReadable = true, fallbackAlreadyLatched = false,+ ),+ )+ assertEquals(+ SloMoSaveAction.DISCARD_AND_REBIND_CAMERAX,+ SloMoSavePathPolicy.actionFor(+ outcomeError = false, outputReadable = false, fallbackAlreadyLatched = false,+ ),+ )+ // Already latched for this bind: discard without a rebind loop.+ assertEquals(+ SloMoSaveAction.DISCARD_LATCHED,+ SloMoSavePathPolicy.actionFor(+ outcomeError = true, outputReadable = false, fallbackAlreadyLatched = true,+ ),+ )+ } }