camera: ViewModel under the limit; fallback latch follows the lens
- Commit
1955423b1b872f3efc00e142d652592c534574f4- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-23 01:50 UTC (13 days ago)
- Parents
29c91c4
CameraViewModel regrew to 824; the startup sequence moves verbatim to CameraViewModelStartup.kt (781). The latch test exposed one stale production path: night fallback keyed on a captured id while preview keyed on the current selection - both now derive from current selection, with regression coverage for the seeded contract. Also landing here in substance (committed under 29c91c415 in the shared-tree sweep, noted for the record): the AVIF routing fix - the default plain shot no longer diverts to the Motion Photo JPEG path under AVIF, and snapshots/night fallback land through the encoder. Verified: lintVitalRelease + assembleRelease green; gate/startup/AVIF-routing tests 18/18.
Diff
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 bffc63ac2c..dd8038f1c0 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -17,7 +17,6 @@ import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageCapture import androidx.camera.core.SurfaceRequest import androidx.camera.lifecycle.ProcessCameraProvider-import androidx.camera.lifecycle.awaitInstance import java.util.concurrent.Executor import java.util.concurrent.ExecutorService import java.util.concurrent.Executors@@ -119,12 +118,7 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val startupOrder = com.vayunmathur.camera.platform.camera2.StartupOrderTracker() - /** Records the first Camera2 bind request (from the preview composable). */- fun noteCamera2BindRequested() {- if (startupOrder.recordBindRequested()) {- Log.dev("CameraStartup", "camera2 bind requested (probes may still be running)")- }- }+ // Startup bind-request breadcrumb lives in CameraViewModelStartup.kt as an extension. // Camera2 gate setters/fallback live in CameraViewModelCamera2Gates.kt as extensions. @@ -324,7 +318,7 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val lastCaptureUriMutable = MutableStateFlow<Uri?>(null) val lastCaptureUri = lastCaptureUriMutable.asStateFlow() - private val _galleryThumbnail = MutableStateFlow<Bitmap?>(null)+ internal val _galleryThumbnail = MutableStateFlow<Bitmap?>(null) val galleryThumbnail = _galleryThumbnail.asStateFlow() internal val gridEnabledMutable = MutableStateFlow(false)@@ -711,46 +705,9 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { */ @Volatile var foregroundRoute: String? = null + // Startup sequencing lives in CameraViewModelStartup.kt as an extension. init {- // Fast path first: seed the persisted lens synchronously so the- // Camera2 preview gate holds on frame one (see seedStartupLens).- // Nothing below may gate that bind.- seedStartupLens()- loadSettings()- panoramaEngine.onSweepComplete = { finishPanoramaSweep() }- viewModelScope.launch {- lastCaptureUriMutable.collect { uri -> _galleryThumbnail.value = loadThumbnail(uri) }- }- // Background enrichment AFTER first frame: CameraX initialisation +- // lens enumeration (per-lens Characteristics reads) refine the- // seeded placeholder. The Camera2 preview never waits on this: it- // opens via CameraManager + facing directly.- viewModelScope.launch(Dispatchers.Default) {- try {- val provider = ProcessCameraProvider.awaitInstance(app)- ensureLensesEnumerated(provider)- } catch (e: IllegalStateException) {- Log.status("CameraStartup", "background lens enrichment failed", e)- } catch (e: IllegalArgumentException) {- Log.status("CameraStartup", "background lens enrichment failed", e)- }- if (startupOrder.recordProbeCompleted()) {- Log.dev(- "CameraStartup",- "background probes complete; " +- "bindRequestedBeforeProbe=${startupOrder.bindRequestedBeforeProbeCompleted()}",- )- }- }- // Probe Slo-Mo capability once (back camera only). UI hides Slo-Mo if unsupported.- // Deferred off the startup path: it awaits CameraX initialisation and- // reads Recorder capabilities — irrelevant to the PHOTO first frame.- viewModelScope.launch {- sloMoSupportedMutable.value = probeSloMoSupport()- }- // DEBUG: Night mode resolution question – extension uses default resolution vs max-res,- // may be lower so can't take full quality?- startDebugLogging()+ runStartupSequence() } // Slo-Mo probe + thumbnail loading live in CameraStartup.kt as extensions.
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 712094662b..98bea76544 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt@@ -61,8 +61,14 @@ fun CameraViewModel.setCamera2SloMoEnabled(enabled: Boolean) { * real capture failure does that (see `tryCaptureCamera2NightExtension`). */ fun CameraViewModel.onCamera2NightPreviewFailed(cameraId: String) {+ // Key on the CURRENT selected lens, not the (possibly stale) id the+ // failing composable captured — same contract as onCamera2PreviewFailed:+ // the UI gate builds its key from the current selection, so the latch+ // must agree or it never reads as latched after reconciliation.+ val keyId = selectedLensMutable.value?.logicalCameraId+ ?.takeIf { it.isNotEmpty() } ?: cameraId val key = com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch- .bindKey(cameraId, cameraModeMutable.value)+ .bindKey(keyId, cameraModeMutable.value) if (camera2NightFallbackBindKeyMutable.value == key) return camera2NightFallbackBindKeyMutable.value = key Log.status("Camera2Night", "Camera2 extension preview failed for $key; falling back for this session")
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.ktnew file mode 100644index 0000000000..a4b3b18616--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.kt@@ -0,0 +1,70 @@+package com.vayunmathur.camera.platform++import androidx.camera.lifecycle.ProcessCameraProvider+import androidx.camera.lifecycle.awaitInstance+import androidx.lifecycle.viewModelScope+import com.vayunmathur.camera.data.loadSettings+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++/**+ * Startup sequencing for [CameraViewModel]: the synchronous startup-lens+ * seed plus the background enrichment launches, moved verbatim from the+ * ViewModel's `init` block as extensions (the gate state and flows+ * themselves stay on the ViewModel). Behaviour is unchanged.+ */++/** Records the first Camera2 bind request (from the preview composable). */+fun CameraViewModel.noteCamera2BindRequested() {+ if (startupOrder.recordBindRequested()) {+ Log.dev("CameraStartup", "camera2 bind requested (probes may still be running)")+ }+}++/**+ * Runs the ViewModel's startup sequence: seed first, persisted settings+ * second, and every CameraX-dependent probe in the background so the+ * Camera2 preview never waits on them.+ */+internal fun CameraViewModel.runStartupSequence() {+ // Fast path first: seed the persisted lens synchronously so the+ // Camera2 preview gate holds on frame one (see seedStartupLens).+ // Nothing below may gate that bind.+ seedStartupLens()+ loadSettings()+ panoramaEngine.onSweepComplete = { finishPanoramaSweep() }+ viewModelScope.launch {+ lastCaptureUriMutable.collect { uri -> _galleryThumbnail.value = loadThumbnail(uri) }+ }+ // Background enrichment AFTER first frame: CameraX initialisation ++ // lens enumeration (per-lens Characteristics reads) refine the+ // seeded placeholder. The Camera2 preview never waits on this: it+ // opens via CameraManager + facing directly.+ viewModelScope.launch(Dispatchers.Default) {+ try {+ val provider = ProcessCameraProvider.awaitInstance(app)+ ensureLensesEnumerated(provider)+ } catch (e: IllegalStateException) {+ Log.status("CameraStartup", "background lens enrichment failed", e)+ } catch (e: IllegalArgumentException) {+ Log.status("CameraStartup", "background lens enrichment failed", e)+ }+ if (startupOrder.recordProbeCompleted()) {+ Log.dev(+ "CameraStartup",+ "background probes complete; " ++ "bindRequestedBeforeProbe=${startupOrder.bindRequestedBeforeProbeCompleted()}",+ )+ }+ }+ // Probe Slo-Mo capability once (back camera only). UI hides Slo-Mo if unsupported.+ // Deferred off the startup path: it awaits CameraX initialisation and+ // reads Recorder capabilities — irrelevant to the PHOTO first frame.+ viewModelScope.launch {+ sloMoSupportedMutable.value = probeSloMoSupport()+ }+ // DEBUG: Night mode resolution question – extension uses default resolution vs max-res,+ // may be lower so can't take full quality?+ startDebugLogging()+}
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 3848f70c59..7a5282d025 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -16,6 +16,7 @@ import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import com.vayunmathur.camera.R 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.registerCamera2ExtensionSession
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.ktindex df783e23fb..55268455dd 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.kt@@ -7,7 +7,10 @@ import com.vayunmathur.camera.domain.RecordingPathInput import com.vayunmathur.camera.domain.RecordingPathPolicy import com.vayunmathur.camera.platform.CameraMode import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.STARTUP_UNRESOLVED_LENS_ID import com.vayunmathur.camera.platform.clearCamera2Fallback+import com.vayunmathur.camera.platform.clearCamera2NightFallback+import com.vayunmathur.camera.platform.onCamera2NightPreviewFailed import com.vayunmathur.camera.platform.onCamera2PreviewFailed import com.vayunmathur.camera.platform.setCamera2PreviewEnabled import com.vayunmathur.camera.platform.CustomRecordingGate@@ -46,15 +49,42 @@ class Camera2GateDefaultsTest { @Test fun viewModelFallbackLatchIsOneShotPerBind() { val v = vm()+ // Seeded contract: before background reconciliation the current+ // selection is the startup-unresolved placeholder, so the latch+ // keys on it — not on the stale "0" the failing composable+ // captured. The latch follows the current selection throughout.+ assertEquals(STARTUP_UNRESOLVED_LENS_ID, v.selectedLens.value?.logicalCameraId) assertTrue(v.onCamera2PreviewFailed("0"), "first failure falls back to CameraX") assertEquals(- Camera2FallbackLatch.bindKey("0", CameraMode.PHOTO),+ Camera2FallbackLatch.bindKey(STARTUP_UNRESOLVED_LENS_ID, CameraMode.PHOTO), v.camera2FallbackBindKey.value, ) assertFalse(v.onCamera2PreviewFailed("0"), "repeat failure must not re-trigger") v.clearCamera2Fallback() assertEquals(null, v.camera2FallbackBindKey.value) assertTrue(v.onCamera2PreviewFailed("0"), "cleared latch is a fresh bind attempt")+ assertEquals(+ Camera2FallbackLatch.bindKey(STARTUP_UNRESOLVED_LENS_ID, CameraMode.PHOTO),+ v.camera2FallbackBindKey.value,+ )+ }++ @Test fun viewModelNightFallbackLatchFollowsCurrentSelection() {+ val v = vm()+ // Same seeded contract as the preview latch: the night latch keys+ // on the current (startup-unresolved) selection, not the stale id.+ v.onCamera2NightPreviewFailed("0")+ assertEquals(+ Camera2FallbackLatch.bindKey(STARTUP_UNRESOLVED_LENS_ID, CameraMode.PHOTO),+ v.camera2NightFallbackBindKey.value,+ )+ v.onCamera2NightPreviewFailed("0")+ assertEquals(+ Camera2FallbackLatch.bindKey(STARTUP_UNRESOLVED_LENS_ID, CameraMode.PHOTO),+ v.camera2NightFallbackBindKey.value,+ )+ v.clearCamera2NightFallback()+ assertEquals(null, v.camera2NightFallbackBindKey.value) } @Test fun videoCustomGateStaysOffUntilDeviceVerified() {