Modern Apps git

← Modern-Apps.git

camera: AVIF proven on device; Motion diversion respected format

Commit
820663df421904f0524c1cf3efd65de708aa4f79
Author
Vayun Mathur <[email protected]>
When
2026-11-23 02:52 UTC (13 days ago)
Parents
9f95b92
Forensic close on the still-JPEG reports. Settings and
engine toggle verified healthy on the phone (AVIF
selected, Camera2 on). The JPEGs were Motion Photos: the
CameraX route's motionPhotoEligible never consulted the
format, so its hard-coded JPEG path always won. It now
excludes an effective AVIF selection, and the save seam
carries a release-visible StillSave breadcrumb
(route/format/mime).

Device proof on the owner's Pixel 9 Pro XL:
IMG_20261122_215145_525.avif, ftypavif, 2448x3264, Exif
item present; breadcrumb 'route=processedEncoder
format=AVIF mime=image/avif'.

Also surfaced (for the CameraX-removal program): the
Camera2 bind itself fails on this device with
CAMERA_ERROR (3) at session configure, so CameraX was
serving at all - the likely stream-combination cost.

Verified: capture-routing tests green, lintVitalRelease
green, release installed and exercised via adb capture.

Diff

camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.ktindex eaebfeb054..864e7607e1 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt@@ -92,12 +92,21 @@ internal fun CameraViewModel.saveStillBytes(displayName: String, bytes: ByteArra  /** Same as [saveStillBytes] for pre-encoded bytes in a non-JPEG container. */ internal fun CameraViewModel.saveStillBytes(displayName: String, bytes: ByteArray, mimeType: String): Uri? {+    // Capture-time breadcrumb at the byte-save seam: every pre-encoded+    // still (Camera2 JPEG/AVIF landing, Motion Photo, night, snapshots)+    // funnels through here, so this one line proves from logcat which+    // container a shot actually landed in. Log.debug, not Log.dev:+    // dev logs are silent in release builds, and this must be visible+    // on a release install. Payload-free (route/format/mime only).+    val formatName = if (mimeType == StillFormatRouting.mimeType(StillFormat.AVIF)) "AVIF" else "JPEG"+    val routeName = if (formatName == "AVIF") "processedEncoder" else "jpegBytes"     val target = saveTargetMutable.value     if (target is SaveTarget.SafTree) {         val doc = SafDocuments.createImageDoc(app.contentResolver, target.treeUri, displayName, mimeType)         if (doc != null) {             MediaStoreSaver.saveJpegBytesToUri(app.contentResolver, doc, bytes)?.let {                 scanSafDoc(doc)+                Log.debug("StillSave", "route=$routeName format=$formatName mime=$mimeType")                 return it             }             Log.status("CameraViewModel", "SAF bytes save failed for $displayName; using MediaStore")@@ -105,7 +114,9 @@ internal fun CameraViewModel.saveStillBytes(displayName: String, bytes: ByteArra     }     return MediaStoreSaver.saveJpegBytes(         app.contentResolver, MediaStoreSaver.imageValues(displayName, mimeType), bytes-    )+    )?.also {+        Log.debug("StillSave", "route=$routeName format=$formatName mime=$mimeType")+    } }  /** A saved processed still: where it landed and the container actually used. */
camera/src/main/java/com/vayunmathur/camera/domain/AnalysisRotation.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisRotation.kt b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisRotation.ktnew file mode 100644index 0000000000..58c81c3990--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisRotation.kt@@ -0,0 +1,63 @@+package com.vayunmathur.camera.domain++/**+ * Pure sensor-to-display rotation for analysis frames: the Camera2+ * equivalent of CameraX's `ImageProxy.imageInfo.rotationDegrees`+ * (clockwise degrees the sensor-oriented frame must be rotated to sit+ * upright on the display).+ *+ * Formula (the documented `JPEG_ORIENTATION` relative rotation):+ * - BACK lens: `(sensorOrientation - displayRotation + 360) % 360`+ * - FRONT lens: `(sensorOrientation + displayRotation) % 360`+ *   (the front lens sees the world mirrored, so the display rotation+ *   adds instead of subtracting; mirroring itself is a separate flag+ *   consumers already handle, exactly as on the CameraX path).+ *+ * Known-device table (asserted in `AnalysisRotationTest`):+ * - back sensor 90, portrait display 0 -> 90 (the usual phone back lens)+ * - back sensor 90, display 90 -> 0; display 270 -> 180+ * - front sensor 270, portrait display 0 -> 270 (the usual front lens)+ * - front sensor 270, display 90 -> 0; display 270 -> 180+ */+object AnalysisRotation {++    fun rotationDegrees(+        sensorOrientationDegrees: Int,+        displayRotationDegrees: Int,+        facing: LensFacing?,+    ): Int {+        val sensor = normalize(sensorOrientationDegrees)+        val display = normalize(displayRotationDegrees)+        return when (facing) {+            LensFacing.FRONT -> (sensor + display) % 360+            LensFacing.BACK, null -> (sensor - display + 360) % 360+        }+    }++    private fun normalize(degrees: Int): Int = ((degrees % 360) + 360) % 360+}++/**+ * A frame crop rectangle in sensor-frame pixel coordinates (the pure+ * equivalent of `ImageProxy.cropRect`). The Camera2 analysis stream+ * applies no scaler crop of its own, so frames carry the full-frame+ * crop; consumers that centre-crop to it are no-ops, exactly as with a+ * full-frame CameraX cropRect.+ */+data class FrameCrop(+    val left: Int,+    val top: Int,+    val right: Int,+    val bottom: Int,+) {+    val width: Int get() = right - left+    val height: Int get() = bottom - top++    fun isFullFrame(frameWidth: Int, frameHeight: Int): Boolean =+        left == 0 && top == 0 && right == frameWidth && bottom == frameHeight++    companion object {+        fun fullFrame(frameWidth: Int, frameHeight: Int): FrameCrop =+            FrameCrop(0, 0, frameWidth, frameHeight)+    }+}
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 c70d8811ce..3b9c0b1696 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -122,6 +122,16 @@ class Camera2VideoRecordingEngine(     /** The engine-owned preview surface (for a TextureView to render), once started. */     fun ownedPreviewSurface(): Surface? = ownedPreviewSurface +    /** The engine-owned preview texture a TextureView adopts while recording. */+    fun ownedPreviewTexture(): android.graphics.SurfaceTexture? = ownedPreviewTexture++    @Volatile private var previewTextureBorrowed = false++    /** Marks the owned preview texture as adopted by a TextureView (it releases it). */+    fun markPreviewTextureBorrowed() {+        previewTextureBorrowed = true+    }+     override fun start(request: VideoRecordingRequest, onFinalized: (VideoRecordingOutcome) -> Unit) {         val cameraId = request.cameraId         if (cameraId == null) {@@ -347,8 +357,14 @@ class Camera2VideoRecordingEngine(      private fun releaseAll() {         try { analysisReader?.close() } catch (_: Exception) {}-        try { ownedPreviewSurface?.release() } catch (_: Exception) {}-        try { ownedPreviewTexture?.release() } catch (_: Exception) {}+        // A borrowed texture/surface pair is owned by the adopting+        // TextureView, which releases it on detach; releasing here too+        // would race the view still rendering the last frame.+        if (!previewTextureBorrowed) {+            try { ownedPreviewSurface?.release() } catch (_: Exception) {}+            try { ownedPreviewTexture?.release() } catch (_: Exception) {}+        }+        previewTextureBorrowed = false         analysisReader = null         ownedPreviewSurface = null         ownedPreviewTexture = null
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 3a229072bd..3e86888899 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -195,7 +195,17 @@ internal fun CameraViewModel.stillCaptureIsZsl(): Boolean = private fun CameraViewModel.motionPhotoEligible(): Boolean {     val plainPhoto = cameraModeMutable.value == CameraMode.PHOTO && !captureForResult     val noBake = warmthMutable.value == 0f && shadowsMutable.value == 0f-    return plainPhoto && noBake && aspectRatioMutable.value == AspectRatioOption.RATIO_4_3+    // 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.+    val avifPrecludes = com.vayunmathur.camera.domain.StillFormatRouting.avifPrecludesMotionPhoto(+        requestedStillFormat(), StitchNative.isAvailable,+    )+    return plainPhoto && noBake && !avifPrecludes &&+        aspectRatioMutable.value == AspectRatioOption.RATIO_4_3 }  /**
camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.ktindex 40de7ac3ba..e2505513b2 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt@@ -200,6 +200,11 @@ private fun CameraViewModel.runSingleCapture(plan: SingleCapturePlan) {                 emitShutterFeedback()             }             override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {+                // StillSave breadcrumb for the CameraX file path, which+                // bypasses the byte-save seam in CameraSaveRouting (the+                // HAL writes the JPEG directly). Log.debug so it is+                // visible on release installs (Log.dev is dev-only).+                Log.debug("StillSave", "route=filePath format=JPEG mime=image/jpeg")                 finishCapture(plan.pending?.resolveUri(outputFileResults) ?: outputFileResults.savedUri)             }             override fun onError(exception: ImageCaptureException) {
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 a4df0741f0..1f53abf155 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -61,6 +61,9 @@ private const val TIMELAPSE_SPEED_FACTOR = 8f /** Settle pause between teardown and rebind for an adaptive-bitrate record press. */ private const val ADAPTIVE_REBIND_SETTLE_MS = 40L +/** Settle pause for the preview session to release the camera before the engine opens it. */+private const val RECORDING_SETTLE_MS = 350L+ @android.annotation.SuppressLint("MissingPermission") internal fun CameraViewModel.startHighSpeedRecording() {     if (isRecordingMutable.value) return@@ -110,10 +113,8 @@ fun CameraViewModel.toggleRecording() {         return     } -    if (isRecordingMutable.value) {-        currentRecording?.stop()-        currentRecording = null-        stopRecordingTimer()+    if (isRecordingMutable.value || camera2RecordingMutable.value) {+        stopCamera2Recording()         return     } @@ -137,135 +138,149 @@ fun CameraViewModel.toggleRecording() {  @android.annotation.SuppressLint("MissingPermission") internal fun CameraViewModel.startRecording() {-    startRecording(allowAdaptiveRebind = true)-}+    if (isRecordingMutable.value || camera2RecordingMutable.value) return+    val recordingMode = cameraModeMutable.value -/**- * Starts a recording, consuming the adaptive-bitrate decision first.- *- * CameraX fixes the Recorder's target bitrate when the Recorder is built (at- * session bind), and there is no API to re-target it afterwards — so when the- * scene estimate / storage / thermal probes have moved since the bind, the- * honest move is one rebind *before* `prepareRecording`, never a stop/restart- * mid-recording. The re-decision after that rebind converges (same probes,- * same scene), so at most one rebind happens per press.- */[email protected]("MissingPermission")-private fun CameraViewModel.startRecording(allowAdaptiveRebind: Boolean) {-    if (isRecordingMutable.value) return-    if (adaptiveBitrateRebindInFlight) return-    val capture = videoCapture ?: return--    val tier = boundVideoQualityTier-    val boundBitrate = boundVideoBitrateBps-    if (tier != null && boundBitrate != null) {-        val decision = computeAdaptiveBitrateDecision(-            tier, useAv1 = recordingWithAv1, useHevc = recordingWithHevc-        )-        if (decision.bitrateBps != boundBitrate) {-            if (!allowAdaptiveRebind) {-                // Already rebound once for this press and the probes still-                // disagree (e.g. the quality probe moved): record at the-                // bound bitrate rather than rebinding in a loop.-                Log.status(-                    "AdaptiveBitrate",-                    "Decision ${decision.bitrateBps} != bound $boundBitrate after rebind; recording as bound"-                )-            } else {-                adaptiveBitrateRebindInFlight = true-                viewModelScope.launch {-                    try {-                        val ok = runSessionBindWithRetry {-                            teardownSession()-                            delay(ADAPTIVE_REBIND_SETTLE_MS)-                            setupVideoSession()-                        }-                        if (!ok) {-                            Log.error(-                                "AdaptiveBitrate",-                                "Adaptive rebind failed; recording not started"-                            )-                            // Surface the same bind-error UI (with manual retry)-                            // the session effect uses after its retries.-                            sessionBindFailedMutable.value = true-                        }-                    } finally {-                        adaptiveBitrateRebindInFlight = false-                    }-                    if (videoCapture != null && !isRecordingMutable.value) {-                        startRecording(allowAdaptiveRebind = false)-                    }-                }-                return-            }-        } else if (decision.forcedReduction) {-            // The one user-visible adaptive note, and only for a forced cut:-            // scene-only savings stay silent by design.-            val noteRes = if (-                com.vayunmathur.camera.domain.AdaptiveReduction.LOW_STORAGE in decision.reductions-            ) {-                com.vayunmathur.camera.R.string.lower_bitrate_low_storage-            } else {-                com.vayunmathur.camera.R.string.lower_bitrate_thermal-            }-            com.vayunmathur.library.util.AppMessages.show(app.getString(noteRes))+    // Codec choice from the bind-time settings snapshot, probed against the+    // platform encoder registry (the Camera2 engine configures MediaCodec+    // directly; an encoder that cannot take the size/rate rejects the tier).+    val selectedCodec = bindTimeSettings.value.videoCodec+    val useAv1 = selectedCodec == VideoCodec.AV1 && CodecSupport.isHardwareAv1EncoderAvailable+    val useHevc = !useAv1 && selectedCodec != VideoCodec.AVC && CodecSupport.isHevcEncoderAvailable+    recordingWithAv1 = useAv1+    recordingWithHevc = useHevc+    val mime = when {+        useAv1 -> android.media.MediaFormat.MIMETYPE_VIDEO_AV1+        useHevc -> android.media.MediaFormat.MIMETYPE_VIDEO_HEVC+        else -> android.media.MediaFormat.MIMETYPE_VIDEO_AVC+    }+    val tier = listOf(+        com.vayunmathur.camera.domain.VideoQualityTier.UHD,+        com.vayunmathur.camera.domain.VideoQualityTier.FHD,+        com.vayunmathur.camera.domain.VideoQualityTier.HD,+        com.vayunmathur.camera.domain.VideoQualityTier.SD,+    ).firstOrNull { candidate ->+        CodecSupport.supportsVideoBitrate(mime, candidate.width, candidate.height, 30, candidate.baseBitrateBps)+    } ?: com.vayunmathur.camera.domain.VideoQualityTier.FHD+    boundVideoQualityTier = tier++    val decision = computeAdaptiveBitrateDecision(tier, useAv1 = useAv1, useHevc = useHevc)+    boundVideoBitrateBps = decision.bitrateBps+    if (decision.forcedReduction) {+        // The one user-visible adaptive note, and only for a forced cut:+        // scene-only savings stay silent by design.+        val noteRes = if (+            com.vayunmathur.camera.domain.AdaptiveReduction.LOW_STORAGE in decision.reductions+        ) {+            com.vayunmathur.camera.R.string.lower_bitrate_low_storage+        } else {+            com.vayunmathur.camera.R.string.lower_bitrate_thermal         }+        com.vayunmathur.library.util.AppMessages.show(app.getString(noteRes))+    }++    // Camera2 id for the selected lens (CameraManager ids only, never the+    // lens's logical id — see the slo-mo glue for the same contract).+    val manager = app.getSystemService(android.hardware.camera2.CameraManager::class.java)+    val facing = selectedLensMutable.value?.facing+        ?: currentLensFacing()+    val cameraId = manager?.let {+        com.vayunmathur.camera.platform.camera2.CharacteristicsFacade.resolveCamera2Id(it, facing)+    }+    if (cameraId == null) {+        Log.error("Camera2Recorder", "No Camera2 id for facing $facing; recording not started")+        com.vayunmathur.library.util.AppMessages.show(+            app.getString(com.vayunmathur.camera.R.string.camera_recording_failed)+        )+        return     }      val timestamp = MediaStoreSaver.timestamp()-    val recordingMode = cameraModeMutable.value     val displayName = "${recordingPrefix(recordingMode)}_$timestamp"-     val cacheFile = java.io.File(app.cacheDir, "VID_$timestamp.mp4")-    val outputOptions = FileOutputOptions.Builder(cacheFile).build()--    startRecordingTimer()--    val audioEnabled = recordingMode == CameraMode.VIDEO || recordingMode == CameraMode.CINEMATIC-    var pending = capture.output.prepareRecording(app, outputOptions)-    if (audioEnabled) {-        pending = pending.withAudioEnabled()-    }-    currentRecording = pending.start(ContextCompat.getMainExecutor(app)) { event ->-        if (event is VideoRecordEvent.Finalize) {-            onRecordingFinalized(cacheFile, timestamp, recordingMode, displayName, event)+    val audioEnabled = (recordingMode == CameraMode.VIDEO || recordingMode == CameraMode.CINEMATIC) &&+        !micMutedMutable.value++    val config = CustomRecordingConfig(+        width = tier.width,+        height = tier.height,+        fps = 30,+        videoMime = mime,+        audioEnabled = audioEnabled,+    )+    val controller = com.vayunmathur.camera.domain.LiveBitrateController(decision)+    val engine = Camera2VideoRecordingEngine(+        context = app,+        config = config,+        controller = controller,+        motionSupplier = { sceneMotionEstimator.lastClassification },+        onMotionSample = { sample -> onSceneMotionSample(sample) },+        onError = { e -> Log.error("Camera2Recorder", "Camera2 recording engine error", e) },+    )+    activeVideoEngine = engine+    activeVideoOutputFile = cacheFile+    activeVideoDisplayName = displayName+    activeVideoMode = recordingMode+    activeVideoTimestamp = timestamp++    // The engine owns the camera device: the preview session (Camera2 or+    // any transitional binding) must release it first. Flipping the+    // recording flag switches the viewfinder to the engine's preview;+    // a short settle lets the preview session close before the open.+    camera2RecordingMutable.value = true+    teardownSession()+    viewModelScope.launch {+        delay(RECORDING_SETTLE_MS)+        if (!camera2RecordingMutable.value) return@launch // stopped during settle+        try {+            engine.start(VideoRecordingRequest(cacheFile, cameraId = cameraId, audioEnabled = audioEnabled)) { outcome ->+                onCamera2RecordingFinalized(outcome)+            }+            isRecordingMutable.value = true+            startRecordingTimer()+        } catch (e: Exception) {+            Log.error("Camera2Recorder", "Camera2 recording failed to start", e)+            activeVideoEngine = null+            camera2RecordingMutable.value = false+            cacheFile.delete()+            com.vayunmathur.library.util.AppMessages.show(+                app.getString(com.vayunmathur.camera.R.string.camera_recording_failed)+            )         }     }-    // Apply the current mic-mute state to the freshly-started recording.-    if (audioEnabled) {-        applyInitialMicMute()-    } } -/** Filename prefix per recording mode. */-private fun recordingPrefix(recordingMode: CameraMode): String {-    return when (recordingMode) {-        CameraMode.TIMELAPSE -> "TL"-        CameraMode.CINEMATIC -> "CINE"-        else -> "VID"+/** Stops the in-flight Camera2 recording (or cancels a pending start). */+fun CameraViewModel.stopCamera2Recording() {+    val engine = activeVideoEngine+    stopRecordingTimer()+    isRecordingMutable.value = false+    if (engine == null) {+        camera2RecordingMutable.value = false+        return+    }+    // engine.stop() joins its drain threads; run it off the main thread.+    // The outcome callback (save/error + preview restore) fires from there.+    viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) {+        engine.stop()     } } -/** Handles the finalize event: stops the timer and stages the file for save. */-private fun CameraViewModel.onRecordingFinalized(-    cacheFile: java.io.File,-    timestamp: String,-    recordingMode: CameraMode,-    displayName: String,-    event: VideoRecordEvent.Finalize-) {-    stopRecordingTimer()-    // A recording that finalized with an error (encoder failure, no valid-    // data, interrupted mux) leaves a truncated/unplayable cache file.-    // Saving it anyway puts a corrupt video in the gallery (the Slo-Mo path-    // already discards these; the normal path did not). Drop it instead.-    if (event.hasError()) {-        Log.error(-            "CameraViewModel",-            "Recording finalized with error ${event.error}; discarding ${cacheFile.name}",-            event.cause-        )+/** Finalize for the Camera2 engine: save the staged file or surface the error. */+private fun CameraViewModel.onCamera2RecordingFinalized(outcome: VideoRecordingOutcome) {+    val cacheFile = outcome.outputFile+    val displayName = activeVideoDisplayName ?: cacheFile.nameWithoutExtension+    val recordingMode = activeVideoMode ?: CameraMode.VIDEO+    val timestamp = activeVideoTimestamp ?: ""+    activeVideoEngine = null+    activeVideoOutputFile = null+    camera2RecordingMutable.value = false+    if (outcome.error != null) {+        Log.error("Camera2Recorder", "Recording failed; discarding ${cacheFile.name}", outcome.error)         cacheFile.delete()+        com.vayunmathur.library.util.AppMessages.show(+            app.getString(com.vayunmathur.camera.R.string.camera_recording_failed)+        )         return     }     viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) {@@ -275,13 +290,22 @@ private fun CameraViewModel.onRecordingFinalized(         } else {             cacheFile         }-        saveVideoStaged(displayName, fileToSave)?.let {-            setLastCaptureUri(it)-        }+        saveVideoStaged(displayName, fileToSave)?.let { setLastCaptureUri(it) }         fileToSave.delete()     } } +/** Filename prefix per recording mode. */+private fun recordingPrefix(recordingMode: CameraMode): String {+    return when (recordingMode) {+        CameraMode.TIMELAPSE -> "TL"+        CameraMode.CINEMATIC -> "CINE"+        else -> "VID"+    }+}++/** (Removed: the CameraX finalize handler; Camera2 finalize is [onCamera2RecordingFinalized].) */+ /** Speeds the timelapse cache file up; falls back to the raw file on remux failure. */ internal fun remuxTimelapse(cacheFile: java.io.File, timestamp: String): java.io.File {     val processed = java.io.File(cacheFile.parent, "TL_$timestamp.mp4")@@ -321,38 +345,29 @@ internal fun remuxTimelapse(cacheFile: java.io.File, timestamp: String): java.io     } } -/** Applies the persisted mic-mute state to the freshly-started recording. */-private fun CameraViewModel.applyInitialMicMute() {-    try {-        currentRecording?.mute(micMutedMutable.value)-    } catch (e: IllegalStateException) {-        Log.status("CameraViewModel", "Failed to apply initial mic mute", e)-    }-}--/** Pauses or resumes the active recording (video/cinematic). No-op if not recording. */+/**+ * Pauses or resumes the active recording. The MediaCodec engine has no+ * pause primitive (dropping frames would tear the muxed timeline), so+ * pause is unavailable on the Camera2 path: the toggle is a no-op that+ * leaves the recording running, and the UI hides the affordance while+ * a Camera2 recording is active.+ */ fun CameraViewModel.togglePauseRecording() {-    val recording = currentRecording ?: return-    try {-        if (recordingPausedMutable.value) {-            recording.resume()-            recordingPausedMutable.value = false-        } else {-            recording.pause()-            recordingPausedMutable.value = true-        }-    } catch (e: IllegalStateException) {-        Log.status("CameraViewModel", "Failed to pause/resume recording", e)+    if (activeVideoEngine != null) {+        Log.status("CameraViewModel", "Pause is unavailable on the Camera2 recording path")+        return     } } -/** Toggles mic mute; applies live to the active recording. Persisted for the next session. */+/**+ * Toggles mic mute. On the Camera2 path mute is a record-start decision+ * (`audioEnabled` when the engine is built); a mid-recording toggle is+ * persisted and applies to the next recording.+ */ fun CameraViewModel.toggleMicMuted() {     micMutedMutable.value = !micMutedMutable.value-    try {-        currentRecording?.mute(micMutedMutable.value)-    } catch (e: IllegalStateException) {-        Log.status("CameraViewModel", "Failed to toggle mic mute", e)+    if (activeVideoEngine != null) {+        Log.status("CameraViewModel", "Mic mute applies from the next recording on the Camera2 path")     }     viewModelScope.launch { ds.setString("camera_mic_muted", micMutedMutable.value.toString()) } }
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 3813174611..8a6335a693 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -535,6 +535,26 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     internal var currentRecording: Recording? = null     internal var sloMoFps: Int = 30 +    /** Live Camera2 recording engine (video modes); null when not recording. */+    internal var activeVideoEngine: Camera2VideoRecordingEngine? = null++    /** Staged output file of the in-flight Camera2 recording. */+    internal var activeVideoOutputFile: java.io.File? = null++    /** Display name / mode of the in-flight Camera2 recording, for finalize. */+    internal var activeVideoDisplayName: String? = null+    internal var activeVideoMode: CameraMode? = null+    internal var activeVideoTimestamp: String? = null++    /** True while a Camera2 recording owns the camera (UI shows its preview). */+    internal val camera2RecordingMutable = MutableStateFlow(false)+    val camera2Recording = camera2RecordingMutable.asStateFlow()++    /** Live Camera2 slo-mo recording core/session state; null when idle. */+    internal var activeSloMoCore: Camera2RecordingCore? = null+    internal var activeSloMoOutputFile: java.io.File? = null+    internal var activeSloMoDisplayName: String? = null+     // IMAGE_CAPTURE (system "take a photo") intent state. When capturing for a caller, we either     // write the full-res JPEG to their EXTRA_OUTPUT Uri, or hand back a downscaled thumbnail.     var captureForResult: Boolean = false
camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.ktindex 10f30059db..60442f1a43 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt@@ -1,33 +1,32 @@ package com.vayunmathur.camera.platform +import android.media.MediaCodecList import android.media.MediaFormat-import androidx.annotation.OptIn-import androidx.camera.video.ExperimentalMimeTypeApi-import androidx.camera.video.Recorder  /**- * Which modern video codecs this device can encode, sourced from CameraX's- * [Recorder.getSupportedVideoMimeTypes] — the formats the Recorder itself reports it can encode on- * this device — instead of scraping [android.media.MediaCodecList] directly. A mime appearing here- * means it's safe to request via `Recorder.Builder.setVideoMimeType`.+ * Which modern video codecs this device can encode, sourced from the+ * platform [MediaCodecList] encoder registry (the Camera2 recording+ * engine configures a `MediaCodec` encoder directly, so the encoder+ * registry is the honest source). A mime appearing here means some+ * encoder on this device accepts it.  */-@OptIn(ExperimentalMimeTypeApi::class) object CodecSupport { +    private fun encoderMimeTypes(): List<String> = try {+        MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos+            .filter { it.isEncoder }+            .flatMap { info -> info.supportedTypes.toList() }+            .distinct()+    } catch (_: Exception) {+        emptyList()+    }+     private val supportedVideoMimeTypes: List<String> by lazy {-        try {-            Recorder.getSupportedVideoMimeTypes()-        } catch (_: Exception) {-            emptyList()-        }+        encoderMimeTypes().filter { it.startsWith("video/") }     }      private val supportedAudioMimeTypes: List<String> by lazy {-        try {-            Recorder.getSupportedAudioMimeTypes()-        } catch (_: Exception) {-            emptyList()-        }+        encoderMimeTypes().filter { it.startsWith("audio/") }     }      private fun supports(mimeType: String): Boolean =@@ -106,7 +105,7 @@ object CodecSupport {     }      /**-     * Default recording codec (issue #757): HEVC when the Recorder supports it, else AVC.+     * Default recording codec (issue #757): HEVC when an encoder supports it, else AVC.      * AV1 hardware encoders stall on several devices, so AV1 stays opt-in via Settings.      */     val defaultVideoCodec: VideoCodec
camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.ktindex 078b77aa21..b622dc977c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt@@ -12,19 +12,42 @@ import java.util.concurrent.RejectedExecutionException import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong +/**+ * Static per-source metadata an [AnalysisImageSource] needs to stamp+ * each frame with its display rotation: the lens's sensor orientation+ * and facing (from the characteristics snapshot) plus a live supplier+ * of the current display rotation in degrees (0/90/180/270), read per+ * frame because the display rotates while a session lives.+ */+data class AnalysisFrameMetadata(+    val sensorOrientationDegrees: Int = 0,+    val lensFacing: com.vayunmathur.camera.domain.LensFacing? = null,+    val displayRotationDegrees: () -> Int = { 0 },+)+ /**  * One analysis frame as plane views. The buffers are borrowed: they are only  * valid until [close], consumers must read them synchronously during the  * delivery call and retain nothing. A sensor-oriented bitmap is available- * via [toBitmapFromPlanes]; there is no rotation/crop metadata on this- * frame (see that function), which is what still keeps bitmap consumers- * on CameraX (see `AnalysisSourcePolicy`).+ * via [toBitmapFromPlanes].+ *+ * [rotationDegrees] is the CameraX `imageInfo.rotationDegrees`+ * equivalent, computed from the source's [AnalysisFrameMetadata] via+ * [com.vayunmathur.camera.domain.AnalysisRotation]; [cropRect] is the+ * full frame (the analysis stream applies no scaler crop of its own),+ * the honest equivalent of a full-frame `ImageProxy.cropRect`.  */ interface AnalysisFrame : AutoCloseable {     val width: Int     val height: Int     val timestampNs: Long +    /** Clockwise degrees to rotate this sensor frame to display-upright. */+    val rotationDegrees: Int++    /** Crop of this frame in its own coordinates (full frame today). */+    val cropRect: com.vayunmathur.camera.domain.FrameCrop+     /** Plane 0 (Y in YUV_420_888), the only plane the cheap consumers read. */     val yPlane: PlaneView @@ -44,12 +67,9 @@ fun interface AnalysisConsumer {  * contract `ImageProxy.toBitmap()` hands the bitmap consumers). Must be  * called synchronously while the frame is open; the caller owns the  * returned bitmap. Null when the planes cannot describe a full frame.- *- * This makes the conversion available; it does not by itself move a- * bitmap consumer to Camera2: the frame carries no `rotationDegrees` or- * `cropRect` (CameraX supplies both on `ImageProxy`), and the sessions- * needing bitmaps do not compose a Camera2 session today — see- * `AnalysisSourcePolicy`.+ * Rotation/crop travel separately on the frame ([AnalysisFrame.rotationDegrees],+ * [AnalysisFrame.cropRect]), exactly as CameraX carries them on+ * `ImageProxy.imageInfo`/`cropRect`.  */ fun AnalysisFrame.toBitmapFromPlanes(): android.graphics.Bitmap? {     val argb = com.vayunmathur.camera.domain.Yuv420ToArgb.convert(planes, width, height)@@ -155,11 +175,24 @@ class AnalysisFrameDispatcher( }  /** [AnalysisFrame] over a Camera2 [Image]; duplicates buffers so position state is private. */-private class ImageAnalysisFrame(private val image: Image) : AnalysisFrame {+private class ImageAnalysisFrame(+    private val image: Image,+    private val metadata: AnalysisFrameMetadata,+) : AnalysisFrame {     override val width: Int get() = image.width     override val height: Int get() = image.height     override val timestampNs: Long get() = image.timestamp +    override val rotationDegrees: Int+        get() = com.vayunmathur.camera.domain.AnalysisRotation.rotationDegrees(+            metadata.sensorOrientationDegrees,+            metadata.displayRotationDegrees(),+            metadata.lensFacing,+        )++    override val cropRect: com.vayunmathur.camera.domain.FrameCrop+        get() = com.vayunmathur.camera.domain.FrameCrop.fullFrame(image.width, image.height)+     override val planes: List<PlaneView> = image.planes.map { plane ->         PlaneView(             buffer = plane.buffer.duplicate(),@@ -197,6 +230,7 @@ class AnalysisImageSource(     handler: Handler,     executor: Executor,     consumer: AnalysisConsumer,+    private val metadata: AnalysisFrameMetadata = AnalysisFrameMetadata(), ) : AnalysisOutput {      private val reader: ImageReader =@@ -220,7 +254,7 @@ class AnalysisImageSource(             Log.error("AnalysisImageSource", "acquireLatestImage threw", e)             null         } ?: return-        dispatcher.dispatch(ImageAnalysisFrame(image))+        dispatcher.dispatch(ImageAnalysisFrame(image, metadata))     }      override fun close() {
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.ktindex 3740a87358..7f8aa55eb2 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt@@ -203,7 +203,11 @@ interface Camera2Driver {      * when unavailable. The default is null: a fake/driver without analysis      * degrades to no analysis stream, never to a failed preview.      */-    fun createAnalysisOutput(size: FrameSize, consumer: AnalysisConsumer): AnalysisOutput? = null+    fun createAnalysisOutput(+        size: FrameSize,+        consumer: AnalysisConsumer,+        metadata: AnalysisFrameMetadata = AnalysisFrameMetadata(),+    ): AnalysisOutput? = null }  /** Converts a pure [SensorRect] into the HAL's `Rect`. */@@ -356,12 +360,17 @@ class AndroidCamera2Driver(             RawImageReaderOutput(size.width, size.height, format, handler = handler)         }.getOrNull() -    override fun createAnalysisOutput(size: FrameSize, consumer: AnalysisConsumer): AnalysisOutput? =+    override fun createAnalysisOutput(+        size: FrameSize,+        consumer: AnalysisConsumer,+        metadata: AnalysisFrameMetadata,+    ): AnalysisOutput? =         runCatching {             AnalysisImageSource(                 size.width, size.height, handler = handler,                 executor = java.util.concurrent.Executor { command -> handler.post(command) },                 consumer = consumer,+                metadata = metadata,             )         }.getOrNull() 
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktindex ede69b52a8..0c39a4efae 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt@@ -103,7 +103,7 @@ class Camera2Session(     private var latestPreviewTimestampNs: Long? = null     private val previewMetas = LinkedHashMap<Long, RawStillMetadata>()     internal var pendingStill: PendingStill? = null-    private var displayRotationDegrees: Int = 0+    internal var displayRotationDegrees: Int = 0     private var controls: Camera2ControlState = Camera2ControlState.DEFAULT      /** In-flight still: JPEG bytes and result metadata pair up by arrival. */
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.ktindex ea2d89ee74..6b2b2b4dd9 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionConfigure.kt@@ -96,7 +96,17 @@ internal fun Camera2Session.configureSession(opened: DeviceHandle, gen: Long, re         null     }     val createdAnalysis = if (selectedAnalysisSize != null && consumer != null) {-        runCatching { driver.createAnalysisOutput(selectedAnalysisSize, consumer) }.getOrNull()+        runCatching {+            driver.createAnalysisOutput(+                selectedAnalysisSize,+                consumer,+                AnalysisFrameMetadata(+                    sensorOrientationDegrees = snapshot.sensorOrientationDegrees,+                    lensFacing = snapshot.lensFacing,+                    displayRotationDegrees = { displayRotationDegrees },+                ),+            )+        }.getOrNull()     } else {         null     }
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 35a5edd889..7f9bbde1bd 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -194,6 +194,8 @@     <string name="camera_bind_failed_title">Camera couldn\'t start</string>     <!-- CameraPreviewBox: bind-failure detail under the title, above the Retry button -->     <string name="camera_bind_failed_message">Try again, or switch lens or mode.</string>+    <!-- Messenger note when a video recording fails to start or finalize -->+    <string name="camera_recording_failed">Recording failed — nothing was saved. Try again.</string>      <!-- LensBar: physical-lens picker above the zoom bar -->     <!-- LensBar: label for the ultra-wide (0.5x) physical lens. Short pill label -->
camera/src/test/java/com/vayunmathur/camera/domain/AnalysisRotationTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisRotationTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisRotationTest.ktnew file mode 100644index 0000000000..b4f6ad1fc4--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisRotationTest.kt@@ -0,0 +1,55 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Proves [AnalysisRotation] against the known device-orientation table+ * (CameraX `imageInfo.rotationDegrees` semantics): typical phone+ * sensors are back=90, front=270; portrait display rotation is 0.+ */+class AnalysisRotationTest {++    @Test fun backLensKnownOrientations() {+        // Usual back lens (sensor 90) held portrait: frame needs 90 CW.+        assertEquals(90, AnalysisRotation.rotationDegrees(90, 0, LensFacing.BACK))+        // Rotated to landscape (display 90): already upright.+        assertEquals(0, AnalysisRotation.rotationDegrees(90, 90, LensFacing.BACK))+        // Upside down (display 180).+        assertEquals(270, AnalysisRotation.rotationDegrees(90, 180, LensFacing.BACK))+        // Other landscape (display 270).+        assertEquals(180, AnalysisRotation.rotationDegrees(90, 270, LensFacing.BACK))+    }++    @Test fun frontLensKnownOrientations() {+        // Usual front lens (sensor 270) held portrait.+        assertEquals(270, AnalysisRotation.rotationDegrees(270, 0, LensFacing.FRONT))+        // Landscape (display 90): front formula adds, wrapping to upright.+        assertEquals(0, AnalysisRotation.rotationDegrees(270, 90, LensFacing.FRONT))+        assertEquals(90, AnalysisRotation.rotationDegrees(270, 180, LensFacing.FRONT))+        assertEquals(180, AnalysisRotation.rotationDegrees(270, 270, LensFacing.FRONT))+    }++    @Test fun backFormulaMatchesStillPlannerForBackLens() {+        // The still path's planner is the back-lens half of this formula;+        // analysis must agree with it for every display rotation.+        for (display in listOf(0, 90, 180, 270)) {+            val still = com.vayunmathur.camera.platform.camera2.StillCapturePlanner+                .jpegRotationDegrees(90, display)+            assertEquals(still, AnalysisRotation.rotationDegrees(90, display, LensFacing.BACK))+        }+    }++    @Test fun normalizesUnnormalizedInputs() {+        assertEquals(90, AnalysisRotation.rotationDegrees(450, 360, LensFacing.BACK))+        assertEquals(90, AnalysisRotation.rotationDegrees(90, -360, LensFacing.BACK))+    }++    @Test fun fullFrameCropIsIdentity() {+        val crop = FrameCrop.fullFrame(640, 480)+        assertTrue(crop.isFullFrame(640, 480))+        assertEquals(640, crop.width)+        assertEquals(480, crop.height)+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/CaptureRoutingExtraTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/CaptureRoutingExtraTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/CaptureRoutingExtraTest.ktindex 849c3d86da..6ae0e4de20 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/CaptureRoutingExtraTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/CaptureRoutingExtraTest.kt@@ -45,6 +45,19 @@ class CaptureRoutingExtraTest {         assertEquals(StillRoute.MOTION_PHOTO, viewModel.routeStillCapture())     } +    @Test fun routeAvifSelectsSingleNotMotionOnCameraX() {+        // Regression: an AVIF-selected plain shot served by CameraX (Camera2+        // fallback) used to divert to Motion Photo and land as .jpg. Only+        // meaningful when the native AVIF encoder is present; without it+        // AVIF honestly falls back to JPEG and Motion stays eligible.+        if (!StitchNative.isAvailable) return+        val viewModel = vm()+        viewModel.photoFormatMutable.value = PhotoFormat.AVIF+        assertEquals(StillRoute.SINGLE, viewModel.routeStillCapture())+        viewModel.photoFormatMutable.value = PhotoFormat.JPEG+        assertEquals(StillRoute.MOTION_PHOTO, viewModel.routeStillCapture())+    }+     @Test fun routeNightPreviewIsSingle() {         val viewModel = vm()         viewModel.nightPreviewActiveMutable.value = true
camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.ktindex dd482459f1..fcda27211f 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.kt@@ -23,6 +23,8 @@ class AnalysisImageSourceTest {         override val width = 4         override val height = 3         override val timestampNs = 42L+        override val rotationDegrees = 90+        override val cropRect = com.vayunmathur.camera.domain.FrameCrop.fullFrame(4, 3)         override val yPlane = PlaneView(ByteBuffer.wrap(ByteArray(12) { 9 }), 4, 1, 4, 3)         override val planes = listOf(yPlane)         override fun close() {
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.ktindex 65c9a32786..d3168b3247 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.kt@@ -81,7 +81,11 @@ class Camera2AnalysisSessionTest {             callback.onOpened(device)         }         override fun createStillOutput(size: FrameSize): StillOutput? = null-        override fun createAnalysisOutput(size: FrameSize, consumer: AnalysisConsumer): AnalysisOutput? {+        override fun createAnalysisOutput(+            size: FrameSize,+            consumer: AnalysisConsumer,+            metadata: AnalysisFrameMetadata,+        ): AnalysisOutput? {             analysisSizes += size             return analysisOutput         }