camera: fix launch crash - Camera2 ids are not CameraX ids
- Commit
304fed6162aca59f73dc7d4bd3e18178278dad39- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-22 22:28 UTC (13 days ago)
- Parents
c95b530
The first device launch with Camera2 live crashed: the
preview was handed camera id '1' (a CameraX lens id) that
this phone's CameraManager does not know, the
characteristics fetch threw out of composition, and the
error path re-reported in a loop (~60x) until the process
died.
IDs now resolve through a pure seam: the selected lens
contributes only its facing; the opened id is the first
cameraIdList entry matching LENS_FACING, with failures
yielding an error path, never a guessed id or exception,
and every characteristics read guarded to null on failure.
Session holders construct never-throw, deliver init errors
from LaunchedEffect, and share a one-shot error reporter,
so the Camera2->CameraX fallback latch is signalled
exactly once per bind and covers init failures too.
Verified: new id-mapping tests (incl. tryFromCameraManager
('1') == null on a list without '1', 60x report latches
once), gate/session/screen-state tests, compile,
lintVitalRelease and assembleRelease all green.Diff
camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.ktindex 0f1f301b5b..d0dd896361 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt@@ -144,13 +144,18 @@ internal fun CameraViewModel.tryCaptureCamera2NightExtension(): Boolean { internal fun CameraViewModel.evaluateCamera2NightDecision() { if (!camera2NightEnabledMutable.value) return try {- val lensId = selectedLensMutable.value?.logicalCameraId+ val facing = selectedLensMutable.value?.facing ?: availableLensesMutable.value .firstOrNull { it.facing == LensFacing.BACK }- ?.logicalCameraId+ ?.facing ?: return val manager = app.getSystemService(CameraManager::class.java) ?: return- camera2NightDecision(CharacteristicsFacade.fromCameraManager(manager, lensId))+ // Only a CameraManager.cameraIdList id (mapped by facing) may be+ // handed to getCameraCharacteristics; the lens's CameraX-derived+ // logicalCameraId need not exist there (unknown-device crash).+ val lensId = CharacteristicsFacade.resolveCamera2Id(manager, facing) ?: return+ val facade = CharacteristicsFacade.tryFromCameraManager(manager, lensId) ?: return+ camera2NightDecision(facade) } catch (e: IllegalStateException) { Log.status("Camera2Night", "Camera2 night decision failed; staying on existing routing", e) } catch (e: IllegalArgumentException) {
camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.ktindex ba14396fc5..b244698c81 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt@@ -95,15 +95,19 @@ internal fun encoderSupportsSloMoCaptureRate(selection: HighSpeedSelection): Boo internal fun CameraViewModel.evaluateCamera2SloMoDecision() { if (!camera2SloMoEnabledMutable.value) return try {- val lensId = selectedLensMutable.value+ val facing = selectedLensMutable.value ?.takeIf { it.facing == LensFacing.BACK }- ?.logicalCameraId+ ?.facing ?: availableLensesMutable.value .firstOrNull { it.facing == LensFacing.BACK }- ?.logicalCameraId+ ?.facing ?: return val manager = app.getSystemService(CameraManager::class.java) ?: return- val facade = CharacteristicsFacade.fromCameraManager(manager, lensId)+ // Only a CameraManager.cameraIdList id (mapped by facing) may be+ // handed to getCameraCharacteristics; the lens's CameraX-derived+ // logicalCameraId need not exist there (unknown-device crash).+ val lensId = CharacteristicsFacade.resolveCamera2Id(manager, facing) ?: return+ val facade = CharacteristicsFacade.tryFromCameraManager(manager, lensId) ?: return val selection = HighSpeedPlanner.select(facade.snapshot) camera2SloMoDecision( facade,
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2IdMapping.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2IdMapping.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2IdMapping.ktnew file mode 100644index 0000000000..ffd57135a4--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2IdMapping.kt@@ -0,0 +1,94 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.domain.LensFacing+import java.util.concurrent.atomic.AtomicBoolean++/**+ * One entry of `CameraManager.cameraIdList` with the `LENS_FACING` read from+ * that id's own characteristics. [facing] is null when the characteristics+ * could not be read; such an entry can never be selected.+ */+data class CameraIdFacing(+ val cameraId: String,+ val facing: LensFacing?,+)++/** Outcome of resolving a selected lens to a Camera2-openable camera id. */+sealed interface Camera2IdResolution {+ /** A camera id taken verbatim from `CameraManager.cameraIdList`. */+ data class Resolved(val cameraId: String) : Camera2IdResolution++ /** No Camera2 id can serve the lens; [reason] is the error-path message. */+ data class Unavailable(val reason: String) : Camera2IdResolution+}++/**+ * Pure seam mapping a selected lens to the camera id the Camera2 stack may+ * open. The only ids ever handed to `CameraManager.getCameraCharacteristics`+ * / `openCamera` on the Camera2 preview path are ids from+ * `CameraManager.cameraIdList` (enumerated by+ * [CharacteristicsFacade.cameraIdFacings]); the selected lens contributes+ * only its [LensFacing], matched against each listed id's `LENS_FACING`.+ *+ * A CameraX-derived id (`PhysicalLens.logicalCameraId`, from+ * `Camera2CameraInfo.getCameraId()` over `availableCameraInfos`) is never an+ * input here: CameraX enumerates physical sub-cameras of a logical+ * multi-camera (and other infos) whose ids need not exist in+ * `cameraIdList` at all — on the crashing Pixel 9 Pro XL the selected lens+ * carried CameraX id "1", which `getCameraCharacteristics("1")` rejected+ * with `IllegalArgumentException: unknown device 1`.+ */+object Camera2IdResolver {++ /**+ * Resolves [facing] against [available] (the `cameraIdList` entries, in+ * list order). The first listed id whose `LENS_FACING` matches wins —+ * `cameraIdList` lists the logical camera of a facing before its+ * physical sub-cameras, so the first match is the openable logical id.+ * Unknown facing, a blank id, or no match is [Camera2IdResolution.Unavailable],+ * never an exception and never a guessed id.+ */+ fun resolve(facing: LensFacing?, available: List<CameraIdFacing>): Camera2IdResolution {+ if (facing == null) {+ return Camera2IdResolution.Unavailable(+ "no lens facing for Camera2 preview (available=${available.map { it.cameraId }})",+ )+ }+ val match = available.firstOrNull { entry ->+ entry.cameraId.isNotBlank() && entry.facing == facing+ }+ return if (match != null) {+ Camera2IdResolution.Resolved(match.cameraId)+ } else {+ Camera2IdResolution.Unavailable(+ "no Camera2 camera id for facing $facing in CameraManager.cameraIdList " ++ "(available=${available.map { "${it.cameraId}:${it.facing}" }})",+ )+ }+ }+}++/**+ * One-shot error sink for one Camera2 preview bind: the first [report]+ * forwards to [sink] and returns true; every later report is dropped and+ * returns false. This breaks the onError -> recomposition -> onError cycle:+ * a session/init failure can be reported from any thread any number of+ * times, but the fallback latch in the ViewModel is signalled exactly once+ * per constructed session holder, and a latched failure never re-enters+ * the error path while the same holder is alive.+ */+class OnceErrorReporter(+ private val sink: (String) -> Unit,+) {+ private val reported = AtomicBoolean(false)++ /** True once an error has been forwarded to [sink]. */+ val hasReported: Boolean get() = reported.get()++ /** Forwards [message] on the first call only; returns whether it did. */+ fun report(message: String): Boolean {+ if (!reported.compareAndSet(false, true)) return false+ sink(message)+ return true+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.ktindex 33140cf1c3..d9bf059a2b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt@@ -541,5 +541,65 @@ class CharacteristicsFacade private constructor( } return fromCharacteristics(cameraId, chars, extensions, support) }++ /**+ * Every id in `manager.cameraIdList` paired with its `LENS_FACING`,+ * in list order — the enumeration [Camera2IdResolver] selects from.+ * Each id's characteristics read is guarded: an id the HAL lists but+ * cannot describe yields a null-facing entry (never selectable),+ * and a failing `cameraIdList` yields an empty list. Never throws.+ */+ fun cameraIdFacings(manager: CameraManager): List<CameraIdFacing> {+ val ids = try {+ manager.cameraIdList.toList()+ } catch (e: RuntimeException) {+ // IllegalArgumentException / ServiceSpecificException from a+ // misbehaving HAL: no list, no mapping, error path upstream.+ return emptyList()+ }+ return ids.map { id ->+ val facingRaw = try {+ manager.getCameraCharacteristics(id)+ .get(CameraCharacteristics.LENS_FACING)+ } catch (e: RuntimeException) {+ null+ }+ CameraIdFacing(+ cameraId = id,+ facing = when (facingRaw) {+ CameraMetadata.LENS_FACING_BACK -> LensFacing.BACK+ CameraMetadata.LENS_FACING_FRONT -> LensFacing.FRONT+ else -> null+ },+ )+ }+ }++ /**+ * Resolves [facing] to a `cameraIdList` id via [cameraIdFacings] ++ * [Camera2IdResolver]; null when no listed id serves that facing.+ */+ fun resolveCamera2Id(manager: CameraManager, facing: LensFacing?): String? =+ when (val resolution = Camera2IdResolver.resolve(facing, cameraIdFacings(manager))) {+ is Camera2IdResolution.Resolved -> resolution.cameraId+ is Camera2IdResolution.Unavailable -> null+ }++ /**+ * [fromCameraManager] that never throws: an unknown id+ * (`IllegalArgumentException: getCameraCharacteristics: ... unknown+ * device`), a binder/HAL failure (`ServiceSpecificException` and+ * other `RuntimeException`s), or a `CameraAccessException` yields+ * null so the caller can route to its error path exactly once+ * instead of escaping composition.+ */+ fun tryFromCameraManager(manager: CameraManager, cameraId: String): CharacteristicsFacade? =+ try {+ fromCameraManager(manager, cameraId)+ } catch (e: RuntimeException) {+ null+ } catch (e: android.hardware.camera2.CameraAccessException) {+ null+ } } }
camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.ktindex c79be01836..5650821e6f 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.kt@@ -3,17 +3,25 @@ package com.vayunmathur.camera.ui import android.content.Context import android.hardware.camera2.CameraManager import android.view.TextureView+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.viewinterop.AndroidView+import com.vayunmathur.camera.domain.LensFacing import com.vayunmathur.camera.platform.camera2.AndroidCamera2Driver import com.vayunmathur.camera.platform.camera2.Camera2Executor import com.vayunmathur.camera.platform.camera2.Camera2ExtensionSession+import com.vayunmathur.camera.platform.camera2.Camera2IdResolution+import com.vayunmathur.camera.platform.camera2.Camera2IdResolver import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade import com.vayunmathur.camera.platform.camera2.FrameSize+import com.vayunmathur.camera.platform.camera2.OnceErrorReporter import com.vayunmathur.camera.platform.camera2.PreviewSurfaceBridge import com.vayunmathur.camera.platform.camera2.PreviewSurfaceEvent import com.vayunmathur.library.log.Log@@ -39,16 +47,26 @@ import com.vayunmathur.library.log.Log * * Ownership: this composition owns the executor and the session; both are * torn down when it leaves composition.+ *+ * [cameraId] is the bind identity only (fallback-latch key / remember key);+ * it is NEVER handed to CameraManager. The session opens the id+ * [Camera2IdResolver] maps from [lensFacing] over+ * `CameraManager.cameraIdList`, and a mapping/characteristics failure is a+ * one-shot [onError] delivered after composition, never an exception+ * escaping composition (see `Camera2Preview`). */ @Composable internal fun Camera2NightPreview( cameraId: String,+ lensFacing: LensFacing?, onSessionChanged: (Camera2ExtensionSession?) -> Unit = {}, onError: (String) -> Unit = {}, modifier: Modifier = Modifier, ) { val context = LocalContext.current- val sessionHolder = remember(cameraId) { Camera2NightPreviewSession(context, cameraId, onError) }+ val sessionHolder = remember(cameraId, lensFacing) {+ Camera2NightPreviewSession(context, lensFacing, onError)+ } DisposableEffect(sessionHolder) { onSessionChanged(sessionHolder.session)@@ -57,11 +75,18 @@ internal fun Camera2NightPreview( sessionHolder.close() } }+ LaunchedEffect(sessionHolder) { sessionHolder.deliverPendingError() }++ val session = sessionHolder.session+ if (session == null) {+ Box(modifier = modifier.background(Color.Black))+ return+ } AndroidView( factory = { ctx -> TextureView(ctx).also { view ->- sessionHolder.session.setDisplayRotationDegrees(+ session.setDisplayRotationDegrees( (view.display?.rotation ?: 0) * 90, ) sessionHolder.bridge.attachTo(view)@@ -71,56 +96,101 @@ internal fun Camera2NightPreview( ) } -/** Executor + bridge + extension session for one camera id; built once, closed once. */+/**+ * Executor + bridge + extension session for one resolved Camera2 id; built+ * once, closed once. Construction never throws (see+ * `Camera2PreviewSession`): failures leave [session] null and are reported+ * once via [deliverPendingError] / the shared one-shot error gate.+ */ private class Camera2NightPreviewSession( context: Context,- private val cameraId: String,- private val onError: (String) -> Unit = {},+ lensFacing: LensFacing?,+ onError: (String) -> Unit = {}, ) {- val executor = Camera2Executor("Camera2NightPreview-$cameraId")- val session: Camera2ExtensionSession+ val executor = Camera2Executor("Camera2NightPreview-${lensFacing?.name ?: "unknown"}")+ val session: Camera2ExtensionSession? val bridge: PreviewSurfaceBridge + private val errorGate = OnceErrorReporter(onError)++ @Volatile+ private var pendingInitError: String? = null+ init {- val manager = context.getSystemService(CameraManager::class.java)- val facade = CharacteristicsFacade.fromCameraManager(manager, cameraId)- val driver = AndroidCamera2Driver(- manager,- android.os.Handler(executor.looper),- )- session = Camera2ExtensionSession(- driver = driver,- executor = executor,- snapshot = facade.snapshot,- listener = object : Camera2ExtensionSession.Listener {- override fun onError(message: String) {- Log.status("Camera2NightPreview", message)- onError(message)+ var built: Camera2ExtensionSession? = 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 = Camera2ExtensionSession(+ driver = driver,+ executor = executor,+ snapshot = facade.snapshot,+ listener = object : Camera2ExtensionSession.Listener {+ override fun onError(message: String) {+ Log.status("Camera2NightPreview", message)+ errorGate.report(message)+ }+ },+ ) }- },- )+ }+ } catch (e: RuntimeException) {+ pendingInitError =+ "Camera2 night 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 -> session.open(- cameraId = cameraId,+ is PreviewSurfaceEvent.Available -> liveSession.open(+ cameraId = liveCameraId, surface = event.surface, requestedSize = FrameSize(event.width, event.height), ) is PreviewSurfaceEvent.SizeChanged -> {- session.close()- session.open(- cameraId = cameraId,+ liveSession.close()+ liveSession.open(+ cameraId = liveCameraId, surface = event.surface, requestedSize = FrameSize(event.width, event.height), ) }- is PreviewSurfaceEvent.Destroyed -> session.close()+ is PreviewSurfaceEvent.Destroyed -> liveSession.close() } } } + /** Delivers a recorded init failure to onError, at most once. */+ fun deliverPendingError() {+ val message = pendingInitError ?: return+ pendingInitError = null+ Log.status("Camera2NightPreview", message)+ errorGate.report(message)+ }+ fun close() {- session.close()+ session?.close() executor.shutdown() } }
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 f5e722fa91..3f50ad3c07 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt@@ -3,20 +3,27 @@ package com.vayunmathur.camera.ui import android.content.Context import android.hardware.camera2.CameraManager import android.view.TextureView+import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectTapGestures+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.remember import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.viewinterop.AndroidView+import com.vayunmathur.camera.domain.LensFacing import com.vayunmathur.camera.platform.camera2.AndroidCamera2Driver import com.vayunmathur.camera.platform.camera2.Camera2Executor+import com.vayunmathur.camera.platform.camera2.Camera2IdResolution+import com.vayunmathur.camera.platform.camera2.Camera2IdResolver import com.vayunmathur.camera.platform.camera2.Camera2Session import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade import com.vayunmathur.camera.platform.camera2.FrameSize+import com.vayunmathur.camera.platform.camera2.OnceErrorReporter import com.vayunmathur.camera.platform.camera2.PreviewSurfaceBridge import com.vayunmathur.camera.platform.camera2.RawRingConfig import com.vayunmathur.camera.platform.camera2.RawRingGate@@ -37,10 +44,19 @@ 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+ * `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. */ @Composable internal fun Camera2Preview( cameraId: String,+ lensFacing: LensFacing?, zoomRatio: Float, torchOn: Boolean, exposureCompEv: Float,@@ -53,8 +69,8 @@ internal fun Camera2Preview( modifier: Modifier = Modifier, ) { val context = LocalContext.current- val sessionHolder = remember(cameraId) {- Camera2PreviewSession(context, cameraId, onError, analysisConsumer)+ val sessionHolder = remember(cameraId, lensFacing) {+ Camera2PreviewSession(context, lensFacing, onError, analysisConsumer) } DisposableEffect(sessionHolder) {@@ -64,19 +80,32 @@ internal fun Camera2Preview( sessionHolder.close() } }- LaunchedEffect(sessionHolder, zoomRatio) { sessionHolder.session.setZoomRatio(zoomRatio) }- LaunchedEffect(sessionHolder, torchOn) { sessionHolder.session.setTorch(torchOn) }+ // 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)+ sessionHolder.session?.setExposureCompEv(exposureCompEv) } LaunchedEffect(sessionHolder, flashSetting) {- sessionHolder.session.setFlashSetting(flashSetting)+ sessionHolder.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.+ Box(modifier = modifier.background(Color.Black))+ return } AndroidView( factory = { ctx -> TextureView(ctx).also { view ->- sessionHolder.session.setDisplayRotationDegrees(+ session.setDisplayRotationDegrees( (view.display?.rotation ?: 0) * 90, ) sessionHolder.bridge.attachTo(view)@@ -85,7 +114,7 @@ internal fun Camera2Preview( modifier = modifier.pointerInput(sessionHolder) { detectTapGestures { offset -> if (size.width > 0 && size.height > 0) {- sessionHolder.session.tapToFocus(+ session.tapToFocus( tapX = offset.x / size.width, tapY = offset.y / size.height, )@@ -95,64 +124,116 @@ internal fun Camera2Preview( ) } -/** Executor + bridge + session for one camera id; built once, closed once. */+/**+ * 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+ * [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,- private val cameraId: String,- private val onError: (String) -> Unit = {},+ lensFacing: LensFacing?,+ onError: (String) -> Unit = {}, analysisConsumer: com.vayunmathur.camera.platform.camera2.AnalysisConsumer? = null, ) {- val executor = Camera2Executor("Camera2Preview-$cameraId")- val session: Camera2Session+ val executor = Camera2Executor("Camera2Preview-${lensFacing?.name ?: "unknown"}")+ val session: Camera2Session? val bridge: PreviewSurfaceBridge + private val errorGate = OnceErrorReporter(onError)++ @Volatile+ private var pendingInitError: String? = null+ init {- val manager = context.getSystemService(CameraManager::class.java)- val facade = CharacteristicsFacade.fromCameraManager(manager, cameraId)- val driver = AndroidCamera2Driver(- manager,- android.os.Handler(executor.looper),- )- session = 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.- onError(message)+ 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)+ }+ },+ ) }- },- )+ }+ } catch (e: RuntimeException) {+ // Any characteristics-fetch failure — an unknown-device error+ // or a HAL binder failure — is an error path here; it must+ // 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 -> session.open(- cameraId = cameraId,+ 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.- session.close()- session.open(- cameraId = cameraId,+ liveSession.close()+ liveSession.open(+ cameraId = liveCameraId, surface = event.surface, requestedSize = FrameSize(event.width, event.height), ) }- is PreviewSurfaceEvent.Destroyed -> session.close()+ is PreviewSurfaceEvent.Destroyed -> liveSession.close() } } } + /** Delivers a recorded init failure to onError, at most once. */+ fun deliverPendingError() {+ val message = pendingInitError ?: return+ pendingInitError = null+ Log.status("Camera2Preview", message)+ errorGate.report(message)+ }+ fun close() {- session.close()+ session?.close() 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 175ec99365..859f0492f6 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -55,6 +55,7 @@ internal fun CameraPreviewSurface( if (nightCamera2Id.isNotEmpty()) { Camera2NightPreview( cameraId = nightCamera2Id,+ lensFacing = state.selectedLens?.facing, onSessionChanged = { session -> viewModel.registerCamera2ExtensionSession(session) },@@ -73,6 +74,7 @@ internal fun CameraPreviewSurface( if (camera2Id.isNotEmpty()) { Camera2Preview( cameraId = camera2Id,+ lensFacing = state.selectedLens?.facing, zoomRatio = state.zoomRatio, torchOn = state.torchEnabled, exposureCompEv = state.exposureComp,
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2IdMappingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2IdMappingTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2IdMappingTest.ktnew file mode 100644index 0000000000..4c40b4e61e--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2IdMappingTest.kt@@ -0,0 +1,177 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraManager+import android.hardware.camera2.CameraMetadata+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.platform.CameraMode+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowCameraCharacteristics++/**+ * The CameraX-id crash seam: a selected lens contributes only its facing;+ * the Camera2 id is resolved from `CameraManager.cameraIdList` entries+ * (via [CharacteristicsFacade.cameraIdFacings]) by `LENS_FACING` match.+ */+class Camera2IdMappingTest {++ // Pixel-9-Pro-XL-shaped list: logical back "0", front logical "1" is+ // NOT what CameraManager lists here — the front logical is "5" and the+ // back physical sub-cameras "2"/"3" follow the logical "0". A CameraX+ // enumeration can hand the preview id "1" for the selected lens; that+ // id must never be opened.+ private val pixelShaped = listOf(+ CameraIdFacing("0", LensFacing.BACK),+ CameraIdFacing("2", LensFacing.BACK),+ CameraIdFacing("3", LensFacing.BACK),+ CameraIdFacing("5", LensFacing.FRONT),+ )++ @Test fun backFacingResolvesToFirstListedBackId() {+ assertEquals(+ Camera2IdResolution.Resolved("0"),+ Camera2IdResolver.resolve(LensFacing.BACK, pixelShaped),+ )+ }++ @Test fun frontFacingResolvesToListedFrontIdNotCameraXId() {+ // The selected front lens's CameraX-derived id was "1"; the only id+ // the Camera2 stack may open is the listed front id "5".+ val resolution = Camera2IdResolver.resolve(LensFacing.FRONT, pixelShaped)+ assertEquals(Camera2IdResolution.Resolved("5"), resolution)+ }++ @Test fun unknownFacingIsErrorPathNotException() {+ val resolution = Camera2IdResolver.resolve(null, pixelShaped)+ assertTrue(resolution is Camera2IdResolution.Unavailable)+ assertTrue((resolution as Camera2IdResolution.Unavailable).reason.contains("no lens facing"))+ }++ @Test fun facingWithNoListedMatchIsUnavailable() {+ val backOnly = listOf(CameraIdFacing("0", LensFacing.BACK))+ val resolution = Camera2IdResolver.resolve(LensFacing.FRONT, backOnly)+ assertTrue(resolution is Camera2IdResolution.Unavailable)+ assertTrue((resolution as Camera2IdResolution.Unavailable).reason.contains("FRONT"))+ }++ @Test fun emptyCameraIdListIsUnavailable() {+ assertTrue(+ Camera2IdResolver.resolve(LensFacing.BACK, emptyList())+ is Camera2IdResolution.Unavailable,+ )+ }++ @Test fun unreadableAndBlankEntriesAreNeverSelected() {+ val entries = listOf(+ CameraIdFacing("", LensFacing.BACK),+ CameraIdFacing("9", null),+ CameraIdFacing("4", LensFacing.BACK),+ )+ assertEquals(+ Camera2IdResolution.Resolved("4"),+ Camera2IdResolver.resolve(LensFacing.BACK, entries),+ )+ }++ @Test fun onceErrorReporterForwardsExactlyOnce() {+ val received = mutableListOf<String>()+ val gate = OnceErrorReporter { received += it }+ assertFalse(gate.hasReported)+ assertTrue(gate.report("init failed"))+ assertTrue(gate.hasReported)+ assertFalse(gate.report("configure failed"))+ assertFalse(gate.report("open failed"))+ assertEquals(listOf("init failed"), received)+ }++ @Test fun initFailureLatchesBindAndBlocksCamera2ForThatBind() {+ // Composition/init failure path: the holder reports its pending+ // init error through the one-shot gate into the fallback latch.+ val latch = Camera2FallbackLatch()+ val bindKey = Camera2FallbackLatch.bindKey("1", CameraMode.PHOTO)+ var sinkCalls = 0+ val gate = OnceErrorReporter {+ sinkCalls+++ latch.recordFailure(bindKey)+ }+ // Repeated reports (listener re-entry / recomposition) signal once.+ repeat(60) { gate.report("getCameraCharacteristics: unknown device 1") }+ assertEquals(1, sinkCalls)+ assertTrue(latch.isLatched(bindKey))+ assertFalse(+ PreviewEnginePolicy.usesCamera2(+ enabled = true,+ mode = CameraMode.PHOTO,+ fallbackLatched = latch.isLatched(bindKey),+ ),+ "latched init failure must keep this bind on CameraX",+ )+ // A different bind (other lens) is a fresh attempt.+ val otherKey = Camera2FallbackLatch.bindKey("5", CameraMode.PHOTO)+ assertFalse(latch.isLatched(otherKey))+ assertTrue(+ PreviewEnginePolicy.usesCamera2(+ enabled = true,+ mode = CameraMode.PHOTO,+ fallbackLatched = latch.isLatched(otherKey),+ ),+ )+ }+}++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CharacteristicsFacadeMappingTest {++ private fun characteristicsWithFacing(facing: Int): CameraCharacteristics {+ val chars = ShadowCameraCharacteristics.newCameraCharacteristics()+ Shadows.shadowOf(chars).set(CameraCharacteristics.LENS_FACING, facing)+ return chars+ }++ private fun managerWith(vararg cameras: Pair<String, Int>): CameraManager {+ val context = RuntimeEnvironment.getApplication()+ val manager = context.getSystemService(CameraManager::class.java)+ val shadow = Shadows.shadowOf(manager)+ for ((id, facing) in cameras) {+ shadow.addCamera(id, characteristicsWithFacing(facing))+ }+ return manager+ }++ @Test fun cameraIdFacingsEnumeratesOnlyListedIdsWithFacing() {+ val manager = managerWith(+ "0" to CameraMetadata.LENS_FACING_BACK,+ "2" to CameraMetadata.LENS_FACING_BACK,+ "5" to CameraMetadata.LENS_FACING_FRONT,+ )+ assertEquals(+ listOf(+ CameraIdFacing("0", LensFacing.BACK),+ CameraIdFacing("2", LensFacing.BACK),+ CameraIdFacing("5", LensFacing.FRONT),+ ),+ CharacteristicsFacade.cameraIdFacings(manager),+ )+ assertEquals("0", CharacteristicsFacade.resolveCamera2Id(manager, LensFacing.BACK))+ assertEquals("5", CharacteristicsFacade.resolveCamera2Id(manager, LensFacing.FRONT))+ assertNull(CharacteristicsFacade.resolveCamera2Id(manager, null))+ }++ @Test fun tryFromCameraManagerReturnsNullForUnknownDeviceId() {+ val manager = managerWith("0" to CameraMetadata.LENS_FACING_BACK)+ // The device crash: "1" is not in cameraIdList on this device shape.+ assertNull(CharacteristicsFacade.tryFromCameraManager(manager, "1"))+ assertNotNull(CharacteristicsFacade.tryFromCameraManager(manager, "0"))+ }+}