Modern Apps git

← Modern-Apps.git

camera: AVIF 4.5x faster, device picker, Motion Photo toggle

Commit
fa605b93e437e7d831cb8b4dbb5651f303d756ed
Author
Vayun Mathur <[email protected]>
When
2026-11-23 15:58 UTC (12 days ago)
Parents
c1fdcfe
Three owner asks.

AVIF encode: ravif speed 8 -> 10 with explicit thread
count is the knee - host 12MP encode 7.6s -> 1.7s at
phone-like threading for -0.06dB PSNR and +3.6% size;
device measures 3.0s encode, ~5s shutter-to-saved vs
~13-14s before. Hardware check: this Pixel exposes NO
image/avif MediaCodec encoder (only video AV1), so
nothing is routed there; the hardware route + Rust EXIF
post-mux are built for devices that ship one, with
software fallback. Saves also leave the shutter path
via a bounded still-save queue.

Audio input is now a physical device picker (Auto/USB/
Bluetooth/built-in from AudioManager, applied via
AudioRecord.setPreferredDevice, disconnect-safe); the
AudioSource-type row is gone.

Motion Photo gains an on/off toggle (default on =
today's behavior); OFF yields plain stills on every
route, the length row hides, and under AVIF the toggle
shows disabled with 'Motion Photo needs JPEG'.

Verified: Rust 164 tests, targeted Kotlin suites,
compile; device AVIF shot saved with Exif.

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 8b8a29e808..1ba2de95de 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt@@ -8,7 +8,7 @@ import androidx.core.net.toUri import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import com.vayunmathur.camera.platform.AspectRatioOption-import com.vayunmathur.camera.platform.AudioInputSource+import com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.CodecSupport import com.vayunmathur.camera.platform.FlashMode@@ -17,6 +17,7 @@ import com.vayunmathur.camera.platform.PhotoFormat import com.vayunmathur.camera.platform.TimerDuration import com.vayunmathur.camera.platform.VideoCodec import com.vayunmathur.camera.platform.applyManualControls+import com.vayunmathur.camera.platform.clearMotionFrames import com.vayunmathur.camera.platform.currentCropAspectRatio import com.vayunmathur.camera.platform.registerLevelSensor import com.vayunmathur.camera.platform.unregisterLevelSensor@@ -27,7 +28,7 @@ internal fun CameraViewModel.loadSettings() {     if (levelEnabledMutable.value) registerLevelSensor() } -/** Flash/timer/aspect/codec/audio-source/save-target/last-capture restores. */+/** Flash/timer/aspect/codec/audio-device/save-target/last-capture restores. */ private fun CameraViewModel.loadCaptureSettings() {     ds.getString("camera_flash")?.let {         runCatching { flashModeMutable.value = FlashMode.valueOf(it) }@@ -49,18 +50,17 @@ private fun CameraViewModel.loadCaptureSettings() {     ds.getString("camera_motion_duration")?.let {         runCatching { motionPhotoDurationMutable.value = MotionPhotoDuration.valueOf(it) }     }-    ds.getString("camera_audio_source")?.let {-        audioInputSourceMutable.value = try {-            AudioInputSource.valueOf(it)-        } catch (_: Exception) {-            AudioInputSource.CAMCORDER-        }+    // Physical input device (id+type), not an AudioSource type. A stale+    // or malformed stored value parses to Auto, never crashes.+    ds.getString("camera_audio_input_device")?.let {+        audioInputDeviceMutable.value = AudioInputDeviceSelection.parse(it)     }-    // Opus-only: the retired audio-codec setting (camera_audio_codec) is-    // never read again — audio encoding is not selectable. Drop any-    // stored value so it cannot linger or be misread later; an unknown-    // or stale value is simply deleted, never parsed.-    viewModelScope.launch { ds.removeKeys(listOf("camera_audio_codec")) }+    // Retired settings are never read again: the AudioSource-type choice+    // (camera_audio_source, e.g. a stale "CAMCORDER"/"MIC" value) and the+    // audio-codec choice (camera_audio_codec; Opus-only). Drop any stored+    // values so they cannot linger or be misread later; they are simply+    // deleted, never parsed.+    viewModelScope.launch { ds.removeKeys(listOf("camera_audio_codec", "camera_audio_source")) }     loadSaveTarget()     // Guard against a blank persisted value: Uri.parse("") yields a non-null     ds.getString("camera_last_capture")?.takeIf { it.isNotBlank() }?.let { lastCaptureUriMutable.value = it.toUri() }@@ -76,6 +76,8 @@ private fun CameraViewModel.loadPreferenceToggles() {     ds.getString("camera_mirror_front")?.let { mirrorFrontMutable.value = it.toBoolean() }     ds.getString("camera_noise_reduction")?.let { noiseReductionEnabledMutable.value = it.toBoolean() }     ds.getString("camera_edge_sharpening")?.let { edgeSharpeningEnabledMutable.value = it.toBoolean() }+    // Absent key keeps the ViewModel default (on), so existing users see no change.+    ds.getString("camera_motion_photo_enabled")?.let { motionPhotoEnabledMutable.value = it.toBoolean() } }  fun CameraViewModel.setFlashMode(mode: FlashMode) {@@ -156,15 +158,27 @@ fun CameraViewModel.setVideoCodec(codec: VideoCodec) {     viewModelScope.launch { ds.setString("camera_video_codec", codec.name) } } +/**+ * Motion Photo on/off. Off takes plain stills always: no capture diversion+ * and no ring-buffer accumulation, whatever the length/ratio/format. Drops+ * any frames buffered while it was on so a later re-enable cannot attach a+ * clip from before the off period.+ */+fun CameraViewModel.setMotionPhotoEnabled(enabled: Boolean) {+    motionPhotoEnabledMutable.value = enabled+    if (!enabled) clearMotionFrames()+    viewModelScope.launch { ds.setString("camera_motion_photo_enabled", enabled.toString()) }+}+ /** Motion-Photo clip length (issue #712); applies to the next capture's ring buffer. */ fun CameraViewModel.setMotionPhotoDuration(duration: MotionPhotoDuration) {     motionPhotoDurationMutable.value = duration     viewModelScope.launch { ds.setString("camera_motion_duration", duration.name) } } -fun CameraViewModel.setAudioInputSource(source: AudioInputSource) {-    audioInputSourceMutable.value = source-    viewModelScope.launch { ds.setString("camera_audio_source", source.name) }+fun CameraViewModel.setAudioInputDevice(selection: AudioInputDeviceSelection) {+    audioInputDeviceMutable.value = selection+    viewModelScope.launch { ds.setString("camera_audio_input_device", selection.encode()) } }  fun CameraViewModel.toggleGrid() {
camera/src/main/java/com/vayunmathur/camera/domain/MotionPhotoEligibility.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/MotionPhotoEligibility.kt b/camera/src/main/java/com/vayunmathur/camera/domain/MotionPhotoEligibility.ktnew file mode 100644index 0000000000..22e47cf0c0--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/MotionPhotoEligibility.kt@@ -0,0 +1,31 @@+package com.vayunmathur.camera.domain++/**+ * Inputs for the Motion Photo diversion, snapshotted at capture time.+ *+ * @property enabled the user's Motion Photo on/off setting. Off means a+ *   plain still always, regardless of every other input.+ * @property plainPhoto a plain PHOTO capture (not another mode, and not+ *   capturing for a caller).+ * @property noBake no warmth/shadows bake is applied to the shot.+ * @property avifPrecludes an effective AVIF selection, which precludes the+ *   diversion because a Motion Photo is a JPEG with an MP4 trailer (see+ *   [StillFormatRouting.avifPrecludesMotionPhoto]).+ * @property nativeFourThree the capture is at the native 4:3 ratio: the+ *   motion still is saved as raw JPEG bytes, which cannot carry a crop, so+ *   other ratios take the single-shot path that saves a cropped JPEG.+ */+data class MotionPhotoInputs(+    val enabled: Boolean,+    val plainPhoto: Boolean,+    val noBake: Boolean,+    val avifPrecludes: Boolean,+    val nativeFourThree: Boolean,+)++/** Pure eligibility for diverting a still to the Motion Photo path. */+object MotionPhotoEligibility {+    fun isEligible(inputs: MotionPhotoInputs): Boolean =+        inputs.enabled && inputs.plainPhoto && inputs.noBake &&+            !inputs.avifPrecludes && inputs.nativeFourThree+}
camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.kt b/camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.ktindex 50f4135b81..e0bbf86f2d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.kt@@ -113,8 +113,8 @@ internal object AvifCodecProbe {             } catch (_: Exception) {                 false             },-            maxWidth = video?.upper?.width,-            maxHeight = video?.upper?.height,+            maxWidth = video?.supportedWidths?.upper,+            maxHeight = video?.supportedHeights?.upper,         )     } }
camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.kt b/camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.ktindex 4c79c49d12..7f61645e40 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.kt@@ -91,7 +91,10 @@ internal object AvifHardwareEncoder {         var codec: MediaCodec? = null         try {             codec = MediaCodec.createByCodecName(codecName)-            val format = MediaFormat.createImageFormat(AVIF_IMAGE_MIME, width, height).apply {+            val format = MediaFormat().apply {+                setString(MediaFormat.KEY_MIME, AVIF_IMAGE_MIME)+                setInteger(MediaFormat.KEY_WIDTH, width)+                setInteger(MediaFormat.KEY_HEIGHT, height)                 setInteger(                     MediaFormat.KEY_COLOR_FORMAT,                     MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible,
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 3c59c93d93..48c985ebc0 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt@@ -38,6 +38,8 @@ class Camera2RecordingCore(     val config: CustomRecordingConfig,     private val initialBitrateBps: () -> Int,     ownership: RecordingSessionOwnership = RecordingSessionOwnership.ENGINE_OWNED,+    /** Live input-device list for [config]'s preferred-device choice (engine-supplied). */+    private val audioInputDevices: () -> List<android.media.AudioDeviceInfo> = { emptyList() }, ) {     val lifecycle = SharedRecordingCoreLifecycle(ownership)     private val encoderHandoff = EncoderSurfaceHandoff()@@ -303,6 +305,8 @@ class Camera2RecordingCore(         }         @SuppressLint("MissingPermission")         val record = AudioRecord(+            // Internal source is always CAMCORDER for video; the user's+            // choice is the physical device below, never this source type.             MediaRecorder.AudioSource.CAMCORDER,             config.audioSampleRate,             AudioFormat.CHANNEL_IN_MONO,@@ -310,6 +314,25 @@ 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+        // 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+        // below just keeps running.+        val applied = com.vayunmathur.camera.platform.camera2.PreferredAudioDeviceApplication.apply(+            selection = config.audioInputDevice,+            devices = runCatching { audioInputDevices() }.getOrDefault(emptyList()),+            idOf = { it.id },+            typeOf = { it.type },+            setPreferred = { device -> record.setPreferredDevice(device) },+        )+        if (!applied.selection.isAuto && !applied.applied) {+            Log.status(+                "Camera2Recorder",+                "Preferred audio input unavailable; recording on the system-routed input",+            )+        }         record.startRecording()         audioThread = Thread({             val chunk = ByteArray(AUDIO_CHUNK_BYTES)
camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.ktindex d9be615fb6..31544efb55 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -71,19 +71,13 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean {         hasJpegOutput = session.hasJpegOutput,         nightRoute = nightPreviewActiveMutable.value || nightCaptureApplies(),         processedRoute = warmthMutable.value != 0f || shadowsMutable.value != 0f,-        // Mirrors the (private) Motion Photo eligibility in CameraPhotoCapture:-        // a plain 4:3 PHOTO shot with no bake would route to Motion Photo.-        // An effective AVIF selection precludes that diversion (a Motion-        // Photo is a JPEG+MP4 trailer): the plain Camera2 still is taken-        // and encoded to .avif instead. The format is read here, at-        // capture time, so a settings change after bind is honoured.-        motionPhotoRoute = cameraModeMutable.value == CameraMode.PHOTO &&-            !captureForResult &&-            warmthMutable.value == 0f && shadowsMutable.value == 0f &&-            aspectRatioMutable.value == AspectRatioOption.RATIO_4_3 &&-            !StillFormatRouting.avifPrecludesMotionPhoto(-                requestedStillFormat(), StitchNative.isAvailable,-            ),+        // The shared Motion Photo eligibility (CameraPhotoCapture): a plain+        // 4:3 PHOTO shot with no bake, the user's toggle on, and no effective+        // AVIF selection would route to Motion Photo, so it is excluded from+        // the direct Camera2 still. Read at capture time via+        // [motionPhotoEligible], so a settings change after bind is honoured+        // exactly as on the other route.+        motionPhotoRoute = motionPhotoEligible(),         captureForResult = captureForResult,         burst = burstActiveMutable.value,     )
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 85496c1d2a..16def9115f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -45,6 +45,13 @@ data class CustomRecordingConfig(      * state when no Opus encoder exists (see [AudioEncoderPolicy]).      */     val audioEnabled: Boolean = true,+    /**+     * Physical microphone to prefer (Auto = system routing). Applied to+     * the AudioRecord via `setPreferredDevice` in the recording core; the+     * internal AudioSource stays CAMCORDER regardless of this choice.+     */+    val audioInputDevice: com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection =+        com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO, )  /** Read-back summary of a finished file (see [Camera2VideoRecordingEngine.validateOutput]). */@@ -127,6 +134,9 @@ class Camera2VideoRecordingEngine(         config,         initialBitrateBps = { controller.currentBitrateBps },         ownership = RecordingSessionOwnership.ENGINE_OWNED,+        audioInputDevices = {+            com.vayunmathur.camera.platform.camera2.AudioInputDevices.enumerateInfos(context)+        },     )      @Volatile private var running = false
camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.ktindex f0b8741fd7..b04e42ec4b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -174,21 +174,27 @@ internal fun CameraViewModel.stillCaptureIsZsl(): Boolean =  * Only at the native 4:3 ratio: the motion still is saved as raw JPEG bytes (to preserve the  * Ultra HDR gain map + motion trailer), which can't carry CameraX's crop. For other ratios the  * single-shot path saves a cropped JPEG.+ *+ * The user's on/off setting gates first (off = plain stills always), and an+ * effective AVIF selection precludes the diversion (a Motion Photo is a JPEG+ * with an MP4 trailer): without that check a plain shot silently landed as+ * .jpg whatever the format setting said. Both this router and the Camera2+ * route in [tryCaptureCamera2Still] call this, so the decision is read once,+ * at capture time, on every route.  */-private fun CameraViewModel.motionPhotoEligible(): Boolean {-    val plainPhoto = cameraModeMutable.value == CameraMode.PHOTO && !captureForResult-    val noBake = warmthMutable.value == 0f && shadowsMutable.value == 0f-    // An effective AVIF selection precludes the Motion Photo diversion on-    // the CameraX path too (a Motion Photo is a JPEG with an MP4 trailer):-    // without this check a CameraX-served plain shot (Camera2 fallback-    // latch, gate off) silently landed as .jpg whatever the setting said.-    // The Camera2 path already applies the same check in-    // tryCaptureCamera2Still; the format is read here, at capture time.+internal fun CameraViewModel.motionPhotoEligible(): Boolean {     val avifPrecludes = com.vayunmathur.camera.domain.StillFormatRouting.avifPrecludesMotionPhoto(         requestedStillFormat(), StitchNative.isAvailable,     )-    return plainPhoto && noBake && !avifPrecludes &&-        aspectRatioMutable.value == AspectRatioOption.RATIO_4_3+    return com.vayunmathur.camera.domain.MotionPhotoEligibility.isEligible(+        com.vayunmathur.camera.domain.MotionPhotoInputs(+            enabled = motionPhotoEnabledMutable.value,+            plainPhoto = cameraModeMutable.value == CameraMode.PHOTO && !captureForResult,+            noBake = warmthMutable.value == 0f && shadowsMutable.value == 0f,+            avifPrecludes = avifPrecludes,+            nativeFourThree = aspectRatioMutable.value == AspectRatioOption.RATIO_4_3,+        )+    ) }  /**@@ -283,6 +289,12 @@ fun CameraViewModel.stopBurst() {  /** Appends an analysis frame to the Motion-Photo ring buffer, trimming by age then count. */ fun CameraViewModel.addMotionFrame(bitmap: Bitmap, timestampNanos: Long, rotationDegrees: Int) {+    // Motion Photo off: buffer nothing. This call takes ownership of the+    // bitmap, so recycle it rather than leak it.+    if (!motionPhotoEnabledMutable.value) {+        bitmap.recycle()+        return+    }     synchronized(motionLock) {         motionFrames.addLast(CameraViewModel.MotionFrame(bitmap, timestampNanos, rotationDegrees))         val windowNanos = motionPhotoDurationMutable.value.seconds * 1_000_000_000L
camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.ktindex 9d081a960f..8b6a1011a1 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -192,6 +192,8 @@ internal fun CameraViewModel.startRecording() {         fps = 30,         videoMime = mime,         audioEnabled = audioEnabled,+        // Physical mic from the bind-time snapshot (held during a take).+        audioInputDevice = bindTimeSettings.value.audioInputDevice,     )     val controller = com.vayunmathur.camera.domain.LiveBitrateController(decision)     val engine = Camera2VideoRecordingEngine(
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.ktindex a1be970c83..432f119c52 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -216,8 +216,14 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     internal val motionPhotoDurationMutable = MutableStateFlow(MotionPhotoDuration.THREE)     val motionPhotoDuration = motionPhotoDurationMutable.asStateFlow() -    internal val audioInputSourceMutable = MutableStateFlow(AudioInputSource.CAMCORDER)-    val audioInputSource = audioInputSourceMutable.asStateFlow()+    // Motion Photo on/off. Default on preserves the pre-toggle behaviour:+    // eligible plain stills diverted to Motion Photo with no explicit opt-in.+    internal val motionPhotoEnabledMutable = MutableStateFlow(true)+    val motionPhotoEnabled = motionPhotoEnabledMutable.asStateFlow()++    internal val audioInputDeviceMutable =+        MutableStateFlow(com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO)+    val audioInputDevice = audioInputDeviceMutable.asStateFlow()      // No recording audio-codec state: audio is always Opus     // (AudioEncoderPolicy), with a video-only recording when a device@@ -408,11 +414,11 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {      /** The user's chosen bind-time settings, before any recording deferral. */     private val desiredBindSettings = combine(-        videoCodecMutable, audioInputSourceMutable, mirrorFrontMutable-    ) { video, source, mirror -> BindTimeSettings(video, source, mirror) }+        videoCodecMutable, audioInputDeviceMutable, mirrorFrontMutable+    ) { video, device, mirror -> BindTimeSettings(video, device, mirror) }      /**-     * The bind-time settings a session bind must actually use. Codec, audio source and+     * The bind-time settings a session bind must actually use. Codec, audio input device and      * mirroring are fixed when the Recorder/VideoCapture is built, so changing them used      * to rebind the session mid-recording: teardown stopped the active recording with no      * warning and the user lost the take believing it continued. While recording, this@@ -426,13 +432,15 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     }         .runningFold(             BindTimeSettings(-                CodecSupport.defaultVideoCodec, AudioInputSource.CAMCORDER, true+                CodecSupport.defaultVideoCodec,+                com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO, true             )         ) { held, gate -> if (gate.recording) held else gate.settings }         .stateIn(             viewModelScope, SharingStarted.Eagerly,             BindTimeSettings(-                CodecSupport.defaultVideoCodec, AudioInputSource.CAMCORDER, true+                CodecSupport.defaultVideoCodec,+                com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO, true             )         ) 
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.ktindex 81414d08ed..0eb696b451 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -2,7 +2,6 @@ package com.vayunmathur.camera.platform  import android.graphics.ColorMatrix import androidx.annotation.StringRes-import android.media.MediaRecorder import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry@@ -58,35 +57,13 @@ enum class MotionPhotoDuration(val seconds: Int) {     THREE(MOTION_THREE_SECONDS),     FIVE(MOTION_FIVE_SECONDS), }-/** Audio input sources selectable for video recording. */-enum class AudioInputSource(-    @StringRes val labelRes: Int,-    @StringRes val descriptionRes: Int,-    val specValue: Int,-) {-    CAMCORDER(-        R.string.audio_source_camcorder_label,-        R.string.audio_source_camcorder_description,-        MediaRecorder.AudioSource.CAMCORDER-    ),-    MIC(R.string.audio_source_mic_label, R.string.audio_source_mic_description, MediaRecorder.AudioSource.MIC),-    VOICE_COMMUNICATION(-        R.string.audio_source_voice_communication_label,-        R.string.audio_source_voice_communication_description,-        MediaRecorder.AudioSource.VOICE_COMMUNICATION-    ),-    UNPROCESSED(-        R.string.audio_source_unprocessed_label,-        R.string.audio_source_unprocessed_description,-        MediaRecorder.AudioSource.UNPROCESSED-    ),-}- /**- * The bind-time recording settings snapshot: video codec, audio source and- * front mirroring are baked into the recording engine when the session binds- * and cannot change mid-recording. (Audio is always Opus — see- * AudioEncoderPolicy — so there is no audio-codec value to snapshot.)+ * The bind-time recording settings snapshot: video codec, audio input+ * device and front mirroring are baked into the recording engine when the+ * session binds and cannot change mid-recording. (Audio is always Opus —+ * see AudioEncoderPolicy — so there is no audio-codec value to snapshot.+ * The internal `MediaRecorder.AudioSource` is always CAMCORDER for video;+ * [audioInputDevice] only picks the physical microphone feeding it.)  * The user's chosen (desired) values live in the individual  * CameraViewModel flows and persist immediately; this snapshot is what  * a bind actually uses, held unchanged while a recording is in progress and@@ -94,7 +71,8 @@ enum class AudioInputSource(  */ data class BindTimeSettings(     val videoCodec: VideoCodec,-    val audioInputSource: AudioInputSource,+    val audioInputDevice: com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection =+        com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO,     val mirrorFront: Boolean, ) 
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.ktnew file mode 100644index 0000000000..4a39bb77f3--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioInputDevices.kt@@ -0,0 +1,170 @@+package com.vayunmathur.camera.platform.camera2++import android.content.Context+import android.media.AudioDeviceInfo+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.+ *+ * 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).+ */+data class AudioInputDeviceSelection(val deviceId: Int? = null, val deviceType: Int? = null) {+    val isAuto: Boolean get() = deviceId == null++    /** Storage form: `auto` or `<id>:<type>`. */+    fun encode(): String = if (isAuto) ENCODED_AUTO else "$deviceId:$deviceType"++    companion object {+        val AUTO = AudioInputDeviceSelection()+        private const val ENCODED_AUTO = "auto"++        /**+         * Parses a stored value. Anything that is not a well-formed+         * `<id>:<type>` pair — including stale values from the retired+         * AudioSource-type setting (`CAMCORDER`, `MIC`, ...) — falls back+         * to [AUTO] instead of crashing.+         */+        fun parse(stored: String?): AudioInputDeviceSelection {+            if (stored.isNullOrBlank() || stored == ENCODED_AUTO) return AUTO+            val parts = stored.split(":")+            if (parts.size != 2) return AUTO+            val id = parts[0].toIntOrNull() ?: return AUTO+            val type = parts[1].toIntOrNull() ?: return AUTO+            return AudioInputDeviceSelection(id, type)+        }+    }+}++/** Platform-neutral snapshot of one connected input device (for mapping/tests). */+data class RawAudioInputDevice(val id: Int, val type: Int, val productName: String?)++/** One row in the input-device picker: Auto first, then connected devices. */+data class AudioInputDeviceOption(+    val selection: AudioInputDeviceSelection,+    val label: String,+    val description: String? = null,+)++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)++    fun typeLabel(type: Int): String = when (type) {+        AudioDeviceInfo.TYPE_BUILTIN_MIC -> "Built-in microphone"+        AudioDeviceInfo.TYPE_USB_DEVICE -> "USB device"+        AudioDeviceInfo.TYPE_USB_HEADSET -> "USB headset"+        AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> "Bluetooth headset"+        AudioDeviceInfo.TYPE_BLE_HEADSET -> "Bluetooth LE headset"+        AudioDeviceInfo.TYPE_WIRED_HEADSET -> "Wired headset"+        AudioDeviceInfo.TYPE_WIRED_HEADPHONES -> "Wired headphones"+        AudioDeviceInfo.TYPE_TELEPHONY -> "Telephony"+        AudioDeviceInfo.TYPE_FM_TUNER -> "FM tuner"+        else -> "Microphone"+    }++    /** Picker rows: Auto (system routing) plus each connected input device. */+    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)+            AudioInputDeviceOption(+                selection = AudioInputDeviceSelection(device.id, device.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.+     */+    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+    }+}++/**+ * Applies a selection to a recorder through a [setPreferred] seam (the+ * recorder's `setPreferredDevice`, which returns false when the device+ * cannot be used). Generic over the device handle so unit tests can drive+ * 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.+ */+data class AppliedPreferredDevice<T>(+    val selection: AudioInputDeviceSelection,+    val device: T?,+    val applied: Boolean,+)++object PreferredAudioDeviceApplication {+    fun <T> apply(+        selection: AudioInputDeviceSelection,+        devices: List<T>,+        idOf: (T) -> Int,+        typeOf: (T) -> Int,+        setPreferred: (T?) -> Boolean,+    ): AppliedPreferredDevice<T> {+        val resolved = AudioInputDevicePolicy.resolve(+            selection,+            devices.map { RawAudioInputDevice(idOf(it), typeOf(it), null) },+        )+        val target = if (resolved.isAuto) {+            null+        } else {+            devices.firstOrNull { idOf(it) == resolved.deviceId && typeOf(it) == resolved.deviceType }+        }+        val applied = runCatching { setPreferred(target) }.getOrDefault(false)+        return AppliedPreferredDevice(resolved, target, applied)+    }+}++/** Enumerates physical input devices via [AudioManager]. */+object AudioInputDevices {+    fun enumerateInfos(context: Context): List<AudioDeviceInfo> {+        val manager = context.getSystemService(AudioManager::class.java) ?: return emptyList()+        return runCatching {+            manager.getDevices(AudioManager.GET_DEVICES_INPUTS).filter { it.isSource }+        }.getOrDefault(emptyList())+    }++    fun enumerate(context: Context): List<RawAudioInputDevice> =+        enumerateInfos(context).map { it.toRaw() }++    fun options(context: Context): List<AudioInputDeviceOption> =+        AudioInputDevicePolicy.options(enumerate(context))++    /** The currently-effective selection (disconnected choice -> Auto). */+    fun resolve(context: Context, selection: AudioInputDeviceSelection): AudioInputDeviceSelection =+        AudioInputDevicePolicy.resolve(selection, enumerate(context))+}++fun AudioDeviceInfo.toRaw(): RawAudioInputDevice =+    RawAudioInputDevice(id = id, type = type, productName = productName?.toString())
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 397945cf5b..a868c5ffb7 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt@@ -15,7 +15,8 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.camera.R-import com.vayunmathur.camera.platform.AudioInputSource+import com.vayunmathur.camera.platform.camera2.AudioInputDeviceOption+import com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection import com.vayunmathur.camera.platform.CodecSupport import com.vayunmathur.camera.platform.VideoCodec import com.vayunmathur.library.ui.DropdownMenu@@ -28,17 +29,20 @@ import com.vayunmathur.library.ui.SettingsSection import com.vayunmathur.library.ui.Text  /**- * Codec and audio-source pickers owned by [SettingsPage]: the video codec- * and audio input source dropdowns. (There is no audio-codec picker:- * recording audio is always Opus.) Stateless: the caller passes values+ * 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+ * 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.  */ @Composable fun CameraCodecSettings(     videoCodec: VideoCodec,-    audioInputSource: AudioInputSource,+    audioInputDevice: AudioInputDeviceSelection,+    audioInputDeviceOptions: List<AudioInputDeviceOption>,     onVideoCodecChange: (VideoCodec) -> Unit,-    onAudioInputSourceChange: (AudioInputSource) -> Unit,+    onAudioInputDeviceChange: (AudioInputDeviceSelection) -> Unit,     modifier: Modifier = Modifier, ) {     Column(modifier = modifier) {@@ -101,10 +105,14 @@ fun CameraCodecSettings(             }         } -        SettingsSection(title = stringResource(R.string.settings_audio_source)) {+        SettingsSection(title = stringResource(R.string.settings_audio_input_device)) {             // 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.+            val selectedOption = audioInputDeviceOptions.firstOrNull {+                it.selection == audioInputDevice+            } ?: audioInputDeviceOptions.firstOrNull()             Box(                 modifier = Modifier                     .fillMaxWidth()@@ -115,7 +123,8 @@ fun CameraCodecSettings(                     modifier = Modifier.fillMaxWidth()                 ) {                     Text(-                        "${stringResource(audioInputSource.labelRes)} — ${stringResource(audioInputSource.descriptionRes)}",+                        listOfNotNull(selectedOption?.label, selectedOption?.description)+                            .joinToString(" — "),                         modifier = Modifier.weight(1f),                         textAlign = TextAlign.Start,                         maxLines = 1,@@ -127,21 +136,23 @@ fun CameraCodecSettings(                     expanded = audioExpanded,                     onDismissRequest = { audioExpanded = false }                 ) {-                    AudioInputSource.entries.forEach { source ->+                    audioInputDeviceOptions.forEach { option ->                         SelectableDropdownMenuItem(-                            selected = source == audioInputSource,+                            selected = option.selection == selectedOption?.selection,                             onClick = {-                                onAudioInputSourceChange(source)+                                onAudioInputDeviceChange(option.selection)                                 audioExpanded = false                             },                             text = {                                 Column {-                                    Text(stringResource(source.labelRes))-                                    Text(-                                        stringResource(source.descriptionRes),-                                        style = MaterialTheme.typography.bodySmall,-                                        color = MaterialTheme.colorScheme.onSurfaceVariant-                                    )+                                    Text(option.label)+                                    option.description?.let { description ->+                                        Text(+                                            description,+                                            style = MaterialTheme.typography.bodySmall,+                                            color = MaterialTheme.colorScheme.onSurfaceVariant+                                        )+                                    }                                 }                             },                             selectedLeadingIcon = { IconCheck() },
camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.ktindex c90d842c5a..e126dd6747 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt@@ -28,16 +28,25 @@ import com.vayunmathur.library.ui.Text  /**  * Post-processing settings rows owned by [SettingsPage]: the noise-reduction and- * edge-sharpening toggles (issue #662) plus the Motion-Photo clip-length picker- * (issue #712). Stateless: the caller passes values plus change callbacks.+ * edge-sharpening toggles (issue #662) plus the Motion Photo on/off toggle and+ * clip-length picker (issue #712). Stateless: the caller passes values plus+ * change callbacks.+ *+ * [motionPhotoBlockedByAvif] is an effective AVIF selection: a Motion Photo is+ * a JPEG with an MP4 trailer, so the toggle renders disabled with that reason+ * (its stored value is kept) and captures stay plain stills. The clip-length+ * picker only shows while Motion Photo is on.  */ @Composable fun CameraPostProcessingSettings(     noiseReductionEnabled: Boolean,     edgeSharpeningEnabled: Boolean,+    motionPhotoEnabled: Boolean,     motionPhotoDuration: MotionPhotoDuration,+    motionPhotoBlockedByAvif: Boolean,     onNoiseReductionChange: (Boolean) -> Unit,     onEdgeSharpeningChange: (Boolean) -> Unit,+    onMotionPhotoEnabledChange: (Boolean) -> Unit,     onMotionDurationChange: (MotionPhotoDuration) -> Unit,     modifier: Modifier = Modifier, ) {@@ -58,6 +67,21 @@ fun CameraPostProcessingSettings(             )         } +        SettingsSection(title = stringResource(R.string.settings_motion_photo)) {+            SettingsSwitchRow(+                title = stringResource(R.string.settings_motion_photo_description),+                supportingText = if (motionPhotoBlockedByAvif) {+                    stringResource(R.string.settings_motion_photo_requires_jpeg)+                } else {+                    null+                },+                checked = motionPhotoEnabled,+                enabled = !motionPhotoBlockedByAvif,+                onCheckedChange = onMotionPhotoEnabledChange,+            )+        }++        if (motionPhotoEnabled) {         SettingsSection(title = stringResource(R.string.settings_motion_duration)) {             // Built from [OutlinedButton] + [DropdownMenu] like the codec/audio pickers             // in SettingsPage, rather than the library's `ExposedDropdownMenu` wrapper,@@ -101,6 +125,7 @@ fun CameraPostProcessingSettings(                 }             }         }+        }     } } 
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex f0cd53a236..2df0396488 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -237,7 +237,7 @@ internal fun CameraScreenEffects(     // backgrounded and rebound on resume. Without this the ManualLifecycleOwner stays RESUMED,     // the OS reclaims the camera while we're away, and the preview comes back frozen.     val lifecycleOwner = LocalLifecycleOwner.current-    // Codec/audio/mirror are fixed at bind time (Recorder mime, AudioSource, MirrorMode), so+    // Codec/audio-device/mirror are fixed at bind time (Recorder mime, preferred device, MirrorMode), so     // they join the effect keys: changing them in Settings rebinds instead of silently waiting     // for the next mode switch. The keys are the APPLIED snapshot (bindTimeSettings), not the     // live desired values: while recording the snapshot is held, so a Settings change made
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex 2eb6264287..42315c9c41 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -6,7 +6,7 @@ import androidx.compose.runtime.MutableIntState import androidx.compose.runtime.MutableState import androidx.compose.runtime.setValue import com.vayunmathur.camera.platform.AspectRatioOption-import com.vayunmathur.camera.platform.AudioInputSource+import com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection import com.vayunmathur.camera.platform.CameraMode import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.FlashMode@@ -30,7 +30,7 @@ import com.vayunmathur.camera.platform.VideoCodec     val flashMode: FlashMode,     val torchEnabled: Boolean,     val videoCodec: VideoCodec,-    val audioInputSource: AudioInputSource,+    val audioInputDevice: AudioInputDeviceSelection,     val isRecording: Boolean,     val recordingDuration: Long,     val timerCountdown: Int,
camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.ktindex ca1ff5b441..507fe3718b 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt@@ -24,7 +24,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen     val flashMode by viewModel.flashMode.collectAsState()     val torchEnabled by viewModel.torchEnabled.collectAsState()     val videoCodec by viewModel.videoCodec.collectAsState()-    val audioInputSource by viewModel.audioInputSource.collectAsState()+    val audioInputDevice by viewModel.audioInputDevice.collectAsState()     val isRecording by viewModel.isRecording.collectAsState()     val recordingDuration by viewModel.recordingDurationSec.collectAsState()     val timerCountdown by viewModel.timerCountdown.collectAsState()@@ -86,7 +86,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen     val deviceRotationState = remember { mutableIntStateOf(0) }      return remember(-        cameraMode, lensFacing, selectedLens, availableLenses, hasFlashUnit, flashMode, torchEnabled, videoCodec, audioInputSource, mirrorFront, isRecording, recordingDuration,+        cameraMode, lensFacing, selectedLens, availableLenses, hasFlashUnit, flashMode, torchEnabled, videoCodec, audioInputDevice, mirrorFront, isRecording, recordingDuration,         timerCountdown, qrResult, aspectRatio, zoomRatio, timerDuration,         isCapturing, burstActive, burstCount, focusLocked, recordingPaused, micMuted,         videoSnapshotSupported, lastCaptureUri, gridEnabled, levelEnabled, roll,@@ -109,7 +109,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen             flashMode = flashMode,             torchEnabled = torchEnabled,             videoCodec = videoCodec,-            audioInputSource = audioInputSource,+            audioInputDevice = audioInputDevice,             isRecording = isRecording,             recordingDuration = recordingDuration,             timerCountdown = timerCountdown,
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 e2796df8e7..c2686922bb 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -32,14 +32,16 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.camera.R import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.MotionPhotoDuration+import com.vayunmathur.camera.platform.requestedStillFormat import com.vayunmathur.camera.data.SafDocuments import com.vayunmathur.camera.data.SaveTarget import com.vayunmathur.camera.data.clearSaveTreeUri-import com.vayunmathur.camera.data.setAudioInputSource+import com.vayunmathur.camera.data.setAudioInputDevice import com.vayunmathur.camera.data.setEdgeSharpeningEnabled import com.vayunmathur.camera.data.setLocationEnabled import com.vayunmathur.camera.data.setMirrorFront import com.vayunmathur.camera.data.setMotionPhotoDuration+import com.vayunmathur.camera.data.setMotionPhotoEnabled import com.vayunmathur.camera.data.setNoiseReductionEnabled import com.vayunmathur.camera.data.setSaveTreeUri import com.vayunmathur.camera.data.setPhotoFormat@@ -58,13 +60,40 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM     val locationEnabled by viewModel.locationEnabled.collectAsState()     val videoCodec by viewModel.videoCodec.collectAsState()     val photoFormat by viewModel.photoFormat.collectAsState()-    val audioInputSource by viewModel.audioInputSource.collectAsState()+    val audioInputDevice by viewModel.audioInputDevice.collectAsState()     val mirrorFront by viewModel.mirrorFront.collectAsState()     val noiseReductionEnabled by viewModel.noiseReductionEnabled.collectAsState()     val edgeSharpeningEnabled by viewModel.edgeSharpeningEnabled.collectAsState()     val motionPhotoDuration by viewModel.motionPhotoDuration.collectAsState()+    val motionPhotoEnabled by viewModel.motionPhotoEnabled.collectAsState()     val saveTarget by viewModel.saveTarget.collectAsState()     val context = LocalContext.current+    // Physical input devices, refreshed when devices connect/disconnect.+    var audioDeviceOptions by remember {+        mutableStateOf(com.vayunmathur.camera.platform.camera2.AudioInputDevices.options(context))+    }+    androidx.compose.runtime.DisposableEffect(context) {+        val audioManager = context.getSystemService(android.media.AudioManager::class.java)+        val callback = object : android.media.AudioDeviceCallback() {+            override fun onAudioDevicesAdded(addedDevices: Array<out android.media.AudioDeviceInfo>?) {+                audioDeviceOptions =+                    com.vayunmathur.camera.platform.camera2.AudioInputDevices.options(context)+            }+            override fun onAudioDevicesRemoved(removedDevices: Array<out android.media.AudioDeviceInfo>?) {+                audioDeviceOptions =+                    com.vayunmathur.camera.platform.camera2.AudioInputDevices.options(context)+            }+        }+        audioManager?.registerAudioDeviceCallback(callback, null)+        onDispose { audioManager?.unregisterAudioDeviceCallback(callback) }+    }+    // Effective picker selection: a disconnected chosen device shows as Auto.+    val effectiveAudioDevice = remember(audioDeviceOptions, audioInputDevice) {+        com.vayunmathur.camera.platform.camera2.AudioInputDevicePolicy.resolve(+            audioInputDevice,+            com.vayunmathur.camera.platform.camera2.AudioInputDevices.enumerate(context),+        )+    }     val messenger = rememberMessenger()     val saveLocationError = stringResource(R.string.settings_save_location_error)     // Bind-time settings (codec/audio/mirror) changed mid-recording are persisted@@ -139,9 +168,10 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM             )             CameraCodecSettings(                 videoCodec = videoCodec,-                audioInputSource = audioInputSource,+                audioInputDevice = effectiveAudioDevice,+                audioInputDeviceOptions = audioDeviceOptions,                 onVideoCodecChange = { viewModel.setVideoCodec(it); noteIfDeferred() },-                onAudioInputSourceChange = { viewModel.setAudioInputSource(it); noteIfDeferred() },+                onAudioInputDeviceChange = { viewModel.setAudioInputDevice(it); noteIfDeferred() },             )              SettingsSection(title = stringResource(R.string.settings_mirror_front)) {@@ -160,9 +190,15 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM             CameraPostProcessingSettings(                 noiseReductionEnabled = noiseReductionEnabled,                 edgeSharpeningEnabled = edgeSharpeningEnabled,+                motionPhotoEnabled = motionPhotoEnabled,                 motionPhotoDuration = motionPhotoDuration,+                // Effective AVIF only (native encoder present): a JPEG-fallback+                // AVIF selection leaves Motion Photo available, as at capture.+                motionPhotoBlockedByAvif = com.vayunmathur.camera.domain.StillFormatRouting+                    .avifPrecludesMotionPhoto(viewModel.requestedStillFormat(), com.vayunmathur.camera.platform.StitchNative.isAvailable),                 onNoiseReductionChange = { viewModel.setNoiseReductionEnabled(it) },                 onEdgeSharpeningChange = { viewModel.setEdgeSharpeningEnabled(it) },+                onMotionPhotoEnabledChange = { viewModel.setMotionPhotoEnabled(it) },                 onMotionDurationChange = { viewModel.setMotionPhotoDuration(it) },             ) 
camera/src/main/res/values-ar/strings.xml
diff --git a/camera/src/main/res/values-ar/strings.xml b/camera/src/main/res/values-ar/strings.xmlindex 675e19449e..6efbbf0cfe 100644--- a/camera/src/main/res/values-ar/strings.xml+++ b/camera/src/main/res/values-ar/strings.xml@@ -16,14 +16,6 @@     <string name="codec_av1_label">AV1</string>     <string name="codec_av1_description">الأكثر كفاءة</string>     <string name="settings_audio_source">مصدر إدخال الصوت</string>-    <string name="audio_source_camcorder_label">كاميرا الفيديو</string>-    <string name="audio_source_camcorder_description">الافتراضي، مُضَبَّط للفيديو</string>-    <string name="audio_source_mic_label">ميكروفون</string>-    <string name="audio_source_mic_description">الميكروفون الرئيسي</string>-    <string name="audio_source_voice_communication_label">صوتي</string>-    <string name="audio_source_voice_communication_description">إلغاء الضوضاء والصدى</string>-    <string name="audio_source_unprocessed_label">غير معالج</string>-    <string name="audio_source_unprocessed_description">خام، لا معالجة</string>     <string name="qr_result">رمز QR</string>     <string name="open_url">فتح عنوان الـ URL</string>     <string name="no_app_to_open_url">لا تطبيق يمكنه فتح هذا الرابط</string>
camera/src/main/res/values-az/strings.xml
diff --git a/camera/src/main/res/values-az/strings.xml b/camera/src/main/res/values-az/strings.xmlindex 0e8837faca..f85bb6d71c 100644--- a/camera/src/main/res/values-az/strings.xml+++ b/camera/src/main/res/values-az/strings.xml@@ -17,14 +17,6 @@     <string name="codec_av1_label">AV1</string>     <string name="codec_av1_description">Ən səmərəli</string>     <string name="settings_audio_source">Audio giriş mənbəyi</string>-    <string name="audio_source_camcorder_label">Video kamera</string>-    <string name="audio_source_camcorder_description">Standart, video üçün tənzimlənib</string>-    <string name="audio_source_mic_label">Mikrofon</string>-    <string name="audio_source_mic_description">Əsas mikrofon</string>-    <string name="audio_source_voice_communication_label">Səs</string>-    <string name="audio_source_voice_communication_description">Səs-küyün və əks-sədanın ləğvi</string>-    <string name="audio_source_unprocessed_label">Emal olunmamış</string>-    <string name="audio_source_unprocessed_description">Xam, emal olunmamış</string>     <string name="qr_result">QR kodu</string>     <string name="open_url">URL aç</string>     <string name="no_app_to_open_url">Heç bir tətbiq bu linki aça bilmir</string>
camera/src/main/res/values-et/strings.xml
diff --git a/camera/src/main/res/values-et/strings.xml b/camera/src/main/res/values-et/strings.xmlindex 8ab62600d9..9a059cee83 100644--- a/camera/src/main/res/values-et/strings.xml+++ b/camera/src/main/res/values-et/strings.xml@@ -25,14 +25,6 @@     <string name="auto">Automaatne</string>     <string name="night_2">Öö %1$s%%</string>     <string name="settings_audio_source">Helisisend</string>-    <string name="audio_source_camcorder_label">Videokaamera</string>-    <string name="audio_source_camcorder_description">Vaikimisi, seadistatud video jaoks</string>-    <string name="audio_source_mic_label">Mikrofon</string>-    <string name="audio_source_mic_description">Põhiline mikrofon</string>-    <string name="audio_source_voice_communication_label">Häälsisend</string>-    <string name="audio_source_voice_communication_description">Müra- ja kajasummutus</string>-    <string name="audio_source_unprocessed_label">Töötlemata</string>-    <string name="audio_source_unprocessed_description">Töötlemata voog</string>     <string name="settings_mirror_front">Peegepilt selfie jaoks</string>     <string name="settings_mirror_front_description">Peegelda esikaamera pilti selfie jaoks nii eelvaates, kui salvestatud failides</string>     <string name="qr_scanning_paused">QR-koodi skaneerimine on peatatud</string>
camera/src/main/res/values-it/strings.xml
diff --git a/camera/src/main/res/values-it/strings.xml b/camera/src/main/res/values-it/strings.xmlindex 0915ee3d40..8a485af102 100644--- a/camera/src/main/res/values-it/strings.xml+++ b/camera/src/main/res/values-it/strings.xml@@ -28,12 +28,4 @@     <string name="settings_mirror_front">Rifletti selfie</string>     <string name="settings_mirror_front_description">Rifletti l\'anteprima della fotocamera frontale e i selfie salvati</string>     <string name="settings_audio_source">Sorgente input audio</string>-    <string name="audio_source_camcorder_label">Camcorder</string>-    <string name="audio_source_camcorder_description">Predefinito, regolato per i video</string>-    <string name="audio_source_mic_label">Microfono</string>-    <string name="audio_source_mic_description">Microfono principale</string>-    <string name="audio_source_voice_communication_label">Voce</string>-    <string name="audio_source_voice_communication_description">Cancellazione di rumore ed eco</string>-    <string name="audio_source_unprocessed_label">Non processato</string>-    <string name="audio_source_unprocessed_description">Grezzo, nessun processo</string> </resources>
camera/src/main/res/values-iw/strings.xml
diff --git a/camera/src/main/res/values-iw/strings.xml b/camera/src/main/res/values-iw/strings.xmlindex 26ddb63f2e..63ad206206 100644--- a/camera/src/main/res/values-iw/strings.xml+++ b/camera/src/main/res/values-iw/strings.xml@@ -5,9 +5,6 @@     <string name="open_gallery">גלריה</string>     <string name="settings_aspect_ratio">יחס תצוגה</string>     <string name="settings_location">מיקום</string>-    <string name="audio_source_mic_label">מיקרופון</string>-    <string name="audio_source_mic_description">מיקרופון ראשי</string>-    <string name="audio_source_unprocessed_description">גולמי, ללא עיבוד</string>     <string name="qr_result">קוד QR</string>     <string name="open_url">פתיחת כתובת</string>     <string name="copy_text">העתקה</string>
camera/src/main/res/values-pl/strings.xml
diff --git a/camera/src/main/res/values-pl/strings.xml b/camera/src/main/res/values-pl/strings.xmlindex 84364d4ffd..567942da9b 100644--- a/camera/src/main/res/values-pl/strings.xml+++ b/camera/src/main/res/values-pl/strings.xml@@ -25,14 +25,6 @@     <string name="codec_hevc_label">H.265 / HEVC</string>     <string name="open_gallery">Galeria</string>     <string name="settings_audio_source">Źródło sygnału dźwieku</string>-    <string name="audio_source_camcorder_label">Kamera</string>-    <string name="audio_source_camcorder_description">Domyślne, dostrojone do wideo</string>-    <string name="audio_source_mic_label">Mikrofon</string>-    <string name="audio_source_mic_description">Główny mikrofon</string>-    <string name="audio_source_voice_communication_label">Głos</string>-    <string name="audio_source_voice_communication_description">Redukcja szumów i echa</string>-    <string name="audio_source_unprocessed_label">Nieprzetworzone</string>-    <string name="audio_source_unprocessed_description">Surowy, bez obróbki</string>     <string name="settings_mirror_front">Lustrzane odbicie selfie</string>     <string name="settings_mirror_front_description">Lustrzane odbicie podglądu z przedniego aparatu oraz zapisanych zdjęć selfie</string>     <string name="qr_scanning_paused">Skanowanie kodów QR wstrzymane</string>
camera/src/main/res/values-sv/strings.xml
diff --git a/camera/src/main/res/values-sv/strings.xml b/camera/src/main/res/values-sv/strings.xmlindex 7b5f11ea0a..bd3f7f15fa 100644--- a/camera/src/main/res/values-sv/strings.xml+++ b/camera/src/main/res/values-sv/strings.xml@@ -17,14 +17,6 @@     <string name="codec_av1_label">AV1</string>     <string name="codec_av1_description">Mest effektiv</string>     <string name="settings_audio_source">Ljudingångskälla</string>-    <string name="audio_source_camcorder_label">Videokamera</string>-    <string name="audio_source_camcorder_description">Standard, anpassad för videoinspelning</string>-    <string name="audio_source_mic_label">Mikrofon</string>-    <string name="audio_source_mic_description">Huvudmikrofon</string>-    <string name="audio_source_voice_communication_label">Röst</string>-    <string name="audio_source_voice_communication_description">Brus- och ekodämpning</string>-    <string name="audio_source_unprocessed_label">Obearbetat</string>-    <string name="audio_source_unprocessed_description">Rått, utan bearbetning</string>     <string name="qr_result">QR-kod</string>     <string name="open_url">Öppna URL</string>     <string name="no_app_to_open_url">Ingen app kan öppna länken</string>
camera/src/main/res/values-zh-rCN/strings.xml
diff --git a/camera/src/main/res/values-zh-rCN/strings.xml b/camera/src/main/res/values-zh-rCN/strings.xmlindex 634245ae1a..1c50d4bb71 100644--- a/camera/src/main/res/values-zh-rCN/strings.xml+++ b/camera/src/main/res/values-zh-rCN/strings.xml@@ -25,14 +25,6 @@     <string name="auto">自动</string>     <string name="night_2">夜景 %1$s%%</string>     <string name="settings_audio_source">音频输入源</string>-    <string name="audio_source_camcorder_label">摄像机</string>-    <string name="audio_source_camcorder_description">默认,针对视频优化</string>-    <string name="audio_source_mic_label">麦克风</string>-    <string name="audio_source_mic_description">主麦克风</string>-    <string name="audio_source_voice_communication_label">语音</string>-    <string name="audio_source_voice_communication_description">噪声和回声消除</string>-    <string name="audio_source_unprocessed_label">未处理</string>-    <string name="audio_source_unprocessed_description">原始,未经处理</string>     <string name="settings_mirror_front">自拍镜像</string>     <string name="settings_mirror_front_description">镜像前置摄像头预览和已保存的自拍照</string>     <string name="qr_scanning_paused">二维码扫描已暂停</string>
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 eeadbfb7ae..bb57c32a2c 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -90,7 +90,13 @@     <string name="photo_format_avif_label">AVIF</string>     <string name="photo_format_avif_description">Smaller files, slower to save; Ultra HDR and Motion Photos stay JPEG</string> -    <!-- Motion-Photo duration settings (SettingsPage, issue #712) -->+    <!-- Motion-Photo settings (SettingsPage, issue #712) -->+    <!-- SettingsPage: section header for the motion-photo on/off toggle -->+    <string name="settings_motion_photo">Motion photo</string>+    <!-- SettingsPage: summary explaining the motion-photo toggle -->+    <string name="settings_motion_photo_description">Save a short clip with each photo</string>+    <!-- SettingsPage: reason shown under the disabled motion-photo toggle when AVIF is the effective format -->+    <string name="settings_motion_photo_requires_jpeg">Motion Photo needs JPEG</string>     <!-- SettingsPage: section header for motion-photo clip-length selection -->     <string name="settings_motion_duration">Motion photo length</string>     <!-- Motion-Photo duration: clip length in seconds. %1$d = seconds -->@@ -99,25 +105,11 @@         <item quantity="other">%1$d seconds</item>     </plurals> -    <!-- Audio input source settings (SettingsPage): mic source used for video recordings -->-    <!-- SettingsPage: section header for audio input source selection -->-    <string name="settings_audio_source">Audio input source</string>-    <!-- Audio source option label: camcorder (default, tuned for video) -->-    <string name="audio_source_camcorder_label">Camcorder</string>-    <!-- Audio source description: default mic tuned for video recording -->-    <string name="audio_source_camcorder_description">Default, tuned for video</string>-    <!-- Audio source option label: main microphone -->-    <string name="audio_source_mic_label">Microphone</string>-    <!-- Audio source description: the device's main microphone -->-    <string name="audio_source_mic_description">Main microphone</string>-    <!-- Audio source option label: voice communication -->-    <string name="audio_source_voice_communication_label">Voice</string>-    <!-- Audio source description: noise and echo cancellation, good for speaking to camera -->-    <string name="audio_source_voice_communication_description">Noise and echo cancellation</string>-    <!-- Audio source option label: unprocessed / raw audio -->-    <string name="audio_source_unprocessed_label">Unprocessed</string>-    <!-- Audio source description: raw audio with no processing -->-    <string name="audio_source_unprocessed_description">Raw, no processing</string>+    <!-- 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 (locale fallback): legacy header name kept for translations -->+    <string name="settings_audio_source">Audio input device</string>      <!-- QR code detection overlay -->     <!-- QrResultOverlay: header title when QR code detected -->
camera/src/main/rust/src/avif.rs
diff --git a/camera/src/main/rust/src/avif.rs b/camera/src/main/rust/src/avif.rsindex 69f09fdefb..892111d9de 100644--- a/camera/src/main/rust/src/avif.rs+++ b/camera/src/main/rust/src/avif.rs@@ -17,6 +17,9 @@  use ravif::{Encoder, Img, RGBA8}; +#[cfg(test)]+use crate::avif_mux::{parse_boxes, read_uint};+ /// Largest width/height accepted, matching the night-frame JNI guard. const MAX_DIM: usize = 20_000; @@ -44,7 +47,7 @@ pub fn encode_avif(rgba: &[u8], width: usize, height: usize, quality: f32, speed  /// True when [exif] is a TIFF payload (`II*\0` / `MM\0*`) or an /// already-framed HEIF Exif item (`[u32 offset][…][TIFF…]`).-fn looks_like_exif(exif: &[u8]) -> bool {+pub(crate) fn looks_like_exif(exif: &[u8]) -> bool {     if exif.starts_with(b"II\x2a\0") || exif.starts_with(b"MM\0\x2a") {         return true;     }
camera/src/main/rust/src/avif_mux.rs
diff --git a/camera/src/main/rust/src/avif_mux.rs b/camera/src/main/rust/src/avif_mux.rsindex 723f7d478a..8b2b26a653 100644--- a/camera/src/main/rust/src/avif_mux.rs+++ b/camera/src/main/rust/src/avif_mux.rs@@ -5,13 +5,13 @@ use crate::avif::looks_like_exif;  /// One parsed ISOBMFF box: type plus absolute payload span in the file.-struct BoxSpan {-    typ: [u8; 4],-    start: usize,-    payload: std::ops::Range<usize>,+pub(crate) struct BoxSpan {+    pub(crate) typ: [u8; 4],+    pub(crate) start: usize,+    pub(crate) payload: std::ops::Range<usize>, } -fn parse_boxes(bytes: &[u8], span: std::ops::Range<usize>) -> Vec<BoxSpan> {+pub(crate) fn parse_boxes(bytes: &[u8], span: std::ops::Range<usize>) -> Vec<BoxSpan> {     let mut out = Vec::new();     let mut off = span.start;     while off + 8 <= span.end && off + 8 <= bytes.len() {@@ -40,7 +40,7 @@ fn parse_boxes(bytes: &[u8], span: std::ops::Range<usize>) -> Vec<BoxSpan> {     out } -fn read_uint(bytes: &[u8], pos: &mut usize, size: usize) -> Option<u64> {+pub(crate) fn read_uint(bytes: &[u8], pos: &mut usize, size: usize) -> Option<u64> {     let mut value = 0u64;     for _ in 0..size {         value = (value << 8) | *bytes.get(*pos)? as u64;
camera/src/main/rust/src/avif_tests.rs
diff --git a/camera/src/main/rust/src/avif_tests.rs b/camera/src/main/rust/src/avif_tests.rsindex a996835393..0f4f9df710 100644--- a/camera/src/main/rust/src/avif_tests.rs+++ b/camera/src/main/rust/src/avif_tests.rs@@ -1,184 +1,182 @@ use super::{avif_dimensions, avif_exif_item, avif_exif_tiff, encode_avif, encode_avif_with_exif, has_avif_magic}; use crate::avif_mux::mux_avif_exif; -    use super::{avif_dimensions, avif_exif_item, avif_exif_tiff, encode_avif, encode_avif_with_exif, has_avif_magic};+/// Minimal little-endian TIFF: IFD0 with one Orientation(=1) entry,+/// then a marker tail so content assertions can find the payload.+fn test_tiff() -> Vec<u8> {+    let mut tiff = Vec::new();+    tiff.extend_from_slice(b"II\x2a\0");+    tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8+    tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry+    tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation+    tiff.extend_from_slice(&3u16.to_le_bytes()); // SHORT+    tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1+    tiff.extend_from_slice(&1u16.to_le_bytes()); // value 1 (Normal)+    tiff.extend_from_slice(&[0, 0]);+    tiff.extend_from_slice(&0u32.to_le_bytes()); // no next IFD+    tiff.extend_from_slice(b"GPSMARK");+    tiff+} -    /// Minimal little-endian TIFF: IFD0 with one Orientation(=1) entry,-    /// then a marker tail so content assertions can find the payload.-    fn test_tiff() -> Vec<u8> {-        let mut tiff = Vec::new();-        tiff.extend_from_slice(b"II\x2a\0");-        tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8-        tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry-        tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation-        tiff.extend_from_slice(&3u16.to_le_bytes()); // SHORT-        tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1-        tiff.extend_from_slice(&1u16.to_le_bytes()); // value 1 (Normal)-        tiff.extend_from_slice(&[0, 0]);-        tiff.extend_from_slice(&0u32.to_le_bytes()); // no next IFD-        tiff.extend_from_slice(b"GPSMARK");-        tiff-    }--    fn gradient(width: usize, height: usize) -> Vec<u8> {-        let mut px = Vec::with_capacity(width * height * 4);-        for y in 0..height {-            for x in 0..width {-                px.extend_from_slice(&[-                    (x % 256) as u8,-                    (y % 256) as u8,-                    ((x + y) % 256) as u8,-                    255,-                ]);-            }+fn gradient(width: usize, height: usize) -> Vec<u8> {+    let mut px = Vec::with_capacity(width * height * 4);+    for y in 0..height {+        for x in 0..width {+            px.extend_from_slice(&[+                (x % 256) as u8,+                (y % 256) as u8,+                ((x + y) % 256) as u8,+                255,+            ]);         }-        px     }+    px+} -    #[test]-    fn encodes_synthetic_rgba_with_avif_header_and_dimensions() {-        let rgba = gradient(64, 48);-        let bytes = encode_avif(&rgba, 64, 48, 80.0, 10).expect("encode must succeed");-        assert!(has_avif_magic(&bytes), "missing ftypavif magic");-        assert_eq!(avif_dimensions(&bytes), Some((64, 48)));-    }+#[test]+fn encodes_synthetic_rgba_with_avif_header_and_dimensions() {+    let rgba = gradient(64, 48);+    let bytes = encode_avif(&rgba, 64, 48, 80.0, 10).expect("encode must succeed");+    assert!(has_avif_magic(&bytes), "missing ftypavif magic");+    assert_eq!(avif_dimensions(&bytes), Some((64, 48)));+} -    #[test]-    fn exif_item_round_trips_through_isobmff_boxes() {-        let rgba = gradient(64, 48);-        let tiff = test_tiff();-        let bytes = encode_avif_with_exif(&rgba, 64, 48, 80.0, 10, Some(&tiff))-            .expect("encode with exif must succeed");-        assert!(has_avif_magic(&bytes));-        assert_eq!(avif_dimensions(&bytes), Some((64, 48)));-        // Item framing: [u32 offset=0][TIFF], located via iinf+iloc.-        let item = avif_exif_item(&bytes).expect("Exif item must be present via iinf/iloc");-        assert_eq!(&item[..4], &[0, 0, 0, 0]);-        let parsed = avif_exif_tiff(&bytes).expect("TIFF payload must parse back");-        assert_eq!(parsed, tiff);-        assert!(parsed.starts_with(b"II\x2a\0"));-        assert!(parsed.windows(7).any(|w| w == b"GPSMARK"));-    }+#[test]+fn exif_item_round_trips_through_isobmff_boxes() {+    let rgba = gradient(64, 48);+    let tiff = test_tiff();+    let bytes = encode_avif_with_exif(&rgba, 64, 48, 80.0, 10, Some(&tiff))+        .expect("encode with exif must succeed");+    assert!(has_avif_magic(&bytes));+    assert_eq!(avif_dimensions(&bytes), Some((64, 48)));+    // Item framing: [u32 offset=0][TIFF], located via iinf+iloc.+    let item = avif_exif_item(&bytes).expect("Exif item must be present via iinf/iloc");+    assert_eq!(&item[..4], &[0, 0, 0, 0]);+    let parsed = avif_exif_tiff(&bytes).expect("TIFF payload must parse back");+    assert_eq!(parsed, tiff);+    assert!(parsed.starts_with(b"II\x2a\0"));+    assert!(parsed.windows(7).any(|w| w == b"GPSMARK"));+} -    #[test]-    fn mux_splices_exif_into_encoded_avif() {-        let rgba = gradient(64, 48);-        let tiff = test_tiff();-        let bare = encode_avif(&rgba, 64, 48, 80.0, 10).expect("encode must succeed");-        assert!(avif_exif_item(&bare).is_none());-        let muxed = mux_avif_exif(&bare, &tiff).expect("mux must succeed");-        if let Ok(dir) = std::env::var("AVIF_BENCH_DIR") {-            let _ = std::fs::write(format!("{dir}/muxed64.avif"), &muxed);-        }-        assert!(has_avif_magic(&muxed));-        assert_eq!(avif_dimensions(&muxed), Some((64, 48)));-        let parsed = avif_exif_tiff(&muxed).expect("muxed TIFF must parse back via iinf/iloc");-        assert_eq!(parsed, tiff);-        // A second mux (file already has an Exif item) and bad inputs refuse.-        assert!(mux_avif_exif(&muxed, &tiff).is_none());-        assert!(mux_avif_exif(&bare, b"not a tiff").is_none());-        assert!(mux_avif_exif(b"not an avif", &tiff).is_none());+#[test]+fn mux_splices_exif_into_encoded_avif() {+    let rgba = gradient(64, 48);+    let tiff = test_tiff();+    let bare = encode_avif(&rgba, 64, 48, 80.0, 10).expect("encode must succeed");+    assert!(avif_exif_item(&bare).is_none());+    let muxed = mux_avif_exif(&bare, &tiff).expect("mux must succeed");+    if let Ok(dir) = std::env::var("AVIF_BENCH_DIR") {+        let _ = std::fs::write(format!("{dir}/muxed64.avif"), &muxed);     }+    assert!(has_avif_magic(&muxed));+    assert_eq!(avif_dimensions(&muxed), Some((64, 48)));+    let parsed = avif_exif_tiff(&muxed).expect("muxed TIFF must parse back via iinf/iloc");+    assert_eq!(parsed, tiff);+    // A second mux (file already has an Exif item) and bad inputs refuse.+    assert!(mux_avif_exif(&muxed, &tiff).is_none());+    assert!(mux_avif_exif(&bare, b"not a tiff").is_none());+    assert!(mux_avif_exif(b"not an avif", &tiff).is_none());+} -    #[test]-    fn no_exif_item_when_no_payload_given() {-        let rgba = gradient(32, 32);-        let bytes = encode_avif(&rgba, 32, 32, 80.0, 10).expect("encode must succeed");-        assert!(avif_exif_item(&bytes).is_none());-    }+#[test]+fn no_exif_item_when_no_payload_given() {+    let rgba = gradient(32, 32);+    let bytes = encode_avif(&rgba, 32, 32, 80.0, 10).expect("encode must succeed");+    assert!(avif_exif_item(&bytes).is_none());+} -    #[test]-    fn non_tiff_exif_is_rejected_so_kotlin_falls_back_to_jpeg() {-        let rgba = gradient(32, 32);-        assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"not a tiff")).is_none());-        assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"")).is_none());-    }+#[test]+fn non_tiff_exif_is_rejected_so_kotlin_falls_back_to_jpeg() {+    let rgba = gradient(32, 32);+    assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"not a tiff")).is_none());+    assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"")).is_none());+} -    #[test]-    fn rejects_mismatched_and_oversized_input() {-        assert!(encode_avif(&[0u8; 10], 64, 48, 80.0, 10).is_none());-        assert!(encode_avif(&[], 0, 0, 80.0, 10).is_none());-        assert!(encode_avif(&[0u8; 4], 20_001, 1, 80.0, 10).is_none());-    }+#[test]+fn rejects_mismatched_and_oversized_input() {+    assert!(encode_avif(&[0u8; 10], 64, 48, 80.0, 10).is_none());+    assert!(encode_avif(&[], 0, 0, 80.0, 10).is_none());+    assert!(encode_avif(&[0u8; 4], 20_001, 1, 80.0, 10).is_none());+} -    /// Photo-like 12 MP frame (4080x3072): smooth gradients + sinusoidal-    /// detail + deterministic sensor-like noise, so encode times are not-    /// flattered by a flat/gradient-only synthetic.-    fn photo_like(width: usize, height: usize) -> Vec<u8> {-        let mut px = Vec::with_capacity(width * height * 4);-        let mut state: u32 = 0x9E37_79B9;-        let mut noise = move || {-            state ^= state << 13;-            state ^= state >> 17;-            state ^= state << 5;-            (state >> 24) as i32 - 128-        };-        for y in 0..height {-            for x in 0..width {-                let fx = x as f32 / width as f32;-                let fy = y as f32 / height as f32;-                let wave = ((x as f32 * 0.11).sin() * 18.0-                    + (y as f32 * 0.043 + x as f32 * 0.017).sin() * 26.0-                    + ((x + y) as f32 * 0.31).sin() * 8.0) as i32;-                let n = noise() / 10;-                let r = (40.0 + fx * 180.0) as i32 + wave + n;-                let g = (60.0 + fy * 150.0) as i32 + wave / 2 + n;-                let b = (90.0 + (1.0 - fx) * 110.0) as i32 - wave / 3 + n;-                px.extend_from_slice(&[-                    r.clamp(0, 255) as u8,-                    g.clamp(0, 255) as u8,-                    b.clamp(0, 255) as u8,-                    255,-                ]);-            }+/// Photo-like 12 MP frame (4080x3072): smooth gradients + sinusoidal+/// detail + deterministic sensor-like noise, so encode times are not+/// flattered by a flat/gradient-only synthetic.+fn photo_like(width: usize, height: usize) -> Vec<u8> {+    let mut px = Vec::with_capacity(width * height * 4);+    let mut state: u32 = 0x9E37_79B9;+    let mut noise = move || {+        state ^= state << 13;+        state ^= state >> 17;+        state ^= state << 5;+        (state >> 24) as i32 - 128+    };+    for y in 0..height {+        for x in 0..width {+            let fx = x as f32 / width as f32;+            let fy = y as f32 / height as f32;+            let wave = ((x as f32 * 0.11).sin() * 18.0+                + (y as f32 * 0.043 + x as f32 * 0.017).sin() * 26.0+                + ((x + y) as f32 * 0.31).sin() * 8.0) as i32;+            let n = noise() / 10;+            let r = (40.0 + fx * 180.0) as i32 + wave + n;+            let g = (60.0 + fy * 150.0) as i32 + wave / 2 + n;+            let b = (90.0 + (1.0 - fx) * 110.0) as i32 - wave / 3 + n;+            px.extend_from_slice(&[+                r.clamp(0, 255) as u8,+                g.clamp(0, 255) as u8,+                b.clamp(0, 255) as u8,+                255,+            ]);         }-        px     }+    px+} -    /// Host-side encode-time probe for a 12 MP frame. Ignored by default-    /// (it takes seconds); run with-    /// `cargo test --release -p camera_stitch bench_12mp -- --ignored --nocapture`-    /// to reproduce the latency figures in the change report. Writes each-    /// speed's .avif to $AVIF_BENCH_DIR (default /tmp/avif_bench) so an-    /// external AV1 decoder (ffmpeg/dav1d) can score PSNR vs the source.-    #[test]-    #[ignore]-    fn bench_12mp_encode_time() {-        let (w, h) = (4080usize, 3072usize);-        let rgba = photo_like(w, h);-        let dir = std::env::var("AVIF_BENCH_DIR").unwrap_or_else(|_| "/tmp/avif_bench".into());-        let _ = std::fs::create_dir_all(&dir);-        // Source dump for PSNR scoring (raw RGBA).-        let _ = std::fs::write(format!("{dir}/source_{w}x{h}.rgba"), &rgba);-        for speed in [4u8, 6, 8, 9, 10] {+/// Host-side encode-time probe for a 12 MP frame. Ignored by default+/// (it takes seconds); run with+/// `cargo test --release -p camera_stitch bench_12mp -- --ignored --nocapture`+/// to reproduce the latency figures in the change report. Writes each+/// speed's .avif to $AVIF_BENCH_DIR (default /tmp/avif_bench) so an+/// external AV1 decoder (ffmpeg/dav1d) can score PSNR vs the source.+#[test]+#[ignore]+fn bench_12mp_encode_time() {+    let (w, h) = (4080usize, 3072usize);+    let rgba = photo_like(w, h);+    let dir = std::env::var("AVIF_BENCH_DIR").unwrap_or_else(|_| "/tmp/avif_bench".into());+    let _ = std::fs::create_dir_all(&dir);+    // Source dump for PSNR scoring (raw RGBA).+    let _ = std::fs::write(format!("{dir}/source_{w}x{h}.rgba"), &rgba);+    for speed in [4u8, 6, 8, 9, 10] {+        let start = std::time::Instant::now();+        let bytes = encode_avif(&rgba, w, h, 80.0, speed).expect("encode must succeed");+        let ms = start.elapsed().as_millis();+        let _ = std::fs::write(format!("{dir}/q80_s{speed}.avif"), &bytes);+        println!("12MP AVIF q80 speed={speed} threads=default: {ms} ms -> {} bytes", bytes.len());+        assert!(has_avif_magic(&bytes));+    }+    // Thread scaling at the production-adjacent speeds, via ravif directly.+    let pixels: Vec<ravif::RGBA8> = rgba+        .chunks_exact(4)+        .map(|p| ravif::RGBA8::new(p[0], p[1], p[2], p[3]))+        .collect();+    for speed in [8u8, 10] {+        for threads in [Some(1usize), Some(4), Some(8), Some(16)] {+            let img = ravif::Img::new(pixels.as_slice(), w, h);             let start = std::time::Instant::now();-            let bytes = encode_avif(&rgba, w, h, 80.0, speed).expect("encode must succeed");-            let ms = start.elapsed().as_millis();-            let _ = std::fs::write(format!("{dir}/q80_s{speed}.avif"), &bytes);-            println!("12MP AVIF q80 speed={speed} threads=default: {ms} ms -> {} bytes", bytes.len());-            assert!(has_avif_magic(&bytes));-        }-        // Thread scaling at the production-adjacent speeds, via ravif directly.-        let pixels: Vec<ravif::RGBA8> = rgba-            .chunks_exact(4)-            .map(|p| ravif::RGBA8::new(p[0], p[1], p[2], p[3]))-            .collect();-        for speed in [8u8, 10] {-            for threads in [Some(1usize), Some(4), Some(8), Some(16)] {-                let img = ravif::Img::new(pixels.as_slice(), w, h);-                let start = std::time::Instant::now();-                let enc = ravif::Encoder::new()-                    .with_quality(80.0)-                    .with_speed(speed)-                    .with_bit_depth(ravif::BitDepth::Eight)-                    .with_num_threads(threads)-                    .encode_rgba(img)-                    .expect("encode must succeed");-                println!(-                    "12MP AVIF q80 speed={speed} threads={threads:?}: {} ms -> {} bytes",-                    start.elapsed().as_millis(),-                    enc.avif_file.len()-                );-            }+            let enc = ravif::Encoder::new()+                .with_quality(80.0)+                .with_speed(speed)+                .with_bit_depth(ravif::BitDepth::Eight)+                .with_num_threads(threads)+                .encode_rgba(img)+                .expect("encode must succeed");+            println!(+                "12MP AVIF q80 speed={speed} threads={threads:?}: {} ms -> {} bytes",+                start.elapsed().as_millis(),+                enc.avif_file.len()+            );         }     }+}
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex 0b1313a7e0..ebd807f4cc 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -23,6 +23,7 @@ mod raw_night; #[allow(dead_code)] mod raw_jni; mod avif;+mod avif_mux; mod luma;  use imgbuf::Rgba;
camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.kt b/camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.ktnew file mode 100644index 0000000000..727d6ee1ef--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/data/CameraMotionPhotoSettingsTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.camera.data++import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.camera.platform.CameraViewModel+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Motion Photo on/off persistence: default on, explicit off survives a new ViewModel. */+@RunWith(AndroidJUnit4::class)+class CameraMotionPhotoSettingsTest {++    private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext())++    /**+     * Waits until the setter's async DataStore write is visible in the+     * synchronous mirror. The setter launches on `viewModelScope` (main), so+     * the main looper is idled between polls instead of blocked on.+     */+    private fun awaitStored(viewModel: CameraViewModel, expected: String) {+        val deadline = System.currentTimeMillis() + 5_000+        while (viewModel.ds.getString(KEY) != expected) {+            assertTrue(System.currentTimeMillis() < deadline, "stored $KEY never became $expected")+            Shadows.shadowOf(Looper.getMainLooper()).idle()+            Thread.sleep(20)+        }+        assertEquals(expected, viewModel.ds.getString(KEY))+    }++    @Test+    fun motionPhotoEnabledDefaultsOnAndPersistsOffAndOn() {+        val first = vm()+        try {+            assertTrue(first.motionPhotoEnabled.value, "default must be on")++            first.setMotionPhotoEnabled(false)+            assertFalse(first.motionPhotoEnabled.value)+            awaitStored(first, "false")+            // A fresh ViewModel loads the persisted off state at startup.+            assertFalse(vm().motionPhotoEnabled.value)+        } finally {+            // Leave the shared store on for other tests, with the restore+            // landed rather than only launched.+            first.setMotionPhotoEnabled(true)+            awaitStored(first, "true")+        }+        assertTrue(vm().motionPhotoEnabled.value)+    }++    private companion object {+        const val KEY = "camera_motion_photo_enabled"+    }+}
camera/src/test/java/com/vayunmathur/camera/domain/MotionPhotoEligibilityTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/MotionPhotoEligibilityTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/MotionPhotoEligibilityTest.ktnew file mode 100644index 0000000000..ef30050529--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/MotionPhotoEligibilityTest.kt@@ -0,0 +1,57 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class MotionPhotoEligibilityTest {++    private val eligible = MotionPhotoInputs(+        enabled = true,+        plainPhoto = true,+        noBake = true,+        avifPrecludes = false,+        nativeFourThree = true,+    )++    @Test+    fun onKeepsPreviousEligibleCase() {+        assertTrue(MotionPhotoEligibility.isEligible(eligible))+    }++    @Test+    fun offNeverEligibleEvenWhenEverythingElseAllows() {+        // 4:3 + JPEG (no AVIF preclusion) + no bake + plain photo, length+        // irrelevant here: off alone must veto.+        assertFalse(MotionPhotoEligibility.isEligible(eligible.copy(enabled = false)))+    }++    @Test+    fun onPreviousMatrixUnchanged() {+        assertFalse(MotionPhotoEligibility.isEligible(eligible.copy(plainPhoto = false)))+        assertFalse(MotionPhotoEligibility.isEligible(eligible.copy(noBake = false)))+        assertFalse(MotionPhotoEligibility.isEligible(eligible.copy(avifPrecludes = true)))+        assertFalse(MotionPhotoEligibility.isEligible(eligible.copy(nativeFourThree = false)))+    }++    @Test+    fun offVetoesEveryOtherCombination() {+        for (plain in listOf(true, false)) {+            for (bake in listOf(true, false)) {+                for (avif in listOf(true, false)) {+                    for (ratio in listOf(true, false)) {+                        assertFalse(+                            MotionPhotoEligibility.isEligible(+                                MotionPhotoInputs(+                                    enabled = false, plainPhoto = plain, noBake = bake,+                                    avifPrecludes = avif, nativeFourThree = ratio,+                                )+                            ),+                            "off must veto plain=$plain bake=$bake avif=$avif ratio=$ratio",+                        )+                    }+                }+            }+        }+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.ktindex bec306c4ed..8a3561ee7e 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/MotionPhotoCaptureStateTest.kt@@ -148,6 +148,25 @@ class MotionPhotoCaptureStateTest {         assertFalse(v.isCapturing.value)     } +    @Test+    fun motionPhotoOffRoutesToPlainStillAndBuffersNothing() {+        val v = vm()+        // Default is on, preserving the pre-toggle behaviour.+        assertTrue(v.motionPhotoEnabled.value)+        v.motionPhotoEnabledMutable.value = false+        // 4:3 + JPEG + a length set: still a plain still, queue untouched.+        assertEquals(StillRoute.SINGLE, v.routeStillCapture())+        assertEquals(0, v.motionSaveQueue.pending)+        // No ring-buffer accumulation while off (bitmap is recycled).+        val frame = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)+        v.addMotionFrame(frame, 0L, 90)+        assertTrue(frame.isRecycled)+        assertTrue(v.drainMotionFrames().isEmpty())+        // Re-enabling restores the previous diversion.+        v.motionPhotoEnabledMutable.value = true+        assertEquals(StillRoute.MOTION_PHOTO, v.routeStillCapture())+    }+     @Test     fun nonMotionModesDoNotTouchTheQueue() {         val v = vm()
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.ktnew file mode 100644index 0000000000..8e67ec372d--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioInputDevicesTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.camera.platform.camera2++import android.media.AudioDeviceInfo+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+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.+ */+class AudioInputDevicesTest {++    private val builtin = RawAudioInputDevice(1, AudioDeviceInfo.TYPE_BUILTIN_MIC, null)+    private val usb = RawAudioInputDevice(2, AudioDeviceInfo.TYPE_USB_DEVICE, "USB Mic Pro")+    private val usbNoName = RawAudioInputDevice(3, AudioDeviceInfo.TYPE_USB_HEADSET, "  ")+    private val bluetooth = RawAudioInputDevice(4, AudioDeviceInfo.TYPE_BLUETOOTH_SCO, null)+    private val wired = RawAudioInputDevice(5, AudioDeviceInfo.TYPE_WIRED_HEADSET, null)++    @Test fun typeLabelsMapToPhysicalDevices() {+        assertEquals("Built-in microphone", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_BUILTIN_MIC))+        assertEquals("USB device", 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))+        assertEquals("Wired headset", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_WIRED_HEADSET))+        assertEquals("Microphone", AudioInputDevicePolicy.typeLabel(AudioDeviceInfo.TYPE_UNKNOWN))+    }++    @Test fun productNameWinsOverTypeLabel() {+        assertEquals("USB Mic Pro", AudioInputDevicePolicy.labelFor(usb.type, usb.productName))+        assertEquals("Built-in microphone", AudioInputDevicePolicy.labelFor(builtin.type, null))+        // A blank product name falls back to the type label.+        assertEquals("USB headset", AudioInputDevicePolicy.labelFor(usbNoName.type, usbNoName.productName))+    }++    @Test fun optionsAreAutoFirstThenDevicesById() {+        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)+    }++    @Test fun selectedDeviceIsAppliedThroughTheSeam() {+        val calls = mutableListOf<RawAudioInputDevice?>()+        val result = PreferredAudioDeviceApplication.apply(+            selection = AudioInputDeviceSelection(usb.id, usb.type),+            devices = listOf(builtin, usb),+            idOf = { it.id },+            typeOf = { it.type },+            setPreferred = { device -> calls += device; true },+        )+        assertEquals(listOf<RawAudioInputDevice?>(usb), calls)+        assertEquals(usb, result.device)+        assertTrue(result.applied)+        assertEquals(AudioInputDeviceSelection(usb.id, usb.type), result.selection)+    }++    @Test fun autoClearsThePreferredDevice() {+        val calls = mutableListOf<RawAudioInputDevice?>()+        val result = PreferredAudioDeviceApplication.apply(+            selection = AudioInputDeviceSelection.AUTO,+            devices = listOf(builtin),+            idOf = { it.id },+            typeOf = { it.type },+            setPreferred = { device -> calls += device; true },+        )+        assertEquals(listOf<RawAudioInputDevice?>(null), calls)+        assertNull(result.device)+        assertTrue(result.selection.isAuto)+    }++    @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.+        assertEquals(+            AudioInputDeviceSelection.AUTO,+            AudioInputDevicePolicy.resolve(AudioInputDeviceSelection(usb.id, usb.type), listOf(builtin)),+        )+        assertEquals(+            AudioInputDeviceSelection.AUTO,+            AudioInputDevicePolicy.resolve(+                AudioInputDeviceSelection(usb.id, AudioDeviceInfo.TYPE_WIRED_HEADSET),+                listOf(usb),+            ),+        )+        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 },+        )+        assertTrue(result.selection.isAuto)+        assertEquals(listOf<RawAudioInputDevice?>(null), calls)+    }++    @Test fun rejectedOrThrowingSetterNeverFailsApplication() {+        val rejected = PreferredAudioDeviceApplication.apply(+            selection = AudioInputDeviceSelection(usb.id, usb.type),+            devices = listOf(usb),+            idOf = { it.id },+            typeOf = { it.type },+            setPreferred = { false },+        )+        assertFalse(rejected.applied)+        assertEquals(usb, rejected.device)++        val throwing = PreferredAudioDeviceApplication.apply(+            selection = AudioInputDeviceSelection(usb.id, usb.type),+            devices = listOf(usb),+            idOf = { it.id },+            typeOf = { it.type },+            setPreferred = { throw IllegalStateException("device gone") },+        )+        assertFalse(throwing.applied)+    }++    @Test fun persistedSelectionRoundTripsAndStaleValuesFallBackToAuto() {+        val chosen = AudioInputDeviceSelection(7, AudioDeviceInfo.TYPE_BLUETOOTH_SCO)+        assertEquals(chosen, AudioInputDeviceSelection.parse(chosen.encode()))+        assertEquals(AudioInputDeviceSelection.AUTO, AudioInputDeviceSelection.parse("auto"))+        assertEquals(AudioInputDeviceSelection.AUTO, AudioInputDeviceSelection.parse(null))+        // Stale values from the retired AudioSource-type setting.+        for (stale in listOf("CAMCORDER", "MIC", "VOICE_COMMUNICATION", "UNPROCESSED", "", "12", "x:y", "1:2:3")) {+            assertEquals(AudioInputDeviceSelection.AUTO, AudioInputDeviceSelection.parse(stale), stale)+        }+        assertTrue(AudioInputDeviceSelection.AUTO.isAuto)+        assertFalse(chosen.isAuto)+    }+}
camera/src/test/java/com/vayunmathur/camera/ui/BottomControlsComposeExtraTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/BottomControlsComposeExtraTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/BottomControlsComposeExtraTest.ktindex ec46da693d..b2491467d0 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/BottomControlsComposeExtraTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/BottomControlsComposeExtraTest.kt@@ -36,7 +36,7 @@ class BottomControlsComposeExtraTest {         selectedLens = null, availableLenses = emptyList(), hasFlashUnit = true,         flashMode = FlashMode.AUTO, torchEnabled = false,         videoCodec = viewModel.videoCodecMutable.value,-        audioInputSource = viewModel.audioInputSourceMutable.value,+        audioInputDevice = viewModel.audioInputDeviceMutable.value,         isRecording = mode == CameraMode.VIDEO, recordingDuration = 65, timerCountdown = 0,         qrResult = null,         aspectRatio = AspectRatioOption.RATIO_4_3,
camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.ktindex a53349ae5a..6a6b82228c 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.kt@@ -38,7 +38,7 @@ class CameraBindFailedComposeTest {         flashMode = FlashMode.OFF,         torchEnabled = false,         videoCodec = viewModel.videoCodecMutable.value,-        audioInputSource = viewModel.audioInputSourceMutable.value,+        audioInputDevice = viewModel.audioInputDeviceMutable.value,         isRecording = false,         recordingDuration = 0,         timerCountdown = 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 b64cdf4ad2..0ce2686d4c 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.camera.ui  import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.hasScrollAction import androidx.compose.ui.test.isToggleable import androidx.compose.ui.test.junit4.createComposeRule@@ -11,7 +12,6 @@ import androidx.compose.ui.test.performScrollToNode import androidx.compose.ui.test.hasText import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4-import com.vayunmathur.camera.platform.AudioInputSource import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.MotionPhotoDuration import com.vayunmathur.library.util.NavBackStack@@ -50,28 +50,43 @@ class CameraCovC2SettingsTest {         assertEquals(!mirrorBefore, viewModel.mirrorFront.value)     } -    @Test fun settingsPageSelectsAudioSource() {+    @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".         val viewModel = vm()         val backStack = NavBackStack<TestRoute>(arrayOf(TestRoute.Home))         rule.setContent { SettingsPage(backStack, viewModel) }-        rule.onNode(hasScrollAction()).performScrollToNode(hasText(str(com.vayunmathur.camera.R.string.settings_audio_source)))-        val before = viewModel.audioInputSource.value-        val other = AudioInputSource.entries.first { it != before }-        // Open the dropdown by clicking the current value's label row.-        rule.onNodeWithText(str(before.labelRes), substring = true).performClick()+        rule.onNode(hasScrollAction()).performScrollToNode(+            hasText(str(com.vayunmathur.camera.R.string.settings_audio_input_device))+        )+        assertEquals(+            com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO,+            viewModel.audioInputDevice.value,+        )+        assertTrue(+            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()         rule.waitForIdle()-        rule.onNodeWithText(str(other.labelRes), substring = true).performClick()-        assertEquals(other, viewModel.audioInputSource.value)+        val autos = rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes()+        rule.onAllNodesWithText("Auto", substring = true)[autos.size - 1].performClick()+        assertEquals(+            com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO,+            viewModel.audioInputDevice.value,+        )     }      @Test fun settingsPageHasNoAudioCodecRow() {         // Opus-only: audio encoding is not selectable, so Settings must-        // not offer an audio-codec row (the audio *source* row stays).+        // not offer an audio-codec row (the audio input device row stays).         val viewModel = vm()         val backStack = NavBackStack<TestRoute>(arrayOf(TestRoute.Home))         rule.setContent { SettingsPage(backStack, viewModel) }         rule.onNode(hasScrollAction()).performScrollToNode(-            hasText(str(com.vayunmathur.camera.R.string.settings_audio_source))+            hasText(str(com.vayunmathur.camera.R.string.settings_audio_input_device))         )         assertTrue(             rule.onAllNodesWithText("Audio codec", substring = true).fetchSemanticsNodes().isEmpty(),@@ -83,12 +98,16 @@ class CameraCovC2SettingsTest {         var noise = true         var edge = false         var duration = MotionPhotoDuration.ONE+        var motionEnabled = true         rule.setContent {             CameraPostProcessingSettings(                 noiseReductionEnabled = noise, edgeSharpeningEnabled = edge,+                motionPhotoEnabled = motionEnabled,                 motionPhotoDuration = duration,+                motionPhotoBlockedByAvif = false,                 onNoiseReductionChange = { noise = it },                 onEdgeSharpeningChange = { edge = it },+                onMotionPhotoEnabledChange = { motionEnabled = it },                 onMotionDurationChange = { duration = it },             )         }@@ -103,4 +122,47 @@ class CameraCovC2SettingsTest {         rule.onAllNodes(hasText("${target.seconds}", substring = true))[0].performClick()         assertNotEquals(MotionPhotoDuration.ONE, duration)     }++    @Test fun motionPhotoOffHidesLengthAndAvifDisablesToggle() {+        var enabled = false+        rule.setContent {+            CameraPostProcessingSettings(+                noiseReductionEnabled = true, edgeSharpeningEnabled = true,+                motionPhotoEnabled = enabled,+                motionPhotoDuration = MotionPhotoDuration.THREE,+                motionPhotoBlockedByAvif = false,+                onNoiseReductionChange = {}, onEdgeSharpeningChange = {},+                onMotionPhotoEnabledChange = { enabled = it },+                onMotionDurationChange = {},+            )+        }+        // Off: the length row is gone.+        assertTrue(+            rule.onAllNodesWithText(str(com.vayunmathur.camera.R.string.settings_motion_duration))+                .fetchSemanticsNodes().isEmpty()+        )+        // Third toggle is Motion Photo; turning it on restores the control.+        rule.onAllNodes(isToggleable())[2].performClick()+        assertEquals(true, enabled)+    }++    @Test fun motionPhotoToggleDisabledWithReasonWhenAvifBlocks() {+        var enabled = true+        rule.setContent {+            CameraPostProcessingSettings(+                noiseReductionEnabled = true, edgeSharpeningEnabled = true,+                motionPhotoEnabled = enabled,+                motionPhotoDuration = MotionPhotoDuration.THREE,+                motionPhotoBlockedByAvif = true,+                onNoiseReductionChange = {}, onEdgeSharpeningChange = {},+                onMotionPhotoEnabledChange = { enabled = it },+                onMotionDurationChange = {},+            )+        }+        rule.onNodeWithText(+            str(com.vayunmathur.camera.R.string.settings_motion_photo_requires_jpeg)+        ).assertIsDisplayed()+        rule.onAllNodes(isToggleable())[2].assertIsNotEnabled()+        assertEquals(true, enabled, "AVIF-blocked toggle must not change")+    } }
camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3ComposeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3ComposeTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3ComposeTest.ktindex 4a0c6d58e6..ddcd2b74b3 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3ComposeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3ComposeTest.kt@@ -121,9 +121,9 @@ class CameraCovW3ComposeTest {             rule.waitForIdle()         }         // Open the audio-source dropdown and pick an entry if present.-        val audioNodes = rule.onAllNodesWithText("Camcorder", substring = true).fetchSemanticsNodes()+        val audioNodes = rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes()         if (audioNodes.isNotEmpty()) {-            rule.onAllNodesWithText("Camcorder", substring = true)[0].performClick()+            rule.onAllNodesWithText("Auto", substring = true)[0].performClick()             rule.waitForIdle()         }         assertTrue(toggles.isNotEmpty())@@ -135,14 +135,21 @@ class CameraCovW3ComposeTest {         rule.setContent { SettingsPage(backStack, viewModel) }         rule.waitForIdle()         // Audio dropdown: the button shows "<label> — <description>"; pick a menu entry.-        val audio = rule.onAllNodesWithText("Camcorder", substring = true).fetchSemanticsNodes()+        val audio = rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes()         if (audio.isNotEmpty()) {-            rule.onAllNodesWithText("Camcorder", substring = true)[0].performClick()+            rule.onAllNodesWithText("Auto", substring = true)[0].performClick()             rule.waitForIdle()             val mics = rule.onAllNodesWithText("Microphone", substring = true).fetchSemanticsNodes()             if (mics.isNotEmpty()) {                 rule.onAllNodesWithText("Microphone", substring = true)[mics.size - 1].performClick()                 rule.waitForIdle()+            } else {+                // No physical device (Auto only): re-pick Auto to close the menu.+                val autos = rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes()+                if (autos.isNotEmpty()) {+                    rule.onAllNodesWithText("Auto", substring = true)[autos.size - 1].performClick()+                    rule.waitForIdle()+                }             }         }         // Motion-duration dropdown lives below the fold; scroll to its label first.
camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3Wave6ComposeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3Wave6ComposeTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3Wave6ComposeTest.ktindex aa54166157..81a61e53cf 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3Wave6ComposeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovW3Wave6ComposeTest.kt@@ -80,7 +80,7 @@ class CameraCovW3Wave6ComposeTest {             flashMode = com.vayunmathur.camera.platform.FlashMode.AUTO,             torchEnabled = false,             videoCodec = viewModel.videoCodecMutable.value,-            audioInputSource = viewModel.audioInputSourceMutable.value,+            audioInputDevice = viewModel.audioInputDeviceMutable.value,             isRecording = mode == CameraMode.VIDEO,             recordingDuration = 12,             timerCountdown = 0,
camera/src/test/java/com/vayunmathur/camera/ui/CameraCovX4ComposeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovX4ComposeTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovX4ComposeTest.ktindex e5c6b9d1ef..097b10d53d 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovX4ComposeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovX4ComposeTest.kt@@ -48,7 +48,7 @@ class CameraCovX4ComposeTest {         selectedLens = null, availableLenses = emptyList(), hasFlashUnit = true,         flashMode = com.vayunmathur.camera.platform.FlashMode.AUTO, torchEnabled = false,         videoCodec = viewModel.videoCodecMutable.value,-        audioInputSource = viewModel.audioInputSourceMutable.value,+        audioInputDevice = viewModel.audioInputDeviceMutable.value,         isRecording = mode == CameraMode.VIDEO, recordingDuration = 12, timerCountdown = 0,         qrResult = null,         aspectRatio = com.vayunmathur.camera.platform.AspectRatioOption.RATIO_4_3,@@ -139,14 +139,21 @@ class CameraCovX4ComposeTest {         val reset = rule.onAllNodesWithText("Reset", substring = true).fetchSemanticsNodes()         assertTrue(reset.isNotEmpty())         // Open the audio dropdown and pick the last microphone entry.-        val audio = rule.onAllNodesWithText("Camcorder", substring = true).fetchSemanticsNodes()+        val audio = rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes()         if (audio.isNotEmpty()) {-            rule.onAllNodesWithText("Camcorder", substring = true)[0].performClick()+            rule.onAllNodesWithText("Auto", substring = true)[0].performClick()             rule.waitForIdle()             val mics = rule.onAllNodesWithText("Microphone", substring = true).fetchSemanticsNodes()             if (mics.isNotEmpty()) {                 rule.onAllNodesWithText("Microphone", substring = true)[mics.size - 1].performClick()                 rule.waitForIdle()+            } else {+                // No physical device (Auto only): re-pick Auto to close the menu.+                val autos = rule.onAllNodesWithText("Auto", substring = true).fetchSemanticsNodes()+                if (autos.isNotEmpty()) {+                    rule.onAllNodesWithText("Auto", substring = true)[autos.size - 1].performClick()+                    rule.waitForIdle()+                }             }         }         assertEquals("settings", viewModel.foregroundRoute)
camera/src/test/java/com/vayunmathur/camera/ui/CameraPanesComposeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraPanesComposeTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraPanesComposeTest.ktindex 6d4040e567..2a57c45a7c 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraPanesComposeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraPanesComposeTest.kt@@ -191,9 +191,12 @@ class CameraPanesComposeTest {         rule.setContent {             CameraPostProcessingSettings(                 noiseReductionEnabled = true, edgeSharpeningEnabled = false,+                motionPhotoEnabled = true,                 motionPhotoDuration = MotionPhotoDuration.THREE,+                motionPhotoBlockedByAvif = false,                 onNoiseReductionChange = { noise = it },                 onEdgeSharpeningChange = {},+                onMotionPhotoEnabledChange = {},                 onMotionDurationChange = {},             )         }
camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.ktindex 1fcc931949..49276ca310 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.kt@@ -4,7 +4,6 @@ import android.hardware.camera2.CameraMetadata import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import com.vayunmathur.camera.platform.AspectRatioOption-import com.vayunmathur.camera.platform.AudioInputSource import com.vayunmathur.camera.platform.CameraMode import com.vayunmathur.camera.platform.FlashMode import com.vayunmathur.camera.platform.TimerDuration@@ -37,7 +36,7 @@ class CameraScreenStateTest {         flashMode = FlashMode.OFF,         torchEnabled = false,         videoCodec = VideoCodec.AVC,-        audioInputSource = AudioInputSource.CAMCORDER,+        audioInputDevice = com.vayunmathur.camera.platform.camera2.AudioInputDeviceSelection.AUTO,         isRecording = false,         recordingDuration = 0,         timerCountdown = 0,
camera/src/test/java/com/vayunmathur/camera/ui/PreviewGalleryComposeExtraTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/PreviewGalleryComposeExtraTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/PreviewGalleryComposeExtraTest.ktindex ee41d888cc..fff26e490d 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/PreviewGalleryComposeExtraTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/PreviewGalleryComposeExtraTest.kt@@ -43,7 +43,7 @@ class PreviewGalleryComposeExtraTest {         selectedLens = null, availableLenses = emptyList(), hasFlashUnit = true,         flashMode = FlashMode.AUTO, torchEnabled = false,         videoCodec = viewModel.videoCodecMutable.value,-        audioInputSource = viewModel.audioInputSourceMutable.value,+        audioInputDevice = viewModel.audioInputDeviceMutable.value,         isRecording = mode == CameraMode.VIDEO, recordingDuration = 3, timerCountdown = 0,         qrResult = null,         aspectRatio = AspectRatioOption.RATIO_16_9,