Modern Apps git

← Modern-Apps.git

camera: settings changes can't silently kill a recording

Commit
4326f00bb78a24d875fdeef2a04d0c3e67506576
Author
Vayun Mathur <[email protected]>
When
2026-11-21 16:22 UTC (14 days ago)
Parents
4031d78
Codec, audio codec, audio source and mirror changes rebind
the video session by effect key - mid-recording that tore
down the session and stopped the take without a word. Those
four are now bind-time settings: while recording, the applied
snapshot is held (the runningFold/zsl pattern), the new value
persists and shows immediately with 'applies after this
recording', and one rebind applies it at stop. Mode and lens
switches can't be deferred sanely, so they're gated while
recording with a messenger note instead of killing the take;
flip gained the same ViewModel backstop. Lifecycle
backgrounding still stops recording - that's the OS, out of
scope.

Verified: new deferral tests plus viewmodel/controls/settings
suites pass. One pre-existing lint error rides along:
SettingsPage.kt exceeds the 350-line FileLength limit at HEAD
(the audio-codec row commit) - splitting it is a follow-up.

Diff

camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.ktindex 2dcbe4449e..4bb89977ea 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt@@ -85,6 +85,8 @@ fun CameraViewModel.setFlashMode(mode: FlashMode) { /**  * Toggle horizontal mirroring of the front-camera preview and saved photo/video (issue #632).  * Takes effect on the next capture; the preview updates immediately via the UI layer.+ * Mid-recording the value persists but the bound session keeps the old MirrorMode+ * (bindTimeSettings) until the recording stops — it never rebinds under a take.  */ fun CameraViewModel.setMirrorFront(enabled: Boolean) {     mirrorFrontMutable.value = enabled
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 fa493aaab2..6f6934b12f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt@@ -106,7 +106,9 @@ internal suspend fun CameraViewModel.prepareVideoSession(): VideoSessionPrep {  /** Resolves codec selection (AV1 > HEVC > AVC) + fps/stabilization/quality tuning. */ internal fun CameraViewModel.resolveVideoChoices(cameraInfo: androidx.camera.core.CameraInfo): VideoChoices {-    val selectedCodec = videoCodecMutable.value+    // Bind-time snapshot, not the live desired flows: a Settings change made+    // mid-recording must not leak into any (re)bind until the recording stops.+    val selectedCodec = bindTimeSettings.value.videoCodec     // Respect user setting with fallback: AV1 > HEVC > AVC priority for availability check.     // If selected codec isn't available, fall back to next best available.     val useAv1 = selectedCodec == VideoCodec.AV1 &&@@ -115,7 +117,7 @@ internal fun CameraViewModel.resolveVideoChoices(cameraInfo: androidx.camera.cor         CodecSupport.isHevcEncoderAvailable && hevcSupportedByCamera(cameraInfo)     // Audio codec follows the user setting with the video-codec fallback style:     // Opus only when chosen AND the Recorder reports an Opus encoder, else AAC.-    val useOpus = audioCodecMutable.value == AudioCodec.OPUS &&+    val useOpus = bindTimeSettings.value.audioCodec == AudioCodec.OPUS &&         CodecSupport.isOpusAudioEncoderAvailable     // HLG10 (10-bit HDR) when the camera's video pipeline supports it. Uses the default     // HEVC/H.264 codec (AV1 stays off). Preview and VideoCapture must share the dynamic@@ -339,7 +341,7 @@ internal fun CameraViewModel.buildVideoCapture(     val choices = session.choices     val recorderBuilder = Recorder.Builder()         .setQualitySelector(choices.qualitySelector)-        .setAudioSource(audioInputSourceMutable.value.specValue)+        .setAudioSource(bindTimeSettings.value.audioInputSource.specValue)         .setTargetVideoEncodingBitRate(choices.videoEncodingBitRate)         .setTargetAudioEncodingBitRate(choices.audioEncodingBitRate)         .setTargetAudioChannelCount(choices.audioChannelCount)@@ -349,7 +351,7 @@ internal fun CameraViewModel.buildVideoCapture(     else recorderBuilder.setAudioMimeType(MediaFormat.MIMETYPE_AUDIO_AAC)     val captureBuilder = VideoCapture.Builder(recorderBuilder.build())         .setMirrorMode(-            if (mirrorFrontMutable.value) MirrorMode.MIRROR_MODE_ON_FRONT_ONLY+            if (bindTimeSettings.value.mirrorFront) MirrorMode.MIRROR_MODE_ON_FRONT_ONLY             else MirrorMode.MIRROR_MODE_OFF         )         .setDynamicRange(dynamicRange)
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 755c95a1f4..e23ac88b6f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -377,6 +377,42 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {         .runningFold(true) { held, gate -> if (gate.capturing) held else gate.compatible }         .stateIn(viewModelScope, SharingStarted.Eagerly, true) +    /** The user's chosen bind-time settings, before any recording deferral. */+    private val desiredBindSettings = combine(+        videoCodecMutable, audioCodecMutable, audioInputSourceMutable, mirrorFrontMutable+    ) { video, audio, source, mirror -> BindTimeSettings(video, audio, source, mirror) }++    /**+     * The bind-time settings a session bind must actually use. Codec, audio source and+     * mirroring are fixed when the Recorder/VideoCapture is built, so changing them used+     * to rebind the session mid-recording: teardown stopped the active recording with no+     * warning and the user lost the take believing it continued. While recording, this+     * snapshot is held at the bound values (the desired values still persist and show in+     * Settings); when the recording stops it releases to the desired values, whose change+     * is the session-effect key that rebinds for the next recording. Same held-value+     * pattern as [zslCompatible] while a still is in flight.+     */+    val bindTimeSettings = combine(desiredBindSettings, isRecordingMutable) { desired, recording ->+        BindSettingsGate(desired, recording)+    }+        .runningFold(+            BindTimeSettings(+                CodecSupport.defaultVideoCodec, AudioCodec.AAC, AudioInputSource.CAMCORDER, true+            )+        ) { held, gate -> if (gate.recording) held else gate.settings }+        .stateIn(+            viewModelScope, SharingStarted.Eagerly,+            BindTimeSettings(+                CodecSupport.defaultVideoCodec, AudioCodec.AAC, AudioInputSource.CAMCORDER, true+            )+        )++    /** True while a bind-time setting has been changed mid-recording and awaits the stop. */+    val deferredBindSettingsPending = combine(+        desiredBindSettings, bindTimeSettings, isRecordingMutable+    ) { desired, applied, recording -> recording && desired != applied }+        .stateIn(viewModelScope, SharingStarted.Eagerly, false)+     // Whether to offer the vendor NIGHT extension. We optimistically probe with the     // isSessionConfigSupported check, but the authoritative signal is the actual bind: if     // the night preview session ever fails to bind on this device, we remember that (persisted, with a@@ -637,6 +673,11 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     // Last-capture persistence lives in CameraSettings.kt as an extension.      fun switchCameraMode(newMode: CameraMode) {+        // Mid-recording mode switches rebind the session, whose teardown stops the+        // active recording. Unlike the persisted bind-time settings they cannot be+        // deferred (a mode jump on stop would surprise), so the switch is gated+        // while recording; the UI explains why. Same-mode taps stay harmless.+        if (isRecordingMutable.value && newMode != cameraModeMutable.value) return         // A pending shutter timer belongs to the old mode: firing capturePhoto() into the         // new session would capture unprompted (and with the wrong use cases bound).         if (newMode != cameraModeMutable.value) {@@ -656,6 +697,9 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     fun flipCamera() {         // Disallow flipping while in Slo-Mo — it's back-camera only, true HFR.         if (cameraModeMutable.value == CameraMode.SLOW_MO) return+        // A flip rebinds the session and teardown would stop an active recording+        // (the shutter row already hides flip while recording; this is the backstop).+        if (isRecordingMutable.value) return         lensFacingMutable.value = if (lensFacingMutable.value == CameraSelector.LENS_FACING_BACK)             CameraSelector.LENS_FACING_FRONT else CameraSelector.LENS_FACING_BACK         // Preserve the lens family across the flip: e.g. UW back -> front lens,@@ -677,6 +721,9 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {      * ignored so a stale UI entry can never crash a bind.      */     fun selectLens(lens: com.vayunmathur.camera.domain.PhysicalLens) {+        // A lens switch rebinds the session and teardown would stop an active+        // recording; gated while recording (the lens bar explains why in the UI).+        if (isRecordingMutable.value) return         if (lens.facing != (             if (lensFacingMutable.value == CameraSelector.LENS_FACING_BACK)                 com.vayunmathur.camera.domain.LensFacing.BACK@@ -744,3 +791,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {  /** One [CameraViewModel.zslCompatible] input sample: wanted value plus whether a shot is in flight. */ internal class ZslGate(val compatible: Boolean, val capturing: Boolean)++/** One [CameraViewModel.bindTimeSettings] input sample: desired settings plus recording state. */+internal class BindSettingsGate(val settings: BindTimeSettings, val recording: Boolean)
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.ktindex 2a6cef193b..27f6531235 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -93,6 +93,21 @@ enum class AudioInputSource(     ), } +/**+ * The bind-time recording settings snapshot: video/audio codec, audio source and+ * front mirroring are baked into the Recorder/VideoCapture when the session binds+ * and cannot change mid-recording. The user's chosen (desired) values live in the+ * individual CameraViewModel flows and persist immediately; this snapshot is what+ * a bind actually uses, held unchanged while a recording is in progress and+ * released to the desired values when it stops (see CameraViewModel.bindTimeSettings).+ */+data class BindTimeSettings(+    val videoCodec: VideoCodec,+    val audioCodec: AudioCodec,+    val audioInputSource: AudioInputSource,+    val mirrorFront: Boolean,+)+ /** Zoom-label tuning: sub-1x threshold, decimal scaling, near-integer snap tolerance. */ private const val ZOOM_SUB_UNIT_MAX = 1f private const val ZOOM_DECIMAL_SCALE = 10f
camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.ktindex dc2509e26a..1c96557c10 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt@@ -15,7 +15,10 @@ import com.vayunmathur.camera.platform.captureVideoSnapshot import com.vayunmathur.camera.platform.startBurst import com.vayunmathur.camera.platform.stopBurst import com.vayunmathur.camera.platform.togglePauseRecording+import androidx.compose.ui.res.stringResource+import com.vayunmathur.camera.R import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.util.NavBackStack  /**@@ -73,11 +76,19 @@ internal fun CameraBottomControls(             }         }.onFailure { Log.status("CameraScreen", "Could not open image viewer", it) }     }+    // Mode switches rebind the session, which would stop an active recording:+    // gated in the ViewModel and explained here instead of silently killing the take.+    val messenger = rememberMessenger()+    val switchBlockedNote = stringResource(R.string.switch_blocked_while_recording)+    val onModeSelected: (CameraMode) -> Unit = { mode ->+        if (state.isRecording && mode != cameraMode) messenger.show(switchBlockedNote)+        else viewModel.switchCameraMode(mode)+    }     val onPickerChanged: (Boolean) -> Unit = { photo ->         if (photo) {-            viewModel.switchCameraMode(CameraMode.PHOTO)+            onModeSelected(CameraMode.PHOTO)         } else {-            viewModel.switchCameraMode(CameraMode.VIDEO)+            onModeSelected(CameraMode.VIDEO)         }     } @@ -110,7 +121,7 @@ internal fun CameraBottomControls(                 isPhotoType = state.isPhotoType,                 sloMoSupported = state.sloMoSupported,                 captureForResult = onCaptureResult != null,-                onModeSelected = { viewModel.switchCameraMode(it) },+                onModeSelected = onModeSelected,                 iconRotation = animatedRotation,                 onPickerChanged = onPickerChanged,                 onSettingsClick = { backStack.add(Route.Settings) },
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex e5bf6d6174..84e290fd4f 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -56,6 +56,7 @@ import com.vayunmathur.camera.platform.retrySessionBind import com.vayunmathur.camera.platform.toggleNightModeOverride import com.vayunmathur.camera.R import com.vayunmathur.library.ui.ErrorState+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.ui.R as UiR  /** Maps the CameraX selector facing int to the pure lens-facing model. */@@ -279,11 +280,18 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(     // below the settings column so its controls stay visually on top.     TapToFocus(state = tapToFocusState, modifier = previewSize) +    // A lens switch rebinds the session, which would stop an active recording:+    // gated in the ViewModel and explained here instead of silently killing the take.+    val lensMessenger = rememberMessenger()+    val lensBlockedNote = stringResource(R.string.switch_blocked_while_recording)     CameraSettingsColumn(         activeSetting = state.activeSetting,         availableLenses = state.availableLenses.filter { it.facing == currentLensFacing(state.lensFacing) },         selectedLens = state.selectedLens,-        onLensSelected = { viewModel.selectLens(it) },+        onLensSelected = { lens ->+            if (state.isRecording && lens != state.selectedLens) lensMessenger.show(lensBlockedNote)+            else viewModel.selectLens(lens)+        },         zoomRatio = state.zoomRatio,         availableZoomLevels = state.availableZoomLevels,         onZoomSelected = { viewModel.setZoomRatio(it) },
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 018d91d8ed..0a50da923b 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -243,13 +243,18 @@ internal fun CameraScreenEffects(     val lifecycleOwner = LocalLifecycleOwner.current     // Codec/audio/mirror are fixed at bind time (Recorder mime, AudioSource, MirrorMode), so     // they join the effect keys: changing them in Settings rebinds instead of silently waiting-    // for the next mode switch. Aspect ratio is applied live (setCropAspectRatio) — no rebind.+    // for the next mode switch. The keys are the APPLIED snapshot (bindTimeSettings), not the+    // live desired values: while recording the snapshot is held, so a Settings change made+    // mid-recording (Settings is a separate route over this screen) persists without tearing+    // down the session — and the recording — and only rebinds when the snapshot releases at+    // stop. Aspect ratio is applied live (setCropAspectRatio) — no rebind.     // The photo session's capture mode (ZSL or not) is fixed at bind time too, so it rebinds when     // manual exposure or night mode makes ZSL unsafe, or safe again (#914). Other kinds ignore it.     val zslCompatible by viewModel.zslCompatible.collectAsState()     val zslKey = if (sessionKind == SessionKind.PHOTO) zslCompatible else null-    LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, zslKey, state.videoCodec, state.audioCodec, state.audioInputSource, state.mirrorFront, state.sessionBindRetry, lifecycleOwner) {-        Log.dev("NightPreview", "CameraScreen session LaunchedEffect START keys zsl=$zslKey lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview codec=${state.videoCodec} audioCodec=${state.audioCodec} audio=${state.audioInputSource} mirror=${state.mirrorFront} lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}")+    val bindSettings by viewModel.bindTimeSettings.collectAsState()+    LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, zslKey, bindSettings, state.sessionBindRetry, lifecycleOwner) {+        Log.dev("NightPreview", "CameraScreen session LaunchedEffect START keys zsl=$zslKey lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview codec=${bindSettings.videoCodec} audioCodec=${bindSettings.audioCodec} audio=${bindSettings.audioInputSource} mirror=${bindSettings.mirrorFront} lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}")         lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {             // A fresh (re)bind supersedes any earlier exhausted-retry failure.             viewModel.sessionBindFailedMutable.value = false
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex db3b3e7f00..26641f6371 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -78,6 +78,13 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM     val context = LocalContext.current     val messenger = rememberMessenger()     val saveLocationError = stringResource(R.string.settings_save_location_error)+    // Bind-time settings (codec/audio/mirror) changed mid-recording are persisted+    // by their setters but deferred by the ViewModel until the recording stops;+    // say so instead of letting the user believe the take switched — or died.+    val deferredNote = stringResource(R.string.setting_applies_after_recording)+    val noteIfDeferred: () -> Unit = {+        if (viewModel.isRecording.value) messenger.show(deferredNote)+    }      val requestLocation = rememberPermissionRequest(         Manifest.permission.ACCESS_FINE_LOCATION@@ -180,6 +187,7 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                                     selected = codec == videoCodec,                                     onClick = {                                         viewModel.setVideoCodec(codec)+                                        noteIfDeferred()                                         expanded = false                                     },                                     text = {@@ -253,6 +261,7 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                                     selected = codec == effectiveAudioCodec,                                     onClick = {                                         viewModel.setAudioCodec(codec)+                                        noteIfDeferred()                                         audioCodecExpanded = false                                     },                                     text = {@@ -304,6 +313,7 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                                 selected = source == audioInputSource,                                 onClick = {                                     viewModel.setAudioInputSource(source)+                                    noteIfDeferred()                                     audioExpanded = false                                 },                                 text = {@@ -327,7 +337,7 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                 SettingsSwitchRow(                     title = stringResource(R.string.settings_mirror_front_description),                     checked = mirrorFront,-                    onCheckedChange = { viewModel.setMirrorFront(it) },+                    onCheckedChange = { viewModel.setMirrorFront(it); noteIfDeferred() },                 )             } 
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 bd810495cf..b1e57cfa3e 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -53,6 +53,12 @@     <!-- SettingsPage: summary explaining edge-sharpening toggle -->     <string name="settings_edge_sharpening_description">Sharpen edges in photos and video (turn off for a natural look)</string> +    <!-- Messenger note when a bind-time setting is changed mid-recording: it is saved+         and takes effect on the next recording, the current one continues untouched -->+    <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>+     <!-- Video codec settings (SettingsPage) -->     <!-- SettingsPage: section header for video codec selection -->     <string name="settings_video_codec">Video codec</string>
camera/src/test/java/com/vayunmathur/camera/platform/RecordingRebindDeferralTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/RecordingRebindDeferralTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/RecordingRebindDeferralTest.ktnew file mode 100644index 0000000000..56a885c42d--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/RecordingRebindDeferralTest.kt@@ -0,0 +1,146 @@+package com.vayunmathur.camera.platform++import android.os.Looper+import androidx.camera.core.CameraSelector+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.camera.data.setAudioCodec+import com.vayunmathur.camera.data.setAudioInputSource+import com.vayunmathur.camera.data.setMirrorFront+import com.vayunmathur.camera.data.setVideoCodec+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.domain.LensType+import com.vayunmathur.camera.domain.PhysicalLens+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Mid-recording rebind protection: bind-time settings (video/audio codec, audio+ * source, mirror) changed while recording used to rebind the session, whose+ * teardown stopped the active recording with no warning. They now persist as+ * desired values, stay out of the applied bind snapshot until the recording+ * stops, and mode/lens/flip switches are gated for the duration.+ */+@RunWith(AndroidJUnit4::class)+class RecordingRebindDeferralTest {++    private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext())++    private fun idle() = shadowOf(Looper.getMainLooper()).idle()++    @Test+    fun bindSettingsTrackDesiredWhenNotRecording() {+        val v = vm()+        idle()+        v.setVideoCodec(VideoCodec.HEVC)+        v.setAudioCodec(AudioCodec.OPUS)+        v.setAudioInputSource(AudioInputSource.MIC)+        v.setMirrorFront(false)+        idle()+        assertEquals(+            BindTimeSettings(VideoCodec.HEVC, AudioCodec.OPUS, AudioInputSource.MIC, false),+            v.bindTimeSettings.value,+        )+        assertFalse(v.deferredBindSettingsPending.value)+    }++    @Test+    fun settingsChangedMidRecordingAreDeferredThenAppliedAtStop() {+        val v = vm()+        idle()+        val boundBefore = v.bindTimeSettings.value++        v.startRecordingTimer()+        assertTrue(v.isRecording.value)++        // The Settings-page setters: desired + persisted change immediately...+        v.setVideoCodec(if (boundBefore.videoCodec == VideoCodec.AVC) VideoCodec.HEVC else VideoCodec.AVC)+        v.setAudioCodec(if (boundBefore.audioCodec == AudioCodec.AAC) AudioCodec.OPUS else AudioCodec.AAC)+        v.setAudioInputSource(+            if (boundBefore.audioInputSource == AudioInputSource.CAMCORDER) {+                AudioInputSource.MIC+            } else {+                AudioInputSource.CAMCORDER+            }+        )+        v.setMirrorFront(!boundBefore.mirrorFront)+        idle()++        // ...but the applied bind snapshot — the session-effect key — is held,+        // so no rebind fires and the recording is untouched.+        assertEquals(boundBefore, v.bindTimeSettings.value)+        assertTrue(v.deferredBindSettingsPending.value)+        assertTrue(v.isRecording.value)+        assertTrue(v.videoCodec.value != boundBefore.videoCodec)+        assertTrue(v.audioCodec.value != boundBefore.audioCodec)+        assertTrue(v.audioInputSource.value != boundBefore.audioInputSource)+        assertEquals(!boundBefore.mirrorFront, v.mirrorFront.value)++        // At stop the snapshot releases: the next bind picks the new values up.+        v.stopRecordingTimer()+        idle()+        assertFalse(v.isRecording.value)+        assertFalse(v.deferredBindSettingsPending.value)+        assertEquals(+            BindTimeSettings(v.videoCodec.value, v.audioCodec.value, v.audioInputSource.value, v.mirrorFront.value),+            v.bindTimeSettings.value,+        )+    }++    @Test+    fun recordingSurvivesAllBindSettingsChangingAtOnce() {+        val v = vm()+        idle()+        v.startRecordingTimer()+        val durationAtStart = v.recordingDurationSec.value+        repeat(2) {+            v.setVideoCodec(VideoCodec.AV1)+            v.setAudioCodec(AudioCodec.OPUS)+            v.setAudioInputSource(AudioInputSource.UNPROCESSED)+            v.setMirrorFront(false)+            idle()+            assertTrue(v.isRecording.value, "recording must survive settings change #$it")+            assertTrue(v.deferredBindSettingsPending.value)+        }+        assertEquals(durationAtStart, v.recordingDurationSec.value)+        v.stopRecordingTimer()+        idle()+        assertEquals(AudioInputSource.UNPROCESSED, v.bindTimeSettings.value.audioInputSource)+    }++    @Test+    fun modeLensAndFlipSwitchesAreGatedWhileRecording() {+        val v = vm()+        idle()+        val back = PhysicalLens("b", LensType.WIDE, LensFacing.BACK, 24f, 1f, null, 0, "wide")+        val tele = PhysicalLens("t", LensType.TELEPHOTO, LensFacing.BACK, 70f, 3f, null, 1, "tele")+        v.availableLensesMutable.value = listOf(back, tele)+        v.selectLens(back)+        assertEquals(back, v.selectedLens.value)+        v.switchCameraMode(CameraMode.VIDEO)+        assertEquals(CameraMode.VIDEO, v.cameraMode.value)++        v.startRecordingTimer()+        // None of the rebind triggers may move while a take is running.+        v.switchCameraMode(CameraMode.PHOTO)+        assertEquals(CameraMode.VIDEO, v.cameraMode.value)+        v.selectLens(tele)+        assertEquals(back, v.selectedLens.value)+        v.flipCamera()+        assertEquals(CameraSelector.LENS_FACING_BACK, v.lensFacing.value)+        assertTrue(v.isRecording.value)++        // After the stop they all work again.+        v.stopRecordingTimer()+        v.selectLens(tele)+        assertEquals(tele, v.selectedLens.value)+        v.switchCameraMode(CameraMode.PHOTO)+        assertEquals(CameraMode.PHOTO, v.cameraMode.value)+        v.flipCamera()+        assertEquals(CameraSelector.LENS_FACING_FRONT, v.lensFacing.value)+    }+}