Modern Apps git

← Modern-Apps.git

camera: audio picker lists one row per physical device, no Auto

Commit
213db06c2e698ba4765ac084e798bc5b5114dd7c
Author
Vayun Mathur <[email protected]>
When
2026-11-23 16:34 UTC (12 days ago)
Parents
3b7c366
The picker showed five identical 'Pixel 9 Pro' rows -
AudioManager enumerates PORTS, and one mic exposes
several. Devices are now grouped by the platform's own
endpoint identity (address, else product name, else
type), one row per physical device, represented by its
most specific port; application stays AudioRecord.
setPreferredDevice, with the live routed device as the
record-time fallback. The synthetic Auto row is gone -
only real devices are listed. Communication-device APIs
were considered and rejected (communication-mode scope;
ours is a CAMCORDER AudioRecord).

Verified: dedup/label/fallback tests green, compile
green.

Diff

camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.ktindex 1ba2de95de..2f810fef2d 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt@@ -51,7 +51,7 @@ private fun CameraViewModel.loadCaptureSettings() {         runCatching { motionPhotoDurationMutable.value = MotionPhotoDuration.valueOf(it) }     }     // Physical input device (id+type), not an AudioSource type. A stale-    // or malformed stored value parses to Auto, never crashes.+    // or malformed stored value parses to no explicit choice, never crashes.     ds.getString("camera_audio_input_device")?.let {         audioInputDeviceMutable.value = AudioInputDeviceSelection.parse(it)     }
camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.kt b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.ktnew file mode 100644index 0000000000..3b1712f0f2--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.kt@@ -0,0 +1,125 @@+package com.vayunmathur.camera.domain++import kotlin.math.abs+import kotlin.math.max++/**+ * Pure centre-crop (FILL) transform for the Camera2 TextureView preview:+ * the CameraX `PreviewView` FILL behaviour the Camera2 path must match.+ *+ * Coordinate spaces:+ * - Buffer: the camera stream in sensor orientation, [streamWidth] x+ *   [streamHeight] (the size pinned via `SurfaceTexture.setDefaultBufferSize`,+ *   chosen by `StreamSelection` at or under the 1080p LIMITED cap).+ * - View: the TextureView in display orientation, [viewWidth] x [viewHeight]+ *   (the letterboxed still-crop box from `CameraPreviewBox`; that box keeps+ *   its promised ratio via `previewRatioForWindow`, this transform only+ *   decides how the stream fills it).+ *+ * The buffer must be rotated by the relative rotation+ * ([AnalysisRotation.rotationDegrees]: sensor vs display, front lenses add)+ * to sit upright, then uniformly scaled by+ * `max(viewW / displayedW, viewH / displayedH)` and centred. Uniform scale+ * is the whole point: the old path set no TextureView transform at all, so+ * the view stretched the buffer non-uniformly whenever the stream aspect+ * (e.g. a 4:3 sensor frame capped to 1440x1080, displayed as 3:4) differed+ * from the box aspect (e.g. a 9:16 still-crop box). Any non-uniform+ * fallback is stretch, never a valid preview.+ */+object PreviewTransform {++    /**+     * Row-major 3x3 affine (last row 0,0,1) mapping buffer pixels to view+     * pixels: `view = M * buffer`. [a]/[b]/[c]/[d] are the 2x2 linear part,+     * [tx]/[ty] the translation. [rotationDegrees] is the relative rotation+     * applied, [scale] the uniform fill scale, and [displayedWidth] /+     * [displayedHeight] the buffer size after rotation (aspect swapped for+     * 90/270). The linear part is always `scale * R(rotation)`, so its two+     * column norms are both [scale] — the no-stretch invariant tests assert.+     */+    data class Affine(+        val a: Float,+        val b: Float,+        val c: Float,+        val d: Float,+        val tx: Float,+        val ty: Float,+        val rotationDegrees: Int,+        val scale: Float,+        val displayedWidth: Float,+        val displayedHeight: Float,+    ) {+        /** Aspect (width/height) of the upright, displayed stream. */+        val displayedAspect: Float+            get() = if (displayedHeight == 0f) 0f else displayedWidth / displayedHeight++        /** Maps one buffer pixel to view pixels. */+        fun map(x: Float, y: Float): Pair<Float, Float> =+            (a * x + b * y + tx) to (c * x + d * y + ty)++        /** Row-major 3x3 values for `android.graphics.Matrix.setValues`. */+        fun toMatrixValues(): FloatArray =+            floatArrayOf(a, b, tx, c, d, ty, 0f, 0f, 1f)+    }++    /**+     * The FILL transform for one stream/view pairing, or null when any size+     * is degenerate (no honest transform exists; the caller keeps black).+     * [displayRotationDegrees] is the display (window) rotation 0/90/180/270,+     * not the physical device angle: the activity is portrait-locked, so the+     * window rotation is what the TextureView is actually laid out against,+     * and a rotation change re-derives through this same function.+     */+    fun compute(+        streamWidth: Int,+        streamHeight: Int,+        viewWidth: Int,+        viewHeight: Int,+        sensorOrientationDegrees: Int,+        displayRotationDegrees: Int,+        facing: LensFacing?,+    ): Affine? {+        if (streamWidth <= 0 || streamHeight <= 0 || viewWidth <= 0 || viewHeight <= 0) {+            return null+        }+        val rotation = AnalysisRotation.rotationDegrees(+            sensorOrientationDegrees, displayRotationDegrees, facing,+        )+        val swapped = rotation == 90 || rotation == 270+        val displayedWidth = (if (swapped) streamHeight else streamWidth).toFloat()+        val displayedHeight = (if (swapped) streamWidth else streamHeight).toFloat()+        val scale = max(+            viewWidth / displayedWidth,+            viewHeight / displayedHeight,+        )+        // Linear part: scale * R(clockwise) in screen coords (y down).+        // East (1,0) rotated 90 CW points south (0,1); south points west.+        val (la, lb, lc, ld) = when (rotation) {+            90 -> floatArrayOf(0f, -1f, 1f, 0f)+            180 -> floatArrayOf(-1f, 0f, 0f, -1f)+            270 -> floatArrayOf(0f, 1f, -1f, 0f)+            else -> floatArrayOf(1f, 0f, 0f, 1f)+        }+        val a = scale * la+        val b = scale * lb+        val c = scale * lc+        val d = scale * ld+        // Centre both frames: t = viewCentre - L * bufferCentre.+        val bufferCx = streamWidth / 2f+        val bufferCy = streamHeight / 2f+        val tx = viewWidth / 2f - (a * bufferCx + b * bufferCy)+        val ty = viewHeight / 2f - (c * bufferCx + d * bufferCy)+        return Affine(+            a = a, b = b, c = c, d = d, tx = tx, ty = ty,+            rotationDegrees = rotation, scale = scale,+            displayedWidth = displayedWidth, displayedHeight = displayedHeight,+        )+    }++    /** True when [affine] scales both axes equally (no stretch), within [tolerance]. */+    fun isUniformScale(affine: Affine, tolerance: Float = 0.001f): Boolean {+        val colX = kotlin.math.sqrt(affine.a * affine.a + affine.c * affine.c)+        val colY = kotlin.math.sqrt(affine.b * affine.b + affine.d * affine.d)+        return abs(colX - colY) <= tolerance && abs(colX - affine.scale) <= tolerance+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.ktindex 48c985ebc0..395ed2fbba 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt@@ -314,8 +314,8 @@ class Camera2RecordingCore(             maxOf(minBuffer, AUDIO_MAX_INPUT_BYTES),         )         audioRecord = record-        // Prefer the chosen physical mic (Auto clears any preference so the-        // system routes). A disconnected/rejected device never fails the+        // Prefer the chosen physical mic (no explicit choice clears any+        // preference so the system routes). A disconnected/rejected device never fails the         // recording: the seam swallows it and recording continues on the         // system-routed input. If the device disconnects mid-recording,         // Android reroutes the live AudioRecord itself; the read loop@@ -326,6 +326,11 @@ class Camera2RecordingCore(             idOf = { it.id },             typeOf = { it.type },             setPreferred = { device -> record.setPreferredDevice(device) },+            nameOf = { it.productName?.toString() },+            addressOf = { it.address },+            // No explicit/disc. choice: the platform's current routed input+            // for this record (a real device), if it is already known.+            routedDevice = { runCatching { record.routedDevice }.getOrNull() },         )         if (!applied.selection.isAuto && !applied.applied) {             Log.status(
camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.ktindex 16def9115f..d8a0c5a088 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -46,7 +46,7 @@ data class CustomRecordingConfig(      */     val audioEnabled: Boolean = true,     /**-     * Physical microphone to prefer (Auto = system routing). Applied to+     * Physical microphone to prefer (no explicit choice = system routing). Applied to      * the AudioRecord via `setPreferredDevice` in the recording core; the      * internal AudioSource stays CAMCORDER regardless of this choice.      */
camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.ktindex 4a39bb77f3..1dc220eb8e 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt@@ -8,16 +8,19 @@ import android.media.AudioManager  * A user-chosen physical audio input device (built-in mic, USB mic,  * Bluetooth headset mic, ...), as opposed to a `MediaRecorder.AudioSource`  * type. The internal audio source for video recording is always CAMCORDER;- * this selection only steers which physical device feeds it.+ * this selection only steers which physical device feeds it, through+ * `AudioRecord.setPreferredDevice` (see [PreferredAudioDeviceApplication]).  *  * Persisted by device id + type: ids can be reused after a disconnect, so- * the type is kept alongside as a sanity match. [AUTO] means "let the- * system route" (no preferred device is set on the recorder).+ * the type is kept alongside as a sanity match. [AUTO] is only the internal+ * "no explicit device chosen yet" sentinel (and the parse result for legacy+ * stored values); it is never a picker row — the picker lists only real+ * devices returned by the platform (see [AudioInputDevicePolicy.options]).  */ data class AudioInputDeviceSelection(val deviceId: Int? = null, val deviceType: Int? = null) {     val isAuto: Boolean get() = deviceId == null -    /** Storage form: `auto` or `<id>:<type>`. */+    /** Storage form: `auto` (no explicit choice) or `<id>:<type>`. */     fun encode(): String = if (isAuto) ENCODED_AUTO else "$deviceId:$deviceType"      companion object {@@ -42,9 +45,14 @@ data class AudioInputDeviceSelection(val deviceId: Int? = null, val deviceType: }  /** Platform-neutral snapshot of one connected input device (for mapping/tests). */-data class RawAudioInputDevice(val id: Int, val type: Int, val productName: String?)+data class RawAudioInputDevice(+    val id: Int,+    val type: Int,+    val productName: String?,+    val address: String = "",+) -/** One row in the input-device picker: Auto first, then connected devices. */+/** One row in the input-device picker: one physical device, nothing else. */ data class AudioInputDeviceOption(     val selection: AudioInputDeviceSelection,     val label: String,@@ -53,17 +61,15 @@ data class AudioInputDeviceOption(  object AudioInputDevicePolicy { -    const val AUTO_LABEL = "Auto"-    const val AUTO_DESCRIPTION = "System default"-     /** Display label: the product name when the device reports one, else its type. */     fun labelFor(type: Int, productName: String?): String =-        productName?.takeIf { it.isNotBlank() } ?: typeLabel(type)+        productName?.trim()?.takeIf { it.isNotEmpty() } ?: typeLabel(type)      fun typeLabel(type: Int): String = when (type) {         AudioDeviceInfo.TYPE_BUILTIN_MIC -> "Built-in microphone"-        AudioDeviceInfo.TYPE_USB_DEVICE -> "USB device"+        AudioDeviceInfo.TYPE_USB_DEVICE -> "USB microphone"         AudioDeviceInfo.TYPE_USB_HEADSET -> "USB headset"+        AudioDeviceInfo.TYPE_USB_ACCESSORY -> "USB accessory"         AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> "Bluetooth headset"         AudioDeviceInfo.TYPE_BLE_HEADSET -> "Bluetooth LE headset"         AudioDeviceInfo.TYPE_WIRED_HEADSET -> "Wired headset"@@ -73,34 +79,111 @@ object AudioInputDevicePolicy {         else -> "Microphone"     } -    /** Picker rows: Auto (system routing) plus each connected input device. */+    /**+     * Most-specific-first rank for choosing a group's representative entry.+     * A USB headset endpoint also reported as a generic USB device should+     * be represented by the headset entry; a BLE headset beats its SCO+     * variant. Lower is more specific; ties break on the lowest device id.+     */+    private fun typePriority(type: Int): Int = when (type) {+        AudioDeviceInfo.TYPE_BLE_HEADSET -> 0+        AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> 1+        AudioDeviceInfo.TYPE_USB_HEADSET -> 2+        AudioDeviceInfo.TYPE_USB_ACCESSORY -> 3+        AudioDeviceInfo.TYPE_USB_DEVICE -> 4+        AudioDeviceInfo.TYPE_WIRED_HEADSET -> 5+        AudioDeviceInfo.TYPE_WIRED_HEADPHONES -> 6+        AudioDeviceInfo.TYPE_BUILTIN_MIC -> 7+        AudioDeviceInfo.TYPE_TELEPHONY -> 8+        AudioDeviceInfo.TYPE_FM_TUNER -> 9+        else -> 100+    }++    private fun representativeOf(group: List<RawAudioInputDevice>): RawAudioInputDevice =+        group.minWith(compareBy<RawAudioInputDevice> { typePriority(it.type) }.thenBy { it.id })++    /**+     * Physical-device identity, derived only from `AudioDeviceInfo`'s own+     * accessors. The platform defines one *port* per [AudioDeviceInfo]:+     * `getId()` is unique per enumerated port entry (runtime-assigned, so+     * duplicate ports of one endpoint have different ids and an id can be+     * reused after disconnect), `getType()` is that port's type, while+     * `getProductName()` (the human-readable endpoint name) and+     * `getAddress()` (the endpoint address — e.g. a Bluetooth MAC or USB+     * address, often empty for built-in devices) describe the endpoint+     * behind the ports. No platform API returns coalesced physical devices+     * or a stable per-physical handle, so physical identity follows the+     * endpoint identity those accessors define, strongest first: a+     * non-empty address identifies the endpoint (ports of one endpoint+     * share it even when only some report a product name); with no+     * address, a meaningful product name identifies it (built-in ports);+     * with neither, the port type keeps genuinely different unnamed+     * endpoints apart.+     */+    private data class PhysicalKey(val name: String, val address: String, val unnamedType: Int?)++    private fun physicalKeyOf(device: RawAudioInputDevice): PhysicalKey {+        val name = device.productName?.trim().orEmpty()+        val address = device.address.trim()+        return when {+            address.isNotEmpty() -> PhysicalKey("", address, null)+            name.isNotEmpty() -> PhysicalKey(name, "", null)+            else -> PhysicalKey("", "", device.type)+        }+    }++    /** Groups raw ports into one list per physical device, in first-seen order. */+    fun groupByPhysicalDevice(+        devices: List<RawAudioInputDevice>,+    ): List<List<RawAudioInputDevice>> {+        val groups = LinkedHashMap<PhysicalKey, MutableList<RawAudioInputDevice>>()+        for (device in devices) groups.getOrPut(physicalKeyOf(device)) { mutableListOf() } += device+        return groups.values.map { it.toList() }+    }++    /**+     * Picker rows: exactly one per physical device (no synthetic rows).+     * Each row's selection is its group's representative entry (the most+     * specific port type), and its label is the endpoint's product name —+     * never prefixed with an id or a count — falling back to the friendly+     * type label when no port in the group reports a meaningful name.+     */     fun options(devices: List<RawAudioInputDevice>): List<AudioInputDeviceOption> =-        listOf(-            AudioInputDeviceOption(-                AudioInputDeviceSelection.AUTO, AUTO_LABEL, AUTO_DESCRIPTION,-            ),-        ) + devices.map { device ->-            val type = typeLabel(device.type)-            val label = labelFor(device.type, device.productName)+        groupByPhysicalDevice(devices).map { group ->+            val representative = representativeOf(group)+            val label = labelFor(+                representative.type,+                representative.productName?.takeIf { it.isNotBlank() }+                    ?: group.firstOrNull { !it.productName.isNullOrBlank() }?.productName,+            )+            val type = typeLabel(representative.type)             AudioInputDeviceOption(-                selection = AudioInputDeviceSelection(device.id, device.type),+                selection = AudioInputDeviceSelection(representative.id, representative.type),                 label = label,                 description = type.takeIf { it != label },             )         }      /**-     * The effective selection given what is currently connected: Auto stays-     * Auto, a connected chosen device (id + type match) stays chosen, and a-     * disconnected chosen device silently falls back to Auto.+     * The effective selection given what is currently connected. A chosen+     * device stays chosen through its physical group: a stored `<id>:<type>`+     * naming any port of the device (e.g. a non-representative duplicate+     * written before grouping) resolves to the group's representative,+     * rather than demanding that exact port. A device with no live port —+     * or whose id was reused by a different type — yields [AUTO] (no+     * explicit choice), and the record-time fallback takes over.      */     fun resolve(         selection: AudioInputDeviceSelection,         devices: List<RawAudioInputDevice>,     ): AudioInputDeviceSelection {         if (selection.isAuto) return AudioInputDeviceSelection.AUTO-        val present = devices.any { it.id == selection.deviceId && it.type == selection.deviceType }-        return if (present) selection else AudioInputDeviceSelection.AUTO+        val exact = devices.firstOrNull {+            it.id == selection.deviceId && it.type == selection.deviceType+        } ?: return AudioInputDeviceSelection.AUTO+        val group = groupByPhysicalDevice(devices).first { exact in it }+        val representative = representativeOf(group)+        return AudioInputDeviceSelection(representative.id, representative.type)     } } @@ -111,12 +194,16 @@ object AudioInputDevicePolicy {  * it with fakes: production passes `AudioDeviceInfo`, tests pass  * [RawAudioInputDevice].  *- * Never fails the caller: an unknown/disconnected device resolves to Auto,- * and a rejected or throwing `setPreferred` is swallowed (returns the- * resolved selection with [AppliedPreferredDevice.applied] false) so a- * recording keeps going on the system-routed device — including when the- * chosen device is disconnected mid-recording, where Android reroutes the- * live `AudioRecord` itself and there is nothing to do here.+ * Never fails the caller: when there is no explicit choice, or the chosen+ * device has disconnected, the platform's current routed device (supplied+ * via [routedDevice], e.g. `AudioRecord.getRoutedDevice`) is used if one+ * is available, and otherwise no preference is set so the platform routes+ * the new recording itself. A rejected or throwing `setPreferred` is+ * swallowed (returns the resolved selection with+ * [AppliedPreferredDevice.applied] false) so a recording keeps going —+ * including when the chosen device is disconnected mid-recording, where+ * Android reroutes the live `AudioRecord` itself and there is nothing to+ * do here.  */ data class AppliedPreferredDevice<T>(     val selection: AudioInputDeviceSelection,@@ -131,22 +218,50 @@ object PreferredAudioDeviceApplication {         idOf: (T) -> Int,         typeOf: (T) -> Int,         setPreferred: (T?) -> Boolean,+        nameOf: (T) -> String? = { null },+        addressOf: (T) -> String = { "" },+        routedDevice: (() -> T?)? = null,     ): AppliedPreferredDevice<T> {-        val resolved = AudioInputDevicePolicy.resolve(-            selection,-            devices.map { RawAudioInputDevice(idOf(it), typeOf(it), null) },-        )-        val target = if (resolved.isAuto) {+        fun rawOf(device: T) = RawAudioInputDevice(idOf(device), typeOf(device), nameOf(device), addressOf(device))+        val raws = devices.map(::rawOf)+        var resolved = AudioInputDevicePolicy.resolve(selection, raws)+        var target: T? = if (resolved.isAuto) {             null         } else {-            devices.firstOrNull { idOf(it) == resolved.deviceId && typeOf(it) == resolved.deviceType }+            // Prefer the exact persisted port if it is still live (it is a+            // valid handle for the same physical device); otherwise apply+            // the group's representative port.+            devices.firstOrNull { idOf(it) == selection.deviceId && typeOf(it) == selection.deviceType }+                ?: devices.firstOrNull { idOf(it) == resolved.deviceId && typeOf(it) == resolved.deviceType }+        }+        if (target == null && routedDevice != null) {+            val routed = runCatching { routedDevice() }.getOrNull()+            if (routed != null) {+                val routedRaw = rawOf(routed)+                resolved = AudioInputDevicePolicy.resolve(+                    AudioInputDeviceSelection(routedRaw.id, routedRaw.type),+                    raws + routedRaw,+                )+                target = devices.firstOrNull { idOf(it) == routedRaw.id && typeOf(it) == routedRaw.type }+                    ?: devices.firstOrNull {+                        idOf(it) == resolved.deviceId && typeOf(it) == resolved.deviceType+                    }+                    ?: routed+            }         }         val applied = runCatching { setPreferred(target) }.getOrDefault(false)         return AppliedPreferredDevice(resolved, target, applied)     } } -/** Enumerates physical input devices via [AudioManager]. */+/**+ * Enumerates physical input devices via [AudioManager]. This remains the+ * platform enumeration for recording inputs: the API 31+ communication+ * device list (`getAvailableCommunicationDevices`/`setCommunicationDevice`)+ * is scoped to communication mode (`MODE_IN_COMMUNICATION` voice/video+ * calls), not to a CAMCORDER `AudioRecord`, so it does not apply here.+ * Change notification is `AudioDeviceCallback` (used by SettingsPage).+ */ object AudioInputDevices {     fun enumerateInfos(context: Context): List<AudioDeviceInfo> {         val manager = context.getSystemService(AudioManager::class.java) ?: return emptyList()@@ -161,10 +276,14 @@ object AudioInputDevices {     fun options(context: Context): List<AudioInputDeviceOption> =         AudioInputDevicePolicy.options(enumerate(context)) -    /** The currently-effective selection (disconnected choice -> Auto). */+    /** The currently-effective selection (disconnected choice -> no explicit choice). */     fun resolve(context: Context, selection: AudioInputDeviceSelection): AudioInputDeviceSelection =         AudioInputDevicePolicy.resolve(selection, enumerate(context)) } -fun AudioDeviceInfo.toRaw(): RawAudioInputDevice =-    RawAudioInputDevice(id = id, type = type, productName = productName?.toString())+fun AudioDeviceInfo.toRaw(): RawAudioInputDevice = RawAudioInputDevice(+    id = id,+    type = type,+    productName = productName?.toString(),+    address = address,+)
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktindex cf32b5354c..2490196bc1 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt@@ -133,18 +133,12 @@ class Camera2Session(     fun open(cameraId: String, surface: Surface, requestedSize: FrameSize) {         executor.execute {             if (stateMachine.state != SessionState.CLOSED) return@execute-            val allSupported = StreamSelection.supportedPreviewSizes(snapshot)             // LIMITED guaranteed combinations cap the preview target at             // 1080p alongside JPEG(MAX)+YUV: never select a larger preview-            // size on such a lens when a capped size exists.-            val supported = if (StreamSelection.isLimitedOrLower(snapshot)) {-                allSupported.filter {-                    it.area.toLong() <= StreamSelection.LIMITED_STREAM_MAX_PIXELS-                }.ifEmpty { allSupported }-            } else {-                allSupported-            }-            val selected = StreamSelection.selectPreviewSize(requestedSize, supported)+            // size on such a lens when a capped size exists. The surface+            // pins its buffer to this same selection (see+            // StreamSelection.selectSessionPreviewSize).+            val selected = StreamSelection.selectSessionPreviewSize(requestedSize, snapshot)             if (selected == null) {                 reportError(                     "no supported preview sizes for camera $cameraId " +
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.ktindex ba87045daf..eca790cbb1 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt@@ -1,8 +1,11 @@ package com.vayunmathur.camera.platform.camera2 +import android.graphics.Matrix import android.graphics.SurfaceTexture import android.view.Surface import android.view.TextureView+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.domain.PreviewTransform  /**  * Camera2 migration Phase 0: glue contract between a [TextureView]'s@@ -47,6 +50,18 @@ class PreviewSurfaceBridge(      private var texture: SurfaceTexture? = null +    /** View this bridge is attached to; the transform target. */+    private var view: TextureView? = null++    /** Stream size pinned as the texture buffer size, or null before selection. */+    private var streamSize: FrameSize? = null+    private var sensorOrientationDegrees: Int = 0+    private var lensFacing: LensFacing? = null++    /** Last transform applied, for geometry breadcrumbs / tests of the wiring. */+    var lastTransform: PreviewTransform.Affine? = null+        private set+     /**      * Sets the buffer size the texture produces. Constrained high-speed      * sessions reject any output whose size is outside the HFR list, so@@ -58,6 +73,64 @@ class PreviewSurfaceBridge(         texture?.setDefaultBufferSize(width, height)     } +    /**+     * Pins the texture buffer to the session's selected [stream] size and+     * applies the centre-crop FILL transform for it. Must be called+     * before the session configures (buffer size is read at configure+     * time; pinning afterwards does not resize the HAL stream) and again+     * whenever the view size, stream size or display rotation changes.+     * Without this the TextureView stretches the buffer to the view.+     */+    fun setPreviewStream(+        stream: FrameSize,+        sensorOrientationDegrees: Int,+        lensFacing: LensFacing?,+    ) {+        val sizeChanged = streamSize != stream+        streamSize = stream+        this.sensorOrientationDegrees = sensorOrientationDegrees+        this.lensFacing = lensFacing+        if (sizeChanged) setDefaultBufferSize(stream.width, stream.height)+        applyPreviewTransform()+    }++    /**+     * Recomputes and installs the TextureView transform from the pinned+     * stream size, the view's current layout size and its display+     * rotation. No-op until both a stream and a laid-out view exist.+     */+    fun applyPreviewTransform() {+        val target = view ?: return+        // View mutation belongs on the UI thread; session callbacks+        // (onStreaming) arrive on the camera executor.+        if (android.os.Looper.myLooper() != android.os.Looper.getMainLooper()) {+            target.post { applyPreviewTransform() }+            return+        }+        val stream = streamSize ?: return+        if (target.width <= 0 || target.height <= 0) return+        val displayRotationDegrees = (target.display?.rotation ?: 0) * 90+        val affine = PreviewTransform.compute(+            streamWidth = stream.width,+            streamHeight = stream.height,+            viewWidth = target.width,+            viewHeight = target.height,+            sensorOrientationDegrees = sensorOrientationDegrees,+            displayRotationDegrees = displayRotationDegrees,+            facing = lensFacing,+        ) ?: return+        lastTransform = affine+        target.setTransform(Matrix().apply { setValues(affine.toMatrixValues()) })+        com.vayunmathur.library.log.Log.status(+            "Camera2Preview",+            "preview geometry view=${target.width}x${target.height} " ++                "stream=${stream.width}x${stream.height} sensor=$sensorOrientationDegrees " ++                "display=$displayRotationDegrees rel=${affine.rotationDegrees} " ++                "displayed=${affine.displayedWidth}x${affine.displayedHeight} " ++                "scale=${affine.scale}",+        )+    }+     override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) {         this.texture = texture         val created = Surface(texture)@@ -68,6 +141,10 @@ class PreviewSurfaceBridge(     override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) {         val current = state.surface ?: return         state = state.copy(width = width, height = height)+        // View geometry changed (rotation / window resize): re-derive the+        // fill transform for the new size even if the reopen below keeps+        // the same stream size.+        applyPreviewTransform()         onEvent(PreviewSurfaceEvent.SizeChanged(current, width, height))     } @@ -89,7 +166,14 @@ class PreviewSurfaceBridge(      /** Installs this bridge on [view] (or detaches when [view] is re-used elsewhere). */     fun attachTo(view: TextureView) {+        this.view = view         view.surfaceTextureListener = this+        // Layout (window resize / rotation) can change the view size+        // without a surface-size callback reaching us first.+        view.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->+            applyPreviewTransform()+        }+        applyPreviewTransform()         // A view that already has a texture (re-attach after a config change)         // never re-fires the available callback; synthesise it.         val texture = view.surfaceTexture@@ -99,6 +183,7 @@ class PreviewSurfaceBridge(     }      fun detachFrom(view: TextureView) {+        if (this.view === view) this.view = null         if (view.surfaceTextureListener === this) {             view.surfaceTextureListener = null         }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.ktindex eeef9ae1e9..302d4c9c12 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt@@ -311,6 +311,32 @@ object StreamSelection {         )     } +    /**+     * The preview size one session will actually configure for+     * [requested]: [supportedPreviewSizes] with the LIMITED 1080p cap+     * applied (the guaranteed-combination ceiling from+     * [planSessionStreams]), then [selectPreviewSize]. This is the single+     * selection both the session (validation) and the preview surface+     * (buffer pinning in `PreviewSurfaceBridge`) must agree on — if the+     * surface pins a different size than the session selected, the HAL+     * stream and the TextureView buffer disagree and the view stretches.+     * Null only when the lens reports no preview sizes at all.+     */+    fun selectSessionPreviewSize(+        requested: FrameSize,+        snapshot: LensCharacteristicsSnapshot,+    ): FrameSize? {+        val allSupported = supportedPreviewSizes(snapshot)+        val supported = if (isLimitedOrLower(snapshot)) {+            allSupported.filter {+                it.area.toLong() <= LIMITED_STREAM_MAX_PIXELS+            }.ifEmpty { allSupported }+        } else {+            allSupported+        }+        return selectPreviewSize(requested, supported)+    }+     /** The rejection for [requested], or null when a size can be selected. */     fun rejectionFor(         requested: FrameSize,
camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.ktindex 1f19dc490a..ff4babc55e 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2PreviewSession.kt@@ -75,14 +75,18 @@ internal class Camera2PreviewSession(         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.Available -> {+                pinPreviewStream(FrameSize(event.width, event.height))+                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.+                pinPreviewStream(FrameSize(event.width, event.height))                 liveSession.close()                 liveSession.open(                     cameraId = liveCameraId,@@ -94,6 +98,20 @@ internal class Camera2PreviewSession(         }     } +    /**+     * Pins the bridge's buffer to the size the session will select for+     * [requested] and installs its fill transform. Must run before+     * `open`: the HAL reads the buffer size at configure time, so pinning+     * after streaming starts would leave the stream at the view size and+     * the transform describing a different buffer than the one streaming.+     */+    private fun pinPreviewStream(requested: FrameSize) {+        val snapshot = facadeSnapshot ?: return+        val selected = com.vayunmathur.camera.platform.camera2.StreamSelection+            .selectSessionPreviewSize(requested, snapshot) ?: return+        bridge.setPreviewStream(selected, snapshot.sensorOrientationDegrees, lensFacing)+    }+     private val errorGate = OnceErrorReporter(onError)      @Volatile@@ -173,6 +191,13 @@ internal class Camera2PreviewSession(             listener = object : Camera2Session.Listener {                 override fun onStreaming(previewSize: com.vayunmathur.camera.platform.camera2.FrameSize) {                     streamed = true+                    // Re-assert the streamed size: same size as pinned, so+                    // this only (re)applies the transform for it.+                    facadeSnapshot?.let { snapshot ->+                        bridge.setPreviewStream(+                            previewSize, snapshot.sensorOrientationDegrees, lensFacing,+                        )+                    }                 }                  override fun onError(message: String) {@@ -228,6 +253,11 @@ internal class Camera2PreviewSession(         val liveSurface = bridge.state.surface         val cameraId = resolvedCameraId         if (built != null && liveSurface != null && cameraId != null) {+            pinPreviewStream(+                com.vayunmathur.camera.platform.camera2.FrameSize(+                    bridge.state.width, bridge.state.height,+                ),+            )             built.open(                 cameraId = cameraId,                 surface = liveSurface,
camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.ktindex a868c5ffb7..337061aa4d 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt@@ -31,7 +31,7 @@ import com.vayunmathur.library.ui.Text /**  * Codec and audio-device pickers owned by [SettingsPage]: the video codec  * and audio input device dropdowns. The device picker lists physical- * microphones (Auto = system routing, then each connected device); there+ * microphones (only real connected devices; no synthetic default row); there  * is no AudioSource-type or audio-codec picker (recording audio is always  * Opus from the CAMCORDER source). Stateless: the caller passes values  * plus change callbacks.@@ -109,10 +109,11 @@ fun CameraCodecSettings(             // Built from [OutlinedButton] + [DropdownMenu] rather than the library's             // `ExposedDropdownMenu` wrapper, which currently recurses into itself.             var audioExpanded by remember { mutableStateOf(false) }-            // A chosen device that is no longer connected shows as Auto.+            // Only real devices are listed; a chosen device that is no+            // longer connected (or no explicit choice yet) selects no row.             val selectedOption = audioInputDeviceOptions.firstOrNull {                 it.selection == audioInputDevice-            } ?: audioInputDeviceOptions.firstOrNull()+            }             Box(                 modifier = Modifier                     .fillMaxWidth()@@ -123,8 +124,9 @@ fun CameraCodecSettings(                     modifier = Modifier.fillMaxWidth()                 ) {                     Text(-                        listOfNotNull(selectedOption?.label, selectedOption?.description)-                            .joinToString(" — "),+                        selectedOption?.let {+                            listOfNotNull(it.label, it.description).joinToString(" — ")+                        } ?: stringResource(R.string.settings_audio_input_device_unselected),                         modifier = Modifier.weight(1f),                         textAlign = TextAlign.Start,                         maxLines = 1,
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex c2686922bb..d1b3d2f205 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -87,7 +87,7 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM         audioManager?.registerAudioDeviceCallback(callback, null)         onDispose { audioManager?.unregisterAudioDeviceCallback(callback) }     }-    // Effective picker selection: a disconnected chosen device shows as Auto.+    // Effective picker selection: a disconnected chosen device selects no row.     val effectiveAudioDevice = remember(audioDeviceOptions, audioInputDevice) {         com.vayunmathur.camera.platform.camera2.AudioInputDevicePolicy.resolve(             audioInputDevice,
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex bb57c32a2c..0e68944b17 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -108,6 +108,8 @@     <!-- Audio input device settings (SettingsPage): physical mic used for video recordings -->     <!-- SettingsPage: section header for audio input device selection -->     <string name="settings_audio_input_device">Audio input device</string>+    <!-- SettingsPage: audio input button when no device is explicitly chosen; the platform route at record time applies -->+    <string name="settings_audio_input_device_unselected">System route at recording</string>     <!-- SettingsPage (locale fallback): legacy header name kept for translations -->     <string name="settings_audio_source">Audio input device</string> 
camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.ktnew file mode 100644index 0000000000..14ffeb6e7d--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.camera.domain++import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * FILL (centre-crop) transform math: stream aspect vs view aspect vs+ * rotation. The regression is stretch, so every case asserts the+ * no-stretch invariant (both matrix column norms equal the uniform+ * scale) plus the exact crop geometry for the known device pairings.+ */+class PreviewTransformTest {++    private fun compute(+        streamW: Int, streamH: Int, viewW: Int, viewH: Int,+        sensor: Int = 90, display: Int = 0, facing: LensFacing? = LensFacing.BACK,+    ) = PreviewTransform.compute(streamW, streamH, viewW, viewH, sensor, display, facing)++    @Test fun matchingAspectsFillExactlyWithoutCrop() {+        // Back sensor 90 portrait: 1440x1080 sensor frame displays as+        // 1080x1440 (3:4); a 3:4 box (previewRatioForWindow in portrait)+        // is filled exactly, scale 1 after the 90-degree rotation.+        val t = assertNotNull(compute(1440, 1080, 1080, 1440))+        assertEquals(90, t.rotationDegrees)+        assertEquals(0.75f, t.displayedAspect, 0.001f)+        assertEquals(1f, t.scale, 0.001f)+        assertTrue(PreviewTransform.isUniformScale(t))+        // Buffer corners land on view corners (no crop, no letterbox).+        assertEquals(1080f to 0f, t.map(0f, 0f).let { (x, y) -> x to y })+        val (x, y) = t.map(1440f, 1080f)+        assertEquals(0f, x, 0.001f)+        assertEquals(1440f, y, 0.001f)+    }++    @Test fun narrowerBoxCentreCropsUniformlyNeverStretches() {+        // Same 3:4 displayed stream into a 9:16 still-crop box+        // (1080x1920): FILL scales by max(1, 1920/1440)=4/3 uniformly and+        // crops the sides symmetrically. The old no-transform path scaled+        // x by 1080/1440 and y by 1920/1080 — different factors (stretch).+        val t = assertNotNull(compute(1440, 1080, 1080, 1920))+        assertEquals(4f / 3f, t.scale, 0.001f)+        assertTrue(PreviewTransform.isUniformScale(t))+        // Displayed stream after scale is 1440x1920: 180 px cropped per side.+        val (left, _) = t.map(720f, 540f) // buffer centre stays view centre+        assertEquals(540f, left, 0.001f)+        val (topLeftX, topLeftY) = t.map(0f, 0f)+        assertEquals(1260f, topLeftX, 0.001f) // 540 + 4/3*540, rotated frame+        assertEquals(0f, topLeftY, 0.001f)+        assertTrue(abs(t.a) + abs(t.d) > 0f)+    }++    @Test fun landscapeDisplayRotationUnswapsAspect() {+        // Display rotated 90 (landscape window): relative rotation 0, the+        // 16:9 stream displays unswapped and fills a 16:9 box exactly.+        val t = assertNotNull(compute(1920, 1080, 1920, 1080, display = 90))+        assertEquals(0, t.rotationDegrees)+        assertEquals(16f / 9f, t.displayedAspect, 0.001f)+        assertEquals(1f, t.scale, 0.001f)+        assertTrue(PreviewTransform.isUniformScale(t))+        assertEquals(0f to 0f, t.map(0f, 0f))+        assertEquals(1920f to 1080f, t.map(1920f, 1080f))+    }++    @Test fun frontLensUsesFrontRotationFormula() {+        // Front sensor 270 portrait: relative 270, aspect swaps like back.+        val t = assertNotNull(+            compute(1440, 1080, 1080, 1440, sensor = 270, facing = LensFacing.FRONT),+        )+        assertEquals(270, t.rotationDegrees)+        assertEquals(0.75f, t.displayedAspect, 0.001f)+        assertTrue(PreviewTransform.isUniformScale(t))+        // Centre invariant holds for every rotation.+        val (cx, cy) = t.map(720f, 540f)+        assertEquals(540f, cx, 0.001f)+        assertEquals(720f, cy, 0.001f)+    }++    @Test fun everyRotationKeepsCentreAndUniformScale() {+        for (display in listOf(0, 90, 180, 270)) {+            val t = assertNotNull(compute(1920, 1080, 1000, 1400, display = display))+            assertTrue(PreviewTransform.isUniformScale(t), "display=$display")+            val (cx, cy) = t.map(960f, 540f)+            assertEquals(500f, cx, 0.001f)+            assertEquals(700f, cy, 0.001f)+            // Fill: the scaled displayed frame covers the view on both axes.+            assertTrue(t.scale * t.displayedWidth >= 1000f - 0.01f)+            assertTrue(t.scale * t.displayedHeight >= 1400f - 0.01f)+        }+    }++    @Test fun degenerateSizesHaveNoTransform() {+        assertNull(compute(0, 1080, 1080, 1440))+        assertNull(compute(1440, 1080, 0, 1440))+        assertNull(compute(1440, 1080, 1080, 0))+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.ktindex 8e67ec372d..f647af61ee 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt@@ -8,9 +8,9 @@ import kotlin.test.assertNull import kotlin.test.assertTrue  /**- * Physical audio input devices: type->label mapping, the Auto-first- * picker list, preferred-device application through a fake seam, and- * stale/disconnected fallback to Auto.+ * Physical audio input devices: type->label mapping, one picker row per+ * physical device (duplicate platform ports grouped), preferred-device+ * application through a fake seam, and stale/disconnected fallback.  */ class AudioInputDevicesTest { @@ -22,7 +22,7 @@ class AudioInputDevicesTest {      @Test fun typeLabelsMapToPhysicalDevices() {         assertEquals("Built-in microphone", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_BUILTIN_MIC))-        assertEquals("USB device", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_USB_DEVICE))+        assertEquals("USB microphone", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_USB_DEVICE))         assertEquals("USB headset", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_USB_HEADSET))         assertEquals("Bluetooth headset", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_BLUETOOTH_SCO))         assertEquals("Bluetooth LE headset", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_BLE_HEADSET))@@ -37,17 +37,119 @@ class AudioInputDevicesTest {         assertEquals("USB headset", AudioInputDevicePolicy.labelFor(usbNoName.type, usbNoName.productName))     } -    @Test fun optionsAreAutoFirstThenDevicesById() {+    @Test fun optionsListOnlyRealDevicesInEnumerationOrder() {         val options = AudioInputDevicePolicy.options(listOf(builtin, usb, bluetooth))-        assertEquals(4, options.size)-        assertTrue(options[0].selection.isAuto)-        assertEquals(AudioInputDevicePolicy.AUTO_LABEL, options[0].label)-        assertEquals(AudioInputDeviceSelection(1, builtin.type), options[1].selection)-        assertEquals("USB Mic Pro", options[2].label)-        assertEquals("USB device", options[2].description)-        assertEquals("Bluetooth headset", options[3].label)-        // No devices: the picker is just Auto.-        assertEquals(1, AudioInputDevicePolicy.options(emptyList()).size)+        // No synthetic rows: exactly the three real devices, in order.+        assertEquals(3, options.size)+        assertTrue(options.none { it.selection.isAuto })+        assertEquals(AudioInputDeviceSelection(1, builtin.type), options[0].selection)+        assertEquals("USB Mic Pro", options[1].label)+        assertEquals("USB microphone", options[1].description)+        assertEquals("Bluetooth headset", options[2].label)+        // No devices: the picker is empty, not a synthetic default row.+        assertEquals(0, AudioInputDevicePolicy.options(emptyList()).size)+    }++    @Test fun duplicatePortsOfOnePhysicalDeviceCollapseToOneRow() {+        // A Pixel-class phone reports several built-in mic ports, all with+        // the same product name and no distinguishing address: five ports,+        // one physical device, one row labelled with the name alone.+        val pixelPorts = (10..14).map {+            RawAudioInputDevice(it, AudioDeviceInfo.TYPE_BUILTIN_MIC, "Pixel 9 Pro", "")+        }+        val pixelOptions = AudioInputDevicePolicy.options(pixelPorts)+        assertEquals(1, pixelOptions.size)+        assertEquals("Pixel 9 Pro", pixelOptions[0].label)+        assertFalse(pixelOptions[0].label.first().isDigit())++        // A USB endpoint reported as both a generic USB device and a USB+        // headset (same name + USB address) is one row, represented by the+        // more specific headset port.+        val usbGeneric = RawAudioInputDevice(20, AudioDeviceInfo.TYPE_USB_DEVICE, "USB Mic Pro", "card=1;device=0")+        val usbHeadset = RawAudioInputDevice(21, AudioDeviceInfo.TYPE_USB_HEADSET, "USB Mic Pro", "card=1;device=0")+        val usbOptions = AudioInputDevicePolicy.options(listOf(usbGeneric, usbHeadset))+        assertEquals(1, usbOptions.size)+        assertEquals(AudioInputDeviceSelection(21, AudioDeviceInfo.TYPE_USB_HEADSET), usbOptions[0].selection)+        assertEquals("USB Mic Pro", usbOptions[0].label)+        assertEquals("USB headset", usbOptions[0].description)++        // A Bluetooth endpoint reported as SCO and BLE (same name + MAC)+        // is one row, represented by the BLE port.+        val sco = RawAudioInputDevice(30, AudioDeviceInfo.TYPE_BLUETOOTH_SCO, "Buds", "AA:BB:CC:DD:EE:FF")+        val ble = RawAudioInputDevice(31, AudioDeviceInfo.TYPE_BLE_HEADSET, "Buds", "AA:BB:CC:DD:EE:FF")+        val btOptions = AudioInputDevicePolicy.options(listOf(sco, ble))+        assertEquals(1, btOptions.size)+        assertEquals(AudioInputDeviceSelection(31, AudioDeviceInfo.TYPE_BLE_HEADSET), btOptions[0].selection)+    }++    @Test fun sameNameDevicesAtDistinctAddressesStaySeparateRows() {+        val first = RawAudioInputDevice(20, AudioDeviceInfo.TYPE_USB_DEVICE, "USB Mic Pro", "card=1;device=0")+        val second = RawAudioInputDevice(21, AudioDeviceInfo.TYPE_USB_DEVICE, "USB Mic Pro", "card=2;device=0")+        assertEquals(2, AudioInputDevicePolicy.options(listOf(first, second)).size)+        val btFirst = RawAudioInputDevice(30, AudioDeviceInfo.TYPE_BLUETOOTH_SCO, "Buds", "AA:BB:CC:DD:EE:01")+        val btSecond = RawAudioInputDevice(31, AudioDeviceInfo.TYPE_BLUETOOTH_SCO, "Buds", "AA:BB:CC:DD:EE:02")+        assertEquals(2, AudioInputDevicePolicy.options(listOf(btFirst, btSecond)).size)+        // Unnamed devices of different types are different endpoints, even+        // with no address to distinguish them.+        assertEquals(2, AudioInputDevicePolicy.options(listOf(builtin, wired)).size)+    }++    @Test fun groupLabelUsesAnyPortNameAndNeverAddsAPrefix() {+        // The representative (headset) port reports no name; its duplicate+        // generic port does. The row still gets the real product name.+        val generic = RawAudioInputDevice(20, AudioDeviceInfo.TYPE_USB_DEVICE, "Desk Mic", "card=1;device=0")+        val headset = RawAudioInputDevice(21, AudioDeviceInfo.TYPE_USB_HEADSET, " ", "card=1;device=0")+        val options = AudioInputDevicePolicy.options(listOf(generic, headset))+        assertEquals(1, options.size)+        assertEquals("Desk Mic", options[0].label)+        for (option in AudioInputDevicePolicy.options(listOf(builtin, usb, bluetooth))) {+            assertFalse(option.label.first().isDigit(), option.label)+            assertFalse(option.label.contains(option.selection.deviceId.toString()), option.label)+        }+    }++    @Test fun storedDuplicatePortSelectionResolvesToItsPhysicalGroup() {+        val usbGeneric = RawAudioInputDevice(20, AudioDeviceInfo.TYPE_USB_DEVICE, "USB Mic Pro", "card=1;device=0")+        val usbHeadset = RawAudioInputDevice(21, AudioDeviceInfo.TYPE_USB_HEADSET, "USB Mic Pro", "card=1;device=0")+        val devices = listOf(builtin, usbGeneric, usbHeadset)+        // Stored before grouping, naming the non-representative generic port.+        val stored = AudioInputDeviceSelection(usbGeneric.id, usbGeneric.type)+        assertEquals(+            AudioInputDeviceSelection(usbHeadset.id, usbHeadset.type),+            AudioInputDevicePolicy.resolve(stored, devices),+        )+        // At record start the group resolves back to a live port of the same+        // device, preferring the exact persisted port while it is present.+        val calls = mutableListOf<RawAudioInputDevice?>()+        val result = PreferredAudioDeviceApplication.apply(+            selection = stored,+            devices = devices,+            idOf = { it.id },+            typeOf = { it.type },+            setPreferred = { device -> calls += device; true },+            nameOf = { it.productName },+            addressOf = { it.address },+        )+        assertEquals(AudioInputDeviceSelection(usbHeadset.id, usbHeadset.type), result.selection)+        assertEquals(usbGeneric, result.device)+        assertEquals(listOf<RawAudioInputDevice?>(usbGeneric), calls)+        assertTrue(result.applied)+    }++    @Test fun disconnectedChoiceFallsBackToTheRoutedDeviceAtRecordTime() {+        val calls = mutableListOf<RawAudioInputDevice?>()+        val result = PreferredAudioDeviceApplication.apply(+            selection = AudioInputDeviceSelection(usb.id, usb.type),+            devices = listOf(builtin, wired),+            idOf = { it.id },+            typeOf = { it.type },+            setPreferred = { device -> calls += device; true },+            routedDevice = { builtin },+        )+        // Still a real device: the platform's current routed input.+        assertEquals(AudioInputDeviceSelection(builtin.id, builtin.type), result.selection)+        assertEquals(builtin, result.device)+        assertEquals(listOf<RawAudioInputDevice?>(builtin), calls)     }      @Test fun selectedDeviceIsAppliedThroughTheSeam() {@@ -65,7 +167,7 @@ class AudioInputDevicesTest {         assertEquals(AudioInputDeviceSelection(usb.id, usb.type), result.selection)     } -    @Test fun autoClearsThePreferredDevice() {+    @Test fun noExplicitChoiceClearsThePreferredDevice() {         val calls = mutableListOf<RawAudioInputDevice?>()         val result = PreferredAudioDeviceApplication.apply(             selection = AudioInputDeviceSelection.AUTO,@@ -81,7 +183,7 @@ class AudioInputDevicesTest {      @Test fun disconnectedChosenDeviceFallsBackToAutoSilently() {         // Chosen USB mic is gone (or its id was reused by a different type):-        // resolve and apply both land on Auto instead of failing.+        // resolve and apply both land on no explicit choice instead of failing.         assertEquals(             AudioInputDeviceSelection.AUTO,             AudioInputDevicePolicy.resolve(AudioInputDeviceSelection(usb.id, usb.type), listOf(builtin)),
camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.ktindex 404ce38ec3..9d7f5853af 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt@@ -176,6 +176,28 @@ class StreamSelectionTest {         assertNull(plan.previewMaxPixels)     } +    @Test fun sessionPreviewSizeAppliesLimitedCapAndMatchesSessionSelection() {+        // LIMITED lens with a 4K-class SurfaceTexture size: the session+        // selection (and the surface buffer pin, which uses this same+        // helper) must stay at/under the 1080p guaranteed cap.+        val snapshot = CharacteristicsFacade.fromFakeMap(+            cameraId = "0",+            hardwareLevel = android.hardware.camera2.CameraMetadata+                .INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,+            sizesByFormat = mapOf(ImageFormat.PRIVATE to listOf(Size(640, 480))),+            surfaceTextureSizes = listOf(+                Size(4000, 3000), Size(1920, 1080), Size(1440, 1080), Size(1280, 720),+            ),+        ).snapshot+        // Portrait view request (TextureView in a 3:4 box): no portrait+        // sizes exist, so closest aspect under the cap wins — never 4K.+        val selected = StreamSelection.selectSessionPreviewSize(+            FrameSize(1080, 1440), snapshot,+        )+        assertEquals(FrameSize(1440, 1080), selected)+        assertTrue(selected!!.area.toLong() <= StreamSelection.LIMITED_STREAM_MAX_PIXELS)+    }+     @Test fun supportedSizesPreferSurfaceTextureThenPrivate() {         val withTexture = CharacteristicsFacade.fromFakeMap(             cameraId = "0",
camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.ktindex 0ce2686d4c..41e7ef1896 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt@@ -51,9 +51,9 @@ class CameraCovC2SettingsTest {     }      @Test fun settingsPageSelectsAudioInputDevice() {-        // The picker is a physical-device picker: Auto plus connected-        // devices (only Auto under Robolectric, which has no input-        // hardware), never AudioSource-type labels like "Camcorder".+        // The picker lists only real physical devices (none under+        // Robolectric, which has no input hardware), never a synthetic+        // default row or AudioSource-type labels like "Camcorder".         val viewModel = vm()         val backStack = NavBackStack<TestRoute>(arrayOf(TestRoute.Home))         rule.setContent { SettingsPage(backStack, viewModel) }@@ -68,11 +68,22 @@ class CameraCovC2SettingsTest {             rule.onAllNodesWithText("Camcorder", substring = true).fetchSemanticsNodes().isEmpty(),             "Settings must not offer AudioSource-type choices",         )-        // Open the dropdown by clicking the current (Auto) row and re-pick Auto.-        rule.onNodeWithText("Auto", substring = true).performClick()+        // No synthetic row: with no real devices the button shows the+        // record-time system-route placeholder, and opening it offers no+        // "Auto" (or any other synthetic) entry to pick.+        assertTrue(+            rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes().isEmpty(),+            "Settings must not offer a synthetic Auto audio device",+        )+        rule.onNodeWithText(+            str(com.vayunmathur.camera.R.string.settings_audio_input_device_unselected),+            substring = true,+        ).performClick()         rule.waitForIdle()-        val autos = rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes()-        rule.onAllNodesWithText("Auto", substring = true)[autos.size - 1].performClick()+        assertTrue(+            rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes().isEmpty(),+            "Audio dropdown must contain only real devices",+        )         assertEquals(             com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO,             viewModel.audioInputDevice.value,