Modern Apps git

← Modern-Apps.git

camera: remove CameraX entirely - every mode is Camera2

Commit
846c79fe206d6c5b1111dc771a5a554761bd7752
Author
Vayun Mathur <[email protected]>
When
2026-11-23 05:58 UTC (13 days ago)
Parents
820663d
Owner order: CameraX gone. Zero androidx.camera references
remain (code, tests, gradle). Video records through the
Camera2 MediaCodec engine with live adaptive bitrate
(device-verified: UHD HEVC mp4, ffprobe-valid). Slo-mo's
final readiness piece was verified on device (240->30
stretch read-back true) and recording is Camera2 (1080p
slomo mp4 pulled). Bitmap modes (QR/portrait/pano/Motion
Photo) run on AnalysisFrame rotation/crop metadata +
YUV->ARGB conversion. All previews bind Camera2; the
CameraX fallback latches and engine toggles are deleted -
bind failure is now an error surface with manual retry.
Tests rewritten as Camera2 contract tests (458 green);
lintVitalRelease and assembleRelease green.

Device-found blocker this exposed: the full stream combo
(max JPEG + JPEG_R + RAW ring + YUV ring + analysis)
exceeds this phone's HAL configure limits - previously
masked by the CameraX fallback. An output-profile degrade
ladder (sheds JPEG_R/RAW, then ring, then analysis) plus
a 4MP YUV-ring cap restores configure; the ladder build
passed full device smoke (still AVIF + video + slo-mo)
except the final ring-cap delta, whose reinstall+recheck
awaits the phone reconnecting (tunnel offline at 00:54).

Diff

camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex 31efb92e41..471ab21f62 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -135,13 +135,6 @@ rustNativeTests { }  dependencies {-    implementation(libs.androidx.camera.core)-    implementation(libs.androidx.camera.camera2)-    implementation(libs.androidx.camera.lifecycle)-    implementation(libs.androidx.camera.view)-    implementation(libs.androidx.camera.video)-    implementation(libs.androidx.camera.compose)-    implementation(libs.androidx.camera.extensions)     implementation(libs.androidx.exifinterface)     implementation(libs.zxing.core)     // On-device portrait segmentation and matting. MediaPipe Selfie Segmentation
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 864e7607e1..71e9cbb45e 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt@@ -5,7 +5,6 @@ import android.media.MediaScannerConnection import android.net.Uri import android.provider.MediaStore import com.vayunmathur.library.log.Log-import androidx.camera.core.ImageCapture import androidx.core.content.ContextCompat import java.io.OutputStream import com.vayunmathur.camera.domain.StillFormat@@ -14,73 +13,6 @@ import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.EncodedStill import com.vayunmathur.camera.platform.StillEncoder.encode import com.vayunmathur.camera.platform.buildAvifExifTiff-import com.vayunmathur.camera.platform.mirrorCaptures--/**- * Shared save-target routing for still captures. When the user picked a SAF- * folder, creates a document there and builds stream-backed- * [ImageCapture.OutputFileOptions]; otherwise builds the classic MediaStore- * options. The caller closes [PendingStill.stream] in both save callbacks- * (close is idempotent even if CameraX already closed it) and must prefer- * [PendingStill.saveUri] over `outputFileResults.savedUri` (null for streams).- */-internal data class PendingStill(-    val outputOptions: ImageCapture.OutputFileOptions,-    /** The URI the capture will land at (doc URI for SAF, null → use savedUri). */-    val saveUri: Uri?,-    val stream: OutputStream?,-    /** Display name used, for logging. */-    val displayName: String,-)--internal fun CameraViewModel.prepareStillSave(displayName: String): PendingStill? {-    // Refresh the fix at capture time: lastLocation is otherwise only read on screen-    // launch / settings toggle and can be stale or null (issue #731).-    updateLocation()-    val metadata = ImageCapture.Metadata().apply {-        if (locationEnabledMutable.value) location = lastLocation-        isReversedHorizontal = mirrorCaptures-    }-    val target = saveTargetMutable.value-    if (target is SaveTarget.SafTree) {-        val doc = SafDocuments.createImageDoc(app.contentResolver, target.treeUri, displayName)-        if (doc != null) {-            try {-                val stream = app.contentResolver.openOutputStream(doc)-                if (stream != null) {-                    val options = ImageCapture.OutputFileOptions.Builder(stream)-                        .setMetadata(metadata).build()-                    return PendingStill(options, doc, stream, displayName)-                }-                Log.status("CameraViewModel", "Could not open SAF doc for $displayName; using MediaStore")-            } catch (e: java.io.FileNotFoundException) {-                Log.status("CameraViewModel", "SAF still save failed for $displayName; using MediaStore", e)-            } catch (e: SecurityException) {-                Log.status("CameraViewModel", "SAF still save failed for $displayName; using MediaStore", e)-            }-        } else {-            Log.status("CameraViewModel", "SAF doc creation failed for $displayName; using MediaStore")-        }-        // Fall through to MediaStore so the shot is never lost.-    }-    val values = MediaStoreSaver.imageValues(displayName)-    val options = ImageCapture.OutputFileOptions.Builder(-        app.contentResolver,-        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,-        values,-    ).setMetadata(metadata).build()-    return PendingStill(options, null, null, displayName)-}--internal fun PendingStill.closeStream() {-    try {-        stream?.close()-    } catch (_: Exception) {}-}--/** Resolve the final saved URI, preferring the pre-created SAF doc. */-internal fun PendingStill.resolveUri(results: ImageCapture.OutputFileResults): Uri? =-    saveUri ?: results.savedUri  /**  * Saves re-encoded bytes/bitmap to the current target: SAF doc when set
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 7a9970e406..d18ca4f25c 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt@@ -79,12 +79,6 @@ 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() }-    // Camera2 gates default on (fields initialise true); a persisted-    // value is the user's opt-out and wins when present.-    ds.getString("camera_camera2_engine")?.let { camera2PreviewEnabledMutable.value = it.toBoolean() }-    ds.getString("camera_camera2_slomo")?.let { camera2SloMoEnabledMutable.value = it.toBoolean() }-    ds.getString("camera_camera2_night")?.let { camera2NightEnabledMutable.value = it.toBoolean() }-    ds.getString("camera_camera2_raw_night")?.let { camera2RawNightEnabledMutable.value = it.toBoolean() } }  fun CameraViewModel.setFlashMode(mode: FlashMode) {@@ -134,9 +128,7 @@ fun CameraViewModel.setTimerDuration(duration: TimerDuration) {  fun CameraViewModel.setAspectRatio(ratio: AspectRatioOption) {     aspectRatioMutable.value = ratio-    // Re-apply the crop to the live capture use case so the next shot (and-    // its preview cropRect) matches the newly selected ratio without a rebind.-    imageCapture?.setCropAspectRatio(currentCropAspectRatio())+    // The Camera2 still size/crop follows this flow at capture time.     viewModelScope.launch { ds.setString("camera_aspect_ratio", ratio.name) } } 
camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.ktindex 25a6e244f1..335608bea9 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/AnalysisSourcePolicy.kt@@ -1,7 +1,7 @@ package com.vayunmathur.camera.domain  /** Which pipeline feeds the per-frame analysis consumers for one session. */-enum class AnalysisSource { CAMERAX, CAMERA2_IMAGE_READER }+enum class AnalysisSource { CAMERA2_IMAGE_READER }  /**  * What one session asks its analysis stream to do.@@ -16,7 +16,6 @@ enum class AnalysisSource { CAMERAX, CAMERA2_IMAGE_READER }  *   from Y-plane views alone (luma sampling, Y-grid motion diff).  */ data class AnalysisSourceInput(-    val camera2Enabled: Boolean = AnalysisSourcePolicy.CAMERA2_ENABLED,     val needsQr: Boolean,     val needsBitmapFrame: Boolean,     val cheapPlaneConsumersOnly: Boolean,@@ -73,14 +72,15 @@ data class AnalysisSourceInput(  * alone.  */ object AnalysisSourcePolicy {-    /** Master policy flag: default on (per-session exclusions still apply). */-    const val CAMERA2_ENABLED: Boolean = true--    fun select(input: AnalysisSourceInput): AnalysisSource = when {-        !input.camera2Enabled -> AnalysisSource.CAMERAX-        input.needsQr -> AnalysisSource.CAMERAX-        input.needsBitmapFrame -> AnalysisSource.CAMERAX-        !input.cheapPlaneConsumersOnly -> AnalysisSource.CAMERAX-        else -> AnalysisSource.CAMERA2_IMAGE_READER-    }+    /**+     * CameraX is removed: the Camera2 ImageReader stream is the only+     * analysis source. QR decodes from the Y plane in place+     * (`PhotoAnalyzer.onAnalysisFrame`), and bitmap consumers+     * (portrait segmentation, panorama, Motion Photo) convert via+     * `Yuv420ToArgb` with the frame's rotation/crop metadata+     * ([AnalysisRotation]/[FrameCrop]) — the exclusions that used to+     * keep those sessions on CameraX no longer exist.+     */+    fun select(input: AnalysisSourceInput): AnalysisSource =+        AnalysisSource.CAMERA2_IMAGE_READER }
camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.kt b/camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.ktindex 8954b46d6e..cf560b9a9a 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.kt@@ -3,7 +3,6 @@ package com.vayunmathur.camera.domain import kotlin.math.abs import kotlin.math.roundToInt import com.vayunmathur.camera.platform.formatZoomLabel-import com.vayunmathur.camera.platform.highestFpsRange import com.vayunmathur.camera.platform.readManualControlRanges import com.vayunmathur.camera.platform.updateZoomLevels 
camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.kt b/camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.ktindex a565ceb268..69c58e87da 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/LiveBitrateController.kt@@ -2,52 +2,6 @@ package com.vayunmathur.camera.domain  import kotlin.math.roundToInt -/** Which recording pipeline a recording should use. */-enum class RecordingPath { CAMERAX_RECORDER, CUSTOM_CAMERA2 }--/**- * Inputs to the recording-path selection rule.- *- * @property customPathEnabled the (still default-off, not device-verified) gate for the Camera2/MediaCodec path.- * @property liveAdaptationWanted live, during-recording bitrate changes are wanted.- * @property hlgRequested 10-bit HLG output is wanted (vendor HDR semantics).- * @property stabilizationRequested a vendor/CameraX stabilization mode is wanted.- * @property codecAv1Requested AV1 output is wanted (custom path is AVC/HEVC only).- * @property analysisBound the motion-analysis stream bound (live changes need it).- */-data class RecordingPathInput(-    val customPathEnabled: Boolean,-    val liveAdaptationWanted: Boolean,-    val hlgRequested: Boolean,-    val stabilizationRequested: Boolean,-    val codecAv1Requested: Boolean,-    val analysisBound: Boolean,-)--/**- * Explicit selection rule for the two recording pipelines.- *- * The custom Camera2/MediaCodec path exists for one thing CameraX cannot do:- * re-targeting the encoder mid-recording. It is selected only when that is- * actually wanted *and* everything the recording asked for is something the- * custom path can honestly provide. Vendor stabilization modes and HLG are- * CameraX/HAL semantics the custom path cannot reproduce, AV1 encoding is not- * attempted there, and without the analysis stream there is no motion signal- * to adapt from — in all of those cases the CameraX Recorder path is used and- * adaptation happens at the pre-recording decision only.- */-object RecordingPathPolicy {-    fun select(input: RecordingPathInput): RecordingPath = when {-        !input.customPathEnabled -> RecordingPath.CAMERAX_RECORDER-        !input.liveAdaptationWanted -> RecordingPath.CAMERAX_RECORDER-        input.hlgRequested -> RecordingPath.CAMERAX_RECORDER-        input.stabilizationRequested -> RecordingPath.CAMERAX_RECORDER-        input.codecAv1Requested -> RecordingPath.CAMERAX_RECORDER-        !input.analysisBound -> RecordingPath.CAMERAX_RECORDER-        else -> RecordingPath.CUSTOM_CAMERA2-    }-}- /**  * During-recording bitrate control, driven by the same policy numbers as the  * pre-recording decision: the recording starts at the decision's bitrate, and
camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.ktindex b452d8d79a..4bf66689d1 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/AdaptiveBitrateProbes.kt@@ -99,43 +99,3 @@ internal fun CameraViewModel.computeAdaptiveBitrateDecision(     )     return decision }--/**- * Builds the recording engine for [path] behind the [VideoRecordingEngine]- * boundary. The CameraX engine adapts the existing session plumbing (its- * finalization keeps flowing through VideoRecordEvent); the Camera2 engine is- * constructed only when the selection rule picks it, and owns its own- * device/session from that point. Record-start selection itself lives in- * [recordingPathFor]; nothing constructs the Camera2 engine while the gate is off.- */-internal fun CameraViewModel.createVideoRecordingEngine(-    path: com.vayunmathur.camera.domain.RecordingPath,-    config: CustomRecordingConfig,-    controller: com.vayunmathur.camera.domain.LiveBitrateController,-): VideoRecordingEngine = when (path) {-    com.vayunmathur.camera.domain.RecordingPath.CUSTOM_CAMERA2 -> Camera2VideoRecordingEngine(-        context = app,-        config = config,-        controller = controller,-        motionSupplier = { sceneMotionEstimator.lastClassification },-        onMotionSample = { sample -> onSceneMotionSample(sample) },-        onError = { e -> Log.error("Camera2Recorder", "Camera2 recording engine error", e) },-    )-    com.vayunmathur.camera.domain.RecordingPath.CAMERAX_RECORDER -> CameraXVideoRecordingEngine(-        startImpl = { startRecording() },-        stopImpl = {-            currentRecording?.stop()-            currentRecording = null-            stopRecordingTimer()-        },-    )-}--/** CameraX quality -> pure ladder tier; unknown quality keeps the FHD rung (as before). */-internal fun tierForQuality(quality: androidx.camera.video.Quality?): VideoQualityTier = when (quality) {-    androidx.camera.video.Quality.UHD -> VideoQualityTier.UHD-    androidx.camera.video.Quality.FHD -> VideoQualityTier.FHD-    androidx.camera.video.Quality.HD -> VideoQualityTier.HD-    androidx.camera.video.Quality.SD -> VideoQualityTier.SD-    else -> VideoQualityTier.FHD-}
camera/src/main/java/com/vayunmathur/camera/platform/BokehAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/BokehAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/platform/BokehAnalyzer.ktindex a8af2640e5..588b4924a4 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/BokehAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/BokehAnalyzer.kt@@ -5,8 +5,6 @@ import android.graphics.Bitmap import android.graphics.Matrix import android.os.SystemClock import com.vayunmathur.library.log.Log-import androidx.camera.core.ImageAnalysis-import androidx.camera.core.ImageProxy import androidx.core.graphics.scale import com.vayunmathur.library.ml.SelfieSegmenter @@ -23,7 +21,7 @@ class BokehAnalyzer(     context: Context,     private val isFrontFacing: Boolean = false,     private val onMaskGenerated: (Bitmap) -> Unit-) : ImageAnalysis.Analyzer {+) {      // Guard for the native handle and buffer fields – analyze() runs on bokehExecutor     // while close() runs on the main composable's DisposableEffect. Without mutual@@ -47,71 +45,57 @@ class BokehAnalyzer(         null     } -    @androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class)-    override fun analyze(imageProxy: ImageProxy) {+    /**+     * Camera2 analysis entry: [bitmap] is the sensor-oriented conversion+     * of an `AnalysisFrame` (`toBitmapFromPlanes`), [rotationDegrees]+     * its display rotation — the same inputs the CameraX path read from+     * `ImageProxy.toBitmap()`/`imageInfo.rotationDegrees`. Takes+     * ownership of [bitmap].+     */+    fun onFrame(bitmap: Bitmap, rotationDegrees: Int) {         try {-            if (closed) return+            if (closed) {+                bitmap.recycle()+                return+            }             val now = SystemClock.elapsedRealtime()             if (now - lastSegmentMs < MIN_SEGMENT_INTERVAL_MS) {+                bitmap.recycle()                 return             }             lastSegmentMs = now--            val frame = prepareFrame(imageProxy) ?: return-            if (closed) {-                frame.recycle()-                return-            }--            // Synchronous forward pass; runs on dedicated bokehExecutor with KEEP_ONLY_LATEST.-            // Hold lock across the native call so close() blocks until the submitted command-            // buffer has been waited on, preventing the SEGV_MTESERR use-after-free seen in-            // tombstones.-            val result = segmentLocked(frame) ?: return-            frame.recycle()-            if (closed) return--            smoothAndEmit(result)+            val downscaled = downscaleIfNeeded(bitmap, MAX_PREVIEW_SIDE)+            if (downscaled !== bitmap) bitmap.recycle()+            val oriented = orientToDisplay(downscaled, rotationDegrees)+            if (oriented !== downscaled) downscaled.recycle()+            runSegmentation(oriented)         } catch (e: IllegalStateException) {             Log.error("BokehAnalyzer", "segmentation failed", e)         } catch (e: IllegalArgumentException) {             Log.error("BokehAnalyzer", "segmentation failed", e)-        } catch (e: NullPointerException) {-            // A frame with no decodable bitmap (null platform return from-            // toBitmap) is a dropped frame, not a crash of the preview path.-            Log.error("BokehAnalyzer", "segmentation failed", e)-        } finally {-            imageProxy.close()         }     } -    /**-     * Copies, downscales and orients the frame for the segmenter. Returns null when there is-     * no mask this frame (throttled, closed, or GPU unavailable); recycles intermediates.-     */-    private fun prepareFrame(imageProxy: ImageProxy): Bitmap? {-        // Raw sensor-oriented buffer; capped to 1024x768 in portrait session,-        // so this is ~0.8MP not 12MP. Full-res final image kept in ImageCapture.-        var frame = imageProxy.toBitmap()+    /** Downscale/orient/segment tail for the Camera2 analysis entry. */+    private fun runSegmentation(frame: Bitmap) {         if (closed) {             frame.recycle()-            return null-        }-        // Immediate downscale to <=512 max side, filter=false to avoid bilinear cost.-        val downscaled = downscaleIfNeeded(frame, MAX_PREVIEW_SIDE)-        if (downscaled !== frame) {-            frame.recycle()+            return         }-        frame = downscaled--        // Orient to display + mirror for front camera, filter=false (was true = bilinear).-        val oriented = orientToDisplay(frame, imageProxy.imageInfo.rotationDegrees)-        if (oriented !== frame) {-            frame.recycle()-        }-        return oriented+        // Synchronous forward pass; runs on the analysis executor.+        // Hold lock across the native call so close() blocks until the submitted command+        // buffer has been waited on, preventing the SEGV_MTESERR use-after-free seen in+        // tombstones.+        val result = segmentLocked(frame) ?: return+        frame.recycle()+        if (closed) return+        smoothAndEmit(result)     } +    /**+     * Copies, downscales and orients the frame for the segmenter. Returns null when there is+     * no mask this frame (throttled, closed, or GPU unavailable); recycles intermediates.+     */     /** Runs the segmenter under lock; null when closed or the GPU yields no mask. */     private fun segmentLocked(frame: Bitmap): com.vayunmathur.library.ml.SegmentationMask? {         return synchronized(lock) {
camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.ktindex 4903650126..640667f2e9 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt@@ -1,47 +1,33 @@ package com.vayunmathur.camera.platform -import com.vayunmathur.camera.domain.AnalysisSource-import com.vayunmathur.camera.domain.AnalysisSourceInput-import com.vayunmathur.camera.domain.AnalysisSourcePolicy import com.vayunmathur.camera.platform.camera2.AnalysisConsumer+import com.vayunmathur.camera.platform.camera2.AnalysisFrame  /**- * Camera2 analysis wiring: the plane consumer for a Camera2 session's YUV- * analysis stream.+ * Camera2 analysis wiring: the single plane consumer handed to every+ * Camera2 session's YUV analysis stream. It dispatches each frame to+ * the mode's current sink ([analysisSink]), which the screen effects+ * install per mode:+ * - PHOTO modes: [PhotoAnalyzer.onAnalysisFrame] (luma + QR + Motion+ *   Photo copies from planes/bitmaps),+ * - PORTRAIT: the bokeh segmenter over converted bitmaps,+ * - PANORAMA/PHOTOSPHERE: `PanoramaEngine.offerFrame` bitmaps,+ * - VIDEO modes: the Y-plane motion grid,+ * - SLOW_MO / NIGHT extension: no sink (null).  *- * The consumer is luma-only by construction: it feeds each frame's Y plane- * to [PhotoAnalyzer.onYPlane] (luma stats via the Rust plane-stats work in- * `StitchNative.lumaStats`, Kotlin fallback identical), which drives the- * night hysteresis through [onLuminance]. QR decode has no plane entry- * point here, and bitmap frame copies — although a conversion now exists- * (`AnalysisFrame.toBitmapFromPlanes`) — are not fed from this glue: the- * frame carries no rotation/crop metadata and those sessions never- * compose a Camera2 session (see [AnalysisSourcePolicy]). Sessions- * needing them — QR, PORTRAIT, PANORAMA/PHOTOSPHERE, Motion-Photo frame- * copies — stay on the CameraX ImageAnalysis path, exactly as before.+ * One stable consumer for the session's whole life: the sink behind it+ * swaps with the mode, so a mode switch never reconfigures the session.  */-internal fun CameraViewModel.camera2AnalysisConsumer(): AnalysisConsumer {-    val analyzer = PhotoAnalyzer(-        onLuminance = { onLuminance(it) },-        onQrDetected = {},-    )-    return AnalysisConsumer { frame -> analyzer.onYPlane(frame.yPlane) }+internal fun CameraViewModel.camera2AnalysisConsumer(): AnalysisConsumer =+    AnalysisConsumer { frame -> dispatchAnalysisFrame(frame) }++/** Routes one Camera2 analysis frame to the installed mode sink. */+internal fun CameraViewModel.dispatchAnalysisFrame(frame: AnalysisFrame) {+    analysisSink?.invoke(frame) } -/**- * True when this session's analysis stream may serve from Camera2: the- * persisted Camera2 preview toggle (the session only exists when that- * gate selected Camera2) AND the [AnalysisSourcePolicy] master flag, for a- * cheap-plane-only consumer. Excluded (QR/bitmap) sessions are not- * classified here — they never compose a Camera2 session.- */-internal fun CameraViewModel.camera2AnalysisServes(): Boolean =-    AnalysisSourcePolicy.select(-        AnalysisSourceInput(-            camera2Enabled = AnalysisSourcePolicy.CAMERA2_ENABLED &&-                camera2PreviewEnabledMutable.value,-            needsQr = false,-            needsBitmapFrame = false,-            cheapPlaneConsumersOnly = true,-        ),-    ) == AnalysisSource.CAMERA2_IMAGE_READER+/** Installs (or clears, with null) the per-mode analysis sink. */+internal fun CameraViewModel.setAnalysisSink(sink: ((AnalysisFrame) -> Unit)?) {+    analysisSink = sink+    analysisStreamActiveMutable.value = sink != null+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.ktindex d0dd896361..9e5e9dd60c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt@@ -10,7 +10,6 @@ import com.vayunmathur.camera.platform.camera2.CapturedStill import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade import com.vayunmathur.camera.platform.camera2.ExtensionsEngineInput import com.vayunmathur.camera.platform.camera2.ExtensionsEnginePolicy-import com.vayunmathur.camera.platform.camera2.NightCamera2Gate import com.vayunmathur.camera.platform.camera2.NightEngine import com.vayunmathur.library.log.Log import kotlinx.coroutines.Dispatchers@@ -62,11 +61,9 @@ internal fun CameraViewModel.camera2NightDecision( ): NightEngine {     val probe = Camera2ExtensionProbe.probeNight(facade.snapshot)     val input = ExtensionsEngineInput(-        camera2GateOn = NightCamera2Gate.ENABLED && camera2NightEnabledMutable.value,         mode = cameraModeMutable.value,         camera2ProbeOk = probe.usable,         failureCacheClear = !nightExtFailedRecently(),-        cameraXExtensionUsable = nightExtensionUsableMutable.value,     )     val engine = ExtensionsEnginePolicy.select(input)     Log.debug(@@ -89,11 +86,9 @@ internal fun CameraViewModel.tryCaptureCamera2NightExtension(): Boolean {     val session = activeCamera2ExtensionSession ?: return false     val probe = session.currentProbe()     val input = ExtensionsEngineInput(-        camera2GateOn = NightCamera2Gate.ENABLED && camera2NightEnabledMutable.value,         mode = cameraModeMutable.value,         camera2ProbeOk = probe?.usable == true && session.hasJpegOutput,         failureCacheClear = !nightExtFailedRecently(),-        cameraXExtensionUsable = nightExtensionUsableMutable.value,     )     if (!ExtensionsEnginePolicy.usesCamera2Extension(input)) return false @@ -142,7 +137,6 @@ internal fun CameraViewModel.tryCaptureCamera2NightExtension(): Boolean {  * `evaluateCamera2SloMoDecision`.  */ internal fun CameraViewModel.evaluateCamera2NightDecision() {-    if (!camera2NightEnabledMutable.value) return     try {         val facing = selectedLensMutable.value?.facing             ?: availableLensesMutable.value
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.ktindex 1a5849c96f..70c7b1186c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt@@ -34,8 +34,6 @@ internal fun CameraViewModel.tryCaptureCamera2RawNight(): Boolean {     val session = activeCamera2Session ?: return false     val snapshot = session.characteristics     val input = RawNightInput(-        rawGateOn = RawRingGate.ENABLED && camera2RawNightEnabledMutable.value,-        explicitRawSelected = camera2RawNightEnabledMutable.value,         mode = cameraModeMutable.value,         nightRoute = true,         rawSupported = session.rawSupported,
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 c8a31659a6..83faee51e4 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt@@ -34,7 +34,7 @@ import java.nio.ByteBuffer  * surface handoff and [SharedRecordingCoreLifecycle] for drain/EOS/finalize.  */ class Camera2RecordingCore(-    private val config: CustomRecordingConfig,+    val config: CustomRecordingConfig,     private val initialBitrateBps: () -> Int,     ownership: RecordingSessionOwnership = RecordingSessionOwnership.ENGINE_OWNED, ) {@@ -51,6 +51,16 @@ class Camera2RecordingCore(     private var videoTrackIndex = -1     private var audioTrackIndex = -1 +    // Per-track PTS bases: encoder output timestamps start at the+    // sensor/monotonic clock (a huge base), audio at zero. Both tracks+    // are rebased to their first sample so the muxed container starts+    // at ~0 and reports a true duration.+    private var videoBasePtsUs = -1L+    private var audioBasePtsUs = -1L++    /** Frames written on the slo-mo path (synthesized playback PTS source). */+    private var videoFrameIndex = 0L+     @Volatile private var draining = false     private var drainThread: Thread? = null     private var audioThread: Thread? = null@@ -86,7 +96,12 @@ class Camera2RecordingCore(                     MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface,                 )                 setInteger(MediaFormat.KEY_BIT_RATE, initialBitrateBps())-                setInteger(MediaFormat.KEY_FRAME_RATE, config.fps)+                // The encoder is told the rate frames actually arrive+                // (capture rate for slo-mo): at the playback rate it+                // frame-drops the high-speed stream down to a fraction+                // of the captured frames (device-proven). Playback+                // timing is carried by the muxed PTS, not this field.+                setInteger(MediaFormat.KEY_FRAME_RATE, maxOf(config.fps, config.captureFps))                 if (config.captureFps != config.fps) {                     setInteger(MediaFormat.KEY_CAPTURE_RATE, config.captureFps)                 }@@ -169,7 +184,35 @@ class Camera2RecordingCore(                         val buffer: ByteBuffer = codec.getOutputBuffer(index) ?: continue                         buffer.position(info.offset)                         buffer.limit(info.offset + info.size)-                        muxer?.writeSampleData(if (isVideo) videoTrackIndex else audioTrackIndex, buffer, info)+                        // Rebase PTS to the track's first sample (see+                        // videoBasePtsUs): write with an adjusted copy,+                        // never the codec's raw monotonic timestamp.+                        val base = if (isVideo) {+                            if (videoBasePtsUs < 0) videoBasePtsUs = info.presentationTimeUs+                            videoBasePtsUs+                        } else {+                            if (audioBasePtsUs < 0) audioBasePtsUs = info.presentationTimeUs+                            audioBasePtsUs+                        }+                        val adjusted = MediaCodec.BufferInfo().apply {+                            set(+                                info.offset, info.size,+                                when {+                                    // Slo-mo: encoder PTS are unusable+                                    // (stale surface backlog, sensor+                                    // clock); synthesize playback timing+                                    // — each captured frame plays for+                                    // 1/playbackFps (see SloMoTimestampStretch).+                                    isVideo && config.captureFps > config.fps ->+                                        com.vayunmathur.camera.platform.camera2.SloMoTimestampStretch+                                            .playbackPtsUs(videoFrameIndex++, config.fps)+                                    isVideo -> maxOf(0L, info.presentationTimeUs - base)+                                    else -> maxOf(0L, info.presentationTimeUs - base)+                                },+                                info.flags,+                            )+                        }+                        muxer?.writeSampleData(if (isVideo) videoTrackIndex else audioTrackIndex, buffer, adjusted)                     }                     codec.releaseOutputBuffer(index, false)                     if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return@@ -281,6 +324,9 @@ class Camera2RecordingCore(         muxerStarted = false         videoTrackIndex = -1         audioTrackIndex = -1+        videoBasePtsUs = -1L+        audioBasePtsUs = -1L+        videoFrameIndex = 0L         drainThread = null         audioThread = null     }
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.ktnew file mode 100644index 0000000000..1bbf31eb0e--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingState.kt@@ -0,0 +1,49 @@+package com.vayunmathur.camera.platform++import kotlinx.coroutines.flow.MutableStateFlow++/**+ * Mutable Camera2 recording state owned by [CameraViewModel]: the live+ * video engine (normal/timelapse/cinematic) and the slo-mo core, plus+ * the staged-file bookkeeping the finalize path needs. Kept in one+ * holder so the ViewModel stays within its file-length budget.+ */+internal class Camera2RecordingState {+    /** Live Camera2 recording engine (video modes); null when not recording. */+    var engine: Camera2VideoRecordingEngine? = null++    /** Staged output file of the in-flight Camera2 recording. */+    var outputFile: java.io.File? = null++    /** Display name / mode / timestamp of the in-flight recording, for finalize. */+    var displayName: String? = null+    var mode: CameraMode? = null+    var timestamp: String? = null++    /** True while a Camera2 recording owns the camera (UI shows its preview). */+    val recordingActive = MutableStateFlow(false)++    /** The recording engine's preview texture, published once it starts. */+    val previewTexture = MutableStateFlow<android.graphics.SurfaceTexture?>(null)++    /** Live Camera2 slo-mo recording core; null when idle. */+    var sloMoCore: Camera2RecordingCore? = null+    var sloMoOutputFile: java.io.File? = null+    var sloMoDisplayName: String? = null++    /** Record start/stop control from the live slo-mo preview holder. */+    var sloMoControl: SloMoRecordingControl? = null+}++/**+ * Start/stop for one Camera2 slo-mo recording, supplied by the preview+ * holder that owns the high-speed session + shared core. [start]+ * begins muxing into the given file; the finalize callback reports+ * (file, true) only when the output validated readable AND stretched+ * (piece 6). [stop] ends the recording; finalization is async through+ * the [start] callback.+ */+internal class SloMoRecordingControl(+    val start: (java.io.File, (java.io.File, Boolean) -> Unit) -> Unit,+    val stop: () -> Unit,+)
camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.ktindex 838529245d..334a7efa4b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2SloMoGlue.kt@@ -6,10 +6,10 @@ import com.vayunmathur.camera.domain.LensFacing import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade import com.vayunmathur.camera.platform.camera2.HighSpeedPlanner import com.vayunmathur.camera.platform.camera2.HighSpeedSelection-import com.vayunmathur.camera.platform.camera2.SloMoCamera2Gate import com.vayunmathur.camera.platform.camera2.SloMoEngine import com.vayunmathur.camera.platform.camera2.SloMoEngineInput import androidx.lifecycle.viewModelScope+import com.vayunmathur.camera.data.MediaStoreSaver import com.vayunmathur.camera.data.saveVideoStaged import com.vayunmathur.camera.data.setLastCaptureUri import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership@@ -82,7 +82,6 @@ internal fun CameraViewModel.camera2SloMoDecision(     val snapshot = facade.snapshot     val selection = HighSpeedPlanner.select(snapshot)     val input = SloMoEngineInput(-        camera2Enabled = SloMoCamera2Gate.ENABLED && camera2SloMoEnabledMutable.value,         mode = cameraModeMutable.value,         lensFacing = snapshot.lensFacing,         hasConstrainedHighSpeed = snapshot.supportsConstrainedHighSpeedVideo,@@ -119,7 +118,6 @@ internal fun encoderSupportsSloMoCaptureRate(selection: HighSpeedSelection): Boo  * while the policy excludes Camera2 (see the file doc).  */ internal fun CameraViewModel.evaluateCamera2SloMoDecision() {-    if (!camera2SloMoEnabledMutable.value) return     try {         val facing = selectedLensMutable.value             ?.takeIf { it.facing == LensFacing.BACK }@@ -175,12 +173,16 @@ internal fun CameraViewModel.handleCamera2SloMoFinalized(                     stagedFile.delete()                 }             }-            SloMoSaveAction.DISCARD_AND_REBIND_CAMERAX -> {+            SloMoSaveAction.DISCARD_AND_ERROR -> {                 withContext(Dispatchers.IO) { stagedFile.delete() }-                // One-shot latch: only the first failure for this bind rebinds.+                // One-shot latch (no CameraX to rebind to): surface a+                // retryable error and clear the latch so the next press+                // gets a fresh Camera2 attempt.                 if (onCamera2SloMoFailed(cameraId)) {-                    teardownSession()-                    setupHighSpeedSession()+                    com.vayunmathur.library.util.AppMessages.show(+                        app.getString(com.vayunmathur.camera.R.string.camera_recording_failed)+                    )+                    clearCamera2SloMoFallback()                 }             }             SloMoSaveAction.DISCARD_LATCHED -> withContext(Dispatchers.IO) {@@ -191,15 +193,75 @@ internal fun CameraViewModel.handleCamera2SloMoFinalized(     return action } +/** Registers the live slo-mo preview holder's record control (null when it leaves composition). */+internal fun CameraViewModel.registerCamera2SloMoControl(control: SloMoRecordingControl?) {+    camera2RecordingState.sloMoControl = control+}+ /**- * Rebinds the CameraX high-speed session after a Camera2 slo-mo attempt- * failed before producing a file. One-shot per bind key, like preview's- * latch; a repeat failure for the same key does not rebind-loop.+ * Starts a Camera2 slo-mo recording through the live preview holder's+ * control. The encoder-at-capture-rate probe runs first (the same+ * honest-support check as the decision); no control or no encoder+ * support is an error surface, never a silent realtime file.  */-internal fun CameraViewModel.rebindCameraXAfterSloMoFailure(cameraId: String) {-    if (!onCamera2SloMoFailed(cameraId)) return-    viewModelScope.launch {-        teardownSession()-        setupHighSpeedSession()+internal fun CameraViewModel.startCamera2SloMoRecording() {+    if (isRecordingMutable.value) return+    val control = camera2RecordingState.sloMoControl+    if (control == null) {+        Log.error("SloMo", "Camera2 slo-mo control unavailable; recording not started")+        com.vayunmathur.library.util.AppMessages.show(+            app.getString(com.vayunmathur.camera.R.string.camera_recording_failed)+        )+        return+    }+    // Encoder probe for the planned operating point.+    try {+        val manager = app.getSystemService(CameraManager::class.java)+        val lensId = manager?.let {+            CharacteristicsFacade.resolveCamera2Id(it, LensFacing.BACK)+        }+        val facade = if (manager != null && lensId != null) {+            CharacteristicsFacade.tryFromCameraManager(manager, lensId)+        } else {+            null+        }+        val selection = facade?.let { HighSpeedPlanner.select(it.snapshot) }+        if (selection == null || !encoderSupportsSloMoCaptureRate(selection)) {+            Log.error("SloMo", "No encoder supports the slo-mo capture rate; recording not started")+            com.vayunmathur.library.util.AppMessages.show(+                app.getString(com.vayunmathur.camera.R.string.camera_recording_failed)+            )+            return+        }+    } catch (e: Exception) {+        Log.error("SloMo", "Camera2 slo-mo probe failed; recording not started", e)+        com.vayunmathur.library.util.AppMessages.show(+            app.getString(com.vayunmathur.camera.R.string.camera_recording_failed)+        )+        return     }+    val timestamp = MediaStoreSaver.timestamp()+    val displayName = "SLOMO_$timestamp"+    val cacheFile = File(app.cacheDir, "$displayName.mp4")+    camera2RecordingState.sloMoOutputFile = cacheFile+    camera2RecordingState.sloMoDisplayName = displayName+    startRecordingTimer()+    isRecordingMutable.value = true+    control.start(cacheFile) { file, ok ->+        isRecordingMutable.value = false+        stopRecordingTimer()+        val cameraId = selectedLensMutable.value?.logicalCameraId.orEmpty()+        handleCamera2SloMoFinalized(+            displayName = displayName,+            stagedFile = file,+            outcomeError = !ok,+            outputReadable = ok,+            cameraId = cameraId,+        )+    }+}++/** Stops the in-flight Camera2 slo-mo recording; finalize arrives via the start callback. */+internal fun CameraViewModel.stopCamera2SloMoRecording() {+    camera2RecordingState.sloMoControl?.stop() }
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 774de375d2..087d1e8e12 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -45,6 +45,9 @@ import kotlinx.coroutines.withContext /** Registers the live gated Camera2 session (null when it leaves composition). */ internal fun CameraViewModel.registerCamera2Session(session: Camera2Session?) {     activeCamera2Session = session+    if (session != null) {+        viewModelScope.launch { refreshCapabilities(session.characteristics.cameraId) }+    } }  private fun FlashMode.toFlashSetting(): FlashSetting = when (this) {@@ -63,7 +66,6 @@ private fun FlashMode.toFlashSetting(): FlashSetting = when (this) { internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean {     val session = activeCamera2Session ?: return false     val input = StillEngineInput(-        camera2Enabled = camera2PreviewEnabledMutable.value,         mode = cameraModeMutable.value,         hasJpegOutput = session.hasJpegOutput,         nightRoute = nightPreviewActiveMutable.value || nightCaptureApplies(),@@ -86,7 +88,7 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean {     )     // Depth-phase ring inputs: gate + facade reprocess + live ring output.     val ringInput = input.copy(-        ringEnabled = ReprocessRingGate.ENABLED && camera2PreviewEnabledMutable.value,+        ringEnabled = ReprocessRingGate.ENABLED,         reprocessSupported = session.reprocessSupported,         hasRingOutput = session.hasRingOutput,     )
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 3b9c0b1696..52b32ac21e 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -14,38 +14,11 @@ import android.os.Handler import android.os.HandlerThread import android.view.Surface import com.vayunmathur.camera.domain.LiveBitrateController-import com.vayunmathur.camera.domain.RecordingPath-import com.vayunmathur.camera.domain.RecordingPathPolicy import com.vayunmathur.camera.domain.SceneMotion import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership import com.vayunmathur.library.log.Log import java.io.File -/**- * Gate for the custom recording path. Default OFF: every recording uses the- * CameraX Recorder until this path has been device-verified end to end- * (see the verification note on [Camera2VideoRecordingEngine]).- */-object CustomRecordingGate {-    const val ENABLED: Boolean = false-}--/** Selection inputs for the currently bound session, via [RecordingPathPolicy]. */-internal fun CameraViewModel.recordingPathFor(-    liveAdaptationWanted: Boolean,-    hlgBound: Boolean,-    stabilizationBound: Boolean,-): RecordingPath = RecordingPathPolicy.select(-    com.vayunmathur.camera.domain.RecordingPathInput(-        customPathEnabled = CustomRecordingGate.ENABLED,-        liveAdaptationWanted = liveAdaptationWanted,-        hlgRequested = hlgBound,-        stabilizationRequested = stabilizationBound,-        codecAv1Requested = recordingWithAv1,-        analysisBound = analysisStreamActiveMutable.value,-    )-)- /** Configuration for one custom-path recording. AVC/HEVC video + AAC audio only. */ data class CustomRecordingConfig(     val width: Int,@@ -105,8 +78,6 @@ class Camera2VideoRecordingEngine(     private val onMotionSample: (com.vayunmathur.camera.domain.FrameDiffSample) -> Unit,     private val onError: (Exception) -> Unit, ) : VideoRecordingEngine {-    override val path: RecordingPath = RecordingPath.CUSTOM_CAMERA2-     private var cameraThread: HandlerThread? = null     private var cameraHandler: Handler? = null     private var cameraDevice: CameraDevice? = null@@ -243,7 +214,13 @@ class Camera2VideoRecordingEngine(         // TextureView to render once the UI migrates off CameraX preview).         val effectivePreview = previewSurface ?: run {             val texture = android.graphics.SurfaceTexture(PREVIEW_TEXTURE_ID).apply {-                setDefaultBufferSize(config.width, config.height)+                // Preview never needs encoder resolution: cap at 1080p so+                // the (encoder + preview + analysis) stream combination+                // stays within guaranteed HAL limits at UHD tiers.+                setDefaultBufferSize(+                    minOf(config.width, PREVIEW_MAX_WIDTH),+                    minOf(config.height, PREVIEW_MAX_HEIGHT),+                )             }             ownedPreviewTexture = texture             Surface(texture).also { ownedPreviewSurface = it }@@ -292,18 +269,21 @@ class Camera2VideoRecordingEngine(                         override fun onConfigured(session: CameraCaptureSession) {                             captureSession = session                             core.markSessionStreaming()-                            val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {-                                addTarget(encoderSurface)-                                addTarget(effectivePreview)-                                addTarget(reader.surface)-                                set(-                                    CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,-                                    android.util.Range(config.captureFps, config.captureFps)-                                )-                            }.build()                             try {+                                val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {+                                    addTarget(encoderSurface)+                                    addTarget(effectivePreview)+                                    addTarget(reader.surface)+                                    set(+                                        CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,+                                        android.util.Range(config.captureFps, config.captureFps)+                                    )+                                }.build()                                 session.setRepeatingRequest(request, null, cameraHandler)                             } catch (e: IllegalStateException) {+                                // Device closed under us (a competing+                                // session took the camera): surface as an+                                // engine error, never an uncaught crash.                                 onError(e)                             }                         }@@ -342,7 +322,13 @@ class Camera2VideoRecordingEngine(         adaptationThread = Thread({             var tickMs = 0L             while (running) {-                Thread.sleep(LiveBitrateController.DEFAULT_EVALUATE_INTERVAL_MS)+                try {+                    Thread.sleep(LiveBitrateController.DEFAULT_EVALUATE_INTERVAL_MS)+                } catch (_: InterruptedException) {+                    // stop() interrupts to end the loop: exit quietly,+                    // never as an uncaught exception.+                    break+                }                 tickMs += LiveBitrateController.DEFAULT_EVALUATE_INTERVAL_MS                 val target = controller.evaluate(motionSupplier(), tickMs) ?: continue                 try {@@ -375,6 +361,8 @@ class Camera2VideoRecordingEngine(      companion object {         private const val PREVIEW_TEXTURE_ID = 1+        private const val PREVIEW_MAX_WIDTH = 1920+        private const val PREVIEW_MAX_HEIGHT = 1080         private const val ANALYSIS_WIDTH = 640         private const val ANALYSIS_HEIGHT = 480         private const val ANALYSIS_MAX_IMAGES = 3
camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.ktindex 92d811afea..e577d396c7 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt@@ -1,22 +1,14 @@ package com.vayunmathur.camera.platform  import com.vayunmathur.library.log.Log-import androidx.camera.core.Camera import com.vayunmathur.camera.domain.LensSelectionLogic-import com.vayunmathur.camera.platform.CameraViewModel-import com.vayunmathur.camera.platform.applyExposureCompensation-import com.vayunmathur.camera.platform.applyManualControls-import com.vayunmathur.camera.platform.readManualControlRanges-import com.vayunmathur.camera.platform.refreshNightExtensionUsable-import com.vayunmathur.camera.platform.restoreZoom-import com.vayunmathur.camera.platform.updateZoomLevels import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext  /**- * Per-lens capability snapshot refreshed after every bind, so the UI (zoom- * pills, flash availability, ISO stops, night/slo-mo affordances) reflects the- * lens that actually bound rather than the previous one.+ * Per-lens capability snapshot refreshed after every Camera2 bind, so the+ * UI (zoom pills, flash availability, ISO stops, night affordances)+ * reflects the lens that actually bound rather than the previous one.  */ data class LensCapabilities(     val lensId: String?,@@ -30,40 +22,39 @@ data class LensCapabilities( )  /**- * Re-probes everything the UI derives from the bound camera and publishes it- * on the ViewModel. Reuses the existing per-bind probes- * ([updateZoomLevels]/[restoreZoom], [readManualControlRanges],- * [observeNightModeIndicator], [refreshNightExtensionUsable]) and adds the- * missing coverage: flash-unit availability per lens.- *- * Call on the main thread (LiveData `observeForever` expects it); the heavier- * extension probe hops to Dispatchers.Default like the UI's launcher effect.+ * Re-probes everything the UI derives from the live Camera2 session's+ * characteristics snapshot and publishes it on the ViewModel. No-op when+ * no Camera2 session is registered yet.  */-suspend fun CameraViewModel.refreshCapabilities(bound: Camera, lensId: String?) {-    val (minZoom, maxZoom) = readZoomBounds(bound)+suspend fun CameraViewModel.refreshCapabilities(lensId: String?) {+    val snapshot = activeCamera2Session?.characteristics ?: return+    val minZoom = snapshot.minZoomRatio+    val maxZoom = snapshot.maxZoomRatio     updateZoomLevels(minZoom, maxZoom)     restoreZoom(minZoom, maxZoom)      readManualControlRanges()     reapplyCaptureControls()-    reapplyTorch(bound)+    try {+        enableTorch(torchEnabledMutable.value)+    } catch (e: IllegalStateException) {+        Log.status("LensSelector", "Could not re-apply torch", e)+    } catch (e: IllegalArgumentException) {+        Log.status("LensSelector", "Could not re-apply torch", e)+    } -    val hasFlash = readFlashUnit(bound)+    val hasFlash = snapshot.hasFlashUnit     hasFlashUnitMutable.value = hasFlash -    val expRange = readExposureRange(bound)+    val expRange = snapshot.exposureCompensationEvRange?.let { it.lower..it.upper }     if (expRange != null) exposureCompRangeMutable.value = expRange -    // Skip the night indicator here: the setup paths own that observation, and-    // re-observing the *extension* camera reports UNKNOWN/NOT_RECOMMENDED, which-    // fights the normal session's RECOMMENDED reading (engage/disengage loop —-    // see the note in setupNightPreviewSession).     withContext(Dispatchers.Default) {         refreshNightExtensionUsable(cameraModeMutable.value)     }      lensCapabilitiesMutable.value = LensCapabilities(-        lensId = lensId,+        lensId = lensId ?: snapshot.cameraId,         minZoom = minZoom,         maxZoom = maxZoom,         zoomLevels = LensSelectionLogic.buildZoomLevels(minZoom, maxZoom),@@ -75,24 +66,10 @@ suspend fun CameraViewModel.refreshCapabilities(bound: Camera, lensId: String?)     Log.dev("LensSelector", "Refreshed capabilities lens=$lensId zoom=[$minZoom,$maxZoom] flash=$hasFlash") } -/** Zoom bounds off the bound camera; unity defaults when unreadable. */-private fun CameraViewModel.readZoomBounds(bound: Camera): Pair<Float, Float> {-    val zs = try {-        bound.cameraInfo.zoomState.value-    } catch (e: IllegalStateException) {-        Log.status("LensSelector", "Could not read zoom state", e)-        null-    } catch (e: IllegalArgumentException) {-        Log.status("LensSelector", "Could not read zoom state", e)-        null-    }-    return (zs?.minZoomRatio ?: 1f) to (zs?.maxZoomRatio ?: 1f)-}- /**- * Re-asserts manual shutter/ISO and exposure compensation onto the fresh bind: the- * session effect only pushes them on value change, so without this a rebind silently- * drops them (video mode never applied them at all).+ * Re-asserts manual shutter/ISO and exposure compensation onto the fresh+ * bind: the session effect only pushes them on value change, so without+ * this a rebind silently drops them.  */ private fun CameraViewModel.reapplyCaptureControls() {     try {@@ -110,50 +87,3 @@ private fun CameraViewModel.reapplyCaptureControls() {         Log.status("LensSelector", "Could not re-apply exposure compensation", e)     } }--/**- * Re-asserts the UI's torch state onto the fresh bind. The session effect- * only calls `enableTorch` when `torchEnabled` changes, so a mode/lens- * rebind (which resets the hardware torch) left the UI lit with the torch- * off until the user toggled it twice.- */-private fun CameraViewModel.reapplyTorch(bound: Camera) {-    try {-        bound.cameraControl.enableTorch(torchEnabledMutable.value)-    } catch (e: IllegalStateException) {-        Log.status("LensSelector", "Could not re-apply torch", e)-    } catch (e: IllegalArgumentException) {-        Log.status("LensSelector", "Could not re-apply torch", e)-    } catch (e: NullPointerException) {-        // Fake controls in unit tests return a null future for enableTorch;-        // a real bind always returns one, so this is "unavailable", not a crash.-        Log.status("LensSelector", "Could not re-apply torch", e)-    }-}--/** Flash-unit availability; keeps the previous value when unreadable. */-private fun CameraViewModel.readFlashUnit(bound: Camera): Boolean {-    return try {-        bound.cameraInfo.hasFlashUnit()-    } catch (e: IllegalStateException) {-        Log.status("LensSelector", "Could not query flash unit", e)-        hasFlashUnitMutable.value-    } catch (e: IllegalArgumentException) {-        Log.status("LensSelector", "Could not query flash unit", e)-        hasFlashUnitMutable.value-    }-}--/** Exposure-compensation range; null when unreadable. */-private fun CameraViewModel.readExposureRange(bound: Camera): ClosedRange<Float>? {-    return try {-        val r = bound.cameraInfo.exposureState.exposureCompensationRange-        r.lower.toFloat()..r.upper.toFloat()-    } catch (e: IllegalStateException) {-        Log.status("LensSelector", "Could not query exposure-compensation range", e)-        null-    } catch (e: IllegalArgumentException) {-        Log.status("LensSelector", "Could not query exposure-compensation range", e)-        null-    }-}
camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.ktindex c9b24f54fd..0e9e37cb79 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt@@ -9,13 +9,11 @@ import android.graphics.Paint import android.graphics.Rect import android.net.Uri import com.vayunmathur.library.log.Log-import androidx.camera.core.ImageProxy import androidx.core.graphics.createBitmap import androidx.core.graphics.scale import androidx.exifinterface.media.ExifInterface import java.io.ByteArrayInputStream import kotlin.math.roundToInt-import com.vayunmathur.camera.data.prepareStillSave import com.vayunmathur.camera.data.updateLocation  /** EXIF orientation buckets (degrees clockwise). */@@ -63,21 +61,16 @@ internal fun uprightCopy(src: Bitmap, rotationDegrees: Int, maxSide: Int): Bitma }  /**- * Rotates the captured frame upright (mirroring for the front camera) and scales it down- * for the result "data" thumbnail.+ * Rotates a decoded captured frame upright (mirroring for the front+ * camera) and scales it down for the result "data" thumbnail.  */-internal fun downscaledThumbnail(image: ImageProxy, mirror: Boolean): Bitmap {-    // toBitmap() is a platform type: a frame that fails YUV->RGB conversion-    // comes back null, which must surface as a decode failure (the caller-    // routes it to onError), not as an intrinsic-null NPE crash.-    val raw: Bitmap? = image.toBitmap()-    requireNotNull(raw) { "captured frame did not decode to a bitmap" }+internal fun downscaledThumbnail(rawFrame: Bitmap, rotationDegrees: Int, mirror: Boolean): Bitmap {     val matrix = Matrix().apply {-        postRotate(image.imageInfo.rotationDegrees.toFloat())+        postRotate(rotationDegrees.toFloat())         if (mirror) postScale(-1f, 1f)     }-    val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, matrix, true)-    if (upright !== raw) raw.recycle()+    val upright = Bitmap.createBitmap(rawFrame, 0, 0, rawFrame.width, rawFrame.height, matrix, true)+    if (upright !== rawFrame) rawFrame.recycle()     val maxSide = 512     val scale = maxSide.toFloat() / maxOf(upright.width, upright.height)     if (scale >= 1f) return upright
camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.ktindex 82f2a076ec..66baf1354d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt@@ -1,13 +1,9 @@ package com.vayunmathur.camera.platform  import com.vayunmathur.library.log.Log-import androidx.camera.core.FocusMeteringAction-import androidx.camera.core.ImageAnalysis-import androidx.core.content.ContextCompat import androidx.lifecycle.viewModelScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch-import java.util.concurrent.Executor import kotlin.math.roundToInt  /** Zoom-out floor for offering the wide-angle zoom-bar entry. */@@ -32,33 +28,12 @@ fun CameraViewModel.onViewfinderZoomRatio(ratio: Float) { }  fun CameraViewModel.setZoomRatio(ratio: Float) {-    val cam = boundCamera-    val zs = cam?.cameraInfo?.zoomState?.value-    Log.dev(-        "NightPreview",-        "setZoomRatio() requested=$ratio clamped? min=${zs?.minZoomRatio} max=${zs?.maxZoomRatio} " +-            "current=${zs?.zoomRatio} nightPreviewActive=${nightPreviewActiveMutable.value} " +-            "photoActive=${photoSessionActiveMutable.value} boundCamera=${cam != null}"-    )-    val clamped = zs?.let {-        ratio.coerceIn(it.minZoomRatio, it.maxZoomRatio)-    } ?: ratio-    if (clamped != ratio) {-        Log.status(-            "NightPreview",-            "setZoomRatio() CLAMPED $ratio -> $clamped due to zoomState min/max – " +-                "vendor NIGHT often reports max=1x, causing bar to show only 1x"-        )-    }+    val session = activeCamera2Session+    val range = session?.characteristics?.zoomRatioRange+    val clamped = if (range != null) ratio.coerceIn(range.lower, range.upper) else ratio     zoomRatioMutable.value = clamped     viewModelScope.launch { ds.setString("camera_zoom_ratio", clamped.toString()) }-    try {-        cam?.cameraControl?.setZoomRatio(clamped)-    } catch (e: IllegalStateException) {-        Log.error("NightPreview", "setZoomRatio() setZoomRatio() threw (was hidden before)", e)-    } catch (e: IllegalArgumentException) {-        Log.error("NightPreview", "setZoomRatio() setZoomRatio() threw (was hidden before)", e)-    }+    session?.setZoomRatio(clamped) }  /**@@ -70,13 +45,7 @@ fun CameraViewModel.setZoomRatio(ratio: Float) { internal fun CameraViewModel.restoreZoom(minZoom: Float, maxZoom: Float) {     val desired = zoomRatioMutable.value.coerceIn(minZoom, maxZoom)     zoomRatioMutable.value = desired-    try {-        boundCamera?.cameraControl?.setZoomRatio(desired)-    } catch (e: IllegalStateException) {-        Log.error("NightPreview", "restoreZoom() setZoomRatio() threw", e)-    } catch (e: IllegalArgumentException) {-        Log.error("NightPreview", "restoreZoom() setZoomRatio() threw", e)-    }+    activeCamera2Session?.setZoomRatio(desired) }  fun CameraViewModel.updateZoomLevels(minZoom: Float, maxZoom: Float) {@@ -104,111 +73,57 @@ fun CameraViewModel.updateZoomLevels(minZoom: Float, maxZoom: Float) {     availableZoomLevelsMutable.value = levels } -fun CameraViewModel.startFocusAndMetering(action: FocusMeteringAction): Boolean {-    // A fresh tap clears any existing AE/AF lock.-    focusLockedMutable.value = false-    return runFocusAndMetering(action, locked = false)-}--/**- * Locks focus + exposure at the metered point by disabling auto-cancel, so 3A stays put until- * the user taps again (long-press-to-lock). Sets [focusLocked] for the on-screen indicator.- */-fun CameraViewModel.lockFocusAndMetering(action: FocusMeteringAction): Boolean {-    val submitted = runFocusAndMetering(action, locked = true)-    if (submitted) focusLockedMutable.value = true-    return submitted-}- /**- * Shared tap/long-press metering dispatch. Returns false (after logging) when- * there is no bound camera or the control throws synchronously — the silent- * `boundCamera?.` no-op this replaces gave the user no focus and no signal.- *- * The returned future is observed, not discarded: an asynchronous failure- * (unsupported metering point, camera closed mid-tap) falls back to the- * default continuous AF/AE via [fallbackToDefaultMetering] instead of leaving- * metering in whatever half-applied state the failure stopped at. A focus- * attempt that completes but does not converge ([androidx.camera.core- * .FocusMeteringResult.isFocusSuccessful] false) is NOT a failure: metering- * was still applied at the point, so it is only logged. Cancellation is the- * normal superseded-by-the-next-tap case and needs no fallback either.+ * Tap-to-focus entry for the overlay gesture layer: routes the tap to+ * the live Camera2 session's metering transform. Returns false when no+ * session is live (the tap is dropped, as before). [locked] keeps the+ * metered point until the next tap (the session holds AF/AE regions+ * until cleared or replaced — there is no auto-cancel timer on this+ * path, so a plain tap also persists; the focus ring UI reflects it).  */-internal fun CameraViewModel.runFocusAndMetering(action: FocusMeteringAction, locked: Boolean): Boolean {-    val cam = boundCamera-    if (cam == null) {-        Log.status("TapToFocus", "focus requested with no bound camera (locked=$locked); tap dropped")-        return false-    }-    val future: com.google.common.util.concurrent.ListenableFuture<androidx.camera.core.FocusMeteringResult>? = try {-        cam.cameraControl.startFocusAndMetering(action)-    } catch (e: Exception) {-        Log.status("TapToFocus", "startFocusAndMetering threw (locked=$locked); falling back to default metering", e)-        if (locked) focusLockedMutable.value = false-        fallbackToDefaultMetering()+fun CameraViewModel.tapToFocusAt(xFraction: Float, yFraction: Float, locked: Boolean): Boolean {+    val session = activeCamera2Session ?: run {+        Log.status("TapToFocus", "focus requested with no live Camera2 session (locked=$locked); tap dropped")         return false     }-    // Real CameraX never returns null; fakes/mocks in unit tests may.-    if (future == null) return true-    com.google.common.util.concurrent.Futures.addCallback(-        future,-        object : com.google.common.util.concurrent.FutureCallback<androidx.camera.core.FocusMeteringResult> {-            override fun onSuccess(result: androidx.camera.core.FocusMeteringResult?) {-                if (result != null && !result.isFocusSuccessful) {-                    Log.dev("TapToFocus", "focus did not converge at metered point (locked=$locked)")-                }-            }--            override fun onFailure(t: Throwable) {-                if (t is androidx.camera.core.CameraControl.OperationCanceledException) {-                    Log.dev("TapToFocus", "focus superseded by a newer request (locked=$locked)")-                    return-                }-                Log.status("TapToFocus", "focus metering failed (locked=$locked); falling back to default metering", t)-                if (locked) focusLockedMutable.value = false-                fallbackToDefaultMetering()-            }-        },-        ContextCompat.getMainExecutor(app),-    )+    session.tapToFocus(xFraction, yFraction)+    focusLockedMutable.value = locked     return true } -/**- * Returns metering to the camera's default continuous AF/AE (the centre-- * weighted behaviour a plain `cancelFocusAndMetering` restores) after a- * failed tap. Best-effort: a dead camera must not crash the tap path.- */+fun CameraViewModel.startFocusAndMeteringAt(xFraction: Float, yFraction: Float): Boolean {+    focusLockedMutable.value = false+    return tapToFocusAt(xFraction, yFraction, locked = false)+}++fun CameraViewModel.lockFocusAndMeteringAt(xFraction: Float, yFraction: Float): Boolean =+    tapToFocusAt(xFraction, yFraction, locked = true)++/** Returns metering to the session's default continuous AF/AE. */ internal fun CameraViewModel.fallbackToDefaultMetering() {-    try {-        boundCamera?.cameraControl?.cancelFocusAndMetering()-    } catch (e: Exception) {-        Log.status("TapToFocus", "fallback cancelFocusAndMetering threw", e)-    }+    activeCamera2Session?.clearMetering() }  fun CameraViewModel.clearFocusLock() {-    try {-        boundCamera?.cameraControl?.cancelFocusAndMetering()-    } catch (e: Exception) {-        Log.status("TapToFocus", "cancelFocusAndMetering threw while clearing lock", e)-    }+    activeCamera2Session?.clearMetering()     focusLockedMutable.value = false }  fun CameraViewModel.enableTorch(enabled: Boolean) {-    boundCamera?.cameraControl?.enableTorch(enabled)+    activeCamera2Session?.setTorch(enabled) }  fun CameraViewModel.applyExposureCompensation(value: Float) {-    val cam = boundCamera ?: return-    val range = cam.cameraInfo.exposureState.exposureCompensationRange-    // The slider is normalized to -1..1, so scale each half against its own-    // end of the (usually asymmetric) range; round, never truncate, so the-    // midpoint of an odd-sized half lands on the nearer index.-    val scaled = if (value >= 0f) value * range.upper else -value * range.lower-    val index = scaled.roundToInt().coerceIn(range.lower, range.upper)-    cam.cameraControl.setExposureCompensationIndex(index)+    val session = activeCamera2Session ?: return+    // The slider is normalized to -1..1; scale each half against its own+    // end of the lens's EV range (as the CameraX index path did).+    val range = session.characteristics.exposureCompensationEvRange+    val ev = if (range != null) {+        if (value >= 0f) value * range.upper else -value * range.lower+    } else {+        value * 2f+    }+    session.setExposureCompEv(ev) }  /**@@ -216,63 +131,28 @@ fun CameraViewModel.applyExposureCompensation(value: Float) {  * The ScreenFlash is attached first (and cleared on hardware lenses) so a  * FLASH_MODE_SCREEN capture never fires without its UI mechanism in place.  */-fun CameraViewModel.applyImageCaptureFlashMode() {-    val capture = imageCapture ?: return-    capture.setScreenFlash(getScreenFlashForCapture())-    capture.flashMode = getImageCaptureFlashMode()-}--/**- * Receives the [androidx.camera.core.ImageCapture.ScreenFlash] created by- * the Compose viewfinder (its overlay + window-brightness mechanism) and- * re-applies it to the bound capture. Brightness is CameraX's job, not ours.- */-fun CameraViewModel.setScreenFlash(screenFlash: androidx.camera.core.ImageCapture.ScreenFlash?) {-    this.screenFlash = screenFlash-    applyImageCaptureFlashMode()-}--/** Swaps the analyzer on the bound ImageAnalysis without rebinding. */-fun CameraViewModel.setImageAnalyzer(analyzer: ImageAnalysis.Analyzer?) {-    setImageAnalyzer(analyzer, ContextCompat.getMainExecutor(app))-}--fun CameraViewModel.setImageAnalyzer(analyzer: ImageAnalysis.Analyzer?, executor: Executor) {-    desiredAnalyzer = analyzer-    desiredAnalyzerExecutor = executor-    attachDesiredAnalyzer()-}--/** Convenience for portrait bokeh – always runs off the dedicated bokeh thread. */-fun CameraViewModel.setBokehAnalyzer(analyzer: ImageAnalysis.Analyzer?) {-    setImageAnalyzer(analyzer, bokehExecutor)-}--/** Convenience for the photo stream – always runs off the dedicated analysis thread. */-fun CameraViewModel.setPhotoAnalyzer(analyzer: ImageAnalysis.Analyzer?) {-    setImageAnalyzer(analyzer, analysisExecutor)-}- /**- * Pushes [desiredAnalyzer] onto whatever ImageAnalysis is currently bound. A no-op while none- * is, which is why the desired analyzer survives teardown: the next successful bind calls this- * again and picks it back up.+ * Flash mode is pushed onto the Camera2 session by the preview+ * composable (flashSetting parameter) and resolved per still by+ * StillCapturePlanner; this no-op keeps the legacy effect call sites+ * compiling until they are removed with the session layer.  */-internal fun CameraViewModel.attachDesiredAnalyzer() {-    val analysis = imageAnalysis ?: return-    val analyzer = desiredAnalyzer-    val executor = desiredAnalyzerExecutor-    if (analyzer == null || executor == null) analysis.clearAnalyzer()-    else analysis.setAnalyzer(executor, analyzer)+fun CameraViewModel.applyImageCaptureFlashMode() {+    activeCamera2Session?.setFlashSetting(+        when (flashModeMutable.value) {+            FlashMode.ON -> com.vayunmathur.camera.domain.FlashSetting.ON+            FlashMode.AUTO -> com.vayunmathur.camera.domain.FlashSetting.AUTO+            FlashMode.OFF -> com.vayunmathur.camera.domain.FlashSetting.OFF+        }+    ) }  /** Recording-timer tick (1s). */ private const val RECORDING_TIMER_TICK_MS = 1000L -/** Publishes whether the session just bound has an analysis stream, and re-arms the analyzer. */+/** Publishes whether the live session carries an analysis stream. */ internal fun CameraViewModel.onSessionBound() {-    analysisStreamActiveMutable.value = imageAnalysis != null-    attachDesiredAnalyzer()+    analysisStreamActiveMutable.value = analysisSink != null }  internal fun CameraViewModel.startRecordingTimer() {
camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.ktindex 86f31f5dd2..a0d5d4a8b6 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt@@ -1,8 +1,5 @@ package com.vayunmathur.camera.platform -import androidx.annotation.OptIn-import androidx.camera.camera2.interop.ExperimentalCamera2Interop- import com.vayunmathur.library.log.Log import com.vayunmathur.camera.domain.PreviewExposurePolicy @@ -17,22 +14,6 @@ fun CameraViewModel.setManualIsoIndex(index: Int) {     applyManualControls() } -@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class)-internal fun CameraViewModel.camera2ControlOrNull(): androidx.camera.camera2.interop.Camera2CameraControl? = try {-    boundCamera?.cameraControl?.let {-        androidx.camera.camera2.interop.Camera2CameraControl.from(it)-    }-} catch (e: IllegalArgumentException) {-    Log.status("CameraViewModel", "Camera2 control unavailable", e)-    null-} catch (e: NullPointerException) {-    // The interop null-checks its implementation internally; a control with-    // no Camera2 implementation is "unavailable", not a crash.-    Log.status("CameraViewModel", "Camera2 control unavailable", e)-    null-}- /** The manual ISO for the current index, or null when set to Auto. */ internal fun CameraViewModel.manualIso(): Int? =     manualIsoIndexMutable.value.takeIf { it > 0 }?.let { isoStopsMutable.value.getOrNull(it - 1) }@@ -60,29 +41,6 @@ internal fun CameraViewModel.currentExposureSplit(): PreviewExposurePolicy.Split internal fun CameraViewModel.stillExposureOverrideRequired(): Boolean =     currentExposureSplit()?.stillOverrideRequired == true -/** AE-off + [nanos]/[iso] capture options for one still, shared by the capture paths. */-@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class)-internal fun stillCaptureRequestOptions(-    nanos: Long,-    iso: Int?-): androidx.camera.camera2.interop.CaptureRequestOptions {-    val builder = androidx.camera.camera2.interop.CaptureRequestOptions.Builder()-        .setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.CONTROL_AE_MODE,-            android.hardware.camera2.CameraMetadata.CONTROL_AE_MODE_OFF-        )-        .setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME, nanos-        )-    if (iso != null) {-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY, iso-        )-    }-    return builder.build()-}- /**  * Rebuilds a single [CaptureRequestOptions] from the current manual exposure/ISO state and  * pushes it to the bound camera. This drives the LIVE (repeating) request shared by preview@@ -93,121 +51,45 @@ internal fun stillCaptureRequestOptions(  * auto behavior (including tap-to-focus). Called on every manual-control change and  * re-applied after a session rebind.  */-@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class) fun CameraViewModel.applyManualControls() {-    val cam2 = camera2ControlOrNull() ?: return-    val builder = androidx.camera.camera2.interop.CaptureRequestOptions.Builder()--    // Manual exposure / ISO with linkage: if either is manual, lock AE off and set both.-    // Only the preview half goes on this live request (long shutters capped, ISO boosted-    // to compensate); the still half is applied at capture time.+    val session = activeCamera2Session ?: return+    // Seed the un-set half of a half-manual exposure from the session's+    // latest AE-converged preview values (as the interop path seeded+    // from its CaptureResult snapshots).+    val (aeNs, aeIso) = session.latestAeSnapshot()+    if (aeNs != null) lastAeExposureNanos = aeNs+    if (aeIso != null) lastAeIso = aeIso+    // Only the preview half goes on the live request: a long manual+    // shutter is capped at 1/30s with a compensating ISO boost, keeping+    // the viewfinder smooth; stills resolve the same state through+    // StillCapturePlanner (manual wins over AE/flash modes there).     val split = currentExposureSplit()-    if (split != null) {-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.CONTROL_AE_MODE,-            android.hardware.camera2.CameraMetadata.CONTROL_AE_MODE_OFF-        )-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME, split.previewNanos-        )-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY, split.previewIso-        )-    }--    // Post-processing toggles (issue #662): OFF explicitly disables the HAL's noise-    // reduction / edge sharpening. ON now explicitly requests the high-quality-    // modes instead of leaving the keys unset, where the HAL default may be-    // FAST. Tonemap joins the high-quality request when either toggle is on,-    // so turning both off does not force a high-quality tonemap either.-    if (noiseReductionEnabledMutable.value) {-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.NOISE_REDUCTION_MODE,-            android.hardware.camera2.CameraMetadata.NOISE_REDUCTION_MODE_HIGH_QUALITY-        )-    } else {-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.NOISE_REDUCTION_MODE,-            android.hardware.camera2.CameraMetadata.NOISE_REDUCTION_MODE_OFF-        )-    }-    if (edgeSharpeningEnabledMutable.value) {-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.EDGE_MODE,-            android.hardware.camera2.CameraMetadata.EDGE_MODE_HIGH_QUALITY-        )-    } else {-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.EDGE_MODE,-            android.hardware.camera2.CameraMetadata.EDGE_MODE_OFF-        )-    }-    if (noiseReductionEnabledMutable.value || edgeSharpeningEnabledMutable.value) {-        builder.setCaptureRequestOption(-            android.hardware.camera2.CaptureRequest.TONEMAP_MODE,-            android.hardware.camera2.CameraMetadata.TONEMAP_MODE_HIGH_QUALITY-        )-    }--    try {-        // An empty options set clears any previously-applied manual 3A → full auto.-        cam2.setCaptureRequestOptions(builder.build())-    } catch (e: IllegalStateException) {-        Log.status("CameraViewModel", "Failed to apply manual controls", e)-    } catch (e: IllegalArgumentException) {-        Log.status("CameraViewModel", "Failed to apply manual controls", e)-    }+    session.setManualExposure(split?.previewNanos, split?.previewIso)+    session.setPostProcessing(+        noiseReductionEnabledMutable.value,+        edgeSharpeningEnabledMutable.value,+    ) }  /** Reads the bound sensor's ISO range → stop list for the manual ISO control. */-@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class) internal fun CameraViewModel.readManualControlRanges() {-    Log.dev(-        "NightPreview",-        "readManualControlRanges() called bound=${boundCamera != null} " +-            "thread=${Thread.currentThread().name}"-    )-    val cam = boundCamera ?: run {-        Log.status("NightPreview", "readManualControlRanges() no bound camera, returning")+    val session = activeCamera2Session ?: run {+        Log.status("NightPreview", "readManualControlRanges() no live Camera2 session, returning")         return     }-    try {-        val info = androidx.camera.camera2.interop.Camera2CameraInfo.from(cam.cameraInfo)-        val isoRange = info.getCameraCharacteristic(-            android.hardware.camera2.CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE-        )-        Log.dev("NightPreview", "readManualControlRanges() isoRange=$isoRange")-        isoStopsMutable.value = if (isoRange != null) {-            val filtered = listOf(50, 100, 200, 400, 800, 1600, 3200, 6400, 12800)-                .filter { it in isoRange.lower..isoRange.upper }-                .ifEmpty { listOf(isoRange.lower, isoRange.upper) }-            Log.dev("NightPreview", "readManualControlRanges() filtered stops=$filtered")-            filtered-        } else {-            Log.status(-                "NightPreview",-                "readManualControlRanges() isoRange null, emitting emptyList -> ISO bar notAvailable",-            )-            emptyList()-        }-        // The stop list is per-lens: a new lens can be shorter, so re-clamp the persisted-        // index instead of pointing past the end (ISO bar read getOrNull → blank label).-        manualIsoIndexMutable.value = manualIsoIndexMutable.value.coerceIn(0, isoStopsMutable.value.size)-    } catch (e: IllegalStateException) {-        Log.error(-            "NightPreview",-            "readManualControlRanges() FAILED (was Warn, hidden) – " +-                "could affect ISO bar + manual controls",-            e-        )-    } catch (e: IllegalArgumentException) {-        Log.error(+    val isoRange = session.characteristics.sensitivityRange+    isoStopsMutable.value = if (isoRange != null) {+        listOf(50, 100, 200, 400, 800, 1600, 3200, 6400, 12800)+            .filter { it in isoRange.lower..isoRange.upper }+            .ifEmpty { listOf(isoRange.lower, isoRange.upper) }+    } else {+        Log.status(             "NightPreview",-            "readManualControlRanges() FAILED (was Warn, hidden) – " +-                "could affect ISO bar + manual controls",-            e+            "readManualControlRanges() isoRange null, emitting emptyList -> ISO bar notAvailable",         )+        emptyList()     }+    // The stop list is per-lens: a new lens can be shorter, so re-clamp the persisted+    // index instead of pointing past the end (ISO bar read getOrNull -> blank label).+    manualIsoIndexMutable.value = manualIsoIndexMutable.value.coerceIn(0, isoStopsMutable.value.size) }
camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.ktindex 4d285cf9dd..39f8649c28 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt@@ -1,219 +1,33 @@ package com.vayunmathur.camera.platform -import androidx.annotation.OptIn-import androidx.camera.camera2.interop.ExperimentalCamera2Interop- import android.graphics.Bitmap import android.graphics.Matrix import android.graphics.Rect import android.net.Uri import com.vayunmathur.library.log.Log-import androidx.camera.core.ImageCapture-import androidx.camera.core.ImageCaptureException-import androidx.camera.core.ImageProxy-import androidx.camera.extensions.ExtensionMode-import androidx.camera.lifecycle.ProcessCameraProvider-import androidx.camera.lifecycle.awaitInstance-import androidx.camera.core.Preview-import androidx.core.content.ContextCompat import androidx.lifecycle.viewModelScope-import com.vayunmathur.camera.platform.lensSelector import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch-import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext-import kotlin.coroutines.resume import kotlin.math.roundToInt import com.vayunmathur.camera.data.MediaStoreSaver-import com.vayunmathur.camera.data.prepareStillSave import com.vayunmathur.camera.data.saveProcessedStill import com.vayunmathur.camera.data.saveStillBitmap import com.vayunmathur.camera.data.saveStillBytes import com.vayunmathur.camera.data.setLastCaptureUri-import com.vayunmathur.camera.data.closeStream-import com.vayunmathur.camera.data.resolveUri import com.vayunmathur.camera.data.setFlashMode -/**- * True when a night-extension still must be captured in memory instead of- * on the JPEG file path: an effective AVIF selection. Read at capture- * time, never cached at bind.- */-internal fun CameraViewModel.nightExtensionInMemory(): Boolean =-    com.vayunmathur.camera.domain.StillFormatRouting.plainSingleNeedsInMemory(-        requestedStillFormat(), StitchNative.isAvailable,-    )--/** Saves one in-memory night-extension frame under the current still format. Blocking: call off main. */-internal fun CameraViewModel.saveNightExtensionStill(-    sourceJpeg: ByteArray,-    degrees: Int,-    mirror: Boolean,-): Uri? {-    if (com.vayunmathur.camera.domain.StillFormatRouting.isUltraHdrJpeg(sourceJpeg)) {-        return saveStillBytes(-            "IMG_${MediaStoreSaver.timestamp()}.jpg",-            stampStillBytes(sourceJpeg, degrees, mirror),-        )-    }-    val decoded = android.graphics.BitmapFactory.decodeByteArray(sourceJpeg, 0, sourceJpeg.size)-        ?: error("Could not decode night extension frame")-    val saved = saveProcessedStill(decoded, degrees, sourceJpeg)-    decoded.recycle()-    if (saved != null && saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG) {-        writeCaptureExif(saved.uri, sourceJpeg, degrees, mirrored = mirror)-    }-    return saved?.uri-}--/**- * On-demand NIGHT-extension capture: briefly rebinds a Preview + ImageCapture session with the- * extension-enabled selector, takes one standard shot (the vendor handles the multi-frame night- * merge internally), saves it, then restores the normal analysis-backed photo session so the- * moon button keeps tracking brightness. The extension does its own timing, so no manual- * long-exposure countdown here.- */-@Suppress("DEPRECATION")-internal suspend fun CameraViewModel.captureNightPhotoExtension() {-    // Ownership snapshot for the finally-restore: this capture borrows the session from-    // the UI session effect. If the effect tore down / rebound while the shot was in-    // flight (mode switch, lens flip, backgrounding), it owns the current session and-    // restoring here would strand the new mode on a photo session.-    val startMode = cameraModeMutable.value-    val startTeardownCount = sessionTeardownCount+internal fun CameraViewModel.captureNightPhotoCustom() {     isCapturingMutable.value = true-    // Drop the photo session so the UI's analyzer effect re-attaches PhotoAnalyzer once we restore.-    photoSessionActiveMutable.value = false-    try {-        val provider = ProcessCameraProvider.awaitInstance(app)-        cameraProvider = provider-        val mgr = getExtensionsManager(provider)-        if (mgr == null) {-            // Unreachable in practice: entry is gated by isNightExtensionAvailable(), which-            // already resolved the manager. Bail out; finally restores the normal session.-            Log.status("CameraViewModel", "ExtensionsManager missing at night capture; skipping")-            return-        }-        provider.unbindAll()-        imageAnalysis = null-        analysisStreamActiveMutable.value = false--        val baseSelector = lensSelector(lensFacingMutable.value, selectedLensMutable.value)-        val nightSelector = mgr.getExtensionEnabledCameraSelector(baseSelector, ExtensionMode.NIGHT)--        val preview = Preview.Builder().build()-        preview.setSurfaceProvider { request -> surfaceRequestMutable.value = request }--        val owner = ManualLifecycleOwner()-        owner.start()-        sessionLifecycleOwner = owner--        val capture = ImageCapture.Builder()-            .setFlashMode(getImageCaptureFlashMode())-            .build()-        imageCapture = capture-        capture.setScreenFlash(getScreenFlashForCapture())-        // Match the still crop the normal photo session uses (1:1 / 3:2 / 16:9 / 4:3), or-        // night-extension shots always save full-frame while the preview shows cropped.-        capture.setCropAspectRatio(currentCropAspectRatio())-        boundCamera = bindSession(provider, owner, nightSelector, preview, capture)--        // With AVIF selected the extension still is captured in memory and-        // lands through the EXIF-carrying StillEncoder (an Ultra HDR source-        // stays JPEG_R), instead of the JPEG-only file path below. The-        // format is read now, at capture time, never cached at bind.-        val inMemory = nightExtensionInMemory()-        val pending = if (inMemory) {-            null-        } else {-            prepareStillSave("IMG_${MediaStoreSaver.timestamp()}.jpg")-        }-        if (!inMemory && pending == null) {-            Log.status("CameraViewModel", "Night extension capture skipped: no save target")-            return-        }-        val outputOptions = pending?.outputOptions-        val mirror = mirrorCaptures--        val savedUri = suspendCancellableCoroutine<Uri?> { cont ->-            if (inMemory) {-                capture.takePicture(-                    ContextCompat.getMainExecutor(app),-                    object : ImageCapture.OnImageCapturedCallback() {-                        override fun onCaptureSuccess(image: ImageProxy) {-                            val degrees = image.imageInfo.rotationDegrees-                            val sourceJpeg = try {-                                image.planes[0].buffer.let { buf ->-                                    ByteArray(buf.remaining()).also { buf.get(it) }-                                }-                            } finally {-                                image.close()-                            }-                            viewModelScope.launch {-                                val uri = withContext(Dispatchers.IO) {-                                    runCatching {-                                        saveNightExtensionStill(sourceJpeg, degrees, mirror)-                                    }.getOrNull()-                                }-                                if (cont.isActive) cont.resume(uri)-                            }-                        }+    val perFrame = computeNightExposure(CameraViewModel.NIGHT_BURST_PER_FRAME_NANOS)+    // Honest progress: frames are sequential full stills of unknown duration, so the+    // overlay tracks frames actually captured (then merging), not perFrame * count.+    showNightCaptureProgress(0) -                        override fun onError(exception: ImageCaptureException) {-                            Log.error("CameraViewModel", "Night extension capture failed", exception)-                            if (cont.isActive) cont.resume(null)-                        }-                    }-                )-            } else {-                capture.takePicture(-                    outputOptions!!,-                    ContextCompat.getMainExecutor(app),-                    object : ImageCapture.OnImageSavedCallback {-                        override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {-                            pending.closeStream()-                            cont.resume(pending.resolveUri(outputFileResults))-                        }-                        override fun onError(exception: ImageCaptureException) {-                            Log.error("CameraViewModel", "Night extension capture failed", exception)-                            pending.closeStream()-                            cont.resume(null)-                        }-                    }-                )-            }-        }-        if (savedUri != null) setLastCaptureUri(savedUri)-    } catch (e: IllegalStateException) {-        Log.error("CameraViewModel", "Night extension capture path failed", e)-    } catch (e: IllegalArgumentException) {-        Log.error("CameraViewModel", "Night extension capture path failed", e)-    } finally {-        // Rebind the normal 3-stream session only when this capture still owns the-        // session (same PHOTO mode, no intervening teardown); otherwise the UI session-        // effect's fresh bind owns it and a blind setupPhotoSession() here would unbind-        // that session and leave the new mode with a dead photo preview.-        if (nightCaptureRestoreApplies(startMode, cameraModeMutable.value, startTeardownCount, sessionTeardownCount)) {-            setupPhotoSession()-        }-        isCapturingMutable.value = false-    }+    captureNightBurst(perFrame, { captured -> showNightCaptureProgress(captured) }, ::onNightBurstDone) } -/**- * Whether [captureNightPhotoExtension]'s finally may restore the normal photo session:- * only when the capture still owns the session — it started in PHOTO, the mode never- * changed, and no teardown (mode switch / lens flip / lifecycle rebind) intervened.- */-internal fun nightCaptureRestoreApplies(-    startMode: CameraMode,-    currentMode: CameraMode,-    startTeardownCount: Int,-    currentTeardownCount: Int-): Boolean =-    startMode == CameraMode.PHOTO && currentMode == startMode && currentTeardownCount == startTeardownCount- /** Frame-count progress label for the night burst (no fabricated duration estimate). */ internal fun nightCaptureProgressLabel(captured: Int, total: Int): String =     if (total <= 0) "Capturing" else "Capturing ${captured.coerceIn(0, total)}/$total"@@ -224,22 +38,6 @@ internal fun nightCaptureProgressFraction(captured: Int, total: Int): Float =  internal const val NIGHT_MERGING_LABEL = "Merging…" -/**- * Multi-frame night capture: locks the sensor to a per-frame night exposure/ISO, collects a- * burst off the ImageAnalysis stream, then aligns + merges + brightens it (via- * [NightCaptureEngine]) and saves. Falls back to the single long-exposure capture if the burst- * is empty or the merge fails, so the user always gets a shot.- */-internal fun CameraViewModel.captureNightPhotoCustom() {-    isCapturingMutable.value = true-    val perFrame = computeNightExposure(CameraViewModel.NIGHT_BURST_PER_FRAME_NANOS)-    // Honest progress: frames are sequential full stills of unknown duration, so the-    // overlay tracks frames actually captured (then merging), not perFrame * count.-    showNightCaptureProgress(0)--    captureNightBurst(perFrame, { captured -> showNightCaptureProgress(captured) }, ::onNightBurstDone)-}- /** Publishes frame-count progress to the existing long-exposure overlay flows. */ internal fun CameraViewModel.showNightCaptureProgress(captured: Int) {     longExposureTimerJob?.cancel()@@ -344,202 +142,84 @@ internal suspend fun CameraViewModel.mergeNightFrames(frames: List<Bitmap>): Uri  * Falls back to empty list if [imageCapture] is unavailable, which makes  * [captureNightPhotoCustom] fall back to single-frame long-exposure.  */-@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class) internal fun CameraViewModel.captureNightBurst(     exposure: NightExposure,     onFrameCaptured: (Int) -> Unit = {},     onDone: (List<Bitmap>) -> Unit ) {-    if (imageCapture == null) {+    val session = activeCamera2Session ?: run {         onDone(emptyList())         return     }-    val cam2Control = camera2ControlQuietly()-    val driver = NightBurstDriver(-        viewModel = this,-        cam2Control = cam2Control,-        mirror = mirrorCaptures,-        exposure = exposure,-        onFrameCaptured = onFrameCaptured,-        onDone = onDone-    )-    driver.start()-}--/** Camera2 control handle; null (logged) when unavailable. */-@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class)-internal fun CameraViewModel.camera2ControlQuietly():-    androidx.camera.camera2.interop.Camera2CameraControl? {-    return try {-        boundCamera?.cameraControl?.let {-            androidx.camera.camera2.interop.Camera2CameraControl.from(it)-        }-    } catch (e: IllegalArgumentException) {-        Log.status("CameraViewModel", "Camera2 control unavailable", e)-        null-    } catch (e: NullPointerException) {-        Log.status("CameraViewModel", "Camera2 control unavailable", e)-        null-    }-}--/**- * Owns one night-burst sequence: locks the night exposure, fires full-resolution- * captures back-to-back, converts each to an upright bitmap and restores 3A + the- * manual-control state when done.- */-@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class)-private class NightBurstDriver(-    private val viewModel: CameraViewModel,-    private val cam2Control: androidx.camera.camera2.interop.Camera2CameraControl?,-    private val mirror: Boolean,-    private val exposure: NightExposure,-    private val onFrameCaptured: (Int) -> Unit = {},-    private val onDone: (List<Bitmap>) -> Unit-) {-    private val collected = mutableListOf<Bitmap>()-    private var alreadyDone = false-    // Captures attempted (successes + failures). Failures skip a frame, but-    // without this bound a persistently failing capture would retry forever-    // and the burst (and its locked exposure) would never finish.-    private var attempted = 0--    fun start() {-        if (cam2Control != null) {-            viewModel.lockNightExposure(cam2Control, exposure, ::takeNext)-        } else {-            takeNext()-        }-    }--    private fun restore3A() {-        if (cam2Control != null) {-            try {-                cam2Control.setCaptureRequestOptions(-                    androidx.camera.camera2.interop.CaptureRequestOptions.Builder()-                        .clearCaptureRequestOption(android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME)-                        .clearCaptureRequestOption(android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY)-                        .clearCaptureRequestOption(android.hardware.camera2.CaptureRequest.CONTROL_AE_MODE)-                        .clearCaptureRequestOption(android.hardware.camera2.CaptureRequest.CONTROL_AWB_LOCK)-                        .build()-                )-            } catch (e: IllegalStateException) {-                Log.status("CameraViewModel", "Failed to restore auto 3A after night burst", e)-            } catch (e: IllegalArgumentException) {-                Log.status("CameraViewModel", "Failed to restore auto 3A after night burst", e)-            }-        }-    }--    private fun finish() {-        if (alreadyDone) return-        alreadyDone = true-        restore3A()-        // Re-assert (auto) manual-control state to fully undo night override.+    // Lock the night exposure on the session (preview + stills inherit+    // it through the control state; AE locks off in the still planner+    // whenever a manual pair is present).+    session.setManualExposure(exposure.nanos, exposure.iso)+    val collected = mutableListOf<Bitmap>()+    var attempted = 0+    var finished = false+    fun finish() {+        if (finished) return+        finished = true+        // Restore AE + the user's manual-control state.+        session.setManualExposure(null, null)         try {-            viewModel.applyManualControls()+            applyManualControls()         } catch (_: Exception) {}         onDone(collected.toList())     }--    private fun takeNext() {+    fun takeNext() {         if (attempted >= NightCaptureEngine.NIGHT_BURST_COUNT) {             finish()             return         }         attempted++-        val cap = viewModel.imageCapture ?: run {-            finish()-            return-        }-        cap.takePicture(-            ContextCompat.getMainExecutor(viewModel.app),-            object : ImageCapture.OnImageCapturedCallback() {-                override fun onCaptureSuccess(image: ImageProxy) {-                    if (convertFrame(image)) onFrameCaptured(collected.size)+        session.capture(+            mirrored = mirrorCaptures,+            callback = object : com.vayunmathur.camera.platform.camera2.Camera2Session.StillCallback {+                override fun onStillCaptured(still: com.vayunmathur.camera.platform.camera2.CapturedStill) {+                    val bmp = decodeNightFrame(still)+                    if (bmp != null) {+                        collected.add(bmp)+                        onFrameCaptured(collected.size)+                    }                     takeNext()                 } -                override fun onError(exception: ImageCaptureException) {-                    Log.status("CameraViewModel", "Night frame capture failed, continuing", exception)+                override fun onStillFailed(message: String) {+                    Log.status("CameraViewModel", "Night frame capture failed, continuing: $message")                     takeNext()                 }-            }+            },         )     }--    /** Converts one burst frame to an upright bitmap and collects it; true if collected. */-    private fun convertFrame(image: ImageProxy): Boolean {-        return try {-            // toBitmap() is provided by CameraX (used also in BokehAnalyzer).-            // Apply the session's cropRect (setCropAspectRatio): the raw frame is-            // always full-frame, so without this the burst ignores the non-4:3 crop.-            val cropRect = android.graphics.Rect(image.cropRect)-            val raw = viewModel.cropToRect(image.toBitmap(), cropRect)-            val matrix = Matrix().apply {-                postRotate(image.imageInfo.rotationDegrees.toFloat())-                if (mirror) postScale(-1f, 1f)-            }-            val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, matrix, true)-            if (upright !== raw) raw.recycle()-            collected.add(upright)-            true-        } catch (e: IllegalStateException) {-            Log.status("CameraViewModel", "Failed to convert night frame", e)-            false-        } catch (e: IllegalArgumentException) {-            Log.status("CameraViewModel", "Failed to convert night frame", e)-            false-        } catch (e: NullPointerException) {-            Log.status("CameraViewModel", "Failed to convert night frame", e)-            false-        } catch (e: OutOfMemoryError) {-            // Skip this frame under memory pressure; the burst can still merge fewer frames.-            Log.status("CameraViewModel", "Night frame conversion OOM; skipping frame", e)-            false-        } finally {-            image.close()-        }-    }+    takeNext() } -/** Locks AE off + night exposure/ISO + AWB, then runs [onLocked]. Falls through on failure. */-@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class)-internal fun CameraViewModel.lockNightExposure(-    cam2Control: androidx.camera.camera2.interop.Camera2CameraControl,-    exposure: NightExposure,-    onLocked: () -> Unit-) {-    try {-        val optsBuilder = androidx.camera.camera2.interop.CaptureRequestOptions.Builder()-            .setCaptureRequestOption(-                android.hardware.camera2.CaptureRequest.CONTROL_AE_MODE,-                android.hardware.camera2.CameraMetadata.CONTROL_AE_MODE_OFF-            )-            .setCaptureRequestOption(-                android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME,-                exposure.nanos-            )-            .setCaptureRequestOption(-                android.hardware.camera2.CaptureRequest.CONTROL_AWB_LOCK, true-            )-        exposure.iso?.let {-            optsBuilder.setCaptureRequestOption(-                android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY, it-            )+/** Decodes one burst still to an upright bitmap; null when undecodable. */+private fun decodeNightFrame(+    still: com.vayunmathur.camera.platform.camera2.CapturedStill,+): Bitmap? {+    return try {+        val raw = android.graphics.BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size)+            ?: return null+        val matrix = android.graphics.Matrix().apply {+            postRotate(still.metadata.rotationDegrees.toFloat())+            if (still.metadata.mirrored) postScale(-1f, 1f)         }-        cam2Control.setCaptureRequestOptions(optsBuilder.build())-            .addListener({ onLocked() }, ContextCompat.getMainExecutor(app))+        val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, matrix, true)+        if (upright !== raw) raw.recycle()+        upright     } catch (e: IllegalStateException) {-        Log.status("CameraViewModel", "Failed to set night exposure for burst", e)-        onLocked()+        Log.status("CameraViewModel", "Failed to decode night frame", e)+        null     } catch (e: IllegalArgumentException) {-        Log.status("CameraViewModel", "Failed to set night exposure for burst", e)-        onLocked()+        Log.status("CameraViewModel", "Failed to decode night frame", e)+        null+    } catch (e: OutOfMemoryError) {+        // Skip this frame under memory pressure; the burst can still merge fewer frames.+        Log.status("CameraViewModel", "Night frame decode OOM; skipping frame", e)+        null     } } @@ -550,33 +230,21 @@ internal data class NightExposure(val nanos: Long, val iso: Int?)  * into the sensor's exposure-time range and picks a high fraction of its sensitivity range.  * Falls back to [targetNanos] (and auto ISO) if the characteristics are unavailable.  */-@Suppress("DEPRECATION")-@OptIn(ExperimentalCamera2Interop::class) internal fun CameraViewModel.computeNightExposure(     targetNanos: Long = CameraViewModel.NIGHT_TARGET_EXPOSURE_NANOS ): NightExposure {     val fallback = NightExposure(targetNanos, null)-    return try {-        val cam = boundCamera ?: return fallback-        val info = androidx.camera.camera2.interop.Camera2CameraInfo.from(cam.cameraInfo)-        val expRange = info.getCameraCharacteristic(-            android.hardware.camera2.CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE-        )-        val isoRange = info.getCameraCharacteristic(-            android.hardware.camera2.CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE-        )-        val nanos = expRange?.let {-            targetNanos.coerceIn(it.lower, it.upper)-        } ?: targetNanos-        val iso = isoRange?.let {-            (it.lower + ((it.upper - it.lower) * CameraViewModel.NIGHT_ISO_FRACTION).roundToInt())-                .coerceIn(it.lower, it.upper)-        }-        NightExposure(nanos, iso)-    } catch (e: IllegalArgumentException) {-        Log.status("CameraViewModel", "Failed to read sensor ranges for night mode", e)-        fallback+    val snapshot = activeCamera2Session?.characteristics ?: return fallback+    val expRange = snapshot.exposureTimeRangeNs+    val isoRange = snapshot.sensitivityRange+    val nanos = expRange?.let {+        targetNanos.coerceIn(it.lower, it.upper)+    } ?: targetNanos+    val iso = isoRange?.let {+        (it.lower + ((it.upper - it.lower) * CameraViewModel.NIGHT_ISO_FRACTION).roundToInt())+            .coerceIn(it.lower, it.upper)     }+    return NightExposure(nanos, iso) }  /** Nanos per millisecond; countdown tick step. */
camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.ktindex ab5a0ada12..3bb4db549a 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightMode.kt@@ -1,22 +1,11 @@ package com.vayunmathur.camera.platform +import android.hardware.camera2.CameraManager import com.vayunmathur.library.log.Log-import androidx.camera.camera2.interop.ExperimentalCamera2Interop-import androidx.camera.extensions.ExtensionMode-import androidx.camera.extensions.ExtensionsManager-import androidx.camera.lifecycle.ProcessCameraProvider-import androidx.camera.lifecycle.awaitInstance-import androidx.camera.core.CameraSelector-import androidx.camera.core.Preview-import androidx.camera.core.ImageCapture-import androidx.camera.extensions.ExtensionSessionConfig-import androidx.core.content.ContextCompat import androidx.lifecycle.viewModelScope-import com.vayunmathur.camera.platform.lensSelector+import com.vayunmathur.camera.platform.camera2.Camera2ExtensionProbe+import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade import kotlinx.coroutines.launch-import kotlinx.coroutines.suspendCancellableCoroutine-import kotlinx.coroutines.CancellableContinuation-import kotlin.coroutines.resume  internal fun CameraViewModel.nightExtFailedRecently(): Boolean {     val at = ds.getString("night_ext_failed_at")?.toLongOrNull() ?: return false@@ -41,63 +30,15 @@ suspend fun CameraViewModel.refreshNightExtensionUsable(cameraMode: CameraMode)     } } -/** Observe getNightModeIndicator() on the freshly-bound camera (call on the main thread). */-internal fun CameraViewModel.observeNightModeIndicator(cameraInfo: androidx.camera.core.CameraInfo) {-    stopObservingNightModeIndicator()-    nightIndicatorSupported = try { cameraInfo.isNightModeIndicatorSupported } catch (_: Exception) { false }-    if (!nightIndicatorSupported) return-    val ld = try { cameraInfo.getNightModeIndicator() } catch (_: Exception) { null } ?: return-    nightIndicatorLiveData = ld-    ld.observeForever(nightIndicatorObserver)-}--internal fun CameraViewModel.stopObservingNightModeIndicator() {-    nightIndicatorLiveData?.removeObserver(nightIndicatorObserver)-    nightIndicatorLiveData = null-}--/** Observe the bound extension camera's processing strength (call on the main thread). */-internal fun CameraViewModel.observeExtensionStrength(cameraInfo: androidx.camera.core.CameraInfo) {-    stopObservingExtensionStrength()-    val mgr = extensionsManager ?: return-    val info = try { mgr.getCameraExtensionsInfo(cameraInfo) } catch (_: Exception) { return }-    if (!info.isExtensionStrengthAvailable) return-    val ld = try { info.getExtensionStrength() } catch (_: Exception) { null } ?: return-    extensionStrengthLiveData = ld-    ld.observeForever(extensionStrengthObserver)-}--internal fun CameraViewModel.stopObservingExtensionStrength() {-    extensionStrengthLiveData?.removeObserver(extensionStrengthObserver)-    extensionStrengthLiveData = null-    extensionStrengthMutable.value = null-}--internal fun CameraViewModel.observeExtensionCameraState(cameraInfo: androidx.camera.core.CameraInfo) {-    stopObservingExtensionCameraState()-    val ld = cameraInfo.cameraState-    extensionCameraStateLiveData = ld-    ld.observeForever(extensionCameraStateObserver)-}--internal fun CameraViewModel.stopObservingExtensionCameraState() {-    extensionCameraStateLiveData?.removeObserver(extensionCameraStateObserver)-    extensionCameraStateLiveData = null-}- /**  * Feeds the PhotoAnalyzer's average scene luminance through a hysteresis + debounce filter so  * night mode engages/disengages smoothly. When the scene brightens back up (true→false), the  * user's per-scene override is reset so the next dark scene re-engages cleanly.  */ fun CameraViewModel.onLuminance(avg: Float) {-    // getNightModeIndicator() is authoritative when the device supports it — skip the luminance-    // heuristic so the two don't fight. This luma path is only the fallback for devices without-    // the indicator.-    // Phase 6: the indicator is a CameraX-only signal (there is no Camera2 equivalent), so on-    // the Camera2 path it is never observed (nightIndicatorSupported stays false) and this luma-    // hysteresis is the engagement trigger; see Camera2ExtensionProbe's detection contract.-    if (nightIndicatorSupported) return+    // Night engagement is this luma hysteresis (there is no Camera2+    // night-mode indicator equivalent; see Camera2ExtensionProbe's+    // detection contract).     val beforeLow = lowLightDetectedMutable.value     val beforeOff = nightModeOverriddenOffMutable.value     Log.dev(@@ -153,7 +94,7 @@ private fun CameraViewModel.trackBrightening(avg: Float) {         Log.dev(             "NightPreview",             "onLuminance() after DISENGAGE lowLight=${lowLightDetectedMutable.value} " +-                "nightActive=${nightModeActive.value} – triggers teardown->setupPhotoSession() rebind"+                "nightActive=${nightModeActive.value} – triggers a session rebind"         )     } }@@ -214,195 +155,15 @@ internal fun CameraViewModel.resetNightModeDetection() {     highLumaFrames = 0 } -/** Obtains (and caches) the ExtensionsManager bound to [provider]. Null if unavailable. */-internal suspend fun CameraViewModel.getExtensionsManager(provider: ProcessCameraProvider): ExtensionsManager? {-    Log.dev(-        "NightPreview",-        "getExtensionsManager() called providerHash=${provider.hashCode()} " +-            "cachedExists=${extensionsManager != null} thread=${Thread.currentThread().name} " +-            "startMs=${System.currentTimeMillis()}"-    )-    extensionsManager?.let {-        Log.dev(-            "NightPreview",-            "getExtensionsManager() returning CACHED manager providerHash=${provider.hashCode()} " +-                "manager=$it – NOTE: cached across provider instances, " +-                "may be tied to old provider if provider changed!"-        )-        return it-    }-    return try {-        val mgr = awaitExtensionsManager(provider)-        Log.dev(-            "NightPreview",-            "getExtensionsManager() obtained mgr=$mgr caching for providerHash=${provider.hashCode()}"-        )-        extensionsManager = mgr-        mgr-    } catch (e: IllegalStateException) {-        Log.error(-            "NightPreview",-            "getExtensionsManager() EXCEPTION – ExtensionsManager unavailable (was hidden as Warn), " +-                "root cause of black preview if NIGHT needed",-            e-        )-        null-    } catch (e: IllegalArgumentException) {-        Log.error(-            "NightPreview",-            "getExtensionsManager() EXCEPTION – ExtensionsManager unavailable (was hidden as Warn), " +-                "root cause of black preview if NIGHT needed",-            e-        )-        null-    }-}--/** Suspends until the ExtensionsManager instance for [provider] resolves. */-private suspend fun CameraViewModel.awaitExtensionsManager(-    provider: ProcessCameraProvider-): ExtensionsManager {-    val start = System.currentTimeMillis()-    return suspendCancellableCoroutine<ExtensionsManager> { cont ->-        Log.dev(-            "NightPreview",-            "getExtensionsManager() creating async instance for providerHash=${provider.hashCode()}"-        )-        val future = ExtensionsManager.getInstanceAsync(app, provider)-        future.addListener({-            resolveManagerFuture(future, start, cont)-        }, ContextCompat.getMainExecutor(app))-    }-}--/** Resumes [cont] with the manager future's result, logging failures. */-private fun CameraViewModel.resolveManagerFuture(-    future: com.google.common.util.concurrent.ListenableFuture<ExtensionsManager>,-    start: Long,-    cont: CancellableContinuation<ExtensionsManager>-) {-    try {-        val res = future.get()-        Log.dev(-            "NightPreview",-            "getExtensionsManager() future.get() SUCCESS res=$res " +-                "elapsed=${System.currentTimeMillis() - start}ms"-        )-        cont.resume(res)-    } catch (e: java.util.concurrent.ExecutionException) {-        Log.error(-            "NightPreview",-            "getExtensionsManager() future.get() FAILED " +-                "elapsed=${System.currentTimeMillis() - start}ms – " +-                "this was previously swallowed as Warn",-            e-        )-        cont.cancel(e)-    } catch (e: InterruptedException) {-        Log.error(-            "NightPreview",-            "getExtensionsManager() future.get() FAILED " +-                "elapsed=${System.currentTimeMillis() - start}ms – " +-                "this was previously swallowed as Warn",-            e-        )-        cont.cancel(e)-    }-}--/** Whether the CameraX NIGHT extension is available on the current lens. */-suspend fun CameraViewModel.isNightExtensionAvailable(): Boolean {-    val startMs = System.currentTimeMillis()-    Log.dev(-        "NightPreview",-        "isNightExtensionAvailable() START lensFacing=${lensFacingMutable.value} " +-            "thread=${Thread.currentThread().name}"-    )-    return try {-        probeNightExtension(startMs)-    } catch (e: IllegalStateException) {-        Log.error(-            "NightPreview",-            "isNightExtensionAvailable() OUTER EXCEPTION – returning false, " +-                "totalTook=${System.currentTimeMillis() - startMs}ms",-            e-        )-        false-    } catch (e: IllegalArgumentException) {-        Log.error(-            "NightPreview",-            "isNightExtensionAvailable() OUTER EXCEPTION – returning false, " +-                "totalTook=${System.currentTimeMillis() - startMs}ms",-            e-        )-        false-    }-}--/** Resolves the provider + manager and probes NIGHT support on the current lens. */-private suspend fun CameraViewModel.probeNightExtension(startMs: Long): Boolean {-    val provider = ProcessCameraProvider.awaitInstance(app)-    Log.dev(-        "NightPreview",-        "isNightExtensionAvailable() got providerHash=${provider.hashCode()} " +-            "elapsed=${System.currentTimeMillis() - startMs}ms"-    )-    val mgr = getExtensionsManager(provider)-    Log.dev(-        "NightPreview",-        "isNightExtensionAvailable() ExtensionsManager=${mgr != null} " +-            "elapsed=${System.currentTimeMillis() - startMs}ms"-    )-    if (mgr == null) {-        Log.status(-            "NightPreview",-            "isNightExtensionAvailable() manager NULL after ${System.currentTimeMillis() - startMs}ms, " +-                "returning false -> moon button may show but useNightPreview false, so no visible transition"-        )-        return false-    }-    val selector = lensSelector(lensFacingMutable.value, selectedLensMutable.value)-    if (!mgr.isExtensionAvailable(selector, ExtensionMode.NIGHT)) {-        Log.dev(-            "NightPreview",-            "isNightExtensionAvailable() isExtensionAvailable(NIGHT)=false " +-                "lens=${lensFacingMutable.value}"-        )-        return false-    }-    return querySessionConfigSupport(provider, selector, mgr, startMs)-}- /**- * Optimistic support query. Neither this nor a getCameraInfo probe reliably predicts the- * GrapheneOS/Pixel extender failure (it only surfaces at actual bind time), so we accept a- * yes here and rely on the daily failure cache (recordNightExtensionFailure) to stop- * offering night after the first real bind failure.+ * Whether the vendor NIGHT extension is usable on the selected lens,+ * probed from Camera2 characteristics (extension mode list + advertised+ * preview/JPEG sizes). Replaces the CameraX ExtensionsManager probe.  */-private fun CameraViewModel.querySessionConfigSupport(-    provider: ProcessCameraProvider,-    selector: CameraSelector,-    mgr: ExtensionsManager,-    startMs: Long-): Boolean {-    val cameraInfo = provider.getCameraInfo(selector)-    val nightConfig = ExtensionSessionConfig.Builder(ExtensionMode.NIGHT, mgr)-        .addUseCase(Preview.Builder().build())-        .addUseCase(ImageCapture.Builder().build())-        .build()-    val supported = try {-        cameraInfo.isSessionConfigSupported(nightConfig)-    } catch (e: IllegalStateException) {-        Log.status("NightPreview", "isNightExtensionAvailable() isSessionConfigSupported threw", e)-        false-    } catch (e: IllegalArgumentException) {-        Log.status("NightPreview", "isNightExtensionAvailable() isSessionConfigSupported threw", e)-        false-    }-    Log.dev(-        "NightPreview",-        "isNightExtensionAvailable() isSessionConfigSupported(NIGHT)=$supported " +-            "lens=${lensFacingMutable.value} total=${System.currentTimeMillis() - startMs}ms"-    )-    return supported+internal fun CameraViewModel.isNightExtensionAvailable(): Boolean {+    val manager = app.getSystemService(CameraManager::class.java) ?: return false+    val facing = selectedLensMutable.value?.facing ?: currentLensFacing()+    val lensId = CharacteristicsFacade.resolveCamera2Id(manager, facing) ?: return false+    val facade = CharacteristicsFacade.tryFromCameraManager(manager, lensId) ?: return false+    return Camera2ExtensionProbe.probeNight(facade.snapshot).usable }
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 3e86888899..f0b8741fd7 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -2,13 +2,7 @@ package com.vayunmathur.camera.platform  import android.graphics.Bitmap import android.net.Uri-import androidx.annotation.OptIn import com.vayunmathur.library.log.Log-import androidx.camera.core.ExperimentalZeroShutterLag-import androidx.camera.core.ImageCapture-import androidx.camera.core.ImageCaptureException-import androidx.camera.core.ImageProxy-import androidx.core.content.ContextCompat import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -19,12 +13,9 @@ import kotlinx.coroutines.withTimeoutOrNull import kotlin.math.roundToInt import com.vayunmathur.camera.data.MediaStoreSaver import com.vayunmathur.camera.domain.MotionPhotoWriter-import com.vayunmathur.camera.data.prepareStillSave import com.vayunmathur.camera.data.saveProcessedStill import com.vayunmathur.camera.data.saveStillBytes import com.vayunmathur.camera.data.setLastCaptureUri-import com.vayunmathur.camera.data.closeStream-import com.vayunmathur.camera.data.resolveUri  /** Shutter-timer countdown tick (1s). */ internal const val TIMER_TICK_MS = 1000L@@ -97,30 +88,23 @@ fun CameraViewModel.takePhoto() {  internal fun CameraViewModel.capturePhoto() {     if (isCapturingMutable.value || burstActiveMutable.value) return-    // Phase 4a: a gated Camera2 session takes plain PHOTO stills itself-    // (StillEnginePolicy excludes night/processed/Motion/burst/result-    // shots, which fall through to the CameraX routing below unchanged).-    // This runs before the imageCapture check: with the gate on, CameraX-    // may not be bound at all.-    if (activeCamera2Session != null) {-        isCapturingMutable.value = true-        if (tryCaptureCamera2Still()) return-        isCapturingMutable.value = false-    }-    if (imageCapture == null) return-    // Claim in-flight synchronously so a second shutter tap (or a stacked timer firing)-    // can't start a concurrent capture. Every path clears it once its frame is captured-    // (Motion Photo) or saved (the other paths) — never later.+    val session = activeCamera2Session ?: return+    // Claim in-flight synchronously so a second shutter tap (or a stacked+    // timer firing) can't start a concurrent capture.     isCapturingMutable.value = true-    // A ZSL press reprocesses the ring buffer's newest converged frame. While AE is-    // still searching after a lighting change that frame is exposed for the previous-    // scene (the intermittent strong overexposure in auto mode), so hold the shutter-    // until AE converges — zero added latency in steady light, where it already has.+    // Plain stills take the direct Camera2 route; everything+    // StillEnginePolicy excludes (night/processed/Motion/burst/result)+    // routes to its dedicated Camera2 path below.+    if (tryCaptureCamera2Still()) return+    // A ring (ZSL) press reprocesses the newest converged frame. While AE+    // is still searching after a lighting change that frame is exposed+    // for the previous scene, so hold the shutter until AE converges —+    // zero added latency in steady light, where it already has.     if (stillCaptureIsZsl() && !isAeConvergedForCapture()) {         viewModelScope.launch {             awaitAeConvergence()             // Teardown claims the flag while we wait; a dead session must not capture.-            if (!isCapturingMutable.value || imageCapture == null) return@launch+            if (!isCapturingMutable.value || activeCamera2Session !== session) return@launch             routeAndCapture()         }     } else {@@ -181,10 +165,9 @@ internal fun CameraViewModel.nightCaptureApplies(): Boolean {     return nightAuto && flashModeMutable.value == FlashMode.OFF && !stillCaptureIsZsl() } -/** True when the bound ImageCapture was built for zero-shutter-lag capture. */-@OptIn(ExperimentalZeroShutterLag::class)+/** True when the live Camera2 session holds a YUV ring (zero-shutter-lag) output. */ internal fun CameraViewModel.stillCaptureIsZsl(): Boolean =-    imageCapture?.captureMode == ImageCapture.CAPTURE_MODE_ZERO_SHUTTER_LAG+    activeCamera2Session?.hasRingOutput == true  /**  * Motion Photo for plain PHOTO captures (no warmth/shadows bake, not capturing for a caller).@@ -213,23 +196,19 @@ private fun CameraViewModel.motionPhotoEligible(): Boolean {  * flight at a time) with `IMG_<ts>_BURSTn` names, until [stopBurst] or [CameraViewModel.BURST_MAX]  * is reached. Uses the plain capture path (no night/manual special-casing).  */-@Suppress("DEPRECATION")-@OptIn(androidx.camera.camera2.interop.ExperimentalCamera2Interop::class) fun CameraViewModel.startBurst() {     if (burstActiveMutable.value || isCapturingMutable.value) return     // A burst is immediate: an armed shutter timer no longer applies.     cancelTimerCountdown()-    val capture = imageCapture ?: return+    val session = activeCamera2Session ?: return     // Mark both in-flight: a single capture must not start mid-burst and a burst must not     // start mid-capture. Releasing the shutter always goes through finishBurst().     isCapturingMutable.value = true     burstActiveMutable.value = true     burstCountMutable.value = 0-    val ts = MediaStoreSaver.timestamp()     // Long manual shutter: lock the full still exposure for the burst's frames (the     // live preview otherwise runs the capped split) and restore it when the burst ends.     val burstSplit = currentExposureSplit()?.takeIf { it.stillOverrideRequired }-    val burstCam2 = if (burstSplit != null) camera2ControlOrNull() else null     var burstExposureLocked = false      fun finishBurst() {@@ -241,140 +220,60 @@ fun CameraViewModel.startBurst() {         }     } -    // AVIF bursts cannot use the JPEG file path: each frame is captured-    // in memory and encoded like a plain AVIF single (Ultra HDR frames-    // stay JPEG_R, as for singles). JPEG bursts keep the fast file path.-    val burstAvif = com.vayunmathur.camera.domain.StillFormatRouting.plainSingleNeedsInMemory(-        if (photoFormatMutable.value == PhotoFormat.AVIF) {-            com.vayunmathur.camera.domain.StillFormat.AVIF-        } else {-            com.vayunmathur.camera.domain.StillFormat.JPEG-        },-        StitchNative.isAvailable,-    )-     fun shootNext(n: Int) {         if (!burstActiveMutable.value || n > CameraViewModel.BURST_MAX) {             finishBurst()             return         }-        if (burstAvif) {-            val mirror = mirrorCaptures-            capture.takePicture(-                ContextCompat.getMainExecutor(app),-                object : ImageCapture.OnImageCapturedCallback() {-                    override fun onCaptureSuccess(image: ImageProxy) {-                        val degrees = image.imageInfo.rotationDegrees-                        val cropRect = android.graphics.Rect(image.cropRect)-                        val sourceJpeg = try {-                            image.planes[0].buffer.let { buf ->-                                ByteArray(buf.remaining()).also { buf.get(it) }-                            }-                        } finally {-                            image.close()-                        }-                        viewModelScope.launch {-                            val uri = kotlinx.coroutines.withContext(Dispatchers.IO) {-                                runCatching {-                                    if (com.vayunmathur.camera.domain.StillFormatRouting-                                            .isUltraHdrJpeg(sourceJpeg)-                                    ) {-                                        saveStillBytes(-                                            "IMG_${ts}_BURST${n}.jpg",-                                            stampStillBytes(sourceJpeg, degrees, mirror),-                                        )-                                    } else {-                                        val decodedRaw = android.graphics.BitmapFactory-                                

Diff truncated.