Modern Apps git

← Modern-Apps.git

camera: Camera2 foundation - characteristics, executor, session machine

Commit
0114cb95e502685274eec97e36b102b8b1c2861e
Author
Vayun Mathur <[email protected]>
When
2026-11-21 17:11 UTC (14 days ago)
Parents
b3853f8
Phase 0 of the CameraX->Camera2 migration, pure addition:
CharacteristicsFacade reads every lens fact once into a pure
snapshot (zoom/flash/exposure/stabilization/FPS/stream map,
RAW+reprocess capabilities, extension modes); Camera2Executor
is the owned HandlerThread executor with deterministic
shutdown; SessionStateMachine models the Camera2 session
lifecycle with a monotonic teardown generation so stale async
callbacks from a previous session are dropped (the night-
capture lesson); PreviewSurfaceBridge translates TextureView
surface events for the session layer. Nothing existing is
touched - the CameraX paths run exactly as before. Part of
this (executor, first facade cut) rode in b3853f8da; this
completes it with the supportedExtensions fix, state machine,
bridge and tests.

Verified: 17 new foundation tests pass. (Detekt's rust
file-length check on rust/lib.rs belongs to the in-flight
AVIF work.)

Diff

camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.ktindex 293cdd0d96..f9d709c861 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.kt@@ -90,7 +90,14 @@ object SafDocuments {         resolver: android.content.ContentResolver,         treeUri: Uri,         displayName: String,-    ): Uri? = createDoc(resolver, treeUri, "image/jpeg", displayName)+    ): Uri? = createImageDoc(resolver, treeUri, displayName, "image/jpeg")++    fun createImageDoc(+        resolver: android.content.ContentResolver,+        treeUri: Uri,+        displayName: String,+        mimeType: String,+    ): Uri? = createDoc(resolver, treeUri, mimeType, displayName)      fun createVideoDoc(         resolver: android.content.ContentResolver,
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 94f8399a08..53fa7230e9 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt@@ -8,7 +8,11 @@ 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+import com.vayunmathur.camera.domain.StillFormatRouting import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.EncodedStill+import com.vayunmathur.camera.platform.StillEncoder.encode import com.vayunmathur.camera.platform.mirrorCaptures  /**@@ -82,10 +86,14 @@ internal fun PendingStill.resolveUri(results: ImageCapture.OutputFileResults): U  * (created under [displayName]), else classic MediaStore insert. Runs the  * blocking I/O on the calling thread — invoke from Dispatchers.IO.  */-internal fun CameraViewModel.saveStillBytes(displayName: String, bytes: ByteArray): Uri? {+internal fun CameraViewModel.saveStillBytes(displayName: String, bytes: ByteArray): Uri? =+    saveStillBytes(displayName, bytes, StillFormatRouting.mimeType(StillFormat.JPEG))++/** Same as [saveStillBytes] for pre-encoded bytes in a non-JPEG container. */+internal fun CameraViewModel.saveStillBytes(displayName: String, bytes: ByteArray, mimeType: String): Uri? {     val target = saveTargetMutable.value     if (target is SaveTarget.SafTree) {-        val doc = SafDocuments.createImageDoc(app.contentResolver, target.treeUri, displayName)+        val doc = SafDocuments.createImageDoc(app.contentResolver, target.treeUri, displayName, mimeType)         if (doc != null) {             MediaStoreSaver.saveJpegBytesToUri(app.contentResolver, doc, bytes)?.let {                 scanSafDoc(doc)@@ -95,10 +103,28 @@ internal fun CameraViewModel.saveStillBytes(displayName: String, bytes: ByteArra         }     }     return MediaStoreSaver.saveJpegBytes(-        app.contentResolver, MediaStoreSaver.imageValues(displayName), bytes+        app.contentResolver, MediaStoreSaver.imageValues(displayName, mimeType), bytes     ) } +/** A saved processed still: where it landed and the container actually used. */+internal data class SavedStill(val uri: Uri, val format: StillFormat)++/**+ * Encodes a processed [bitmap] in the user's still format and saves it.+ * AVIF has no EXIF orientation tag (ravif exposes no EXIF API), so the+ * rotation is baked into the pixels first; JPEG keeps the bitmap as-is+ * and the caller stamps orientation via `writeCaptureExif` as before.+ * Falls back to JPEG bytes when the native AVIF encoder is unavailable.+ */+internal fun CameraViewModel.saveProcessedStill(bitmap: Bitmap, rotationDegrees: Int): SavedStill? {+    val encoded: EncodedStill = encode(bitmap, rotationDegrees)+    val name = StillFormatRouting.displayName(MediaStoreSaver.timestamp(), encoded.format)+    val uri = saveStillBytes(name, encoded.bytes, StillFormatRouting.mimeType(encoded.format))+        ?: return null+    return SavedStill(uri, encoded.format)+}+ /** Same as [saveStillBytes] for a [bitmap]. */ internal fun CameraViewModel.saveStillBitmap(displayName: String, bitmap: Bitmap): Uri? {     val target = saveTargetMutable.value
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 4bb89977ea..f6548430e3 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt@@ -14,6 +14,7 @@ import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.CodecSupport import com.vayunmathur.camera.platform.FlashMode import com.vayunmathur.camera.platform.MotionPhotoDuration+import com.vayunmathur.camera.platform.PhotoFormat import com.vayunmathur.camera.platform.TimerDuration import com.vayunmathur.camera.platform.VideoCodec import com.vayunmathur.camera.platform.applyManualControls@@ -43,6 +44,9 @@ private fun CameraViewModel.loadCaptureSettings() {             CodecSupport.defaultVideoCodec         }     }+    ds.getString("camera_photo_format")?.let {+        runCatching { photoFormatMutable.value = PhotoFormat.valueOf(it) }+    }     ds.getString("camera_motion_duration")?.let {         runCatching { motionPhotoDurationMutable.value = MotionPhotoDuration.valueOf(it) }     }@@ -147,6 +151,11 @@ fun CameraViewModel.setLocationEnabled(enabled: Boolean) {     viewModelScope.launch { ds.setString("camera_location", enabled.toString()) } } +fun CameraViewModel.setPhotoFormat(format: PhotoFormat) {+    photoFormatMutable.value = format+    viewModelScope.launch { ds.setString("camera_photo_format", format.name) }+}+ fun CameraViewModel.setVideoCodec(codec: VideoCodec) {     videoCodecMutable.value = codec     viewModelScope.launch { ds.setString("camera_video_codec", codec.name) }
camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.kt b/camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.ktindex 2858c80ad4..7702947dd5 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.kt@@ -36,6 +36,9 @@ object MediaStoreSaver {      fun imageValues(displayName: String): ContentValues = contentValues(displayName, "image/jpeg") +    fun imageValues(displayName: String, mimeType: String): ContentValues =+        contentValues(displayName, mimeType)+     fun videoValues(displayName: String): ContentValues = contentValues(displayName, "video/mp4")      private fun contentValues(displayName: String, mimeType: String) = ContentValues().apply {
camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt b/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.ktnew file mode 100644index 0000000000..c17a59137f--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt@@ -0,0 +1,52 @@+package com.vayunmathur.camera.domain++/** Still container the user picked in camera settings. */+enum class StillFormat {+    JPEG,+    AVIF,+}++/**+ * Pure routing decisions for still saving: which container a capture+ * actually lands in. Kept Android-free so the fallback rules are unit+ * tested on the host.+ */+object StillFormatRouting {++    /** JPEG quality used for the platform/Bitmap JPEG fallback path. */+    const val JPEG_QUALITY = 95++    /** AVIF quality (ravif scale 1..100) for the native encoder. */+    const val AVIF_QUALITY = 80f++    /** AVIF speed (rav1e scale 1..10, 10 = fastest) for stills. */+    const val AVIF_SPEED = 8++    /**+     * The format a still is really saved as. AVIF is only honoured when+     * the native encoder is present; Motion Photos always stay JPEG+     * because the format is a JPEG with an appended MP4 trailer.+     */+    fun effectiveFormat(requested: StillFormat, nativeAvailable: Boolean, motionPhoto: Boolean): StillFormat =+        when {+            motionPhoto -> StillFormat.JPEG+            requested == StillFormat.AVIF && !nativeAvailable -> StillFormat.JPEG+            else -> requested+        }++    /** File extension (no dot) matching [format]. */+    fun extension(format: StillFormat): String = when (format) {+        StillFormat.JPEG -> "jpg"+        StillFormat.AVIF -> "avif"+    }++    /** MediaStore MIME type matching [format]. */+    fun mimeType(format: StillFormat): String = when (format) {+        StillFormat.JPEG -> "image/jpeg"+        StillFormat.AVIF -> "image/avif"+    }++    /** `IMG_<timestamp>` display name in the container's extension. */+    fun displayName(timestamp: String, format: StillFormat): String =+        "IMG_$timestamp.${extension(format)}"+}
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 e9e681af31..d6a51de43d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt@@ -27,6 +27,7 @@ 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.setLastCaptureUri import com.vayunmathur.camera.data.closeStream@@ -209,7 +210,11 @@ internal fun CameraViewModel.onNightBurstDone(frames: List<Bitmap>) { /** Completes a successful night merge: stamps EXIF, clears state, publishes the URI. */ internal suspend fun CameraViewModel.finishNightMerge(uri: Uri) {     // Merged pixels are already upright/mirrored, so the orientation tag is normal.-    withContext(Dispatchers.IO) { writeCaptureExif(uri, null, 0) }+    // AVIF stills carry no EXIF (orientation is in the pixels); only stamp JPEG.+    val isAvif = runCatching { app.contentResolver.getType(uri) }.getOrNull() == "image/avif"+    if (!isAvif) {+        withContext(Dispatchers.IO) { writeCaptureExif(uri, null, 0) }+    }     isCapturingMutable.value = false     stopLongExposureCountdown()     setLastCaptureUri(uri)@@ -232,14 +237,17 @@ internal suspend fun CameraViewModel.mergeNightFrames(frames: List<Bitmap>): Uri     }     if (merged != null) {         frames.forEach { it.recycle() }-        return saveStillBitmap("IMG_${MediaStoreSaver.timestamp()}.jpg", merged)-            .also { merged.recycle() }+        // Merged pixels are already upright, so rotation 0: AVIF encodes+        // them as-is, JPEG keeps the EXIF path in finishNightMerge.+        val saved = saveProcessedStill(merged, 0)+        merged.recycle()+        return saved?.uri     }     // Middle-frame fallback (frames are still owned here; save before recycling).     val middle = frames.getOrNull(frames.size / 2)     val fallbackUri = middle?.let {         try {-            saveStillBitmap("IMG_${MediaStoreSaver.timestamp()}.jpg", it)+            saveProcessedStill(it, 0)?.uri         } catch (e: kotlinx.coroutines.CancellationException) {             throw e         } catch (e: Throwable) {
camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.ktindex cdddf2b93c..86c7e02396 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt@@ -18,6 +18,7 @@ import kotlinx.coroutines.withContext import com.vayunmathur.camera.data.MediaStoreSaver import com.vayunmathur.camera.data.PendingStill import com.vayunmathur.camera.data.prepareStillSave+import com.vayunmathur.camera.data.saveProcessedStill import com.vayunmathur.camera.data.saveStillBitmap import com.vayunmathur.camera.data.setLastCaptureUri import com.vayunmathur.camera.data.updateLocation@@ -247,10 +248,15 @@ private fun CameraViewModel.processSingleFrame(         stillBokeh.render(decoded, degrees, plan.strength, plan.warmth, plan.shadows, plan.mirror)     } else null)         ?: applyColorAdjustments(decoded, plan.warmth, plan.shadows, plan.mirror)-    val name = "IMG_${MediaStoreSaver.timestamp()}.jpg"-    return saveStillBitmap(name, adjusted)-        ?.also { writeCaptureExif(it, sourceJpeg, degrees, mirrored = plan.mirror) }-        .also { adjusted.recycle() }+    // AVIF (when chosen) bakes orientation into the pixels and carries no+    // EXIF; JPEG keeps the EXIF stamping path below.+    val saved = saveProcessedStill(adjusted, degrees)+    adjusted.recycle()+    if (saved == null) return null+    if (saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG) {+        writeCaptureExif(saved.uri, sourceJpeg, degrees, mirrored = plan.mirror)+    }+    return saved.uri }  /**
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.ktindex ece694ea74..8cc5aca740 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -195,6 +195,9 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     internal val videoCodecMutable = MutableStateFlow(CodecSupport.defaultVideoCodec)     val videoCodec = videoCodecMutable.asStateFlow() +    internal val photoFormatMutable = MutableStateFlow(PhotoFormat.JPEG)+    val photoFormat = photoFormatMutable.asStateFlow()+     // Motion-Photo clip length (issue #712). Default 3s ≈ the old ~1.5s-12-frame buffer.     internal val motionPhotoDurationMutable = MutableStateFlow(MotionPhotoDuration.THREE)     val motionPhotoDuration = motionPhotoDurationMutable.asStateFlow()
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.ktindex 27f6531235..17e75537c6 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -41,6 +41,12 @@ enum class VideoCodec(@StringRes val labelRes: Int, @StringRes val descriptionRe     AV1(R.string.codec_av1_label, R.string.codec_av1_description), } +/** Still photo formats selectable in settings. AVIF is encoded natively (ravif). */+enum class PhotoFormat(@StringRes val labelRes: Int, @StringRes val descriptionRes: Int) {+    JPEG(R.string.photo_format_jpeg_label, R.string.photo_format_jpeg_description),+    AVIF(R.string.photo_format_avif_label, R.string.photo_format_avif_description),+}+ /** Audio codecs selectable for video recording, with display text and Recorder mime. */ enum class AudioCodec(     @StringRes val labelRes: Int,
camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt b/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.ktnew file mode 100644index 0000000000..4f3bfaa43d--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt@@ -0,0 +1,89 @@+package com.vayunmathur.camera.platform++import android.graphics.Bitmap+import com.vayunmathur.camera.domain.StillFormat+import com.vayunmathur.camera.domain.StillFormatRouting+import com.vayunmathur.library.log.Log+import java.io.ByteArrayOutputStream++/** One encoded still plus the container it actually landed in. */+internal data class EncodedStill(val bytes: ByteArray, val format: StillFormat) {+    override fun equals(other: Any?): Boolean =+        other is EncodedStill && format == other.format && bytes.contentEquals(other.bytes)++    override fun hashCode(): Int = 31 * bytes.contentHashCode() + format.hashCode()+}++/**+ * Encodes a processed bitmap to the user's still format.+ *+ * AVIF goes through the Rust `ravif` encoder behind [StitchNative]; when+ * the native library is missing or encoding fails, this falls back to+ * JPEG bytes so a shot is never lost. Orientation must already be baked+ * into the pixels by the caller: ravif exposes no EXIF API, so AVIF+ * stills carry no orientation/GPS tags (the JPEG path stamps them via+ * `writeCaptureExif` instead).+ */+internal object StillEncoder {++    /**+     * Encoded container for [bitmap] under the current settings.+     * [rotationDegrees] is baked into the pixels on the AVIF path (no+     * EXIF orientation tag there); the JPEG path leaves pixels untouched+     * and the caller stamps orientation via EXIF as before.+     */+    fun CameraViewModel.encode(bitmap: Bitmap, rotationDegrees: Int = 0): EncodedStill {+        val requested = if (photoFormatMutable.value == PhotoFormat.AVIF) {+            StillFormat.AVIF+        } else {+            StillFormat.JPEG+        }+        val effective = StillFormatRouting.effectiveFormat(+            requested = requested,+            nativeAvailable = StitchNative.isAvailable,+            motionPhoto = false,+        )+        if (effective == StillFormat.AVIF) {+            val upright = uprightCopy(bitmap, rotationDegrees, 0)+            try {+                encodeAvif(upright)?.let { return EncodedStill(it, StillFormat.AVIF) }+            } finally {+                if (upright !== bitmap) upright.recycle()+            }+            Log.status("StillEncoder", "AVIF encode failed; falling back to JPEG")+        }+        return EncodedStill(encodeJpeg(bitmap), StillFormat.JPEG)+    }++    private fun encodeAvif(bitmap: Bitmap): ByteArray? {+        if (!StitchNative.isAvailable) return null+        val width = bitmap.width+        val height = bitmap.height+        if (width <= 0 || height <= 0) return null+        val pixels = IntArray(width * height)+        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)+        val rgba = ByteArray(pixels.size * 4)+        for (i in pixels.indices) {+            val px = pixels[i]+            rgba[i * 4] = (px shr 16 and 0xFF).toByte()+            rgba[i * 4 + 1] = (px shr 8 and 0xFF).toByte()+            rgba[i * 4 + 2] = (px and 0xFF).toByte()+            rgba[i * 4 + 3] = (px ushr 24 and 0xFF).toByte()+        }+        return try {+            StitchNative.encodeAvif(+                rgba, width, height,+                StillFormatRouting.AVIF_QUALITY, StillFormatRouting.AVIF_SPEED,+            )+        } catch (e: UnsatisfiedLinkError) {+            Log.status("StillEncoder", "AVIF native call failed; JPEG fallback", e)+            null+        }+    }++    private fun encodeJpeg(bitmap: Bitmap): ByteArray =+        ByteArrayOutputStream().use { out ->+            bitmap.compress(Bitmap.CompressFormat.JPEG, StillFormatRouting.JPEG_QUALITY, out)+            out.toByteArray()+        }+}
camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.ktindex afe323bed8..3b4604d0f5 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt@@ -48,4 +48,11 @@ object StitchNative {      /** Releases a night session (also cleans pano registry if mixed). */     external fun freeNight(handle: Long)++    /**+     * Encodes one RGBA frame (len = width*height*4) to AVIF bytes, or null on+     * failure. [quality] is 1..100, [speed] is rav1e's 1..10 (10 = fastest).+     * Callers must check [isAvailable] first and fall back to JPEG on null.+     */+    external fun encodeAvif(rgba: ByteArray, width: Int, height: Int, quality: Float, speed: Int): ByteArray? }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.ktindex 0c9144276d..7629cdc0b9 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt@@ -228,7 +228,7 @@ class CharacteristicsFacade private constructor(             val chars = manager.getCameraCharacteristics(cameraId)             val extensions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {                 runCatching {-                    manager.getCameraExtensionCharacteristics(cameraId).availableExtensionModes+                    manager.getCameraExtensionCharacteristics(cameraId).supportedExtensions                 }.getOrDefault(emptyList())             } else {                 emptyList()
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.ktnew file mode 100644index 0000000000..fdca54d359--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt@@ -0,0 +1,91 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.SurfaceTexture+import android.view.Surface+import android.view.TextureView++/**+ * Camera2 migration Phase 0: glue contract between a [TextureView]'s+ * [SurfaceTexture] lifecycle and the session layer.+ *+ * The bridge owns the [Surface] created from the texture and translates the+ * view callbacks into [PreviewSurfaceEvent]s. It deliberately has no session+ * binding yet: consumers map events to [SessionStateMachine] inputs+ * (available/resized → reconfigure, destroyed → teardown) in a later phase.+ *+ * Ownership: the [TextureView] owns the [SurfaceTexture]; this bridge owns the+ * [Surface] it wraps it in and releases that [Surface] on destroy. The texture+ * itself is never released here (returning `true` from the destroyed callback+ * lets the view release it).+ */+sealed interface PreviewSurfaceEvent {+    data class Available(val surface: Surface, val width: Int, val height: Int) : PreviewSurfaceEvent+    data class SizeChanged(val surface: Surface, val width: Int, val height: Int) : PreviewSurfaceEvent++    /** [surface] is already released by the bridge; consumers must drop every reference. */+    data class Destroyed(val surface: Surface) : PreviewSurfaceEvent+}++/** Immutable view of what the bridge currently holds. */+data class PreviewSurfaceState(+    val surface: Surface? = null,+    val width: Int = 0,+    val height: Int = 0,+) {+    val isAvailable: Boolean get() = surface != null+}++class PreviewSurfaceBridge(+    private val onEvent: (PreviewSurfaceEvent) -> Unit,+) : TextureView.SurfaceTextureListener {++    var state: PreviewSurfaceState = PreviewSurfaceState()+        private set++    /** The current preview surface, or null between destroy and the next available. */+    val surface: Surface? get() = state.surface++    override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) {+        val created = Surface(texture)+        state = PreviewSurfaceState(created, width, height)+        onEvent(PreviewSurfaceEvent.Available(created, width, height))+    }++    override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) {+        val current = state.surface ?: return+        state = state.copy(width = width, height = height)+        onEvent(PreviewSurfaceEvent.SizeChanged(current, width, height))+    }++    override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean {+        val current = state.surface+        state = PreviewSurfaceState()+        if (current != null) {+            onEvent(PreviewSurfaceEvent.Destroyed(current))+            current.release()+        }+        // True: the TextureView may release the SurfaceTexture.+        return true+    }++    override fun onSurfaceTextureUpdated(texture: SurfaceTexture) {+        // Per-frame callback: intentionally not forwarded — consumers poll [state].+    }++    /** Installs this bridge on [view] (or detaches when [view] is re-used elsewhere). */+    fun attachTo(view: TextureView) {+        view.surfaceTextureListener = this+        // A view that already has a texture (re-attach after a config change)+        // never re-fires the available callback; synthesise it.+        val texture = view.surfaceTexture+        if (view.isAvailable && texture != null && state.surface == null) {+            onSurfaceTextureAvailable(texture, view.width, view.height)+        }+    }++    fun detachFrom(view: TextureView) {+        if (view.surfaceTextureListener === this) {+            view.surfaceTextureListener = null+        }+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.ktnew file mode 100644index 0000000000..c438d105b8--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SessionStateMachine.kt@@ -0,0 +1,153 @@+package com.vayunmathur.camera.platform.camera2++/**+ * Camera2 migration Phase 0: pure state machine for a Camera2 capture session.+ * No `CameraDevice`/`CameraCaptureSession` calls live here — this phase is the+ * transition contract the later phases bind real callbacks into.+ *+ * Teardown token: [generation] is a monotonically increasing counter bumped by+ * every [beginTeardown]. Async callbacks capture the generation at scheduling+ * time and hand it back to [dispatch]/[isCurrent]; a callback from a previous+ * generation is dropped instead of acting on a session that no longer exists.+ * This is the same pattern the night-capture lifecycle fix used: bump first,+ * close second, let stale completions observe the mismatch and no-op.+ */+enum class SessionState {+    CLOSED,+    OPENING,+    OPEN,+    CONFIGURING,+    STREAMING,+    CLOSING,+    ERROR,+}++/** Inputs that can move the machine. Async callbacks carry a generation; see [SessionStateMachine.dispatch]. */+enum class SessionEvent {+    OPEN_REQUESTED,+    DEVICE_OPENED,+    CONFIGURE_REQUESTED,+    SESSION_CONFIGURED,+    CONFIGURE_FAILED,+    CLOSE_REQUESTED,+    DEVICE_CLOSED,+    ERROR_OCCURRED,+}++/** Outcome of a [SessionStateMachine.transition] / [SessionStateMachine.dispatch] call. */+sealed interface TransitionResult {+    data class Applied(val from: SessionState, val to: SessionState) : TransitionResult+    data class Rejected(val state: SessionState, val event: SessionEvent) : TransitionResult++    /** The callback's generation is no longer current; the event was dropped untouched. */+    data class StaleGeneration(val expected: Long, val actual: Long) : TransitionResult+}++class SessionStateMachine {++    var state: SessionState = SessionState.CLOSED+        private set++    /** Monotonic teardown token. Only ever increases. */+    var generation: Long = 0L+        private set++    fun isCurrent(candidateGeneration: Long): Boolean = candidateGeneration == generation++    /** Applies [event] if it is legal from the current state; otherwise rejects without mutating. */+    fun transition(event: SessionEvent): TransitionResult {+        val from = state+        val to = legalTarget(from, event) ?: return TransitionResult.Rejected(from, event)+        state = to+        return TransitionResult.Applied(from, to)+    }++    /**+     * Generation-guarded entry point for async callbacks: a stale generation is+     * dropped ([TransitionResult.StaleGeneration]) before legality is checked.+     */+    fun dispatch(callbackGeneration: Long, event: SessionEvent): TransitionResult {+        if (!isCurrent(callbackGeneration)) {+            return TransitionResult.StaleGeneration(expected = generation, actual = callbackGeneration)+        }+        return transition(event)+    }++    /** Runs [block] only when [callbackGeneration] is still current. Returns whether it ran. */+    fun runIfCurrent(callbackGeneration: Long, block: () -> Unit): Boolean {+        if (!isCurrent(callbackGeneration)) return false+        block()+        return true+    }++    /**+     * Begins teardown: bumps the generation (invalidating every outstanding+     * callback) and moves to CLOSING unless already CLOSED. Returns the new+     * generation — callbacks scheduled after teardown must use it.+     */+    fun beginTeardown(): Long {+        generation+++        if (state != SessionState.CLOSED) {+            state = SessionState.CLOSING+        }+        return generation+    }++    /** Completes teardown from CLOSING/ERROR; a no-op in any other state. */+    fun completeTeardown(): TransitionResult =+        if (state == SessionState.CLOSING || state == SessionState.ERROR) {+            val from = state+            state = SessionState.CLOSED+            TransitionResult.Applied(from, SessionState.CLOSED)+        } else {+            TransitionResult.Rejected(state, SessionEvent.DEVICE_CLOSED)+        }++    companion object {+        /** The full legal-transition table; anything absent is rejected. */+        fun legalTarget(from: SessionState, event: SessionEvent): SessionState? = when (from) {+            SessionState.CLOSED -> when (event) {+                SessionEvent.OPEN_REQUESTED -> SessionState.OPENING+                else -> null+            }+            SessionState.OPENING -> when (event) {+                SessionEvent.DEVICE_OPENED -> SessionState.OPEN+                SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING+                SessionEvent.ERROR_OCCURRED -> SessionState.ERROR+                else -> null+            }+            SessionState.OPEN -> when (event) {+                SessionEvent.CONFIGURE_REQUESTED -> SessionState.CONFIGURING+                SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING+                SessionEvent.ERROR_OCCURRED -> SessionState.ERROR+                else -> null+            }+            SessionState.CONFIGURING -> when (event) {+                SessionEvent.SESSION_CONFIGURED -> SessionState.STREAMING+                SessionEvent.CONFIGURE_FAILED -> SessionState.OPEN+                SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING+                SessionEvent.ERROR_OCCURRED -> SessionState.ERROR+                else -> null+            }+            SessionState.STREAMING -> when (event) {+                SessionEvent.CONFIGURE_REQUESTED -> SessionState.CONFIGURING+                SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING+                SessionEvent.ERROR_OCCURRED -> SessionState.ERROR+                else -> null+            }+            SessionState.CLOSING -> when (event) {+                SessionEvent.DEVICE_CLOSED -> SessionState.CLOSED+                SessionEvent.ERROR_OCCURRED -> SessionState.ERROR+                else -> null+            }+            SessionState.ERROR -> when (event) {+                SessionEvent.CLOSE_REQUESTED -> SessionState.CLOSING+                SessionEvent.DEVICE_CLOSED -> SessionState.CLOSED+                else -> null+            }+        }++        fun isLegal(from: SessionState, event: SessionEvent): Boolean =+            legalTarget(from, event) != null+    }+}
camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.ktindex 80d11cd77d..0b81c336b9 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt@@ -18,6 +18,7 @@ import com.vayunmathur.camera.R import com.vayunmathur.camera.platform.AudioCodec import com.vayunmathur.camera.platform.AudioInputSource import com.vayunmathur.camera.platform.CodecSupport+import com.vayunmathur.camera.platform.PhotoFormat import com.vayunmathur.camera.platform.VideoCodec import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.IconArrowDropDown@@ -35,6 +36,8 @@ import com.vayunmathur.library.ui.Text  */ @Composable fun CameraCodecSettings(+    photoFormat: PhotoFormat,+    onPhotoFormatChange: (PhotoFormat) -> Unit,     videoCodec: VideoCodec,     audioCodec: AudioCodec,     audioInputSource: AudioInputSource,@@ -44,6 +47,54 @@ fun CameraCodecSettings(     modifier: Modifier = Modifier, ) {     Column(modifier = modifier) {+        SettingsSection(title = stringResource(R.string.settings_photo_format)) {+            var photoExpanded by remember { mutableStateOf(false) }+            Box(+                modifier = Modifier+                    .fillMaxWidth()+                    .padding(horizontal = 16.dp)+            ) {+                OutlinedButton(+                    onClick = { photoExpanded = true },+                    modifier = Modifier.fillMaxWidth()+                ) {+                    Text(+                        "${stringResource(photoFormat.labelRes)} — ${stringResource(photoFormat.descriptionRes)}",+                        modifier = Modifier.weight(1f),+                        textAlign = TextAlign.Start,+                        maxLines = 1,+                        overflow = TextOverflow.Ellipsis,+                    )+                    IconArrowDropDown()+                }+                DropdownMenu(+                    expanded = photoExpanded,+                    onDismissRequest = { photoExpanded = false }+                ) {+                    PhotoFormat.entries.forEach { format ->+                        SelectableDropdownMenuItem(+                            selected = format == photoFormat,+                            onClick = {+                                onPhotoFormatChange(format)+                                photoExpanded = false+                            },+                            text = {+                                Column {+                                    Text(stringResource(format.labelRes))+                                    Text(+                                        stringResource(format.descriptionRes),+                                        style = MaterialTheme.typography.bodySmall,+                                        color = MaterialTheme.colorScheme.onSurfaceVariant+                                    )+                                }+                            },+                            selectedLeadingIcon = { IconCheck() },+                        )+                    }+                }+            }+        }+         val availableCodecs = remember {             buildList {                 add(VideoCodec.AVC)
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex 3d2e4b611f..49fc1e1d66 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -43,6 +43,7 @@ import com.vayunmathur.camera.data.setMirrorFront import com.vayunmathur.camera.data.setMotionPhotoDuration import com.vayunmathur.camera.data.setNoiseReductionEnabled import com.vayunmathur.camera.data.setSaveTreeUri+import com.vayunmathur.camera.data.setPhotoFormat import com.vayunmathur.camera.data.setVideoCodec import com.vayunmathur.camera.data.updateLocation import com.vayunmathur.library.ui.IconFolder@@ -57,6 +58,7 @@ import com.vayunmathur.library.util.NavKey fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewModel) {     val locationEnabled by viewModel.locationEnabled.collectAsState()     val videoCodec by viewModel.videoCodec.collectAsState()+    val photoFormat by viewModel.photoFormat.collectAsState()     val audioCodec by viewModel.audioCodec.collectAsState()     val audioInputSource by viewModel.audioInputSource.collectAsState()     val mirrorFront by viewModel.mirrorFront.collectAsState()@@ -138,6 +140,8 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                 onReset = { viewModel.clearSaveTreeUri() },             )             CameraCodecSettings(+                photoFormat = photoFormat,+                onPhotoFormatChange = { viewModel.setPhotoFormat(it); noteIfDeferred() },                 videoCodec = videoCodec,                 audioCodec = audioCodec,                 audioInputSource = audioInputSource,
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex 6141c28f3a..8a8ed0335b 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -80,6 +80,13 @@     <!-- Video codec description: most efficient but may not be supported everywhere -->     <string name="codec_av1_description">Most efficient</string> +    <!-- Photo format settings (SettingsPage) -->+    <string name="settings_photo_format">Photo format</string>+    <string name="photo_format_jpeg_label">JPEG</string>+    <string name="photo_format_jpeg_description">Most compatible</string>+    <string name="photo_format_avif_label">AVIF</string>+    <string name="photo_format_avif_description">Smaller files, slower to save</string>+     <!-- Motion-Photo duration settings (SettingsPage, issue #712) -->     <!-- SettingsPage: section header for motion-photo clip-length selection -->     <string name="settings_motion_duration">Motion photo length</string>
camera/src/main/rust/Cargo.toml
diff --git a/camera/src/main/rust/Cargo.toml b/camera/src/main/rust/Cargo.tomlindex 46e9ed3f06..0dcf23709e 100644--- a/camera/src/main/rust/Cargo.toml+++ b/camera/src/main/rust/Cargo.toml@@ -18,6 +18,7 @@ vision_core = { path = "../../../../library/vision/src/main/rust", features = [" # image crate 0.25 removed – pulled moxcms/pxfm/bytemuck; now jpeg-decoder + jpeg-encoder (trivial 1-function) jpeg-decoder.workspace = true jpeg-encoder.workspace = true+ravif.workspace = true # nalgebra removed – replaced by a tiny in-crate linalg module (src/linalg.rs): # fixed 3×3 Matrix3/Vector3, closed-form inverse, Jacobi symmetric-eigen, SVD # (3×3 + dense DLT null-space), and partial-pivot LU solve. Drops ~9 transitive
camera/src/main/rust/src/avif.rs
diff --git a/camera/src/main/rust/src/avif.rs b/camera/src/main/rust/src/avif.rsnew file mode 100644index 0000000000..c211d7c614--- /dev/null+++ b/camera/src/main/rust/src/avif.rs@@ -0,0 +1,152 @@+//! AVIF still encoding on top of `ravif` (pure-Rust rav1e AV1 encoder).+//!+//! Android has no platform AVIF encoder, so stills that the user sets to+//! AVIF are encoded here from raw RGBA pixels. The encoder is 8-bit only:+//! the capture pipeline hands us 8-bit RGBA, and asking ravif for a 10-bit+//! container would only pad those samples, so we do not offer it.+//!+//! EXIF is intentionally not written here. ravif/avif-serialize expose no+//! EXIF item API, so the Kotlin side bakes orientation (rotation + mirror)+//! into the pixels before calling in, instead of stamping an orientation+//! tag the way the JPEG path does. GPS/maker tags are likewise not carried+//! into AVIF stills; see the Kotlin `StillEncoder` report comment.++use ravif::{Encoder, Img, RGBA8};++/// Largest width/height accepted, matching the night-frame JNI guard.+const MAX_DIM: usize = 20_000;++/// Quality bounds mirroring the JPEG quality scale (0..=100).+const QUALITY_MIN: f32 = 1.0;+const QUALITY_MAX: f32 = 100.0;++/// Speed bounds accepted by rav1e (1 = slowest/best, 10 = fastest).+const SPEED_MIN: u8 = 1;+const SPEED_MAX: u8 = 10;++/// Encode one RGBA frame (`rgba.len() == width * height * 4`, straight+/// alpha) to AVIF bytes. `quality` is on the JPEG-like 1..=100 scale and+/// `speed` is rav1e's 1..=10 scale; both are clamped. Returns `None` for+/// empty/oversized/mismatched input or any encoder failure, so the Kotlin+/// side can fall back to JPEG.+///+/// # Panics+///+/// Never panics on untrusted sizes: dimensions are validated before any+/// allocation sized by them.+pub fn encode_avif(rgba: &[u8], width: usize, height: usize, quality: f32, speed: u8) -> Option<Vec<u8>> {+    if width == 0 || height == 0 || width > MAX_DIM || height > MAX_DIM {+        return None;+    }+    let expected = width.checked_mul(height)?.checked_mul(4)?;+    if rgba.len() != expected {+        return None;+    }+    let pixels: Vec<RGBA8> = rgba+        .chunks_exact(4)+        .map(|px| match px {+            [r, g, b, a] => RGBA8::new(*r, *g, *b, *a),+            _ => RGBA8::new(0, 0, 0, 0),+        })+        .collect();+    let img = Img::new(pixels.as_slice(), width, height);+    let encoded = Encoder::new()+        .with_quality(quality.clamp(QUALITY_MIN, QUALITY_MAX))+        .with_speed(speed.clamp(SPEED_MIN, SPEED_MAX))+        .with_bit_depth(ravif::BitDepth::Eight)+        .encode_rgba(img)+        .ok()?;+    if encoded.avif_file.is_empty() {+        None+    } else {+        Some(encoded.avif_file)+    }+}++/// True when `bytes` carry the AVIF file-type box (`....ftypavif`).+pub fn has_avif_magic(bytes: &[u8]) -> bool {+    bytes.len() >= 12 && &bytes[4..12] == b"ftypavif"+}++/// Read the `ispe` (image spatial extents) dimensions out of an AVIF+/// container by walking top-level/meta boxes. Used by tests to confirm a+/// real round-trip without pulling in a decoder crate.+pub fn avif_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {+    fn boxes(bytes: &[u8]) -> Vec<(&[u8], &[u8])> {+        let mut out = Vec::new();+        let mut off = 0usize;+        while off + 8 <= bytes.len() {+            let size = u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]) as usize;+            if size < 8 || off + size > bytes.len() {+                break;+            }+            out.push((&bytes[off + 4..off + 8], &bytes[off + 8..off + size]));+            off += size;+        }+        out+    }+    let meta = boxes(bytes).into_iter().find(|(t, _)| *t == b"meta")?.1;+    // `meta` starts with 4 bytes of version/flags before its children.+    let meta = meta.get(4..)?;+    let iprp = boxes(meta).into_iter().find(|(t, _)| *t == b"iprp")?.1;+    let ipco = boxes(iprp).into_iter().find(|(t, _)| *t == b"ipco")?.1;+    let ispe = boxes(ipco).into_iter().find(|(t, _)| *t == b"ispe")?.1;+    // `ispe`: version/flags (4) then width, height as big-endian u32.+    let ispe = ispe.get(4..12)?;+    Some((+        u32::from_be_bytes([ispe[0], ispe[1], ispe[2], ispe[3]]),+        u32::from_be_bytes([ispe[4], ispe[5], ispe[6], ispe[7]]),+    ))+}++#[cfg(test)]+mod avif_tests {+    use super::{avif_dimensions, encode_avif, has_avif_magic};++    fn gradient(width: usize, height: usize) -> Vec<u8> {+        let mut px = Vec::with_capacity(width * height * 4);+        for y in 0..height {+            for x in 0..width {+                px.extend_from_slice(&[+                    (x % 256) as u8,+                    (y % 256) as u8,+                    ((x + y) % 256) as u8,+                    255,+                ]);+            }+        }+        px+    }++    #[test]+    fn encodes_synthetic_rgba_with_avif_header_and_dimensions() {+        let rgba = gradient(64, 48);+        let bytes = encode_avif(&rgba, 64, 48, 80.0, 10).expect("encode must succeed");+        assert!(has_avif_magic(&bytes), "missing ftypavif magic");+        assert_eq!(avif_dimensions(&bytes), Some((64, 48)));+    }++    #[test]+    fn rejects_mismatched_and_oversized_input() {+        assert!(encode_avif(&[0u8; 10], 64, 48, 80.0, 10).is_none());+        assert!(encode_avif(&[], 0, 0, 80.0, 10).is_none());+        assert!(encode_avif(&[0u8; 4], 20_001, 1, 80.0, 10).is_none());+    }++    /// Host-side encode-time probe for a 12 MP frame. Ignored by default+    /// (it takes seconds); run with `cargo test -- --ignored bench_12mp`+    /// to reproduce the latency figure in the change report.+    #[test]+    #[ignore]+    fn bench_12mp_encode_time() {+        let rgba = gradient(4000, 3000);+        let start = std::time::Instant::now();+        let bytes = encode_avif(&rgba, 4000, 3000, 80.0, 10).expect("encode must succeed");+        println!(+            "12MP AVIF encode: {:?} -> {} bytes",+            start.elapsed(),+            bytes.len()+        );+        assert!(has_avif_magic(&bytes));+    }+}
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex 2ece9e34b2..e5982b8c30 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -19,6 +19,7 @@ mod seam; mod blend; mod stitch; mod night;+mod avif;  use imgbuf::Rgba; use std::collections::HashMap;@@ -432,6 +433,50 @@ mod jni_bindings {         night_registry().lock().unwrap().remove(&handle);     } ++    /// Encode one RGBA frame (`rgba.len() == width * height * 4`) to AVIF+    /// bytes, or null when the input is invalid or encoding fails (the+    /// Kotlin side then falls back to JPEG).+    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_encodeAvif<'l>(+        mut env: EnvUnowned<'l>,+        _class: JClass<'l>,+        rgba: JByteArray<'l>,+        width: jint,+        height: jint,+        quality: jfloat,+        speed: jint,+    ) -> jbyteArray {+        env.with_env(|env| -> jni::errors::Result<jbyteArray> {+            let null = std::ptr::null_mut();+            if width <= 0 || height <= 0 {+                return Ok(null);+            }+            let bytes = match env.convert_byte_array(&rgba) {+                Ok(b) => b,+                Err(_) => return Ok(null),+            };+            let encoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+                crate::avif::encode_avif(+                    &bytes,+                    width as usize,+                    height as usize,+                    quality,+                    speed.clamp(1, 10) as u8,+                )+            }))+            .unwrap_or(None);+            match encoded {+                Some(b) => match env.byte_array_from_slice(&b) {+                    Ok(arr) => Ok(arr.into_raw()),+                    Err(_) => Ok(null),+                },+                None => Ok(null),+            }+        })+        .resolve::<jni::errors::LogErrorAndDefault>()+    }+     fn run_and_return(env: &mut Env, handle: jlong, panorama: bool) -> jbyteArray {         let null = std::ptr::null_mut();         let mut session = match registry().lock().unwrap().get_mut(&handle) {
camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.ktnew file mode 100644index 0000000000..3f6a941c7e--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt@@ -0,0 +1,48 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals++class StillFormatRoutingTest {++    @Test+    fun avifHonouredWhenNativeAvailable() {+        assertEquals(+            StillFormat.AVIF,+            StillFormatRouting.effectiveFormat(StillFormat.AVIF, nativeAvailable = true, motionPhoto = false),+        )+    }++    @Test+    fun avifFallsBackToJpegWhenNativeMissing() {+        assertEquals(+            StillFormat.JPEG,+            StillFormatRouting.effectiveFormat(StillFormat.AVIF, nativeAvailable = false, motionPhoto = false),+        )+    }++    @Test+    fun motionPhotosAlwaysStayJpeg() {+        assertEquals(+            StillFormat.JPEG,+            StillFormatRouting.effectiveFormat(StillFormat.AVIF, nativeAvailable = true, motionPhoto = true),+        )+    }++    @Test+    fun jpegStaysJpeg() {+        assertEquals(+            StillFormat.JPEG,+            StillFormatRouting.effectiveFormat(StillFormat.JPEG, nativeAvailable = true, motionPhoto = false),+        )+    }++    @Test+    fun extensionAndMimeMatchContainer() {+        assertEquals("jpg", StillFormatRouting.extension(StillFormat.JPEG))+        assertEquals("image/jpeg", StillFormatRouting.mimeType(StillFormat.JPEG))+        assertEquals("avif", StillFormatRouting.extension(StillFormat.AVIF))+        assertEquals("image/avif", StillFormatRouting.mimeType(StillFormat.AVIF))+        assertEquals("IMG_20260101_120000_000.avif", StillFormatRouting.displayName("20260101_120000_000", StillFormat.AVIF))+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExecutorTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExecutorTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExecutorTest.ktnew file mode 100644index 0000000000..eb8a5989af--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ExecutorTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.camera.platform.camera2++import java.util.concurrent.CountDownLatch+import java.util.concurrent.RejectedExecutionException+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicBoolean+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlin.test.fail+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Camera2ExecutorTest {++    @Test fun executesTasksOnItsOwnThread() {+        val executor = Camera2Executor("Camera2ExecutorTest-worker")+        try {+            val ran = CountDownLatch(1)+            val onWorker = AtomicBoolean(false)+            executor.execute {+                onWorker.set(executor.isOnCameraThread())+                ran.countDown()+            }+            assertTrue(ran.await(5, TimeUnit.SECONDS), "task did not run")+            assertTrue(onWorker.get(), "task did not run on the executor thread")+            assertFalse(executor.isOnCameraThread(), "test thread must not be the executor thread")+        } finally {+            executor.shutdown()+        }+    }++    @Test fun shutdownIsDeterministicAndIdempotent() {+        val executor = Camera2Executor("Camera2ExecutorTest-shutdown")+        val ran = CountDownLatch(1)+        executor.execute { ran.countDown() }+        assertTrue(ran.await(5, TimeUnit.SECONDS))++        assertTrue(executor.shutdown(), "thread did not terminate within the timeout")+        assertTrue(executor.isShutdown)+        // Second shutdown is a no-op and still reports terminated.+        assertTrue(executor.shutdown())+    }++    @Test fun workSubmittedAfterShutdownIsRejected() {+        val executor = Camera2Executor("Camera2ExecutorTest-reject")+        executor.shutdown()+        try {+            executor.execute { fail("must not run after shutdown") }+            fail("expected RejectedExecutionException")+        } catch (expected: RejectedExecutionException) {+            // expected+        }+        assertFalse(executor.postMain { fail("must not post after shutdown") })+    }++    @Test fun closeDelegatesToShutdown() {+        val executor = Camera2Executor("Camera2ExecutorTest-close")+        executor.use {+            val ran = CountDownLatch(1)+            it.execute { ran.countDown() }+            assertTrue(ran.await(5, TimeUnit.SECONDS))+        }+        assertTrue(executor.isShutdown)+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacadeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacadeTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacadeTest.ktnew file mode 100644index 0000000000..c665697a5b--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacadeTest.kt@@ -0,0 +1,150 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraMetadata+import android.hardware.camera2.params.StreamConfigurationMap+import android.util.Range+import android.util.Size+import com.vayunmathur.camera.domain.LensFacing+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowCameraCharacteristics++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CharacteristicsFacadeTest {++    private fun characteristics(+        vararg entries: Pair<CameraCharacteristics.Key<*>, Any?>,+    ): CameraCharacteristics {+        val chars = ShadowCameraCharacteristics.newCameraCharacteristics()+        val shadow = Shadows.shadowOf(chars)+        for ((key, value) in entries) {+            @Suppress("UNCHECKED_CAST")+            shadow.set(key as CameraCharacteristics.Key<Any?>, value)+        }+        return chars+    }++    @Test fun mapsEveryProbeFieldFromRealCharacteristics() {+        val chars = characteristics(+            CameraCharacteristics.LENS_FACING to CameraMetadata.LENS_FACING_BACK,+            CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE to Range(0.5f, 10f),+            CameraCharacteristics.FLASH_INFO_AVAILABLE to true,+            CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE to Range(1_000L, 1_000_000_000L),+            CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE to Range(100, 6400),+            CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE to Range(-24, 24),+            CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP to android.util.Rational(1, 6),+            CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES to+                intArrayOf(CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_ON),+            CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION to+                intArrayOf(CameraMetadata.LENS_OPTICAL_STABILIZATION_MODE_ON),+            CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES to+                arrayOf(Range(30, 30), Range(15, 30)),+            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL to+                CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_FULL,+            CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES to intArrayOf(+                CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_RAW,+                CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING,+                CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA,+            ),+            CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS to floatArrayOf(4.3f),+            CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT to+                CameraMetadata.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB,+        )+        val facade = CharacteristicsFacade.fromCharacteristics(+            cameraId = "0",+            chars = chars,+            availableExtensionModes = listOf(1, 4),+        )+        val s = facade.snapshot+        assertEquals("0", facade.cameraId)+        assertEquals(LensFacing.BACK, s.lensFacing)+        assertEquals(Range(0.5f, 10f), s.zoomRatioRange)+        assertEquals(0.5f, s.minZoomRatio)+        assertEquals(10f, s.maxZoomRatio)+        assertTrue(s.hasFlashUnit)+        assertEquals(Range(1_000L, 1_000_000_000L), s.exposureTimeRangeNs)+        assertEquals(Range(100, 6400), s.sensitivityRange)+        // ±24 steps at 1/6 EV per step = ±4 EV.+        assertEquals(Range(-4f, 4f), s.exposureCompensationEvRange)+        assertEquals(listOf(CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_ON), s.videoStabilizationModes)+        assertEquals(listOf(Range(30, 30), Range(15, 30)), s.aeTargetFpsRanges)+        assertTrue(s.supportsRaw)+        assertTrue(s.supportsReprocess)+        assertTrue(s.isLogicalMultiCamera)+        assertFalse(s.supportsManualSensor)+        assertTrue(s.hasExtension(4))+        assertFalse(s.hasExtension(2))+        assertEquals(listOf(4.3f), s.focalLengthsMm)+    }++    @Test fun missingKeysDegradeToEmptyAndDefaults() {+        val facade = CharacteristicsFacade.fromCharacteristics("1", characteristics())+        val s = facade.snapshot+        assertNull(s.lensFacing)+        assertNull(s.zoomRatioRange)+        assertEquals(1f, s.minZoomRatio)+        assertEquals(1f, s.maxZoomRatio)+        assertFalse(s.hasFlashUnit)+        assertNull(s.exposureTimeRangeNs)+        assertTrue(s.aeTargetFpsRanges.isEmpty())+        assertEquals(StreamConfigSummary.EMPTY, s.streamConfig)+        assertTrue(s.availableExtensionModes.isEmpty())+    }++    @Test fun digitalZoomFallbackWhenZoomRatioRangeAbsent() {+        // CONTROL_ZOOM_RATIO_RANGE is left unset; the shadow returns null, so+        // the facade must fall back to SCALER_AVAILABLE_MAX_DIGITAL_ZOOM.+        val facade = CharacteristicsFacade.fromCharacteristics(+            "0",+            characteristics(+                CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM to 8f,+            ),+        )+        assertEquals(Range(1f, 8f), facade.snapshot.zoomRatioRange)+    }++    @Test fun fakeMapBuildsSnapshotWithoutCharacteristics() {+        val facade = CharacteristicsFacade.fromFakeMap(+            cameraId = "2",+            lensFacingRaw = CameraMetadata.LENS_FACING_FRONT,+            physicalCameraIds = setOf("3", "4"),+            zoomRatioRange = Range(1f, 5f),+            hasFlashUnit = false,+            sizesByFormat = mapOf(+                ImageFormat.JPEG to listOf(Size(4032, 3024), Size(1920, 1080)),+                ImageFormat.RAW_SENSOR to listOf(Size(4032, 3024)),+            ),+            availableCapabilities = setOf(CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_RAW),+        )+        val s = facade.snapshot+        assertEquals(LensFacing.FRONT, s.lensFacing)+        assertEquals(setOf("3", "4"), s.physicalCameraIds)+        assertTrue(s.streamConfig.supportsRawSensor)+        assertEquals(Size(4032, 3024), s.streamConfig.maxSizeFor(ImageFormat.JPEG))+        assertEquals(2, s.streamConfig.formats.getValue(ImageFormat.JPEG).sizeCount)+        assertTrue(s.supportsRaw)+    }++    @Test fun streamConfigSummaryFromSizesPicksLargestArea() {+        val summary = StreamConfigSummary.fromSizes(+            mapOf(ImageFormat.YUV_420_888 to listOf(Size(640, 480), Size(1280, 720), Size(320, 240))),+        )+        assertEquals(Size(1280, 720), summary.maxSizeFor(ImageFormat.YUV_420_888))+        assertEquals(emptyList(), summary.sizesFor(ImageFormat.JPEG))+        assertFalse(summary.supportsRawSensor)+    }++    @Test fun streamConfigSummaryFromNullMapIsEmpty() {+        assertEquals(StreamConfigSummary.EMPTY, StreamConfigSummary.fromMap(null as StreamConfigurationMap?))+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.ktnew file mode 100644index 0000000000..72f489624b--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/SessionStateMachineTest.kt@@ -0,0 +1,150 @@+package com.vayunmathur.camera.platform.camera2++import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertTrue+import org.junit.Test++class SessionStateMachineTest {++    private fun streamingMachine(): SessionStateMachine {+        val m = SessionStateMachine()+        m.transition(SessionEvent.OPEN_REQUESTED)+        m.transition(SessionEvent.DEVICE_OPENED)+        m.transition(SessionEvent.CONFIGURE_REQUESTED)+        m.transition(SessionEvent.SESSION_CONFIGURED)+        return m+    }++    @Test fun happyPathClosedToStreaming() {+        val m = SessionStateMachine()+        assertEquals(SessionState.CLOSED, m.state)+        assertIs<TransitionResult.Applied>(m.transition(SessionEvent.OPEN_REQUESTED))+        assertEquals(SessionState.OPENING, m.state)+        assertIs<TransitionResult.Applied>(m.transition(SessionEvent.DEVICE_OPENED))+        assertEquals(SessionState.OPEN, m.state)+        assertIs<TransitionResult.Applied>(m.transition(SessionEvent.CONFIGURE_REQUESTED))+        assertEquals(SessionState.CONFIGURING, m.state)+        assertIs<TransitionResult.Applied>(m.transition(SessionEvent.SESSION_CONFIGURED))+        assertEquals(SessionState.STREAMING, m.state)+    }++    @Test fun illegalTransitionsAreRejectedWithoutMutating() {+        val m = SessionStateMachine()+        assertIs<TransitionResult.Rejected>(m.transition(SessionEvent.DEVICE_OPENED))+        assertIs<TransitionResult.Rejected>(m.transition(SessionEvent.SESSION_CONFIGURED))+        assertIs<TransitionResult.Rejected>(m.transition(SessionEvent.DEVICE_CLOSED))+        assertEquals(SessionState.CLOSED, m.state)++        val streaming = streamingMachine()+        assertIs<TransitionResult.Rejected>(streaming.transition(SessionEvent.OPEN_REQUESTED))+        assertIs<TransitionResult.Rejected>(streaming.transition(SessionEvent.DEVICE_OPENED))+        assertEquals(SessionState.STREAMING, streaming.state)+    }++    @Test fun configureFailedFallsBackToOpenAndCanRetry() {+        val m = SessionStateMachine()+        m.transition(SessionEvent.OPEN_REQUESTED)+        m.transition(SessionEvent.DEVICE_OPENED)+        m.transition(SessionEvent.CONFIGURE_REQUESTED)+        assertIs<TransitionResult.Applied>(m.transition(SessionEvent.CONFIGURE_FAILED))+        assertEquals(SessionState.OPEN, m.state)+        assertIs<TransitionResult.Applied>(m.transition(SessionEvent.CONFIGURE_REQUESTED))+        assertEquals(SessionState.CONFIGURING, m.state)+    }++    @Test fun everyStateCanReachClosedThroughTeardownOrError() {+        val m = streamingMachine()+        assertIs<TransitionResult.Applied>(m.transition(SessionEvent.CLOSE_REQUESTED))+        assertEquals(SessionState.CLOSING, m.state)+        assertIs<TransitionResult.Applied>(m.transition(SessionEvent.DEVICE_CLOSED))+        assertEquals(SessionState.CLOSED, m.state)++        val errored = streamingMachine()+        errored.transition(SessionEvent.ERROR_OCCURRED)+        assertEquals(SessionState.ERROR, errored.state)+        assertIs<TransitionResult.Applied>(errored.transition(SessionEvent.DEVICE_CLOSED))+        assertEquals(SessionState.CLOSED, errored.state)+    }++    @Test fun staleGenerationCallbacksAreDropped() {+        val m = streamingMachine()+        val scheduledGeneration = m.generation+        var ran = false++        val newGeneration = m.beginTeardown()+        assertTrue(newGeneration > scheduledGeneration)+        assertEquals(SessionState.CLOSING, m.state)+        assertFalse(m.isCurrent(scheduledGeneration))+        assertTrue(m.isCurrent(newGeneration))++        val result = m.dispatch(scheduledGeneration, SessionEvent.DEVICE_CLOSED)+        assertIs<TransitionResult.StaleGeneration>(result)+        // The stale DEVICE_CLOSED must not have completed the teardown.+        assertEquals(SessionState.CLOSING, m.state)++        assertFalse(m.runIfCurrent(scheduledGeneration) { ran = true })+        assertFalse(ran)+        assertTrue(m.runIfCurrent(newGeneration) { ran = true })+        assertTrue(ran)++        assertIs<TransitionResult.Applied>(m.dispatch(newGeneration, SessionEvent.DEVICE_CLOSED))+        assertEquals(SessionState.CLOSED, m.state)+    }++    @Test fun generationOnlyEverIncreases() {+        val m = SessionStateMachine()+        val g0 = m.generation+        // Teardown from CLOSED still bumps the token, stays CLOSED.+        val g1 = m.beginTeardown()+        assertEquals(SessionState.CLOSED, m.state)+        m.transition(SessionEvent.OPEN_REQUESTED)+        val g2 = m.beginTeardown()+        assertTrue(g0 < g1 && g1 < g2)+        assertEquals(SessionState.CLOSING, m.state)+        m.completeTeardown()+        assertEquals(SessionState.CLOSED, m.state)+        // completeTeardown outside CLOSING/ERROR is a rejected no-op.+        assertIs<TransitionResult.Rejected>(m.completeTeardown())+    }++    @Test fun legalTableAgreesWithMachine() {+        for (from in SessionState.entries) {+            for (event in SessionEvent.entries) {+                val machine = SessionStateMachine()+                // Drive the machine into `from` via the shortest legal path, then probe.+                driveTo(machine, from)+                assertEquals(from, machine.state)+                val result = machine.transition(event)+                assertEquals(+                    SessionStateMachine.isLegal(from, event),+                    result is TransitionResult.Applied,+                    "legality mismatch for $from + $event",+                )+            }+        }+    }++    private fun driveTo(m: SessionStateMachine, target: SessionState) {+        when (target) {+            SessionState.CLOSED -> Unit+            SessionState.OPENING -> m.transition(SessionEvent.OPEN_REQUESTED)+            SessionState.OPEN -> {+                driveTo(m, SessionState.OPENING); m.transition(SessionEvent.DEVICE_OPENED)+            }+            SessionState.CONFIGURING -> {+                driveTo(m, SessionState.OPEN); m.transition(SessionEvent.CONFIGURE_REQUESTED)+            }+            SessionState.STREAMING -> {+                driveTo(m, SessionState.CONFIGURING); m.transition(SessionEvent.SESSION_CONFIGURED)+            }+            SessionState.CLOSING -> {+                driveTo(m, SessionState.OPEN); m.transition(SessionEvent.CLOSE_REQUESTED)+            }+            SessionState.ERROR -> {+                driveTo(m, SessionState.OPEN); m.transition(SessionEvent.ERROR_OCCURRED)+            }+        }+    }+}