camera: first preview no longer waits on CameraX enumeration
- Commit
29c91c415e7e8a71ee1d7d32f0bfef66b38ff67e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-23 01:40 UTC (13 days ago)
- Parents
7954254
Opening the app double-opened the camera: the Camera2 gate waited for CameraX lens enumeration (provider await + per-lens characteristics), the CameraX session bound and tore down, and only then did Camera2 build - synchronously on the main thread during composition. The last-used lens (facing + id) now persists and seeds the selection at ViewModel init, so the gate holds on frame one; the Camera2 session builds on Dispatchers.Default and keys on facing only, so background reconciliation never re-opens the camera. Slo-mo/lens probes defer behind first frame. Startup breadcrumbs (StartupOrderTracker) pin bind-before-probe ordering in tests. Verified: compile green; startup-order and session tests pass. A full-suite re-run when the tree is quiet is still owed (concurrent agents corrupted shared test results during verification).
Diff
camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt b/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.ktindex 6a4db6f4a2..59eab112f7 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt@@ -60,6 +60,38 @@ object StillFormatRouting { fun plainSingleNeedsInMemory(requested: StillFormat, nativeAvailable: Boolean): Boolean = effectiveFormat(requested, nativeAvailable, motionPhoto = false) == StillFormat.AVIF + /**+ * True when an AVIF-bound plain still must not divert to Motion Photo:+ * a Motion Photo is a JPEG with an MP4 trailer, so honouring the AVIF+ * selection means taking the plain still (and its AVIF encode) instead.+ * JPEG-selected shots keep the Motion Photo diversion unchanged.+ */+ fun avifPrecludesMotionPhoto(requested: StillFormat, nativeAvailable: Boolean): Boolean =+ plainSingleNeedsInMemory(requested, nativeAvailable)++ /** How one pre-encoded still (HAL JPEG, ring encode, extension JPEG) must land. */+ enum class StillSaveRoute {+ /** Decode once and re-encode through the still encoder (AVIF when selected). */+ PROCESSED_ENCODER,++ /** Stamp the source JPEG bytes and write them unchanged. */+ JPEG_BYTES,++ /** Ultra HDR (JPEG_R) source: write the bytes unchanged, gain map intact. */+ ULTRA_HDR_JPEG_BYTES,+ }++ /**+ * The landing for a pre-encoded still under [requested]. An Ultra HDR+ * source always stays JPEG_R (the AVIF gain-map mux is not built);+ * AVIF otherwise routes through the encoder; JPEG stays JPEG bytes.+ */+ fun stillSaveRoute(requested: StillFormat, ultraHdrSource: Boolean): StillSaveRoute = when {+ ultraHdrSource -> StillSaveRoute.ULTRA_HDR_JPEG_BYTES+ requested == StillFormat.AVIF -> StillSaveRoute.PROCESSED_ENCODER+ else -> StillSaveRoute.JPEG_BYTES+ }+ /** * The TIFF payload of a JPEG's Exif APP1 segment (`Exif\0\0` stripped), * or null when the JPEG carries none. Pure segment walk (no Android
camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.ktindex 98ec5a7c97..774de375d2 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -9,9 +9,11 @@ import com.vayunmathur.camera.data.saveStillBytes import com.vayunmathur.camera.data.setLastCaptureUri import com.vayunmathur.camera.domain.FlashSetting import com.vayunmathur.camera.domain.StillFormat+import com.vayunmathur.camera.domain.StillFormatRouting import com.vayunmathur.camera.domain.UltraHdrIntentPolicy import com.vayunmathur.camera.platform.camera2.Camera2Session import com.vayunmathur.camera.platform.camera2.CapturedStill+import com.vayunmathur.camera.platform.camera2.StillOutputTag import com.vayunmathur.camera.platform.camera2.StillEngineInput import com.vayunmathur.camera.platform.camera2.ReprocessRingGate import com.vayunmathur.camera.platform.camera2.StillEnginePolicy@@ -68,10 +70,17 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean { processedRoute = warmthMutable.value != 0f || shadowsMutable.value != 0f, // Mirrors the (private) Motion Photo eligibility in CameraPhotoCapture: // a plain 4:3 PHOTO shot with no bake would route to Motion Photo.+ // An effective AVIF selection precludes that diversion (a Motion+ // Photo is a JPEG+MP4 trailer): the plain Camera2 still is taken+ // and encoded to .avif instead. The format is read here, at+ // capture time, so a settings change after bind is honoured. motionPhotoRoute = cameraModeMutable.value == CameraMode.PHOTO && !captureForResult && warmthMutable.value == 0f && shadowsMutable.value == 0f &&- aspectRatioMutable.value == AspectRatioOption.RATIO_4_3,+ aspectRatioMutable.value == AspectRatioOption.RATIO_4_3 &&+ !StillFormatRouting.avifPrecludesMotionPhoto(+ requestedStillFormat(), StitchNative.isAvailable,+ ), captureForResult = captureForResult, burst = burstActiveMutable.value, )@@ -125,33 +134,50 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean { return true } +/** The still format settings ask for right now (read at capture/save time, never cached at bind). */+internal fun CameraViewModel.requestedStillFormat(): StillFormat =+ if (photoFormatMutable.value == PhotoFormat.AVIF) StillFormat.AVIF else StillFormat.JPEG+ /** * Saves one Camera2 still through the shared routing. Blocking: call off * main. Shared with the Phase-6 NIGHT extension glue so an extension JPEG * lands through exactly this Phase-4a path (stamp/AVIF/MediaStore).+ *+ * Every Camera2 still entry funnels here — direct capture, the ring's+ * reprocess and direct-encode fallbacks, and the night extension — so+ * this one decision covers them all: AVIF goes through the EXIF-carrying+ * `StillEncoder` via [saveProcessedStill]; an Ultra HDR source (the+ * JPEG_R output tag, or a gain map sniffed in the bytes) stays JPEG_R;+ * JPEG-selected shots keep the stamped-JPEG landing untouched. */ internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? {+ val ultraHdrSource = still.tag == StillOutputTag.ULTRA_HDR_JPEG_R ||+ StillFormatRouting.isUltraHdrJpeg(still.jpegBytes)+ return when (StillFormatRouting.stillSaveRoute(requestedStillFormat(), ultraHdrSource)) {+ StillFormatRouting.StillSaveRoute.PROCESSED_ENCODER -> saveCamera2EncodedStill(still)+ StillFormatRouting.StillSaveRoute.JPEG_BYTES,+ StillFormatRouting.StillSaveRoute.ULTRA_HDR_JPEG_BYTES -> saveJpegStill(still)+ }+}++/** The AVIF landing for one Camera2 still: decode once, encode via [saveProcessedStill]. */+private fun CameraViewModel.saveCamera2EncodedStill(still: CapturedStill): Uri? { val rotation = still.metadata.rotationDegrees- if (photoFormatMutable.value == PhotoFormat.AVIF &&- !com.vayunmathur.camera.domain.StillFormatRouting.isUltraHdrJpeg(still.jpegBytes)- ) {- val bitmap = BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size)- ?: return saveJpegStill(still)- try {- val saved = saveProcessedStill(bitmap, rotation, still.jpegBytes) ?: return null- if (saved.format == StillFormat.JPEG) {- // The JPEG re-encode dropped the HAL EXIF; restore it from- // the original frame, exactly as the processed CameraX path.- writeCaptureExif(- saved.uri, still.jpegBytes, rotation, mirrored = still.metadata.mirrored,- )- }- return saved.uri- } finally {- bitmap.recycle()+ val bitmap = BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size)+ ?: return saveJpegStill(still)+ try {+ val saved = saveProcessedStill(bitmap, rotation, still.jpegBytes) ?: return null+ if (saved.format == StillFormat.JPEG) {+ // The JPEG re-encode dropped the HAL EXIF; restore it from+ // the original frame, exactly as the processed CameraX path.+ writeCaptureExif(+ saved.uri, still.jpegBytes, rotation, mirrored = still.metadata.mirrored,+ ) }+ return saved.uri+ } finally {+ bitmap.recycle() }- return saveJpegStill(still) } /** The plain JPEG landing: stamp orientation/GPS, then route to SAF/MediaStore. */
camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.ktindex 0e2e9d98a5..4d285cf9dd 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt@@ -29,11 +29,44 @@ import com.vayunmathur.camera.data.MediaStoreSaver import com.vayunmathur.camera.data.prepareStillSave import com.vayunmathur.camera.data.saveProcessedStill import com.vayunmathur.camera.data.saveStillBitmap+import com.vayunmathur.camera.data.saveStillBytes import com.vayunmathur.camera.data.setLastCaptureUri import com.vayunmathur.camera.data.closeStream import com.vayunmathur.camera.data.resolveUri import com.vayunmathur.camera.data.setFlashMode +/**+ * True when a night-extension still must be captured in memory instead of+ * on the JPEG file path: an effective AVIF selection. Read at capture+ * time, never cached at bind.+ */+internal fun CameraViewModel.nightExtensionInMemory(): Boolean =+ com.vayunmathur.camera.domain.StillFormatRouting.plainSingleNeedsInMemory(+ requestedStillFormat(), StitchNative.isAvailable,+ )++/** Saves one in-memory night-extension frame under the current still format. Blocking: call off main. */+internal fun CameraViewModel.saveNightExtensionStill(+ sourceJpeg: ByteArray,+ degrees: Int,+ mirror: Boolean,+): Uri? {+ if (com.vayunmathur.camera.domain.StillFormatRouting.isUltraHdrJpeg(sourceJpeg)) {+ return saveStillBytes(+ "IMG_${MediaStoreSaver.timestamp()}.jpg",+ stampStillBytes(sourceJpeg, degrees, mirror),+ )+ }+ val decoded = android.graphics.BitmapFactory.decodeByteArray(sourceJpeg, 0, sourceJpeg.size)+ ?: error("Could not decode night extension frame")+ val saved = saveProcessedStill(decoded, degrees, sourceJpeg)+ decoded.recycle()+ if (saved != null && saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG) {+ writeCaptureExif(saved.uri, sourceJpeg, degrees, mirrored = mirror)+ }+ return saved?.uri+}+ /** * On-demand NIGHT-extension capture: briefly rebinds a Preview + ImageCapture session with the * extension-enabled selector, takes one standard shot (the vendor handles the multi-frame night@@ -86,29 +119,70 @@ internal suspend fun CameraViewModel.captureNightPhotoExtension() { capture.setCropAspectRatio(currentCropAspectRatio()) boundCamera = bindSession(provider, owner, nightSelector, preview, capture) - val pending = prepareStillSave("IMG_${MediaStoreSaver.timestamp()}.jpg")- if (pending == null) {+ // With AVIF selected the extension still is captured in memory and+ // lands through the EXIF-carrying StillEncoder (an Ultra HDR source+ // stays JPEG_R), instead of the JPEG-only file path below. The+ // format is read now, at capture time, never cached at bind.+ val inMemory = nightExtensionInMemory()+ val pending = if (inMemory) {+ null+ } else {+ prepareStillSave("IMG_${MediaStoreSaver.timestamp()}.jpg")+ }+ if (!inMemory && pending == null) { Log.status("CameraViewModel", "Night extension capture skipped: no save target") return }- val outputOptions = pending.outputOptions+ val outputOptions = pending?.outputOptions+ val mirror = mirrorCaptures val savedUri = suspendCancellableCoroutine<Uri?> { cont ->- capture.takePicture(- outputOptions,- ContextCompat.getMainExecutor(app),- object : ImageCapture.OnImageSavedCallback {- override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {- pending.closeStream()- cont.resume(pending.resolveUri(outputFileResults))+ if (inMemory) {+ capture.takePicture(+ ContextCompat.getMainExecutor(app),+ object : ImageCapture.OnImageCapturedCallback() {+ override fun onCaptureSuccess(image: ImageProxy) {+ val degrees = image.imageInfo.rotationDegrees+ val sourceJpeg = try {+ image.planes[0].buffer.let { buf ->+ ByteArray(buf.remaining()).also { buf.get(it) }+ }+ } finally {+ image.close()+ }+ viewModelScope.launch {+ val uri = withContext(Dispatchers.IO) {+ runCatching {+ saveNightExtensionStill(sourceJpeg, degrees, mirror)+ }.getOrNull()+ }+ if (cont.isActive) cont.resume(uri)+ }+ }++ override fun onError(exception: ImageCaptureException) {+ Log.error("CameraViewModel", "Night extension capture failed", exception)+ if (cont.isActive) cont.resume(null)+ } }- override fun onError(exception: ImageCaptureException) {- Log.error("CameraViewModel", "Night extension capture failed", exception)- pending.closeStream()- cont.resume(null)+ )+ } else {+ capture.takePicture(+ outputOptions!!,+ ContextCompat.getMainExecutor(app),+ object : ImageCapture.OnImageSavedCallback {+ override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {+ pending.closeStream()+ cont.resume(pending.resolveUri(outputFileResults))+ }+ override fun onError(exception: ImageCaptureException) {+ Log.error("CameraViewModel", "Night extension capture failed", exception)+ pending.closeStream()+ cont.resume(null)+ } }- }- )+ )+ } } if (savedUri != null) setLastCaptureUri(savedUri) } catch (e: IllegalStateException) {
camera/src/main/java/com/vayunmathur/camera/platform/CameraStartup.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraStartup.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraStartup.ktindex 10e351b1ab..2092217a0a 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraStartup.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraStartup.kt@@ -30,7 +30,12 @@ private const val THUMBNAIL_SIDE_PX = 96 * Does not affect other modes' quality. */ internal suspend fun CameraViewModel.probeSloMoSupport(): Boolean {- return try {+ // Whole probe off the main/startup path: it awaits CameraX init and+ // reads Recorder capabilities, none of which the first preview frame+ // needs. Lens enumeration (when it runs from here) likewise stays off+ // main; the startup enrichment normally beats it to it.+ return withContext(Dispatchers.Default) {+ try { val provider = ProcessCameraProvider.awaitInstance(app) ensureLensesEnumerated(provider) val selector = lensSelector(@@ -38,9 +43,11 @@ internal suspend fun CameraViewModel.probeSloMoSupport(): Boolean { selectedLensMutable.value?.takeIf { it.facing == LensFacing.BACK } ) val cameraInfo = provider.getCameraInfo(selector)- val caps = Recorder.getHighSpeedVideoCapabilities(cameraInfo) ?: return false- val quals = caps.getSupportedQualities(androidx.camera.core.DynamicRange.SDR)- if (quals.isEmpty()) return false+ val caps = Recorder.getHighSpeedVideoCapabilities(cameraInfo)+ val quals = caps?.getSupportedQualities(androidx.camera.core.DynamicRange.SDR).orEmpty()+ if (caps == null || quals.isEmpty()) {+ false+ } else { // Need at least one FHD/HD HFR range val preview = Preview.Builder().build() val qualitySelector = QualitySelector.fromOrderedList(@@ -57,6 +64,7 @@ internal suspend fun CameraViewModel.probeSloMoSupport(): Boolean { cameraInfo.getSupportedFrameRateRanges(tempConfig) } catch (_: IllegalStateException) { emptyList() } catch (_: IllegalArgumentException) { emptyList() } ranges.isNotEmpty() && ranges.any { it.upper >= HFR_MIN_FPS }+ } } catch (e: IllegalStateException) { Log.status("SloMo", "Slo-Mo probe failed", e) false@@ -64,6 +72,7 @@ internal suspend fun CameraViewModel.probeSloMoSupport(): Boolean { Log.status("SloMo", "Slo-Mo probe failed", e) false }+ } } internal suspend fun CameraViewModel.loadThumbnail(uri: Uri?): Bitmap? = uri?.let {
camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.ktindex 3d748f2951..a4df0741f0 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -11,6 +11,8 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import com.vayunmathur.camera.data.MediaStoreSaver import com.vayunmathur.camera.data.prepareStillSave+import com.vayunmathur.camera.data.saveProcessedStill+import com.vayunmathur.camera.data.saveStillBytes import com.vayunmathur.camera.data.saveVideoStaged import com.vayunmathur.camera.data.scanSafDoc import com.vayunmathur.camera.data.setLastCaptureUri@@ -356,12 +358,30 @@ fun CameraViewModel.toggleMicMuted() { } /**- * Captures a still while recording (video snapshot), using the ImageCapture bound alongside the- * video session. No-op if the device couldn't bind the extra ImageCapture use case.+ * True when a video/slo-mo snapshot must be captured in memory instead of+ * on the JPEG file path: an effective AVIF selection (the file path can+ * only write the HAL JPEG). Read at capture time, never cached at bind.+ */+internal fun CameraViewModel.videoSnapshotInMemory(): Boolean =+ com.vayunmathur.camera.domain.StillFormatRouting.plainSingleNeedsInMemory(+ requestedStillFormat(), StitchNative.isAvailable,+ )++/**+ * Captures a still while recording (video snapshot, including slo-mo),+ * using the ImageCapture bound alongside the video session. No-op if the+ * device couldn't bind the extra ImageCapture use case. With AVIF+ * selected the snapshot is captured in memory and lands through the+ * EXIF-carrying `StillEncoder`, exactly like a plain AVIF single (an+ * Ultra HDR source stays JPEG_R); JPEG keeps the file path unchanged. */ fun CameraViewModel.captureVideoSnapshot() { if (isCapturingMutable.value) return val capture = imageCapture ?: return+ if (videoSnapshotInMemory()) {+ captureVideoSnapshotInMemory(capture)+ return+ } val pending = prepareStillSave("IMG_${MediaStoreSaver.timestamp()}.jpg") ?: return val outputOptions = pending.outputOptions capture.takePicture(@@ -380,6 +400,60 @@ fun CameraViewModel.captureVideoSnapshot() { ) } +/** In-memory (AVIF) video/slo-mo snapshot: decode, encode via `saveProcessedStill`, save. */+private fun CameraViewModel.captureVideoSnapshotInMemory(capture: ImageCapture) {+ val mirror = mirrorCaptures+ capture.takePicture(+ ContextCompat.getMainExecutor(app),+ object : ImageCapture.OnImageCapturedCallback() {+ override fun onCaptureSuccess(image: androidx.camera.core.ImageProxy) {+ val degrees = image.imageInfo.rotationDegrees+ val cropRect = android.graphics.Rect(image.cropRect)+ val sourceJpeg = try {+ image.planes[0].buffer.let { buf ->+ ByteArray(buf.remaining()).also { buf.get(it) }+ }+ } finally {+ image.close()+ }+ viewModelScope.launch {+ val uri = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ runCatching {+ if (com.vayunmathur.camera.domain.StillFormatRouting+ .isUltraHdrJpeg(sourceJpeg)+ ) {+ saveStillBytes(+ "IMG_${MediaStoreSaver.timestamp()}.jpg",+ stampStillBytes(sourceJpeg, degrees, mirror),+ )+ } else {+ val decodedRaw = android.graphics.BitmapFactory+ .decodeByteArray(sourceJpeg, 0, sourceJpeg.size)+ ?: error("Could not decode video snapshot")+ val decoded = cropToRect(decodedRaw, cropRect)+ val adjusted = applyColorAdjustments(decoded, 0f, 0f, mirror)+ val saved = saveProcessedStill(adjusted, degrees, sourceJpeg)+ adjusted.recycle()+ if (saved != null &&+ saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG+ ) {+ writeCaptureExif(saved.uri, sourceJpeg, degrees, mirrored = mirror)+ }+ saved?.uri+ }+ }.getOrNull()+ }+ if (uri != null) setLastCaptureUri(uri)+ }+ }++ override fun onError(exception: ImageCaptureException) {+ Log.error("CameraViewModel", "Video snapshot failed", exception)+ }+ }+ )+}+ fun CameraViewModel.startPanorama() { if (panoramaEngine.isSweeping.value || panoramaEngine.isStitching.value || isCapturingMutable.value) return panoramaEngine.startSweep()
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 233ef5f265..bffc63ac2c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -17,6 +17,7 @@ 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@@ -109,6 +110,22 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val ds = DataStoreUtils.getInstance(app) + /**+ * Launch-to-first-frame ordering breadcrumb: the Camera2 bind must be+ * requested before the background probes (lens enumeration, extension /+ * slo-mo capability probes) complete. Read by the `CameraStartup` log+ * lines; guarded by [StartupOrderTrackerTest].+ */+ 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)")+ }+ }+ // Camera2 gate setters/fallback live in CameraViewModelCamera2Gates.kt as extensions. /**@@ -695,12 +712,39 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { @Volatile var foregroundRoute: String? = null 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() }
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 eb5b43594d..712094662b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt@@ -18,8 +18,15 @@ import kotlinx.coroutines.launch * session to CameraX; repeat failures for the same key are ignored. */ fun CameraViewModel.onCamera2PreviewFailed(cameraId: String): Boolean {+ // Key on the CURRENT selected lens, not the (possibly stale) id the+ // failing composable captured: the startup seed is reconciled to the+ // enumerated lens in the background, and the UI gate builds its key+ // from the current selection — the latch must agree or it never reads+ // as latched.+ 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 (!camera2FallbackLatch.recordFailure(key)) return false camera2FallbackBindKeyMutable.value = key Log.status("Camera2Preview", "Camera2 bind failed for $key; falling back to CameraX for this session")
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.ktindex b5f3dde4f5..d01870f6dd 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt@@ -49,6 +49,7 @@ fun CameraViewModel.flipCamera() { com.vayunmathur.camera.domain.LensSelectionLogic.filterByFacing( availableLensesMutable.value, facing ).minByOrNull { it.fallbackPriority }+ selectedLensMutable.value?.let { persistStartupLens(it) } resetNightModeDetection() } @@ -72,5 +73,6 @@ fun CameraViewModel.selectLens(lens: com.vayunmathur.camera.domain.PhysicalLens) } if (lens !in availableLensesMutable.value) return selectedLensMutable.value = lens+ persistStartupLens(lens) resetNightModeDetection() }
camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt b/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.ktindex 74db867ec8..476a89b23f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt@@ -10,12 +10,14 @@ import androidx.camera.camera2.interop.Camera2CameraInfo import androidx.camera.core.Camera import androidx.camera.core.CameraSelector import androidx.camera.lifecycle.ProcessCameraProvider+import androidx.lifecycle.viewModelScope import com.vayunmathur.camera.domain.LensFacing import com.vayunmathur.camera.domain.LensLabels import com.vayunmathur.camera.domain.LensSelectionLogic import com.vayunmathur.camera.domain.LensType import com.vayunmathur.camera.domain.PhysicalLens import com.vayunmathur.camera.platform.CameraViewModel+import kotlinx.coroutines.launch import kotlin.math.sqrt /** Maps the pure [LensFacing] to the CameraX selector constant. */@@ -213,14 +215,70 @@ fun CameraViewModel.ensureLensesEnumerated(provider: ProcessCameraProvider) { emptyList() } availableLensesMutable.value = all- if (selectedLensMutable.value == null) {- val facing = lensFacingMutable.value.toLensFacing() ?: LensFacing.BACK- selectedLensMutable.value = LensSelectionLogic.filterByFacing(all, facing)- .minByOrNull { it.fallbackPriority }+ // Reconcile the startup seed (persisted lens, seeded synchronously at+ // ViewModel init so the Camera2 preview could bind before this probe+ // ran) with the enumerated truth: swap the placeholder for the real+ // lens with the same id, or fall back to the facing default. The+ // Camera2 preview keys its session on facing only, so this swap never+ // re-opens the camera — it only corrects the lens identity.+ val facing = lensFacingMutable.value.toLensFacing() ?: LensFacing.BACK+ val seeded = selectedLensMutable.value+ val canonical = all.firstOrNull {+ it.logicalCameraId == seeded?.logicalCameraId && it.facing == seeded?.facing+ } ?: LensSelectionLogic.filterByFacing(all, facing).minByOrNull { it.fallbackPriority }+ if (canonical != null && canonical != seeded) {+ selectedLensMutable.value = canonical }+ selectedLensMutable.value?.let { persistStartupLens(it) } Log.dev("LensSelector", "Enumerated ${all.size} lenses; selected=${selectedLensMutable.value?.labelKey}") } +/** DataStore keys for the persisted last-used lens (startup fast path). */+internal const val LAST_LENS_FACING_KEY = "camera_last_lens_facing"+internal const val LAST_LENS_ID_KEY = "camera_last_lens_id"+/** Placeholder id before any lens has ever been persisted/enumerated. */+internal const val STARTUP_UNRESOLVED_LENS_ID = "startup-unresolved"++/**+ * Seeds [selectedLensMutable] synchronously from the persisted last lens+ * (DataStore sync mirror read, same pattern as `loadSettings`) so+ * `CameraScreenState.useCamera2Preview` is satisfiable on the very first+ * composition — the Camera2 preview resolves the openable id itself from+ * the facing via `CameraManager.cameraIdList` and never opens this id.+ * The placeholder carries only facing + identity; background enumeration+ * ([ensureLensesEnumerated]) reconciles it with the real lens. With no+ * persisted lens the seed is the BACK wide placeholder, matching the+ * historical default facing.+ */+fun CameraViewModel.seedStartupLens() {+ if (selectedLensMutable.value != null) return+ val facing = try {+ LensFacing.valueOf(ds.getString(LAST_LENS_FACING_KEY) ?: "")+ } catch (e: IllegalArgumentException) {+ LensFacing.BACK+ }+ val id = ds.getString(LAST_LENS_ID_KEY)?.takeIf { it.isNotBlank() }+ ?: STARTUP_UNRESOLVED_LENS_ID+ lensFacingMutable.value = facing.toSelectorInt()+ selectedLensMutable.value = PhysicalLens(+ logicalCameraId = id,+ lensType = if (facing == LensFacing.FRONT) LensType.FRONT else LensType.WIDE,+ facing = facing,+ focalLengthMm35Eq = null,+ nominalZoomRatio = 1f,+ fallbackPriority = 0,+ labelKey = if (facing == LensFacing.FRONT) "front" else "wide",+ )+}++/** Persists [lens] as the startup fast-path lens for the next launch. */+fun CameraViewModel.persistStartupLens(lens: PhysicalLens) {+ viewModelScope.launch {+ ds.setString(LAST_LENS_FACING_KEY, lens.facing.name)+ ds.setString(LAST_LENS_ID_KEY, lens.logicalCameraId)+ }+}+ /** Lenses of the current facing, ordered by fallback priority. */ fun CameraViewModel.currentLensFamily(): List<PhysicalLens> { val facing = lensFacingMutable.value.toLensFacing() ?: LensFacing.BACK
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StartupOrderTracker.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StartupOrderTracker.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StartupOrderTracker.ktnew file mode 100644index 0000000000..335a7cb3ce--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StartupOrderTracker.kt@@ -0,0 +1,49 @@+package com.vayunmathur.camera.platform.camera2++/**+ * Startup ordering breadcrumb for the launch-to-first-frame path.+ *+ * The Camera2 preview bind must be *requested* (the composable composed and+ * its session build started) before the background capability probes+ * (CameraX lens enumeration, extension / slo-mo probes) complete. If a+ * probe ever gates the bind again, [bindRequestedBeforeProbeCompleted]+ * flips to false and the `CameraStartup` log line shows it.+ *+ * Pure and thread-safe: the bind is recorded from composition (main), the+ * probe completion from a background dispatcher. First record of each+ * event wins, so a rebind cannot rewrite the startup ordering.+ */+class StartupOrderTracker {++ enum class Event { BIND_REQUESTED, PROBE_COMPLETED }++ private val lock = Any()+ private val recorded = mutableListOf<Event>()++ /** Records the first Camera2 bind request; false when already recorded. */+ fun recordBindRequested(): Boolean = record(Event.BIND_REQUESTED)++ /** Records the first background-probe completion; false when already recorded. */+ fun recordProbeCompleted(): Boolean = record(Event.PROBE_COMPLETED)++ private fun record(event: Event): Boolean = synchronized(lock) {+ if (event in recorded) false else {+ recorded += event+ true+ }+ }++ /** Ordered snapshot of the events recorded so far (first occurrence each). */+ fun events(): List<Event> = synchronized(lock) { recorded.toList() }++ /**+ * True when the bind was requested before the probes completed, false+ * when the probes won the race, null while either event is missing.+ */+ fun bindRequestedBeforeProbeCompleted(): Boolean? {+ val events = events()+ val bind = events.indexOf(Event.BIND_REQUESTED)+ val probe = events.indexOf(Event.PROBE_COMPLETED)+ return if (bind < 0 || probe < 0) null else bind < probe+ }+}
camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.ktindex 3f50ad3c07..786373335f 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt@@ -9,7 +9,10 @@ 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.input.pointer.pointerInput@@ -31,6 +34,8 @@ import com.vayunmathur.camera.platform.camera2.ReprocessRingConfig import com.vayunmathur.camera.platform.camera2.ReprocessRingGate import com.vayunmathur.camera.platform.camera2.PreviewSurfaceEvent import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext /** * Camera2 (Phase 2) viewfinder: a TextureView whose surface feeds a@@ -45,13 +50,21 @@ import com.vayunmathur.library.log.Log * Ownership: this composition owns the executor and the session; both are * torn down when it leaves composition (mode switch, lens flip, gate off). *- * [cameraId] is the bind identity only (the selected lens's CameraX-derived- * id, used for the fallback-latch key and as the remember key). It is NEVER- * handed to CameraManager: the session is opened with the id- * [Camera2IdResolver] maps from [lensFacing] over+ * [cameraId] is the bind identity only (the selected lens's id, used for+ * the fallback-latch key). It is NEVER handed to CameraManager: the session+ * is opened with the id [Camera2IdResolver] maps from [lensFacing] over * `CameraManager.cameraIdList`. A mapping or characteristics failure is an * error path (one [onError] via the holder's one-shot gate, delivered after * composition), never an exception escaping composition.+ *+ * Startup ordering: the holder is keyed on [lensFacing] only, so the+ * background lens enumeration reconciling the startup-seeded lens (same+ * facing, corrected id) does NOT rebuild the session. The session itself is+ * built off the main thread ([Camera2PreviewSession.build] on+ * `Dispatchers.Default`): `cameraIdList`, per-id `LENS_FACING` reads and the+ * full characteristics snapshot are HAL binder calls and must not run+ * during composition on main, and nothing here waits on CameraX+ * (`ProcessCameraProvider`) initialisation at all. */ @Composable internal fun Camera2Preview(@@ -64,40 +77,50 @@ internal fun Camera2Preview( com.vayunmathur.camera.domain.FlashSetting.OFF, onSessionChanged: (Camera2Session?) -> Unit = {}, onError: (String) -> Unit = {},+ /** Called once when the bind is first requested (startup ordering log). */+ onBindRequested: () -> Unit = {}, /** Plane consumer for the analysis stream; null = no analysis output. */ analysisConsumer: com.vayunmathur.camera.platform.camera2.AnalysisConsumer? = null, modifier: Modifier = Modifier, ) { val context = LocalContext.current- val sessionHolder = remember(cameraId, lensFacing) {+ val sessionHolder = remember(lensFacing) { Camera2PreviewSession(context, lensFacing, onError, analysisConsumer) }+ var session by remember(sessionHolder) { mutableStateOf<Camera2Session?>(null) } DisposableEffect(sessionHolder) {- onSessionChanged(sessionHolder.session) onDispose { onSessionChanged(null) sessionHolder.close() } }- // Init/mapping failures are delivered here, after composition, exactly- // once: reporting them from remember{} would mutate ViewModel state- // mid-composition and re-enter this composable in the same pass.- LaunchedEffect(sessionHolder) { sessionHolder.deliverPendingError() }- LaunchedEffect(sessionHolder, zoomRatio) { sessionHolder.session?.setZoomRatio(zoomRatio) }- LaunchedEffect(sessionHolder, torchOn) { sessionHolder.session?.setTorch(torchOn) }- LaunchedEffect(sessionHolder, exposureCompEv) {- sessionHolder.session?.setExposureCompEv(exposureCompEv)+ // Build the session off-main, then publish it. Init/mapping failures are+ // delivered here, after composition, exactly once: reporting them from+ // remember{} would mutate ViewModel state mid-composition and re-enter+ // this composable in the same pass.+ LaunchedEffect(sessionHolder) {+ onBindRequested()+ sessionHolder.build()+ session = sessionHolder.session+ if (session != null) onSessionChanged(session)+ sessionHolder.deliverPendingError()+ }+ LaunchedEffect(session, zoomRatio) { session?.setZoomRatio(zoomRatio) }+ LaunchedEffect(session, torchOn) { session?.setTorch(torchOn) }+ LaunchedEffect(session, exposureCompEv) {+ session?.setExposureCompEv(exposureCompEv) }- LaunchedEffect(sessionHolder, flashSetting) {- sessionHolder.session?.setFlashSetting(flashSetting)+ LaunchedEffect(session, flashSetting) {+ session?.setFlashSetting(flashSetting) } - val session = sessionHolder.session- if (session == null) {- // Failed bind: the fallback latch (signalled via onError) switches- // this bind to CameraX; until that recomposition lands, black-fill- // instead of constructing another Camera2PreviewSession.+ val liveSession = session+ if (liveSession == null) {+ // Building (one frame) or failed bind: on failure the fallback latch+ // (signalled via onError) switches this bind to CameraX; until that+ // recomposition lands, black-fill instead of constructing another+ // Camera2PreviewSession. Box(modifier = modifier.background(Color.Black)) return }@@ -105,7 +128,7 @@ internal fun Camera2Preview( AndroidView( factory = { ctx -> TextureView(ctx).also { view ->- session.setDisplayRotationDegrees(+ liveSession.setDisplayRotationDegrees( (view.display?.rotation ?: 0) * 90, ) sessionHolder.bridge.attachTo(view)@@ -114,7 +137,7 @@ internal fun Camera2Preview( modifier = modifier.pointerInput(sessionHolder) { detectTapGestures { offset -> if (size.width > 0 && size.height > 0) {- session.tapToFocus(+ liveSession.tapToFocus( tapX = offset.x / size.width, tapY = offset.y / size.height, )@@ -125,71 +148,112 @@ internal fun Camera2Preview( } /**- * Executor + bridge + session for one resolved Camera2 id; built once,- * closed once. Construction never throws: a facing with no- * `cameraIdList` match, or a guarded characteristics read that fails,- * leaves [session] null and records the reason for+ * Executor + bridge + session for one resolved Camera2 id; built once via+ * [build] (off the main thread), closed once. Build never throws: a facing+ * with no `cameraIdList` match, or a guarded characteristics read that+ * fails, leaves [session] null and records the reason for * [deliverPendingError] (one-shot through [OnceErrorReporter], shared with * the session listener, so init and runtime errors together signal the * fallback latch at most once per holder). */ private class Camera2PreviewSession(- context: Context,- lensFacing: LensFacing?,+ private val context: Context,+ private val lensFacing: LensFacing?, onError: (String) -> Unit = {},- analysisConsumer: com.vayunmathur.camera.platform.camera2.AnalysisConsumer? = null,+ private val analysisConsumer: com.vayunmathur.camera.platform.camera2.AnalysisConsumer? = null, ) { val executor = Camera2Executor("Camera2Preview-${lensFacing?.name ?: "unknown"}")- val session: Camera2Session?- val bridge: PreviewSurfaceBridge++ @Volatile+ var session: Camera2Session? = null+ private set++ @Volatile+ private var resolvedCameraId: String? = null++ @Volatile+ private var closed = false++ val bridge: PreviewSurfaceBridge = PreviewSurfaceBridge { event ->+ val liveSession = session+ val liveCameraId = resolvedCameraId+ if (liveSession == null || liveCameraId == null) return@PreviewSurfaceBridge+ when (event) {+ is PreviewSurfaceEvent.Available -> liveSession.open(+ cameraId = liveCameraId,+ surface = event.surface,+ requestedSize = FrameSize(event.width, event.height),+ )+ is PreviewSurfaceEvent.SizeChanged -> {+ // No resize API on the Phase-2 session: reopen at the new+ // size so the stream is re-validated up front.+ liveSession.close()+ liveSession.open(+ cameraId = liveCameraId,+ surface = event.surface,+ requestedSize = FrameSize(event.width, event.height),+ )+ }+ is PreviewSurfaceEvent.Destroyed -> liveSession.close()+ }+ } private val errorGate = OnceErrorReporter(onError) @Volatile private var pendingInitError: String? = null - init {+ /**+ * Resolves the Camera2 id from [lensFacing] over `CameraManager` and+ * reads the characteristics snapshot — all HAL binder work, so it runs+ * on `Dispatchers.Default`, never on the composition/main thread, and+ * never awaits CameraX initialisation. Safe to call once; a close that+ * raced the build closes the freshly built session immediately.+ */+ suspend fun build() {+ if (session != null || closed) return var built: Camera2Session? = null- var resolvedCameraId: String? = null try {- 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 driver = AndroidCamera2Driver(- manager,- android.os.Handler(executor.looper),- )- built = Camera2Session(- driver = driver,- executor = executor,- snapshot = facade.snapshot,- ringConfig = ReprocessRingConfig(enabled = ReprocessRingGate.ENABLED),- rawRingConfig = RawRingConfig(enabled = RawRingGate.ENABLED),- analysisConsumer = analysisConsumer,- listener = object : Camera2Session.Listener {- override fun onError(message: String) {- Log.status("Camera2Preview", message)- // Configure/bind/open failures drive the one-shot- // CameraX fallback latch in the ViewModel; the- // gate keeps a failing session from signalling- // it (and re-entering composition) repeatedly.- errorGate.report(message)- }- },+ 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 driver = AndroidCamera2Driver(+ manager,+ android.os.Handler(executor.looper),+ )+ built = Camera2Session(+ driver = driver,+ executor = executor,+ snapshot = facade.snapshot,+ ringConfig = ReprocessRingConfig(enabled = ReprocessRingGate.ENABLED),+ rawRingConfig = RawRingConfig(enabled = RawRingGate.ENABLED),+ analysisConsumer = analysisConsumer,+ listener = object : Camera2Session.Listener {+ override fun onError(message: String) {+ Log.status("Camera2Preview", message)+ // Configure/bind/open failures drive the one-shot+ // CameraX fallback latch in the ViewModel; the+ // gate keeps a failing session from signalling+ // it (and re-entering composition) repeatedly.+ errorGate.report(message)+ }+ },+ )+ } } } } catch (e: RuntimeException) {@@ -198,30 +262,11 @@ private class Camera2PreviewSession( // never escape composition as a thrown exception. pendingInitError = "Camera2 preview init failed for facing $lensFacing: ${e.message}" }- session = built- val liveSession = built- val liveCameraId = resolvedCameraId- bridge = PreviewSurfaceBridge { event ->- if (liveSession == null || liveCameraId == null) return@PreviewSurfaceBridge- when (event) {- is PreviewSurfaceEvent.Available -> liveSession.open(- cameraId = liveCameraId,- surface = event.surface,- requestedSize = FrameSize(event.width, event.height),- )- is PreviewSurfaceEvent.SizeChanged -> {- // No resize API on the Phase-2 session: reopen at the new- // size so the stream is re-validated up front.- liveSession.close()- liveSession.open(- cameraId = liveCameraId,- surface = event.surface,- requestedSize = FrameSize(event.width, event.height),- )- }- is PreviewSurfaceEvent.Destroyed -> liveSession.close()- }+ if (closed) {+ built?.close()+ return }+ session = built } /** Delivers a recorded init failure to onError, at most once. */@@ -233,7 +278,9 @@ private class Camera2PreviewSession( } fun close() {+ closed = true session?.close()+ session = null executor.shutdown() } }
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 859f0492f6..3848f70c59 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -98,6 +98,7 @@ internal fun CameraPreviewSurface( null }, onError = { viewModel.onCamera2PreviewFailed(camera2Id) },+ onBindRequested = { viewModel.noteCamera2BindRequested() }, modifier = previewModifier, ) } else {
camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.ktindex 088a28b2cd..5bd25d8408 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt@@ -90,6 +90,40 @@ class StillFormatRoutingTest { assertEquals(null, StillFormatRouting.extractExifTiff(byteArrayOf(9, 9))) } + @Test+ fun stillSaveRoutePerEntryFormatAndSource() {+ // AVIF-selected, plain source: every pre-encoded entry (Camera2+ // direct, ring direct/reprocess, night extension) goes through+ // the EXIF-carrying encoder.+ assertEquals(+ StillFormatRouting.StillSaveRoute.PROCESSED_ENCODER,+ StillFormatRouting.stillSaveRoute(StillFormat.AVIF, ultraHdrSource = false),+ )+ // Ultra HDR sources stay JPEG_R under either selection.+ assertEquals(+ StillFormatRouting.StillSaveRoute.ULTRA_HDR_JPEG_BYTES,+ StillFormatRouting.stillSaveRoute(StillFormat.AVIF, ultraHdrSource = true),+ )+ assertEquals(+ StillFormatRouting.StillSaveRoute.ULTRA_HDR_JPEG_BYTES,+ StillFormatRouting.stillSaveRoute(StillFormat.JPEG, ultraHdrSource = true),+ )+ // JPEG-selected stays on the stamped-JPEG landing, untouched.+ assertEquals(+ StillFormatRouting.StillSaveRoute.JPEG_BYTES,+ StillFormatRouting.stillSaveRoute(StillFormat.JPEG, ultraHdrSource = false),+ )+ }++ @Test+ fun avifPrecludesMotionPhotoDiversionOnlyWhenEffective() {+ assertTrue(StillFormatRouting.avifPrecludesMotionPhoto(StillFormat.AVIF, nativeAvailable = true))+ // No native encoder: AVIF honestly falls back to JPEG, so the+ // Motion Photo diversion is unchanged.+ assertFalse(StillFormatRouting.avifPrecludesMotionPhoto(StillFormat.AVIF, nativeAvailable = false))+ assertFalse(StillFormatRouting.avifPrecludesMotionPhoto(StillFormat.JPEG, nativeAvailable = true))+ }+ @Test fun extensionAndMimeMatchContainer() { assertEquals("jpg", StillFormatRouting.extension(StillFormat.JPEG))
camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.ktnew file mode 100644index 0000000000..9dd228c064--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt@@ -0,0 +1,353 @@+package com.vayunmathur.camera.platform++import android.graphics.Bitmap+import android.graphics.Color+import android.graphics.ImageFormat+import android.hardware.camera2.CameraMetadata+import android.net.Uri+import android.provider.MediaStore+import android.util.Range+import android.util.Size+import android.view.Surface+import androidx.camera.core.ImageCapture+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.camera.data.saveProcessedStill+import com.vayunmathur.camera.platform.camera2.Camera2Driver+import com.vayunmathur.camera.platform.camera2.Camera2Executor+import com.vayunmathur.camera.platform.camera2.Camera2Session+import com.vayunmathur.camera.platform.camera2.CaptureSessionCallback+import com.vayunmathur.camera.platform.camera2.CaptureSessionHandle+import com.vayunmathur.camera.platform.camera2.CapturedStill+import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade+import com.vayunmathur.camera.platform.camera2.DeviceCallback+import com.vayunmathur.camera.platform.camera2.DeviceHandle+import com.vayunmathur.camera.platform.camera2.FrameSize+import com.vayunmathur.camera.platform.camera2.JpegImageListener+import com.vayunmathur.camera.platform.camera2.LensCharacteristicsSnapshot+import com.vayunmathur.camera.platform.camera2.PreviewResultCallback+import com.vayunmathur.camera.platform.camera2.RawStillMetadata+import com.vayunmathur.camera.platform.camera2.ReprocessRingConfig+import com.vayunmathur.camera.platform.camera2.ResolvedRequestParams+import com.vayunmathur.camera.platform.camera2.ResolvedStillParams+import com.vayunmathur.camera.platform.camera2.RingFrameListener+import com.vayunmathur.camera.platform.camera2.RingFrameMeta+import com.vayunmathur.camera.platform.camera2.RingHeldFrame+import com.vayunmathur.camera.platform.camera2.RingOutput+import com.vayunmathur.camera.platform.camera2.SessionState+import com.vayunmathur.camera.platform.camera2.StillCaptureMetadata+import com.vayunmathur.camera.platform.camera2.StillOutput+import com.vayunmathur.camera.platform.camera2.StillOutputTag+import com.vayunmathur.camera.platform.camera2.StillResultCallback+import java.io.ByteArrayOutputStream+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.mockito.Mockito+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/**+ * Per-entry AVIF routing pins for the Camera2 still entries: the format is+ * read at capture/save time, so each test sets it after the ViewModel (and+ * any session) already exists — a bind-time snapshot would fail these.+ */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Camera2AvifRoutingTest {++ private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ private fun vm() = CameraViewModel(context.applicationContext as android.app.Application)++ private fun jpegBytes(): ByteArray {+ val bitmap = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)+ bitmap.eraseColor(Color.BLUE)+ val out = ByteArrayOutputStream()+ bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out)+ bitmap.recycle()+ return out.toByteArray()+ }++ private fun still(+ bytes: ByteArray,+ tag: StillOutputTag = StillOutputTag.JPEG,+ ) = CapturedStill(+ jpegBytes = bytes,+ jpegWidth = 16,+ jpegHeight = 16,+ metadata = StillCaptureMetadata(rotationDegrees = 0, mirrored = false),+ tag = tag,+ )++ private fun savedMime(uri: Uri): String? {+ context.contentResolver.query(+ uri, arrayOf(MediaStore.MediaColumns.MIME_TYPE), null, null, null,+ )?.use { cursor -> if (cursor.moveToFirst()) return cursor.getString(0) }+ return context.contentResolver.getType(uri)+ }++ // -- save routing (direct / ring / night-extension landing) ---------------++ @Test fun camera2StillWithAvifSavesAvif() {+ if (!StitchNative.isAvailable) return+ val viewModel = vm()+ viewModel.photoFormatMutable.value = PhotoFormat.AVIF+ val uri = viewModel.saveCamera2Still(still(jpegBytes()))+ assertNotNull(uri)+ assertEquals("image/avif", savedMime(uri))+ }++ @Test fun camera2StillWithJpegSelectedStaysJpeg() {+ val viewModel = vm()+ viewModel.photoFormatMutable.value = PhotoFormat.JPEG+ val uri = viewModel.saveCamera2Still(still(jpegBytes()))+ assertNotNull(uri)+ assertEquals("image/jpeg", savedMime(uri))+ }++ @Test fun ultraHdrTaggedStillStaysJpegRUnderAvif() {+ val viewModel = vm()+ viewModel.photoFormatMutable.value = PhotoFormat.AVIF+ // Plain header bytes: only the JPEG_R output tag marks this Ultra+ // HDR, so a header-sniff-only check would wrongly encode it.+ val uri = viewModel.saveCamera2Still(+ still(jpegBytes(), StillOutputTag.ULTRA_HDR_JPEG_R),+ )+ assertNotNull(uri)+ assertEquals("image/jpeg", savedMime(uri))+ }++ @Test fun processedStillLandingWithAvifSavesAvif() {+ // The landing RAW night and the custom night merge save through.+ if (!StitchNative.isAvailable) return+ val viewModel = vm()+ viewModel.photoFormatMutable.value = PhotoFormat.AVIF+ val bitmap = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)+ bitmap.eraseColor(Color.RED)+ val saved = viewModel.saveProcessedStill(bitmap, 0, jpegBytes())+ bitmap.recycle()+ assertNotNull(saved)+ assertEquals(com.vayunmathur.camera.domain.StillFormat.AVIF, saved.format)+ assertEquals("image/avif", savedMime(saved.uri))+ }++ // -- entry routing over session fakes -------------------------------------++ private class FakeStillOutput : StillOutput {+ override val surface: Surface = Mockito.mock(Surface::class.java)+ var jpegListener: JpegImageListener? = null+ override fun setListener(listener: JpegImageListener?) { jpegListener = listener }+ override fun close() {}+ }++ private class FakeRingFrame(+ ts: Long,+ private val jpeg: ByteArray?,+ ) : RingHeldFrame {+ override val meta = RingFrameMeta(+ sensorTimestampNs = ts, exposureTimeNs = 10L, width = 16, height = 16,+ )+ override fun encodeJpeg(quality: Int): ByteArray? = jpeg+ override fun close() {}+ }++ private class FakeRingOutput : RingOutput {+ override val surface: Surface = Mockito.mock(Surface::class.java)+ var ringListener: RingFrameListener? = null+ override fun setListener(listener: RingFrameListener?) { ringListener = listener }+ override fun close() {}+ fun emit(frame: RingHeldFrame) = ringListener?.onRingFrame(frame)+ }++ private class FakeHandle : CaptureSessionHandle {+ val stillRequests = mutableListOf<ResolvedStillParams>()+ var stillCallback: StillResultCallback? = null+ var closed = false+ override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}+ override fun setRepeatingStreaming(+ params: ResolvedRequestParams, targets: List<Surface>, callback: PreviewResultCallback?,+ ) {}+ override fun captureStill(+ params: ResolvedStillParams, stillTarget: Surface, callback: StillResultCallback,+ ) {+ stillRequests += params+ stillCallback = callback+ }+ override fun close() { closed = true }+ }++ private class FakeDevice(private val handle: FakeHandle) : DeviceHandle {+ override val cameraId: String = "0"+ override fun createCaptureSession(+ surfaces: List<Surface>, callback: CaptureSessionCallback,+ ) = callback.onConfigured(handle)+ override fun close() {}+ }++ private class FakeDriver(+ private val device: FakeDevice,+ private val still: FakeStillOutput?,+ private val ring: FakeRingOutput? = null,+ ) : Camera2Driver {+ override fun openCamera(cameraId: String, callback: DeviceCallback) =+ callback.onOpened(device)+ override fun createStillOutput(size: FrameSize): StillOutput? = still+ override fun createRingOutput(size: FrameSize): RingOutput? = ring+ }++ private fun snapshot(ring: Boolean): LensCharacteristicsSnapshot =+ CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ lensFacingRaw = CameraMetadata.LENS_FACING_BACK,+ zoomRatioRange = Range(1f, 10f),+ hasFlashUnit = true,+ exposureCompensationEvRange = Range(-4f, 4f),+ sizesByFormat = buildMap {+ put(ImageFormat.PRIVATE, listOf(Size(1280, 720)))+ put(ImageFormat.JPEG, listOf(Size(4000, 3000)))+ if (ring) put(ImageFormat.YUV_420_888, listOf(Size(1920, 1080)))+ },+ activeArrayWidth = 4000,+ activeArrayHeight = 3000,+ sensorOrientationDegrees = 90,+ exposureCompensationStepEv = 1f / 6f,+ maxAfRegions = 1,+ maxAeRegions = 1,+ ).snapshot++ private fun Camera2Executor.drain() {+ val latch = CountDownLatch(1)+ execute { latch.countDown() }+ assertTrue(latch.await(5, TimeUnit.SECONDS), "executor did not drain")+ }++ private fun streamingSession(+ executor: Camera2Executor,+ handle: FakeHandle,+ ring: FakeRingOutput? = null,+ ): Camera2Session {+ val session = Camera2Session(+ FakeDriver(FakeDevice(handle), FakeStillOutput(), ring),+ executor,+ snapshot(ring != null),+ ringConfig = if (ring != null) ReprocessRingConfig(enabled = true) else ReprocessRingConfig.DISABLED,+ )+ session.open("0", Mockito.mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ return session+ }++ @Test fun avifPlainShotTakesCamera2InsteadOfMotionDiversion() {+ val executor = Camera2Executor("AvifRouting-direct")+ try {+ val handle = FakeHandle()+ val session = streamingSession(executor, handle)+ val viewModel = vm()+ viewModel.registerCamera2Session(session)+ // Default plain shot (PHOTO, 4:3, no bake): Motion-eligible.+ // JPEG keeps the diversion; AVIF (set after bind) must not.+ viewModel.photoFormatMutable.value = PhotoFormat.JPEG+ assertFalse(viewModel.tryCaptureCamera2Still())+ executor.drain()+ assertEquals(0, handle.stillRequests.size)++ viewModel.photoFormatMutable.value = PhotoFormat.AVIF+ assertTrue(viewModel.tryCaptureCamera2Still())+ executor.drain()+ assertEquals(1, handle.stillRequests.size)+ session.close()+ executor.drain()+ } finally {+ executor.shutdown()+ }+ }++ @Test fun ringDirectEncodeStillWithAvifSavesAvif() {+ if (!StitchNative.isAvailable) return+ val executor = Camera2Executor("AvifRouting-ring")+ try {+ val handle = FakeHandle()+ val ring = FakeRingOutput()+ // No YUV reprocessing on this snapshot: captureFromRing serves+ // the shutter by direct-encoding the held frame.+ val session = streamingSession(executor, handle, ring)+ ring.emit(FakeRingFrame(200, jpegBytes()))+ executor.drain()++ val captured = mutableListOf<CapturedStill>()+ session.captureFromRing(+ callback = object : Camera2Session.StillCallback {+ override fun onStillCaptured(still: CapturedStill) { captured += still }+ override fun onStillFailed(message: String) {}+ },+ shutterTimestampNs = 215,+ )+ executor.drain()+ assertEquals(1, captured.size)+ assertEquals(0, handle.stillRequests.size)++ val viewModel = vm()+ viewModel.photoFormatMutable.value = PhotoFormat.AVIF+ val uri = viewModel.saveCamera2Still(captured.single())+ assertNotNull(uri)+ assertEquals("image/avif", savedMime(uri))+ session.close()+ executor.drain()+ } finally {+ executor.shutdown()+ }+ }++ // -- video / slo-mo snapshot + night-extension entry decisions -------------++ @Test fun snapshotAndNightExtensionReadFormatAtCaptureTime() {+ val viewModel = vm()+ // JPEG (default, set at bind): both entries stay on the file path.+ assertFalse(viewModel.videoSnapshotInMemory())+ assertFalse(viewModel.nightExtensionInMemory())+ // Changed after bind: both entries must follow without a rebind.+ viewModel.photoFormatMutable.value = PhotoFormat.AVIF+ if (StitchNative.isAvailable) {+ assertTrue(viewModel.videoSnapshotInMemory())+ assertTrue(viewModel.nightExtensionInMemory())+ }+ viewModel.photoFormatMutable.value = PhotoFormat.JPEG+ assertFalse(viewModel.videoSnapshotInMemory())+ assertFalse(viewModel.nightExtensionInMemory())+ }++ @Test fun videoSnapshotUsesInMemoryCaptureWhenAvif() {+ if (!StitchNative.isAvailable) return+ val viewModel = vm()+ val capture = Mockito.mock(ImageCapture::class.java)+ Mockito.`when`(capture.captureMode).thenReturn(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)+ viewModel.imageCapture = capture+ viewModel.photoFormatMutable.value = PhotoFormat.AVIF+ viewModel.captureVideoSnapshot()+ Mockito.verify(capture).takePicture(+ Mockito.any(java.util.concurrent.Executor::class.java),+ Mockito.any(ImageCapture.OnImageCapturedCallback::class.java),+ )+ }++ @Test fun videoSnapshotUsesFilePathWhenJpeg() {+ val viewModel = vm()+ val capture = Mockito.mock(ImageCapture::class.java)+ Mockito.`when`(capture.captureMode).thenReturn(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)+ viewModel.imageCapture = capture+ viewModel.photoFormatMutable.value = PhotoFormat.JPEG+ viewModel.captureVideoSnapshot()+ Mockito.verify(capture).takePicture(+ Mockito.any(ImageCapture.OutputFileOptions::class.java),+ Mockito.any(java.util.concurrent.Executor::class.java),+ Mockito.any(ImageCapture.OnImageSavedCallback::class.java),+ )+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/CameraCovW3MockSessionsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovW3MockSessionsTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovW3MockSessionsTest.ktindex b38d132fd0..89581c9f54 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovW3MockSessionsTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovW3MockSessionsTest.kt@@ -196,7 +196,11 @@ class CameraCovW3MockSessionsTest { assertTrue(enumerateLenses(provider).isEmpty()) viewModel.ensureLensesEnumerated(provider) assertTrue(viewModel.availableLensesMutable.value.isEmpty())- assertNull(viewModel.selectedLensMutable.value)+ // Startup contract: the seeded persisted-lens placeholder survives an+ // empty enumeration — it carries only the facing, which Camera2+ // resolves via CameraManager and CameraX ignores (family is empty,+ // so selectors stay facing-only, as before).+ assertEquals(LensFacing.BACK, viewModel.selectedLensMutable.value?.facing) assertTrue(viewModel.currentLensFamily().isEmpty()) // Selectors build for null and pinned lenses without a real camera. assertNotNull(viewModel.lensSelector(CameraSelector.LENS_FACING_BACK, null))
camera/src/test/java/com/vayunmathur/camera/platform/camera2/StartupOrderTrackerTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StartupOrderTrackerTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StartupOrderTrackerTest.ktnew file mode 100644index 0000000000..532f8b5c7c--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StartupOrderTrackerTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.camera.platform.camera2++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Ordering contract for the launch-to-first-frame path: the Camera2+ * preview bind must be requested before the background capability probes+ * (CameraX lens enumeration, extension / slo-mo probes) complete, so the+ * first frame never waits on CameraX initialisation.+ */+class StartupOrderTrackerTest {++ @Test+ fun `bind requested before probe completion reports true`() {+ val tracker = StartupOrderTracker()+ tracker.recordBindRequested()+ tracker.recordProbeCompleted()+ assertEquals(true, tracker.bindRequestedBeforeProbeCompleted())+ assertEquals(+ listOf(+ StartupOrderTracker.Event.BIND_REQUESTED,+ StartupOrderTracker.Event.PROBE_COMPLETED,+ ),+ tracker.events(),+ )+ }++ @Test+ fun `probe completing first reports false - the regression this guards`() {+ val tracker = StartupOrderTracker()+ tracker.recordProbeCompleted()+ tracker.recordBindRequested()+ assertEquals(false, tracker.bindRequestedBeforeProbeCompleted())+ }++ @Test+ fun `missing either event reports null`() {+ assertNull(StartupOrderTracker().bindRequestedBeforeProbeCompleted())+ val bindOnly = StartupOrderTracker().apply { recordBindRequested() }+ assertNull(bindOnly.bindRequestedBeforeProbeCompleted())+ val probeOnly = StartupOrderTracker().apply { recordProbeCompleted() }+ assertNull(probeOnly.bindRequestedBeforeProbeCompleted())+ }++ @Test+ fun `first record wins - a rebind cannot rewrite startup ordering`() {+ val tracker = StartupOrderTracker()+ assertTrue(tracker.recordBindRequested())+ tracker.recordProbeCompleted()+ assertFalse(tracker.recordBindRequested())+ assertFalse(tracker.recordProbeCompleted())+ assertEquals(true, tracker.bindRequestedBeforeProbeCompleted())+ }+}