Modern Apps git

← Modern-Apps.git

camera: offer every lens the HAL exposes (#878)

Commit
38fb82fdbbe63207c48574e05844c3608981b160
Author
Vayun Mathur <[email protected]>
When
2026-11-30 19:06 UTC (5 days ago)
Parents
55b4bc3
On multi-camera devices not all lenses were available: enumeration
only followed the facing to the first logical camera id, so the
physical ultra-wide/telephoto sub-cameras the HAL hides behind a
logical camera were never listed, covered ultra-wides were dropped
for overlapping the logical zoom range, and even an offered lens
changed nothing optically because selection never applied zoom.

LensSelector.enumerateLenses now walks every top-level id plus each
logical camera's getPhysicalCameraIds() sub-cameras and feeds pure
LensCandidates to the new domain/LensDiscovery. Every candidate
validated as session-configurable (stream-configuration map has
output sizes; sub-cameras inherit configurability from their
logical parent, where sessions actually open) is offered. On
logical-only devices the zoom-ratio range synthesizes the sub-1x
ultra-wide and 2x tele stops no id exposes, anchored to the logical
id (PhysicalLens.synthesizedFromZoomRange). LensLabels dedupe no
longer collapses entries that legitimately share an anchor id, and
selectLens applies the lens's nominal ratio through setZoomRatio —
the only reachability path on the logical camera, honouring the
panorama 1x lock.

New LensDiscoveryTest: logical-only devices synthesize .5/1x/2x,
exposed physical ultra-wides survive, single cameras stay honest,
unconfigurable telephotos are dropped unsynthesized. Verified:
:camera:testDevUnitTest 634 tests pass; lint clean in touched
files (the Route.Settings screenshot-coverage error predates this).

Diff

camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex 51eaf3e583..490201b7df 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -19,6 +19,7 @@ _Install: ./install camera (dev by default)._ - Portrait mode with on-device segmentation (MediaPipe selfie + MODNet matting on a Vulkan compute runtime, `.maml` assets) - QR/barcode scanning (zxing) and optional GPS geotagging written into EXIF **Architecture / data-flow:** Single-screen `ui/CameraScreen` + `platform/CameraViewModel` over per-mode `platform/` session objects on the `platform/camera2/` driver; `domain/` holds pure lens-selection logic, `platform/` capability queries; heavy work (stitch, night align, bokeh) goes through Rust JNI (`platform/StitchNative`) and lands in MediaStore via `data/MediaStoreSaver`. `onCreateBeforeContent` only honors the `ACTION_IMAGE_CAPTURE` capture-for-result intent; `Content()` sits behind a camera+mic permission gate.+**Lens selection:** `platform/LensSelector.enumerateLenses` feeds `domain/LensDiscovery` with every top-level camera id plus each logical camera's `getPhysicalCameraIds()` sub-cameras (validated against their stream-configuration maps); the Camera2 preview always opens the facing's logical camera, so picking a lens applies its nominal zoom ratio to that session (sub-1x / tele stops included) rather than opening a sub-camera id. **Entry points + reading order:** `MainActivity.kt` → `Route.kt` (`Route.Camera`/`Settings`) → `ui/CameraScreen.kt` → `platform/CameraViewModel.kt` → `platform/CameraSessions.kt` → `platform/PanoramaEngine.kt` / `NightCaptureEngine.kt`. **Gotchas:** - Capture code lives in `platform/` (the Camera2 driver in `platform/camera2/`); there is no `util/` root in this module@@ -34,6 +35,7 @@ _Install: ./install camera (dev by default)._ - com/vayunmathur/camera/Route.kt ### domain/ — pure lens-selection logic - com/vayunmathur/camera/domain/LensModel.kt+- com/vayunmathur/camera/domain/LensDiscovery.kt — offered-lens computation over pure `LensCandidate`s: every session-configurable camera the HAL exposes (top-level ids plus logical cameras' physical sub-cameras) is offered; a physical ultra-wide is never dropped for overlapping the logical zoom range; on logical-only devices the logical camera's zoom-ratio range synthesizes the ultra-wide (sub-1x) and telephoto (2x) stops no camera id exposes, anchored to the logical id (`PhysicalLens.synthesizedFromZoomRange`) - com/vayunmathur/camera/domain/LensSelectionLogic.kt - com/vayunmathur/camera/domain/ArgbToI420Converter.kt — bulk ARGB→YUV 4:2:0 for the Motion Photo clip - com/vayunmathur/camera/domain/MotionSaveQueue.kt — bound on Motion Photos still saving after the shutter
camera/src/main/java/com/vayunmathur/camera/domain/LensDiscovery.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/LensDiscovery.kt b/camera/src/main/java/com/vayunmathur/camera/domain/LensDiscovery.ktnew file mode 100644index 0000000000..e7724b9e84--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/LensDiscovery.kt@@ -0,0 +1,186 @@+package com.vayunmathur.camera.domain++import kotlin.math.abs++/**+ * One camera the HAL described during enumeration, in pure data.+ *+ * The platform layer (`platform/LensSelector.kt`) builds these from+ * `CameraManager.cameraIdList` **plus** every physical sub-camera id a+ * logical multi-camera exposes via+ * `CameraCharacteristics.getPhysicalCameraIds()` — on many devices those+ * sub-cameras never appear in the top-level id list, so iterating that+ * list alone sees a single back lens where the hardware has three+ * (issue #878). Each candidate carries the facts [LensDiscovery] needs to+ * decide what may be offered; no Android types leak in, so the offered-set+ * logic is unit-testable against synthetic characteristics sets.+ *+ * @param canConfigureSession false when the characteristics cannot back a+ *   capture session (no usable stream-configuration output sizes, or the+ *   id is neither a listed/openable id nor a physical sub-camera of an+ *   enumerated logical camera). Such candidates are never offered:+ *   offering a lens that cannot configure a session would strand the user+ *   on a dead bind.+ * @param isLogicalCamera true for a top-level logical camera (the id the+ *   Camera2 stack actually opens for its facing); zoom-range synthesis+ *   anchors to this camera.+ */+data class LensCandidate(+    val cameraId: String,+    val facing: LensFacing,+    val focalMm: Float,+    val eq35Mm: Float?,+    val mono: Boolean,+    val minZoomRatio: Float?,+    val maxZoomRatio: Float?,+    val canConfigureSession: Boolean,+    val isLogicalCamera: Boolean,+)++/**+ * Pure offered-lens computation over [LensCandidate]s.+ *+ * Offered-set rules, per facing family:+ * 1. Every candidate that can configure a session is offered, classified+ *    by focal length against the family's wide reference (closest+ *    35mm-equivalent to ~27mm). A physical ultra-wide is offered even when+ *    the wide logical camera's zoom range also reaches its stop — the+ *    pill is the physical lens, not a duplicate of the zoom bar.+ * 2. When the wide logical camera's zoom-ratio range reaches a stop no+ *    enumerated lens represents — below 1x for ultra-wide, at/above the+ *    canonical 2x tele stop — a [PhysicalLens.synthesizedFromZoomRange]+ *    entry anchored to that logical camera is added, so the stop stays+ *    reachable on logical-only devices that hide their sub-cameras.+ *    Synthesis never duplicates a stop a physical lens already covers.+ * 3. Duplicated enumerations of one physical lens collapse (see+ *    [LensLabels.dedupe]); synthesized entries share the logical id with+ *    their anchor wide lens and survive dedupe by type/factor.+ */+object LensDiscovery {++    private const val WIDE_REFERENCE_EQ_MM = 27f+    private const val ULTRA_WIDE_RATIO = 0.85f+    private const val TELEPHOTO_RATIO = 1.4f+    /** A zoom floor at/above this is not an ultra-wide stop worth offering. */+    private const val ZOOM_OUT_OFFER_MAX = 0.95f+    /** First canonical tele stop, mirroring the zoom bar's tele levels. */+    private const val TELE_SYNTHETIC_FACTOR = 2f+    private const val TELE_SYNTHETIC_TOLERANCE = 0.05f++    private const val PRIORITY_WIDE = 0+    private const val PRIORITY_ULTRA_WIDE = 1+    private const val PRIORITY_TELEPHOTO = 2+    private const val PRIORITY_MONO = 3++    /** Every lens the app may offer, across all facings. */+    fun discover(candidates: List<LensCandidate>): List<PhysicalLens> =+        LensLabels.dedupe(+            LensFacing.entries.flatMap { facing -> buildFamily(facing, candidates) },+        )++    /** Classifies one facing family and synthesizes any missing zoom stops. */+    private fun buildFamily(facing: LensFacing, candidates: List<LensCandidate>): List<PhysicalLens> {+        val family = candidates+            .filter { it.facing == facing && it.canConfigureSession }+            .sortedBy { it.focalMm }+        if (family.isEmpty()) return emptyList()+        val nonMono = family.filterNot { it.mono }+        // Wide reference: 35mm-eq closest to ~27mm; fall back to the median focal length.+        val reference = nonMono.minByOrNull {+            it.eq35Mm?.let { eq -> abs(eq - WIDE_REFERENCE_EQ_MM) } ?: Float.MAX_VALUE+        }+            ?: nonMono.getOrNull(nonMono.size / 2)+            ?: family.first()+        val classified = family.map { candidate -> classify(candidate, reference, facing) }+        return classified + synthesizeZoomRangeLenses(classified, reference, facing)+    }++    /**+     * Zoom-range stops the HAL exposes through the logical (reference)+     * camera but no enumerated lens represents. Anchored to the reference+     * candidate so selection resolves to the openable logical id and takes+     * effect through CONTROL_ZOOM_RATIO on that camera.+     */+    private fun synthesizeZoomRangeLenses(+        classified: List<PhysicalLens>,+        reference: LensCandidate,+        facing: LensFacing,+    ): List<PhysicalLens> {+        if (!reference.isLogicalCamera) return emptyList()+        val synthesized = mutableListOf<PhysicalLens>()+        val minZoom = reference.minZoomRatio+        if (minZoom != null && minZoom.isFinite() && minZoom < ZOOM_OUT_OFFER_MAX &&+            classified.none { it.nominalZoomRatio < ZOOM_OUT_OFFER_MAX }+        ) {+            synthesized += PhysicalLens(+                logicalCameraId = reference.cameraId,+                lensType = LensType.ULTRA_WIDE,+                facing = facing,+                focalLengthMm35Eq = reference.eq35Mm?.let { it * minZoom },+                nominalZoomRatio = minZoom,+                fallbackPriority = PRIORITY_ULTRA_WIDE,+                labelKey = "ultrawide",+                synthesizedFromZoomRange = true,+            )+        }+        val maxZoom = reference.maxZoomRatio+        if (maxZoom != null && maxZoom.isFinite() &&+            maxZoom + TELE_SYNTHETIC_TOLERANCE >= TELE_SYNTHETIC_FACTOR &&+            classified.none { it.nominalZoomRatio >= TELEPHOTO_RATIO }+        ) {+            synthesized += PhysicalLens(+                logicalCameraId = reference.cameraId,+                lensType = LensType.TELEPHOTO,+                facing = facing,+                focalLengthMm35Eq = reference.eq35Mm?.let { it * TELE_SYNTHETIC_FACTOR },+                nominalZoomRatio = TELE_SYNTHETIC_FACTOR,+                fallbackPriority = PRIORITY_TELEPHOTO,+                labelKey = "tele",+                synthesizedFromZoomRange = true,+            )+        }+        return synthesized+    }++    /** Classifies one candidate against the family reference into a [PhysicalLens]. */+    private fun classify(candidate: LensCandidate, reference: LensCandidate, facing: LensFacing): PhysicalLens {+        val type = classifyType(candidate, reference, facing)+        return PhysicalLens(+            logicalCameraId = candidate.cameraId,+            lensType = type,+            facing = facing,+            focalLengthMm35Eq = candidate.eq35Mm,+            nominalZoomRatio = candidate.focalMm / reference.focalMm,+            fallbackPriority = priorityOf(type),+            labelKey = labelOf(type),+        )+    }++    /** Lens type from the family reference geometry (mono wins over the focal heuristic). */+    private fun classifyType(candidate: LensCandidate, reference: LensCandidate, facing: LensFacing): LensType {+        if (candidate.mono) return LensType.MONOCHROME+        if (candidate.cameraId == reference.cameraId) {+            return if (facing == LensFacing.FRONT) LensType.FRONT else LensType.WIDE+        }+        if (candidate.focalMm < reference.focalMm * ULTRA_WIDE_RATIO) return LensType.ULTRA_WIDE+        if (candidate.focalMm > reference.focalMm * TELEPHOTO_RATIO) return LensType.TELEPHOTO+        return LensType.WIDE+    }++    /** Bind-attempt order for a lens type (wide/front first). */+    private fun priorityOf(type: LensType): Int = when (type) {+        LensType.WIDE, LensType.FRONT -> PRIORITY_WIDE+        LensType.ULTRA_WIDE -> PRIORITY_ULTRA_WIDE+        LensType.TELEPHOTO -> PRIORITY_TELEPHOTO+        LensType.MONOCHROME -> PRIORITY_MONO+    }++    /** Short UI key for a lens type. */+    private fun labelOf(type: LensType): String = when (type) {+        LensType.ULTRA_WIDE -> "ultrawide"+        LensType.WIDE -> "wide"+        LensType.TELEPHOTO -> "tele"+        LensType.MONOCHROME -> "mono"+        LensType.FRONT -> "front"+    }+}
camera/src/main/java/com/vayunmathur/camera/domain/LensLabels.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/LensLabels.kt b/camera/src/main/java/com/vayunmathur/camera/domain/LensLabels.ktindex 5c2148de5f..911d4ff03a 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/LensLabels.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/LensLabels.kt@@ -175,13 +175,17 @@ object LensLabels {     }      /**-     * Drops duplicate enumerations of one physical lens: same logical camera-     * ID twice, or identical characteristics (facing, type, 35mm-eq,-     * nominal ratio) surfacing under two IDs. Order-preserving.+     * Drops duplicate enumerations of one physical lens: the same lens+     * twice (same camera ID, type and factors), or identical+     * characteristics (facing, type, 35mm-eq, nominal ratio) surfacing+     * under two IDs. Order-preserving. The camera ID alone is not the key:+     * zoom-range-synthesized stops legitimately share their anchor logical+     * camera's ID with the wide lens and differ by type/factor.      */     fun dedupe(lenses: List<PhysicalLens>): List<PhysicalLens> {-        return lenses.distinctBy { it.logicalCameraId }-            .distinctBy { "${it.facing}/${it.lensType}/${it.focalLengthMm35Eq}/${it.nominalZoomRatio}" }+        return lenses.distinctBy {+            "${it.logicalCameraId}/${it.lensType}/${it.focalLengthMm35Eq}/${it.nominalZoomRatio}"+        }.distinctBy { "${it.facing}/${it.lensType}/${it.focalLengthMm35Eq}/${it.nominalZoomRatio}" }     } } 
camera/src/main/java/com/vayunmathur/camera/domain/LensModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/LensModel.kt b/camera/src/main/java/com/vayunmathur/camera/domain/LensModel.ktindex cd2a27e73b..d90cf6867a 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/LensModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/LensModel.kt@@ -40,6 +40,14 @@ enum class LensType {  *   facing (wide/front default = 0).  * @param labelKey stable key for the display label ("ultrawide", "wide",  *   "tele", "mono", "front"); the UI maps it to `strings.xml`.+ * @param synthesizedFromZoomRange true when this entry was synthesized from+ *   the logical camera's zoom-ratio range (CONTROL_ZOOM_RATIO_RANGE) rather+ *   than enumerated as its own camera id: the HAL exposes no separate+ *   ultra-wide/telephoto camera id on such devices, so the stop is reached+ *   by applying [nominalZoomRatio] to the logical camera ([logicalCameraId])+ *   instead of opening a different device. Such an entry is only offered+ *   when the logical camera's characteristics were validated to cover the+ *   ratio and to configure a session (see `domain/LensDiscovery.kt`).  */ data class PhysicalLens(     val logicalCameraId: String,@@ -50,4 +58,5 @@ data class PhysicalLens(     val intrinsicZoomRatio: Float? = null,     val fallbackPriority: Int,     val labelKey: String,+    val synthesizedFromZoomRange: Boolean = false, )
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 30c2486ef3..0226fc2a86 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt@@ -90,6 +90,15 @@ fun CameraViewModel.flipCamera() {  * rebind effect is keyed on [selectedLens], so this triggers a rebind with  * the filtered selector plus a capability refresh. Unknown lenses are  * ignored so a stale UI entry can never crash a bind.+ *+ * The Camera2 preview opens the facing's logical camera, so the lens+ * takes effect through zoom: selecting a lens applies its nominal ratio+ * (ultra-wide < 1x, tele > 1x, wide/front back to 1x) to the live+ * session. That is also the only reachability path for a+ * zoom-range-synthesized lens, whose camera id is the logical camera+ * itself. [setZoomRatio] clamps to the bound camera's advertised range+ * and honours the panorama/photosphere 1x lock, so a lens tap can never+ * request a ratio the HAL did not expose.  */ fun CameraViewModel.selectLens(lens: com.vayunmathur.camera.domain.PhysicalLens) {     // A lens switch rebinds the session and teardown would stop an active@@ -106,5 +115,6 @@ fun CameraViewModel.selectLens(lens: com.vayunmathur.camera.domain.PhysicalLens)     if (lens !in availableLensesMutable.value) return     selectedLensMutable.value = lens     persistStartupLens(lens)+    setZoomRatio(lens.nominalZoomRatio)     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 e3238d0c7a..77eb9615fa 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt@@ -6,7 +6,6 @@ import android.hardware.camera2.CameraMetadata import com.vayunmathur.library.log.Log 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@@ -28,42 +27,67 @@ fun Int.toLensFacing(): LensFacing? = when (this) { }  /**- * Enumerates every physical/logical lens from `CameraManager.cameraIdList`- * + `CameraCharacteristics` (`LENS_FACING`, focal lengths, sensor physical- * size for the 35mm-equivalent label, mono color-filter detection).+ * Enumerates every physical/logical lens the HAL exposes.  *- * Types are assigned per facing family sorted by focal length: the lens whose- * 35mm-equivalent is closest to ~27mm is the wide reference (1x); shorter is- * ultra-wide, longer is telephoto; a MONO color-filter arrangement wins over the- * focal heuristic. Front-facing families mark their reference lens FRONT.+ * Discovery walks `CameraManager.cameraIdList` **and** the physical+ * sub-camera ids each logical multi-camera reports via+ * `CameraCharacteristics.getPhysicalCameraIds()` (API 28+): on devices+ * whose back camera is one logical camera hiding wide/ultra-wide/tele+ * sub-cameras, the sub-cameras are not guaranteed to appear in the+ * top-level list, so iterating that list alone offers a single lens+ * (issue #878). `getCameraCharacteristics` accepts those physical ids+ * whether or not they are listed. The pure offered-set computation+ * (classification, configurability gate, zoom-range synthesis for+ * logical-only devices) lives in `domain/LensDiscovery.kt`.  *  * Safe to call off the main thread; never throws (returns empty on failure).  */ fun enumerateLenses(manager: CameraManager): List<PhysicalLens> {-    val raws = manager.cameraIdList.mapNotNull { id -> readRawLens(manager, id) }--    // Logical multi-camera (e.g. a UW stop reachable via the wide camera's-    // zoom range) plus same-physical-lens duplicates would each render an-    // extra identical pill — `buildFamily` handles the former per facing,-    // and the dedupe collapses the latter (issue #876).-    return LensLabels.dedupe(-        LensFacing.entries.flatMap { facing -> buildFamily(facing, raws) }-    )+    val topLevelIds = try {+        manager.cameraIdList.toList()+    } catch (e: RuntimeException) {+        Log.status("LensSelector", "cameraIdList failed during lens enumeration", e)+        return emptyList()+    }+    val candidates = mutableListOf<com.vayunmathur.camera.domain.LensCandidate>()+    val seen = mutableSetOf<String>()+    for (id in topLevelIds) {+        val raw = readRawLens(manager, id, isLogicalCamera = true) ?: continue+        if (seen.add(id)) candidates += raw.candidate+        // Expand the logical camera's physical sub-cameras: they carry the+        // real focal lengths behind the logical zoom range, and on many+        // HALs they exist nowhere else.+        for (physicalId in raw.physicalCameraIds) {+            if (physicalId in seen || physicalId.isBlank()) continue+            val sub = readRawLens(manager, physicalId, isLogicalCamera = false) ?: continue+            if (seen.add(physicalId)) {+                // A sub-camera that reports no stream map of its own is+                // still configurable through its logical parent (the+                // session is opened on the parent, never on the sub-id),+                // so it inherits the parent's configurability; a top-level+                // camera gets no such inheritance.+                candidates += if (sub.candidate.canConfigureSession) {+                    sub.candidate+                } else {+                    sub.candidate.copy(canConfigureSession = raw.candidate.canConfigureSession)+                }+            }+        }+    }+    return com.vayunmathur.camera.domain.LensDiscovery.discover(candidates) } -/** Full-frame diagonal (mm) of 35mm film; wide-reference eq focal length + family ratios. */-/** Value CameraX returns from `CameraInfo.getIntrinsicZoomRatio()` when unknown. */-private const val INTRINSIC_ZOOM_RATIO_UNKNOWN_SENTINEL = 1.0f-+/** Full-frame diagonal (mm) of 35mm film, for the 35mm-equivalent label. */ private const val FULL_FRAME_DIAGONAL_MM = 43.27f-private const val WIDE_REFERENCE_EQ_MM = 27f-private const val ULTRA_WIDE_RATIO = 0.85f-private const val TELEPHOTO_RATIO = 1.4f -/** Reads one camera id's physical-lens description; null when unusable. */-private fun readRawLens(manager: CameraManager, cameraId: String): RawLens? {+/** Reads one camera id's lens candidate; null when unusable. */+private fun readRawLens(+    manager: CameraManager,+    cameraId: String,+    isLogicalCamera: Boolean,+): RawLens? {     return try {-        readRawLensOrThrow(manager, cameraId)+        readRawLensOrThrow(manager, cameraId, isLogicalCamera)     } catch (e: IllegalArgumentException) {         Log.status("LensSelector", "Skipping camera during lens enumeration", e)         null@@ -73,8 +97,12 @@ private fun readRawLens(manager: CameraManager, cameraId: String): RawLens? {     } } -/** Physical-lens description probed off one camera id (null for external/unknown lenses). */-private fun readRawLensOrThrow(manager: CameraManager, cameraId: String): RawLens? {+/** Lens candidate probed off one camera id (null for external/unknown lenses). */+private fun readRawLensOrThrow(+    manager: CameraManager,+    cameraId: String,+    isLogicalCamera: Boolean,+): RawLens? {     val chars = manager.getCameraCharacteristics(cameraId)     val facing = when (         chars.get(CameraCharacteristics.LENS_FACING)@@ -99,98 +127,48 @@ private fun readRawLensOrThrow(manager: CameraManager, cameraId: String): RawLen     val mono = chars.get(         CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT     ) == CameraMetadata.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_MONO-    // CameraX's intrinsic zoom ratio has no Camera2 equivalent; the-    // eq-35mm ratio stays primary and the field stays null (unknown).-    val intrinsic: Float? = null-    val zoomFloor = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {-        chars.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE)?.lower-    } else {-        null-    }-    return RawLens(cameraId, facing, focal, eq35, mono, intrinsic, zoomFloor)-}--private data class RawLens(-    val id: String,-    val facing: LensFacing,-    val focalMm: Float,-    val eq35Mm: Float?,-    val mono: Boolean,-    val intrinsicZoomRatio: Float?,-    val minZoomRatio: Float?,-)--/** Classifies one facing family into [PhysicalLens] entries with fallback priorities. */-private fun buildFamily(facing: LensFacing, raws: List<RawLens>): List<PhysicalLens> {-    val family = raws.filter { it.facing == facing }.sortedBy { it.focalMm }-    if (family.isEmpty()) return emptyList()-    val nonMono = family.filterNot { it.mono }-    // Wide reference: 35mm-eq closest to ~27mm; fall back to the median focal length.-    val reference = nonMono.minByOrNull {-        it.eq35Mm?.let { eq -> kotlin.math.abs(eq - WIDE_REFERENCE_EQ_MM) } ?: Float.MAX_VALUE-    }-        ?: nonMono.getOrNull(nonMono.size / 2)-        ?: family.first()-    val classified = family.map { raw -> classifyLens(raw, reference, facing) }-    // Logical multi-camera dedup: when the wide logical camera already-    // reaches a UW stop via zoom-out (min zoom at/below its factor),-    // a separate UW pill would duplicate the zoom bar's sub-1x range —-    // drop it (issue #876).-    val wideFloor = classified.firstOrNull {-        it.lensType == LensType.WIDE || it.lensType == LensType.FRONT-    }?.let { ref -> family.firstOrNull { it.id == ref.logicalCameraId }?.minZoomRatio }-    return LensLabels.dropCoveredUltrawides(classified, wideFloor)-}--/** Classifies one raw lens against the family reference into a [PhysicalLens]. */-private fun classifyLens(raw: RawLens, reference: RawLens, facing: LensFacing): PhysicalLens {-    val type = classifyType(raw, reference, facing)-    return PhysicalLens(-        logicalCameraId = raw.id,-        lensType = type,+    // minSdk is 31, so the API-30 zoom-ratio range is always readable.+    val zoomRange = chars.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE)+    // Session-configurability gate: a lens whose stream configuration map+    // advertises no output size at all can never configure a capture+    // session, so it must not be offered (issue #878).+    val canConfigure = canConfigureSession(chars)+    // A physical sub-camera is configurable in this architecture when its+    // logical parent is: selection opens the logical camera and reaches+    // the sub-camera through its zoom range / HAL sensor switching. Its+    // own stream map still has to describe real outputs.+    val candidate = com.vayunmathur.camera.domain.LensCandidate(+        cameraId = cameraId,         facing = facing,-        focalLengthMm35Eq = raw.eq35Mm,-        nominalZoomRatio = raw.focalMm / reference.focalMm,-        intrinsicZoomRatio = raw.intrinsicZoomRatio,-        fallbackPriority = priorityOf(type),-        labelKey = labelOf(type),+        focalMm = focal,+        eq35Mm = eq35,+        mono = mono,+        minZoomRatio = zoomRange?.lower,+        maxZoomRatio = zoomRange?.upper+            ?: chars.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM),+        canConfigureSession = canConfigure,+        isLogicalCamera = isLogicalCamera,     )+    val physicalIds = runCatching { chars.physicalCameraIds }.getOrDefault(emptySet())+    return RawLens(candidate, physicalIds) } -/** Lens type from the family reference geometry (mono wins over the focal heuristic). */-private fun classifyType(raw: RawLens, reference: RawLens, facing: LensFacing): LensType {-    if (raw.mono) return LensType.MONOCHROME-    if (raw == reference) return if (facing == LensFacing.FRONT) LensType.FRONT else LensType.WIDE-    if (raw.focalMm < reference.focalMm * ULTRA_WIDE_RATIO) return LensType.ULTRA_WIDE-    if (raw.focalMm > reference.focalMm * TELEPHOTO_RATIO) return LensType.TELEPHOTO-    return LensType.WIDE-}--/** Bind-attempt order for a lens type (wide/front first). */-private fun priorityOf(type: LensType): Int {-    return when (type) {-        LensType.WIDE, LensType.FRONT -> PRIORITY_WIDE-        LensType.ULTRA_WIDE -> PRIORITY_ULTRA_WIDE-        LensType.TELEPHOTO -> PRIORITY_TELEPHOTO-        LensType.MONOCHROME -> PRIORITY_MONO-    }+/** True when the stream configuration map advertises at least one output size. */+private fun canConfigureSession(chars: CameraCharacteristics): Boolean {+    val map = runCatching {+        chars.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)+    }.getOrNull() ?: return false+    return runCatching {+        map.outputFormats.any { format ->+            !map.getOutputSizes(format).isNullOrEmpty()+        }+    }.getOrDefault(false) } -private const val PRIORITY_WIDE = 0-private const val PRIORITY_ULTRA_WIDE = 1-private const val PRIORITY_TELEPHOTO = 2-private const val PRIORITY_MONO = 3--/** Short UI key for a lens type. */-private fun labelOf(type: LensType): String {-    return when (type) {-        LensType.ULTRA_WIDE -> "ultrawide"-        LensType.WIDE -> "wide"-        LensType.TELEPHOTO -> "tele"-        LensType.MONOCHROME -> "mono"-        LensType.FRONT -> "front"-    }-}+private data class RawLens(+    val candidate: com.vayunmathur.camera.domain.LensCandidate,+    val physicalCameraIds: Set<String>,+)  /**  * Fills [availableLensesMutable][com.vayunmathur.camera.platform.CameraViewModel] once per
camera/src/test/java/com/vayunmathur/camera/domain/LensDiscoveryTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/LensDiscoveryTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/LensDiscoveryTest.ktnew file mode 100644index 0000000000..aa41b1cefa--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/LensDiscoveryTest.kt@@ -0,0 +1,150 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Regression tests for issue #878 ("Not All Lenses Available") against+ * synthetic characteristics sets: the offered lens set is computed from+ * [LensCandidate]s, so each device shape is asserted without a HAL.+ */+class LensDiscoveryTest {++    private fun candidate(+        id: String,+        facing: LensFacing = LensFacing.BACK,+        focalMm: Float,+        eq35Mm: Float?,+        mono: Boolean = false,+        minZoom: Float? = null,+        maxZoom: Float? = null,+        canConfigure: Boolean = true,+        logical: Boolean = true,+    ) = LensCandidate(+        cameraId = id,+        facing = facing,+        focalMm = focalMm,+        eq35Mm = eq35Mm,+        mono = mono,+        minZoomRatio = minZoom,+        maxZoomRatio = maxZoom,+        canConfigureSession = canConfigure,+        isLogicalCamera = logical,+    )++    private fun back(lenses: List<PhysicalLens>) = lenses.filter { it.facing == LensFacing.BACK }++    @Test+    fun logicalOnlyMultiCameraSynthesizesUltraWideAndTele() {+        // Reporter's shape: cameraIdList holds one logical back camera;+        // its zoom range is the only trace of the UW/tele sub-cameras.+        val offered = LensDiscovery.discover(+            listOf(+                candidate("0", focalMm = 4.3f, eq35Mm = 27f, minZoom = 0.5f, maxZoom = 5f),+                candidate("1", facing = LensFacing.FRONT, focalMm = 3.5f, eq35Mm = 25f),+            ),+        )+        val back = back(offered)+        assertEquals(+            setOf(LensType.ULTRA_WIDE, LensType.WIDE, LensType.TELEPHOTO),+            back.map { it.lensType }.toSet(),+        )+        assertEquals(+            listOf(LensType.ULTRA_WIDE, LensType.WIDE, LensType.TELEPHOTO),+            LensLabels.sortedByFactor(back).map { it.lensType },+        )+        // All three stops anchor to the openable logical id; UW/tele are+        // zoom-range stops, the wide lens is the real enumerated camera.+        assertTrue(back.all { it.logicalCameraId == "0" })+        assertFalse(back.single { it.lensType == LensType.WIDE }.synthesizedFromZoomRange)+        assertTrue(back.single { it.lensType == LensType.ULTRA_WIDE }.synthesizedFromZoomRange)+        assertTrue(back.single { it.lensType == LensType.TELEPHOTO }.synthesizedFromZoomRange)+        assertEquals(0.5f, back.single { it.lensType == LensType.ULTRA_WIDE }.nominalZoomRatio)+        assertEquals(1f, back.single { it.lensType == LensType.WIDE }.nominalZoomRatio)+        assertEquals(2f, back.single { it.lensType == LensType.TELEPHOTO }.nominalZoomRatio)+        // Lens-bar labels read Aperture-style for the synthesized family.+        assertEquals(listOf(".5", "1x", "2x"), LensLabels.labelsFor(LensLabels.sortedByFactor(back)))+        // The single front camera is offered untouched.+        assertEquals(listOf(LensType.FRONT), offered.filter { it.facing == LensFacing.FRONT }.map { it.lensType })+    }++    @Test+    fun physicalIdsExposedAreAllOfferedEvenWhenZoomRangeCoversThem() {+        // Pixel-shaped: logical wide plus physical UW/tele sub-cameras+        // (here fed from getPhysicalCameraIds, not the top-level list).+        // The wide zoom range reaches 0.5x, but the physical UW pill must+        // survive — it, not the zoom bar, is the lens choice.+        val offered = LensDiscovery.discover(+            listOf(+                candidate("0", focalMm = 4.3f, eq35Mm = 27f, minZoom = 0.5f, maxZoom = 10f),+                candidate("2", focalMm = 2.2f, eq35Mm = 13f, logical = false),+                candidate("3", focalMm = 12.9f, eq35Mm = 81f, logical = false),+                candidate("5", facing = LensFacing.FRONT, focalMm = 3.5f, eq35Mm = 25f),+            ),+        )+        val back = back(offered)+        assertEquals(+            listOf(LensType.ULTRA_WIDE, LensType.WIDE, LensType.TELEPHOTO),+            back.map { it.lensType },+        )+        assertEquals(listOf("2", "0", "3"), back.map { it.logicalCameraId })+        assertTrue(back.none { it.synthesizedFromZoomRange })+    }++    @Test+    fun singleCameraOffersOnlyItsWideLens() {+        val offered = LensDiscovery.discover(+            listOf(candidate("0", focalMm = 4.3f, eq35Mm = 27f, minZoom = 1f, maxZoom = 1f)),+        )+        assertEquals(1, offered.size)+        assertEquals(LensType.WIDE, offered.single().lensType)+        assertFalse(offered.single().synthesizedFromZoomRange)+    }++    @Test+    fun lensThatCannotConfigureASessionIsNotOffered() {+        // A physical tele whose stream map advertises no outputs can+        // never configure, so it is dropped; with the logical zoom capped+        // below the 2x tele stop nothing synthesizes in its place.+        val offered = LensDiscovery.discover(+            listOf(+                candidate("0", focalMm = 4.3f, eq35Mm = 27f, minZoom = 1f, maxZoom = 1.5f),+                candidate("3", focalMm = 12.9f, eq35Mm = 81f, canConfigure = false, logical = false),+            ),+        )+        assertEquals(listOf(LensType.WIDE), back(offered).map { it.lensType })+    }++    @Test+    fun zoomRangeSynthesisNeverDuplicatesAPhysicalStop() {+        // Physical UW at exactly the zoom floor: no synthesized twin, and+        // no synthesized tele when a physical tele already exists.+        val offered = LensDiscovery.discover(+            listOf(+                candidate("0", focalMm = 4.3f, eq35Mm = 27f, minZoom = 0.6f, maxZoom = 4f),+                candidate("2", focalMm = 2.6f, eq35Mm = 16f, logical = false),+                candidate("3", focalMm = 8.6f, eq35Mm = 54f, logical = false),+            ),+        )+        val back = back(offered)+        assertEquals(3, back.size)+        assertTrue(back.none { it.synthesizedFromZoomRange })+    }++    @Test+    fun logicalZoomOutWithoutPhysicalUltraWideSynthesizesOnlyUltraWideBelowTeleThreshold() {+        // Zoom reaches 0.7x out and only 1.8x in: UW synthesizes, tele+        // does not (the canonical 2x stop is not exposed).+        val offered = LensDiscovery.discover(+            listOf(candidate("0", focalMm = 4.3f, eq35Mm = 27f, minZoom = 0.7f, maxZoom = 1.8f)),+        )+        val back = back(offered)+        assertEquals(+            listOf(LensType.ULTRA_WIDE, LensType.WIDE),+            LensLabels.sortedByFactor(back).map { it.lensType },+        )+        assertEquals(0.7f, back.first { it.lensType == LensType.ULTRA_WIDE }.nominalZoomRatio)+    }+}