camera: AVIF for all captures with EXIF; Ultra HDR in Camera2
- Commit
e743fa67b29683061930b4e2ee27b2b8a6f75455- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-22 14:06 UTC (13 days ago)
- Parents
61d50e7
Two owner asks landed together because they share the still
save path.
AVIF actually produces .avif now: plain singles and bursts
previously stayed JPEG by design (only processed/night stills
reached the encoder). Every still entry routes through the
encoder when AVIF is selected, and EXIF is preserved by
muxing a TIFF Exif item into the ISOBMFF container in Rust
(ravif with_exif; our own parser test round-trips it) built
from the same tag set the JPEG path stamps, GPS included.
The encoder refuses an EXIF-less AVIF and falls back to
JPEG rather than silently dropping tags. Ultra HDR sources
stay JPEG_R with gain map intact - the AVIF tmap gain-map
mux is explicitly NOT done, and the format row now says so
('Ultra HDR and Motion Photos stay JPEG'). Default stays
JPEG; Motion Photo/panorama/for-result stay JPEG by design.
Ultra HDR is no longer CameraX-only: the gated Camera2
engine detects JPEG_R in the camera's output formats and
captures it directly from the HAL, falling back to plain
JPEG when unsupported; HDR intent mirrors (not forks) the
existing capability decision.
Verified: Rust avif tests 5/5 incl. Exif round-trip; camera
routing/encoder/camera2 test batches green; compile green.
On-device stream-combo validation for Camera2 JPEG_R remains
the only device check owed. (+38 lockfile crates for ravif
as previously flagged.)Diff
camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.ktindex 53fa7230e9..eaebfeb054 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt@@ -13,6 +13,7 @@ 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.buildAvifExifTiff import com.vayunmathur.camera.platform.mirrorCaptures /**@@ -112,14 +113,38 @@ 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.+ * On the AVIF path the rotation is baked into the pixels first and a+ * TIFF payload — the same tags the JPEG path stamps (see+ * `buildAvifExifTiff`), orientation Normal, plus GPS when enabled — is+ * muxed in as the file's Exif item; 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 or no EXIF payload could be built (never an EXIF-less+ * AVIF). [sourceJpeg] is the capture's original JPEG bytes, when one+ * exists, used only as the EXIF tag source. [fileStem], when given,+ * replaces the `IMG_<timestamp>` stem (burst frame names). */-internal fun CameraViewModel.saveProcessedStill(bitmap: Bitmap, rotationDegrees: Int): SavedStill? {- val encoded: EncodedStill = encode(bitmap, rotationDegrees)- val name = StillFormatRouting.displayName(MediaStoreSaver.timestamp(), encoded.format)+internal fun CameraViewModel.saveProcessedStill(+ bitmap: Bitmap,+ rotationDegrees: Int,+ sourceJpeg: ByteArray? = null,+ fileStem: String? = null,+): SavedStill? {+ val exifTiff = if (photoFormatMutable.value == com.vayunmathur.camera.platform.PhotoFormat.AVIF) {+ val carrier = java.io.ByteArrayOutputStream().use { out ->+ bitmap.compress(Bitmap.CompressFormat.JPEG, StillFormatRouting.JPEG_QUALITY, out)+ out.toByteArray()+ }+ buildAvifExifTiff(sourceJpeg, carrier)+ } else {+ null+ }+ val encoded: EncodedStill = encode(bitmap, rotationDegrees, exifTiff)+ val name = if (fileStem != null) {+ "$fileStem.${StillFormatRouting.extension(encoded.format)}"+ } else {+ StillFormatRouting.displayName(MediaStoreSaver.timestamp(), encoded.format)+ } val uri = saveStillBytes(name, encoded.bytes, StillFormatRouting.mimeType(encoded.format)) ?: return null return SavedStill(uri, encoded.format)
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.ktindex c17a59137f..6a4db6f4a2 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt@@ -49,4 +49,82 @@ object StillFormatRouting { /** `IMG_<timestamp>` display name in the container's extension. */ fun displayName(timestamp: String, format: StillFormat): String = "IMG_$timestamp.${extension(format)}"++ /**+ * True when a plain (unprocessed) single must leave the CameraX file+ * path and be captured in memory instead: only an AVIF-bound still+ * needs that (the file path can only write the HAL JPEG). JPEG, and+ * AVIF with no native encoder (which honestly falls back to JPEG),+ * stay on the file path so EXIF/Ultra HDR are never re-encoded away.+ */+ fun plainSingleNeedsInMemory(requested: StillFormat, nativeAvailable: Boolean): Boolean =+ effectiveFormat(requested, nativeAvailable, motionPhoto = false) == StillFormat.AVIF++ /**+ * The TIFF payload of a JPEG's Exif APP1 segment (`Exif\0\0` stripped),+ * or null when the JPEG carries none. Pure segment walk (no Android+ * types) so it is host-testable; used to feed the AVIF Exif item.+ */+ fun extractExifTiff(jpeg: ByteArray): ByteArray? {+ for ((marker, payload) in jpegHeaderSegments(jpeg)) {+ if (marker == 0xE1 && payload.size > 6 &&+ payload[0] == 'E'.code.toByte() && payload[1] == 'x'.code.toByte() &&+ payload[2] == 'i'.code.toByte() && payload[3] == 'f'.code.toByte() &&+ payload[4].toInt() == 0 && payload[5].toInt() == 0+ ) {+ return payload.copyOfRange(6, payload.size)+ }+ }+ return null+ }++ /**+ * True when [jpeg] is an Ultra HDR (JPEG_R) still: its header segments+ * advertise a gain map (Adobe `hdrgm` XMP / HDRGainMap, an ISO 21496-1+ * gain-map container item, or an MPF `MP Extension` second image).+ * Only header segments (before SOS) are scanned, so compressed image+ * data can never false-positive. Such stills stay JPEG_R when AVIF is+ * selected — decoding them would discard the gain map.+ */+ fun isUltraHdrJpeg(jpeg: ByteArray): Boolean {+ if (jpeg.size < 4 || jpeg[0] != 0xFF.toByte() || jpeg[1] != 0xD8.toByte()) return false+ val needles = listOf("hdrgm", "hdr-gain-map", "HDRGainMap", "GainMap", "MP Extension")+ for ((_, payload) in jpegHeaderSegments(jpeg)) {+ val text = String(payload, Charsets.ISO_8859_1)+ if (needles.any { it in text }) return true+ }+ return false+ }++ /**+ * Header segments of a JPEG as (marker, payload) pairs, stopping at+ * SOS (start of compressed data) or the first malformed segment.+ */+ private fun jpegHeaderSegments(jpeg: ByteArray): List<Pair<Int, ByteArray>> {+ if (jpeg.size < 4 || jpeg[0] != 0xFF.toByte() || jpeg[1] != 0xD8.toByte()) return emptyList()+ val out = mutableListOf<Pair<Int, ByteArray>>()+ var pos = 2+ while (pos + 4 <= jpeg.size) {+ if (jpeg[pos] != 0xFF.toByte()) break+ var markerPos = pos + 1+ while (markerPos < jpeg.size && jpeg[markerPos] == 0xFF.toByte()) markerPos+++ if (markerPos >= jpeg.size) break+ val marker = jpeg[markerPos].toInt() and 0xFF+ if (marker == 0xDA) break // SOS: compressed data follows+ // Standalone markers (SOI/EOI/TEM/RSTn) carry no length.+ if (marker == 0xD8 || marker == 0xD9 || marker == 0x01 || marker in 0xD0..0xD7) {+ pos = markerPos + 1+ continue+ }+ if (markerPos + 3 > jpeg.size) break+ val length = ((jpeg[markerPos + 1].toInt() and 0xFF) shl 8) or+ (jpeg[markerPos + 2].toInt() and 0xFF)+ if (length < 2 || markerPos + 1 + length > jpeg.size) break+ val payloadStart = markerPos + 3+ val payloadEnd = markerPos + 1 + length+ out.add(marker to jpeg.copyOfRange(payloadStart, payloadEnd))+ pos = payloadEnd+ }+ return out+ } }
camera/src/main/java/com/vayunmathur/camera/domain/UltraHdrIntent.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/UltraHdrIntent.kt b/camera/src/main/java/com/vayunmathur/camera/domain/UltraHdrIntent.ktnew file mode 100644index 0000000000..463f09d27e--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/UltraHdrIntent.kt@@ -0,0 +1,29 @@+package com.vayunmathur.camera.domain++/** Caller's still-output intent, resolved before any platform capture runs. */+enum class UltraHdrIntent {+ PLAIN_JPEG,+ ULTRA_HDR,+}++/**+ * Mirrors the decision CameraX still capture makes today, so Camera2 does+ * not fork it: there is no user-facing Ultra HDR toggle. `CameraPhotoSessionShared.probeUltraHdr`+ * asks CameraX for `OUTPUT_FORMAT_JPEG_ULTRA_HDR` in the lens's supported+ * output formats and `CameraPhotoSessionSetup.buildPhotoCapture` selects it+ * whenever that probe passes (the bind ladder, not a setting, falls back to+ * plain JPEG when the combo cannot bind). CameraX's Ultra HDR format is in+ * turn backed by the HAL advertising `ImageFormat.JPEG_R` (API 34+), which+ * is exactly the boolean the Camera2 facade reports, so the same decision+ * is: supported -> Ultra HDR intent, unsupported -> plain JPEG.+ */+object UltraHdrIntentPolicy {++ /** The intent for a lens whose JPEG_R (Ultra HDR) support is [jpegRSupported]. */+ fun resolve(jpegRSupported: Boolean): UltraHdrIntent =+ if (jpegRSupported) UltraHdrIntent.ULTRA_HDR else UltraHdrIntent.PLAIN_JPEG++ /** True when the caller should request an Ultra HDR (JPEG_R) still. */+ fun wantsUltraHdr(jpegRSupported: Boolean): Boolean =+ resolve(jpegRSupported) == UltraHdrIntent.ULTRA_HDR+}
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 b1e3902cdf..98ec5a7c97 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -9,6 +9,7 @@ import com.vayunmathur.camera.data.saveStillBytes import com.vayunmathur.camera.data.setLastCaptureUri import com.vayunmathur.camera.domain.FlashSetting import com.vayunmathur.camera.domain.StillFormat+import com.vayunmathur.camera.domain.UltraHdrIntentPolicy import com.vayunmathur.camera.platform.camera2.Camera2Session import com.vayunmathur.camera.platform.camera2.CapturedStill import com.vayunmathur.camera.platform.camera2.StillEngineInput@@ -108,10 +109,18 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean { // Ring first when the policy selects it; its runtime fallback to a // regular still lives inside captureFromRing. Night captures never // reach here (policy excludes the night route, Phase 6 is separate).+ // Ultra HDR intent mirrors CameraX exactly (see UltraHdrIntentPolicy):+ // capability-only, no separate user setting. The ring path reprocesses+ // to its JPEG output, so Ultra HDR applies to the direct still path;+ // an unsupported lens falls back to plain JPEG inside the session.+ val ultraHdrRequested = UltraHdrIntentPolicy.wantsUltraHdr(session.ultraHdrSupportedJpegR) if (StillEnginePolicy.usesRing(ringInput)) { session.captureFromRing(callback = stillCallback, mirrored = mirrored) } else {- session.capture(mirrored = mirrored, callback = stillCallback)+ session.capture(+ mirrored = mirrored, callback = stillCallback,+ ultraHdrRequested = ultraHdrRequested,+ ) } return true }@@ -123,11 +132,13 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean { */ internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? { val rotation = still.metadata.rotationDegrees- if (photoFormatMutable.value == PhotoFormat.AVIF) {+ if (photoFormatMutable.value == PhotoFormat.AVIF &&+ !com.vayunmathur.camera.domain.StillFormatRouting.isUltraHdrJpeg(still.jpegBytes)+ ) { val bitmap = BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size) ?: return saveJpegStill(still) try {- val saved = saveProcessedStill(bitmap, rotation) ?: return null+ val saved = saveProcessedStill(bitmap, rotation, still.jpegBytes) ?: return null if (saved.format == StillFormat.JPEG) { // The JPEG re-encode dropped the HAL EXIF; restore it from // the original frame, exactly as the processed CameraX path.
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 d3930adc17..c9b24f54fd 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt@@ -131,6 +131,44 @@ internal fun CameraViewModel.writeCaptureExif( } } +/**+ * Builds the TIFF payload for an AVIF Exif item from the same tag set+ * the JPEG path stamps: [CameraViewModel.EXIF_TAGS_TO_COPY] copied from+ * [sourceJpeg] (when there is a source frame), orientation Normal — the+ * AVIF pixels are baked upright by `StillEncoder`, so a sensor-rotation+ * tag would double-rotate — plus GPS when location is enabled. The tags+ * are written onto [carrierJpeg] (a clean JPEG encode of the saved+ * bitmap, so no stale dimension tags leak in) in a temp file, then the+ * Exif APP1's TIFF payload is extracted for the Rust mux. Null on any+ * failure: the caller then falls back to JPEG instead of shipping an+ * EXIF-less AVIF. Blocking (file I/O): call off the main thread.+ */+internal fun CameraViewModel.buildAvifExifTiff(sourceJpeg: ByteArray?, carrierJpeg: ByteArray): ByteArray? {+ updateLocation()+ var tmp: java.io.File? = null+ return try {+ tmp = java.io.File.createTempFile("avif_exif_", ".jpg", app.cacheDir)+ tmp.writeBytes(carrierJpeg)+ val dest = ExifInterface(tmp.absolutePath)+ copyExifTags(sourceJpeg?.let { ExifInterface(ByteArrayInputStream(it)) }, dest)+ dest.setAttribute(+ ExifInterface.TAG_ORIENTATION,+ ExifInterface.ORIENTATION_NORMAL.toString()+ )+ if (locationEnabledMutable.value) lastLocation?.let { dest.setGpsInfo(it) }+ dest.saveAttributes()+ com.vayunmathur.camera.domain.StillFormatRouting.extractExifTiff(tmp.readBytes())+ } catch (e: java.io.IOException) {+ Log.status("CameraViewModel", "Failed to build AVIF EXIF payload", e)+ null+ } catch (e: SecurityException) {+ Log.status("CameraViewModel", "Failed to build AVIF EXIF payload", e)+ null+ } finally {+ try { tmp?.delete() } catch (_: Exception) {}+ }+}+ /** Opens [uri] for EXIF read/write and stamps orientation (+GPS +copied tags). */ private fun CameraViewModel.writeExifAttributes( uri: Uri,
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 d6a51de43d..0e2e9d98a5 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt@@ -210,7 +210,8 @@ 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.- // AVIF stills carry no EXIF (orientation is in the pixels); only stamp JPEG.+ // AVIF stills already carry their Exif item from saveProcessedStill;+ // only JPEG needs the file-level stamp here. val isAvif = runCatching { app.contentResolver.getType(uri) }.getOrNull() == "image/avif" if (!isAvif) { withContext(Dispatchers.IO) { writeCaptureExif(uri, null, 0) }
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 e18ab78eba..68570e8988 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -10,6 +10,7 @@ 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 import kotlinx.coroutines.delay import kotlinx.coroutines.launch@@ -19,6 +20,7 @@ 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@@ -229,11 +231,80 @@ 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+ .decodeByteArray(sourceJpeg, 0, sourceJpeg.size)+ ?: error("Could not decode burst frame")+ val decoded = cropToRect(decodedRaw, cropRect)+ val adjusted = applyColorAdjustments(decoded, 0f, 0f, mirror)+ val saved = saveProcessedStill(+ adjusted, degrees, sourceJpeg, "IMG_${ts}_BURST${n}"+ )+ adjusted.recycle()+ if (saved != null &&+ saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG+ ) {+ writeCaptureExif(saved.uri, sourceJpeg, degrees, mirrored = mirror)+ }+ saved?.uri+ }+ }.getOrNull()+ }+ burstCountMutable.value = n+ uri?.let { setLastCaptureUri(it) }+ shootNext(n + 1)+ }+ }+ override fun onError(exception: ImageCaptureException) {+ Log.error("CameraViewModel", "Burst frame $n failed", exception)+ shootNext(n + 1)+ }+ }+ )+ return+ } // prepareStillSave falls back to MediaStore, so null is unexpected — but a null // here must terminate, never retry (the old `?: run { shootNext(n + 1) }` looped // forever when the save target was unusable).
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 86c7e02396..40de7ac3ba 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt@@ -20,18 +20,44 @@ 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.saveStillBytes import com.vayunmathur.camera.data.setLastCaptureUri import com.vayunmathur.camera.data.updateLocation import com.vayunmathur.camera.data.closeStream import com.vayunmathur.camera.data.resolveUri +/**+ * True when this single leaves the CameraX file path for an in-memory+ * capture: a preview effect must be baked in, or AVIF is the effective+ * format (the file path can only write the HAL JPEG, so an AVIF single+ * captured there would land as `.jpg` whatever the setting says).+ */+private fun CameraViewModel.singleCaptureInMemory(): Boolean {+ val requested = if (photoFormatMutable.value == PhotoFormat.AVIF) {+ com.vayunmathur.camera.domain.StillFormat.AVIF+ } else {+ com.vayunmathur.camera.domain.StillFormat.JPEG+ }+ return cameraModeMutable.value == CameraMode.PORTRAIT ||+ warmthMutable.value != 0f || shadowsMutable.value != 0f ||+ com.vayunmathur.camera.domain.StillFormatRouting.plainSingleNeedsInMemory(+ requested, StitchNative.isAvailable+ )+}+ internal fun CameraViewModel.captureSinglePhoto() { val capture = imageCapture ?: return isCapturingMutable.value = true- val fileName = "IMG_${MediaStoreSaver.timestamp()}.jpg"- val pending = prepareStillSave(fileName) ?: run {- isCapturingMutable.value = false- return+ // In-memory captures save through saveProcessedStill, which creates+ // its own save target — preparing a `.jpg` file target for them+ // would leave an empty JPEG document behind on SAF targets.+ val pending = if (singleCaptureInMemory()) {+ null+ } else {+ prepareStillSave("IMG_${MediaStoreSaver.timestamp()}.jpg") ?: run {+ isCapturingMutable.value = false+ return+ } } val plan = buildSingleCapturePlan(pending) ?: run { isCapturingMutable.value = false@@ -49,8 +75,8 @@ internal fun CameraViewModel.captureSinglePhoto() { @OptIn(ExperimentalCamera2Interop::class) private data class SingleCapturePlan( val capture: ImageCapture,- val pending: PendingStill,- val outputOptions: ImageCapture.OutputFileOptions,+ val pending: PendingStill?,+ val outputOptions: ImageCapture.OutputFileOptions?, val exposureNanos: Long?, val nightIso: Int?, val cam2Control: androidx.camera.camera2.interop.Camera2CameraControl?,@@ -68,9 +94,9 @@ private data class SingleCapturePlan( */ @Suppress("DEPRECATION") @OptIn(ExperimentalCamera2Interop::class)-private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill): SingleCapturePlan? {+private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill?): SingleCapturePlan? { val capture = imageCapture ?: return null- val outputOptions = pending.outputOptions+ val outputOptions = pending?.outputOptions val stop = CameraViewModel.EXPOSURE_TIME_STOPS[exposureTimeIndexMutable.value] // applyManualControls() applies only the preview half of a manual exposure live; the@@ -157,24 +183,24 @@ private fun CameraViewModel.runSingleCapture(plan: SingleCapturePlan) { isCapturingMutable.value = false stopLongExposureCountdown() restoreAfterNight()- plan.pending.closeStream()+ plan.pending?.closeStream() if (uri != null) setLastCaptureUri(uri) } - if (plan.bokeh || plan.warmth != 0f || plan.shadows != 0f) {+ if (plan.bokeh || plan.warmth != 0f || plan.shadows != 0f || singleCaptureInMemory()) { captureProcessedSingle(plan, ::finishCapture) return } plan.capture.takePicture(- plan.outputOptions,+ plan.outputOptions!!, ContextCompat.getMainExecutor(app), object : ImageCapture.OnImageSavedCallback { override fun onCaptureStarted() { emitShutterFeedback() } override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {- finishCapture(plan.pending.resolveUri(outputFileResults))+ finishCapture(plan.pending?.resolveUri(outputFileResults) ?: outputFileResults.savedUri) } override fun onError(exception: ImageCaptureException) { finishCapture(null)@@ -188,9 +214,13 @@ private fun CameraViewModel.runSingleCapture(plan: SingleCapturePlan) { * since the warmth/shadows adjustment and portrait bokeh only live in the preview * RenderEffect. Re-encoding drops the JPEG's EXIF, so it is copied back from the * original frame (plus GPS and the orientation tag) to match the normal path.- * Caveat: this processed path is always SDR JPEG — decoding to an ARGB_8888 bitmap- * discards any Ultra HDR gain map, so processed captures lose HDR even when- * Ultra HDR is otherwise active. Normal (unprocessed) captures keep the gain map.+ * Caveat: the processed (bokeh/colour) path is always SDR — decoding to+ * an ARGB_8888 bitmap discards any Ultra HDR gain map, so processed+ * captures lose HDR even when Ultra HDR is otherwise active. A plain+ * single that only took this path because AVIF is selected keeps its+ * gain map instead: an Ultra HDR source stays JPEG_R (see+ * [processSingleFrame]), because AVIF gain-map (`tmap`) muxing is not+ * implemented yet. */ private fun CameraViewModel.captureProcessedSingle( plan: SingleCapturePlan,@@ -238,6 +268,20 @@ private fun CameraViewModel.processSingleFrame( cropRect: Rect, degrees: Int ): Uri? {+ // Plain AVIF single + Ultra HDR source: decoding would discard the+ // gain map and AVIF `tmap` muxing is not implemented, so the shot+ // stays JPEG_R — stamped (orientation/GPS, gain map preserved by+ // ExifInterface) exactly like the Motion Photo still. Processed+ // shots (bokeh/colour) already trade HDR for the effect, as before.+ val plainAvif = !plan.bokeh && plan.warmth == 0f && plan.shadows == 0f &&+ photoFormatMutable.value == PhotoFormat.AVIF+ if (plainAvif && com.vayunmathur.camera.domain.StillFormatRouting.isUltraHdrJpeg(sourceJpeg)) {+ val stamped = stampStillBytes(sourceJpeg, degrees, plan.mirror)+ val name = com.vayunmathur.camera.domain.StillFormatRouting.displayName(+ MediaStoreSaver.timestamp(), com.vayunmathur.camera.domain.StillFormat.JPEG+ )+ return saveStillBytes(name, stamped)+ } val decodedRaw = BitmapFactory.decodeByteArray(sourceJpeg, 0, sourceJpeg.size) ?: error("Could not decode captured frame") val decoded = cropToRect(decodedRaw, cropRect)@@ -248,9 +292,10 @@ 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)- // AVIF (when chosen) bakes orientation into the pixels and carries no- // EXIF; JPEG keeps the EXIF stamping path below.- val saved = saveProcessedStill(adjusted, degrees)+ // AVIF (when chosen) bakes orientation into the pixels and carries+ // its tags in the muxed Exif item; JPEG keeps the EXIF stamping+ // path below.+ val saved = saveProcessedStill(adjusted, degrees, sourceJpeg) adjusted.recycle() if (saved == null) return null if (saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG) {
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.ktindex 4f3bfaa43d..408e1b2fb9 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt@@ -17,45 +17,56 @@ internal data class EncodedStill(val bytes: ByteArray, val format: StillFormat) /** * 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).+ * AVIF goes through the Rust `ravif` encoder behind [StitchNative];+ * the TIFF payload in `exifTiff` is muxed in as the file's ISOBMFF+ * Exif item (see `buildAvifExifTiff`). When the native library is+ * missing, encoding fails, or no EXIF payload was built, this falls+ * back to JPEG bytes so a shot is never lost — and never lands as an+ * EXIF-less AVIF. Orientation is baked into the pixels on the AVIF+ * path, and the payload's orientation tag accordingly reads Normal;+ * the JPEG path leaves pixels untouched and the caller stamps+ * orientation/GPS via `writeCaptureExif` as before. */ internal object StillEncoder { + /** The still format settings currently ask for (before fallbacks). */+ fun CameraViewModel.requestedStillFormat(): StillFormat =+ if (photoFormatMutable.value == PhotoFormat.AVIF) StillFormat.AVIF else StillFormat.JPEG+ /** * 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.+ * [rotationDegrees] is baked into the pixels on the AVIF path; 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- }+ fun CameraViewModel.encode(+ bitmap: Bitmap,+ rotationDegrees: Int = 0,+ exifTiff: ByteArray? = null,+ ): EncodedStill {+ val requested = requestedStillFormat() 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()+ if (exifTiff == null || exifTiff.isEmpty()) {+ Log.status("StillEncoder", "AVIF without EXIF payload; falling back to JPEG")+ } else {+ val upright = uprightCopy(bitmap, rotationDegrees, 0)+ try {+ encodeAvif(upright, exifTiff)?.let { return EncodedStill(it, StillFormat.AVIF) }+ } finally {+ if (upright !== bitmap) upright.recycle()+ }+ Log.status("StillEncoder", "AVIF encode failed; falling back to JPEG") }- Log.status("StillEncoder", "AVIF encode failed; falling back to JPEG") } return EncodedStill(encodeJpeg(bitmap), StillFormat.JPEG) } - private fun encodeAvif(bitmap: Bitmap): ByteArray? {+ private fun encodeAvif(bitmap: Bitmap, exifTiff: ByteArray): ByteArray? { if (!StitchNative.isAvailable) return null val width = bitmap.width val height = bitmap.height@@ -71,9 +82,10 @@ internal object StillEncoder { rgba[i * 4 + 3] = (px ushr 24 and 0xFF).toByte() } return try {- StitchNative.encodeAvif(+ StitchNative.encodeAvifExif( rgba, width, height, StillFormatRouting.AVIF_QUALITY, StillFormatRouting.AVIF_SPEED,+ exifTiff, ) } catch (e: UnsatisfiedLinkError) { Log.status("StillEncoder", "AVIF native call failed; JPEG fallback", e)
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 6abd92024c..004db08ee0 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt@@ -82,6 +82,16 @@ object StitchNative { */ external fun encodeAvif(rgba: ByteArray, width: Int, height: Int, quality: Float, speed: Int): ByteArray? + /**+ * Like [encodeAvif], but muxes [exif] (a TIFF payload; empty = none)+ * into the AVIF as its ISOBMFF Exif item. Null on any failure —+ * including a non-TIFF payload — so callers fall back to JPEG rather+ * than saving an EXIF-less AVIF.+ */+ external fun encodeAvifExif(+ rgba: ByteArray, width: Int, height: Int, quality: Float, speed: Int, exif: ByteArray,+ ): ByteArray?+ // --- Zero-copy luma on-ramp (Camera2 migration Phase 3) --- /**
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.ktindex 30c413c907..02a0fb8ba4 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt@@ -177,6 +177,14 @@ interface Camera2Driver { /** Creates the JPEG still output for [size], or null when unavailable. */ fun createStillOutput(size: FrameSize): StillOutput? + /**+ * Creates the JPEG_R (Ultra HDR) still output for [size], or null when+ * unavailable (pre-API 34, unsupported size, reader failure). The+ * default is null: a fake/driver without Ultra HDR degrades still+ * capture to the plain JPEG output, never to a failed capture.+ */+ fun createUltraHdrStillOutput(size: FrameSize): StillOutput? = null+ /** Creates the YUV ring output for [size]; null when unavailable. */ fun createRingOutput(size: FrameSize): RingOutput? = null @@ -315,6 +323,17 @@ class AndroidCamera2Driver( override fun createStillOutput(size: FrameSize): StillOutput? = runCatching { JpegStillOutput(size.width, size.height, handler = handler) }.getOrNull() + override fun createUltraHdrStillOutput(size: FrameSize): StillOutput? {+ // JPEG_R exists only from API 34; older releases keep plain JPEG.+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return null+ return runCatching {+ JpegStillOutput(+ size.width, size.height, handler = handler,+ format = android.graphics.ImageFormat.JPEG_R,+ )+ }.getOrNull()+ }+ override fun createRingOutput(size: FrameSize): RingOutput? = runCatching { YuvRingOutput(size.width, size.height, handler = handler) }.getOrNull()
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktindex 3ad0d9f3a5..7d229b2cca 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt@@ -77,6 +77,8 @@ class Camera2Session( private var previewSize: FrameSize? = null private var stillOutput: StillOutput? = null private var stillSize: FrameSize? = null+ private var ultraHdrOutput: StillOutput? = null+ private var ultraHdrSize: FrameSize? = null private var ringOutput: RingOutput? = null private var ringSize: FrameSize? = null private val ring = ReprocessRing<RingHeldFrame>(ringConfig.capacity)@@ -94,6 +96,7 @@ class Camera2Session( private class PendingStill( val params: ResolvedStillParams, val callback: StillCallback,+ val tag: StillOutputTag = StillOutputTag.JPEG, var rawMetadata: RawStillMetadata? = null, var jpegBytes: ByteArray? = null, var jpegWidth: Int = 0,@@ -226,6 +229,15 @@ class Camera2Session( /** True when a JPEG output exists (see [StillEnginePolicy]). */ val hasJpegOutput: Boolean get() = stillOutput != null + /** Facade-reported JPEG_R (Ultra HDR) support for this lens. */+ val ultraHdrSupportedJpegR: Boolean get() = snapshot.supportsJpegR++ /** True when a JPEG_R output is configured (Ultra HDR captures can be served). */+ val hasUltraHdrOutput: Boolean get() = ultraHdrOutput != null++ /** The JPEG_R still size configured at [open], or null when unavailable. */+ fun currentUltraHdrSize(): FrameSize? = ultraHdrSize+ /** True when the YUV ring output is configured (see [StillEnginePolicy]). */ val hasRingOutput: Boolean get() = ringOutput != null @@ -411,6 +423,7 @@ class Camera2Session( callback: StillCallback, displayRotationDegrees: Int? = null, mirrored: Boolean = false,+ ultraHdrRequested: Boolean = false, ) { executor.execute { val session = captureSession@@ -422,7 +435,7 @@ class Camera2Session( callback.onStillFailed("no JPEG output on this session") pendingStill != null -> callback.onStillFailed("a still capture is already in flight")- else -> startStillCapture(callback, displayRotationDegrees, mirrored)+ else -> startStillCapture(callback, displayRotationDegrees, mirrored, ultraHdrRequested) } } }@@ -432,12 +445,13 @@ class Camera2Session( callback: StillCallback, displayRotationDegrees: Int?, mirrored: Boolean,+ ultraHdrRequested: Boolean = false, ) { val session = captureSession ?: run { callback.onStillFailed("still capture requires a streaming session") return }- val output = stillOutput ?: run {+ val jpegOutput = stillOutput ?: run { callback.onStillFailed("no JPEG output on this session") return }@@ -445,6 +459,15 @@ class Camera2Session( callback.onStillFailed("a still capture is already in flight") return }+ // JPEG_R only when requested and a JPEG_R output was configured;+ // every other case is the plain JPEG output (graceful fallback,+ // never a failed capture because Ultra HDR was requested).+ val tag = StillOutputRouter.select(ultraHdrRequested, ultraHdrOutput != null)+ val output = if (tag == StillOutputTag.ULTRA_HDR_JPEG_R) {+ ultraHdrOutput ?: jpegOutput+ } else {+ jpegOutput+ } val params = StillCapturePlanner.resolve( state = controls, snapshot = snapshot,@@ -452,7 +475,7 @@ class Camera2Session( ?: [email protected], mirrored = mirrored, )- val pending = PendingStill(params, callback)+ val pending = PendingStill(params, callback, tag) pendingStill = pending runCatching { session.captureStill(params, output.surface, object : StillResultCallback {@@ -528,9 +551,20 @@ class Camera2Session( } private fun onJpegAvailable(bytes: ByteArray, width: Int, height: Int) {+ onStillBytesAvailable(bytes, width, height, StillOutputTag.JPEG)+ }++ private fun onUltraHdrJpegAvailable(bytes: ByteArray, width: Int, height: Int) {+ onStillBytesAvailable(bytes, width, height, StillOutputTag.ULTRA_HDR_JPEG_R)+ }++ private fun onStillBytesAvailable(bytes: ByteArray, width: Int, height: Int, tag: StillOutputTag) { try { executor.execute { val pending = pendingStill ?: return@execute+ // Bytes from the output the pending capture did not target+ // are not this still (both readers share the session).+ if (pending.tag != tag) return@execute pending.jpegBytes = bytes pending.jpegWidth = width pending.jpegHeight = height@@ -552,6 +586,7 @@ class Camera2Session( metadata = StillMetadataMapper.map( raw, pending.params.jpegOrientationDegrees, pending.params.mirrored, ),+ tag = pending.tag, ), ) }@@ -588,6 +623,9 @@ class Camera2Session( runCatching { stillOutput?.close() } stillOutput = null stillSize = null+ runCatching { ultraHdrOutput?.close() }+ ultraHdrOutput = null+ ultraHdrSize = null runCatching { ringOutput?.close() } ringOutput = null ringSize = null@@ -644,6 +682,23 @@ class Camera2Session( } stillOutput = output stillSize = if (output != null) jpegSize else null+ // Additional output: the JPEG_R (Ultra HDR) reader, only when the+ // facade advertises JPEG_R sizes. Failure degrades to no Ultra HDR+ // output (captures requesting it fall back to the JPEG output).+ val jpegRSize = if (snapshot.supportsJpegR) {+ StreamSelection.selectJpegRSize(snapshot)+ } else {+ null+ }+ val createdUltraHdr = jpegRSize?.let { size ->+ runCatching { driver.createUltraHdrStillOutput(size) }.getOrNull()?.also { created ->+ created.setListener(JpegImageListener { bytes, width, height, _ ->+ onUltraHdrJpegAvailable(bytes, width, height)+ })+ }+ }+ ultraHdrOutput = createdUltraHdr+ ultraHdrSize = if (createdUltraHdr != null) jpegRSize else null // Third output: the YUV ring, only when this session was built // with the ring enabled. Failure degrades to no-ring (the // policy then excludes the ring path, capture stays Phase 4a).@@ -681,7 +736,8 @@ class Camera2Session( rawRingSize = if (createdRawRing != null) selectedRawSize else null rawRingFormat = if (createdRawRing != null) selectedRawFormat else null val surfaces = listOfNotNull(- surface, output?.surface, createdRing?.surface, createdRawRing?.surface,+ surface, output?.surface, createdUltraHdr?.surface,+ createdRing?.surface, createdRawRing?.surface, ) val callback = SessionCallbackImpl(gen) runCatching {
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 29361be42b..33140cf1c3 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@@ -189,6 +189,16 @@ data class LensCharacteristicsSnapshot( } val minZoomRatio: Float get() = zoomRatioRange?.lower ?: 1f val maxZoomRatio: Float get() = zoomRatioRange?.upper ?: 1f+ /**+ * True when the HAL advertises an Ultra HDR still output: `JPEG_R`+ * (API 34+) with at least one size in the stream configuration map.+ * A JPEG_R output targeted by a still capture yields a JPEG with an+ * embedded gain map from the HAL — the same output CameraX selects+ * via `OUTPUT_FORMAT_JPEG_ULTRA_HDR`. No extra capability bit gates+ * JPEG_R; the advertised format/size list is the whole contract.+ */+ val supportsJpegR: Boolean+ get() = streamConfig.sizesFor(ImageFormat.JPEG_R).isNotEmpty() val supportsRaw: Boolean get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_RAW in availableCapabilities val supportsReprocess: Boolean@@ -263,6 +273,17 @@ class CharacteristicsFacade private constructor( ) { val cameraId: String get() = snapshot.cameraId + /**+ * True when [cameraId] is this facade's lens and it advertises a+ * JPEG_R (Ultra HDR, API 34+) still output. Pure snapshot read:+ * false for any other camera id, never a HAL call.+ */+ fun ultraHdrSupportedJpegR(cameraId: String): Boolean =+ cameraId == snapshot.cameraId && snapshot.supportsJpegR++ /** This facade's own lens: see [ultraHdrSupportedJpegR]. */+ fun ultraHdrSupportedJpegR(): Boolean = ultraHdrSupportedJpegR(snapshot.cameraId)+ companion object { /** Builds a facade from an already-materialised snapshot (tests / fakes). */ fun fromSnapshot(snapshot: LensCharacteristicsSnapshot): CharacteristicsFacade =
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.ktindex 8c853c9255..789475c763 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt@@ -54,16 +54,43 @@ data class StillCaptureMetadata( val frameNumber: Long? = null, ) +/** Which still output a [CapturedStill] came from. */+enum class StillOutputTag {+ JPEG,++ /** JPEG_R surface: [CapturedStill.jpegBytes] are an Ultra HDR JPEG (gain map embedded). */+ ULTRA_HDR_JPEG_R,+}++/**+ * Pure still-output routing: JPEG_R only when the caller asked for Ultra+ * HDR *and* a JPEG_R output exists on the session; plain JPEG in every+ * other case. Requesting Ultra HDR can therefore never fail a capture —+ * unsupported devices, a failed JPEG_R reader, and plain requests all land+ * on the JPEG output that Phase 4a already requires.+ */+object StillOutputRouter {+ fun select(ultraHdrRequested: Boolean, hasUltraHdrOutput: Boolean): StillOutputTag =+ if (ultraHdrRequested && hasUltraHdrOutput) {+ StillOutputTag.ULTRA_HDR_JPEG_R+ } else {+ StillOutputTag.JPEG+ }+}+ /** One finished still: HAL JPEG bytes plus their mapped metadata. */ data class CapturedStill( val jpegBytes: ByteArray, val jpegWidth: Int, val jpegHeight: Int, val metadata: StillCaptureMetadata,+ /** Output the bytes came from; JPEG_R bytes carry EXIF + gain map untouched. */+ val tag: StillOutputTag = StillOutputTag.JPEG, ) { override fun equals(other: Any?): Boolean = other is CapturedStill && jpegWidth == other.jpegWidth && jpegHeight == other.jpegHeight && metadata == other.metadata &&+ tag == other.tag && jpegBytes.contentEquals(other.jpegBytes) override fun hashCode(): Int {@@ -71,6 +98,7 @@ data class CapturedStill( result = 31 * result + jpegWidth result = 31 * result + jpegHeight result = 31 * result + metadata.hashCode()+ result = 31 * result + tag.hashCode() return result } }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.ktindex e1452c6052..b6b39ead89 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.kt@@ -37,10 +37,12 @@ class JpegStillOutput( height: Int, maxImages: Int = DEFAULT_MAX_IMAGES, private val handler: Handler,+ /** Reader format: [ImageFormat.JPEG], or [ImageFormat.JPEG_R] (API 34+) for Ultra HDR. */+ format: Int = ImageFormat.JPEG, ) : StillOutput { private val reader: ImageReader =- ImageReader.newInstance(width, height, ImageFormat.JPEG, maxImages)+ ImageReader.newInstance(width, height, format, maxImages) override val surface: Surface get() = reader.surface
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.ktindex 99b686f422..d8b0af7323 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt@@ -130,6 +130,21 @@ object StreamSelection { supportedJpegSizes(snapshot) .maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height })) + /** Supported JPEG_R (Ultra HDR) still sizes in facade order. */+ fun supportedJpegRSizes(snapshot: LensCharacteristicsSnapshot): List<FrameSize> =+ snapshot.streamConfig.sizesFor(ImageFormat.JPEG_R)+ .map { FrameSize.from(it) }.distinct()++ /**+ * The JPEG_R still size to configure: the largest advertised, matching+ * [selectJpegSize]. Null when the lens reports no JPEG_R sizes (pre-API 34+ * or no Ultra HDR output) — the session then has no Ultra HDR output and+ * still capture falls back to plain JPEG.+ */+ fun selectJpegRSize(snapshot: LensCharacteristicsSnapshot): FrameSize? =+ supportedJpegRSizes(snapshot)+ .maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height }))+ /** Supported YUV_420_888 sizes in facade order (empty = no ring). */ fun supportedYuvSizes(snapshot: LensCharacteristicsSnapshot): List<FrameSize> = snapshot.streamConfig.sizesFor(ImageFormat.YUV_420_888)
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 8a8ed0335b..82a939e960 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -85,7 +85,7 @@ <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>+ <string name="photo_format_avif_description">Smaller files, slower to save; Ultra HDR and Motion Photos stay JPEG</string> <!-- Motion-Photo duration settings (SettingsPage, issue #712) --> <!-- SettingsPage: section header for motion-photo clip-length selection -->
camera/src/main/rust/src/avif.rs
diff --git a/camera/src/main/rust/src/avif.rs b/camera/src/main/rust/src/avif.rsindex 96602fd4f2..2ce3e67ede 100644--- a/camera/src/main/rust/src/avif.rs+++ b/camera/src/main/rust/src/avif.rs@@ -5,11 +5,15 @@ //! 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.+//! EXIF: `ravif`'s `with_exif` hands a TIFF payload to `avif-serialize`,+//! which muxes it at the ISOBMFF level as a dedicated `Exif` item (an+//! `infe` entry in `iinf`, extents in `iloc`, a `cdsc` reference to the+//! colour item, and the item data in `mdat` framed as+//! `[u32 TIFF-offset = 0][TIFF header …]`, per ISO/IEC 23008-12). The+//! Kotlin side builds that TIFF payload from the same tag set the JPEG+//! path stamps (orientation baked upright, so the tag reads Normal, plus+//! GPS when enabled). The tests below parse the result back with the+//! in-file box parser and assert the item is really there. use ravif::{Encoder, Img, RGBA8}; @@ -35,9 +39,42 @@ const SPEED_MAX: u8 = 10; /// 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>> {+ encode_avif_with_exif(rgba, width, height, quality, speed, None)+}++/// True when [exif] is a TIFF payload (`II*\0` / `MM\0*`) or an+/// already-framed HEIF Exif item (`[u32 offset][…][TIFF…]`).+fn looks_like_exif(exif: &[u8]) -> bool {+ if exif.starts_with(b"II\x2a\0") || exif.starts_with(b"MM\0\x2a") {+ return true;+ }+ let Some(offset) = exif.get(..4) else { return false };+ let Ok(offset) = <[u8; 4]>::try_from(offset) else { return false };+ let start = 4usize.checked_add(u32::from_be_bytes(offset) as usize);+ let Some(tiff) = start.and_then(|s| exif.get(s..)) else { return false };+ tiff.starts_with(b"II\x2a\0") || tiff.starts_with(b"MM\0\x2a")+}++/// Encode one RGBA frame to AVIF, muxing [exif] (a TIFF payload) in as+/// the file's Exif item when present. Returns `None` for invalid input,+/// a non-TIFF [exif], or any encoder failure — the Kotlin side then+/// falls back to JPEG rather than shipping an EXIF-less AVIF.+pub fn encode_avif_with_exif(+ rgba: &[u8],+ width: usize,+ height: usize,+ quality: f32,+ speed: u8,+ exif: Option<&[u8]>,+) -> Option<Vec<u8>> { if width == 0 || height == 0 || width > MAX_DIM || height > MAX_DIM { return None; }+ if let Some(exif) = exif {+ if exif.is_empty() || !looks_like_exif(exif) {+ return None;+ }+ } let expected = width.checked_mul(height)?.checked_mul(4)?; if rgba.len() != expected { return None;@@ -50,12 +87,14 @@ pub fn encode_avif(rgba: &[u8], width: usize, height: usize, quality: f32, speed }) .collect(); let img = Img::new(pixels.as_slice(), width, height);- let encoded = Encoder::new()+ let mut encoder = 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()?;+ .with_bit_depth(ravif::BitDepth::Eight);+ if let Some(exif) = exif {+ encoder = encoder.with_exif(exif.to_vec());+ }+ let encoded = encoder.encode_rgba(img).ok()?; if encoded.avif_file.is_empty() { None } else {@@ -101,9 +140,160 @@ pub fn avif_dimensions(bytes: &[u8]) -> Option<(u32, u32)> { )) } +/// One parsed ISOBMFF box: type plus absolute payload span in the file.+#[cfg(test)]+struct BoxSpan {+ typ: [u8; 4],+ payload: std::ops::Range<usize>,+}++#[cfg(test)]+fn parse_boxes(bytes: &[u8], span: std::ops::Range<usize>) -> Vec<BoxSpan> {+ let mut out = Vec::new();+ let mut off = span.start;+ while off + 8 <= span.end && off + 8 <= bytes.len() {+ let size32 = u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]);+ let (size, header) = if size32 == 1 && off + 16 <= bytes.len() {+ (+ u64::from_be_bytes(bytes[off + 8..off + 16].try_into().unwrap()) as usize,+ 16usize,+ )+ } else if size32 == 0 {+ (span.end.saturating_sub(off), 8usize)+ } else {+ (size32 as usize, 8usize)+ };+ if size < header || off + size > bytes.len() {+ break;+ }+ let mut typ: [u8; 4] = bytes[off + 4..off + 8].try_into().unwrap();+ let payload_start = if typ == *b"uuid" { off + header + 16 } else { off + header };+ if typ == *b"uuid" {+ typ = *b"uuid";+ }+ out.push(BoxSpan { typ, payload: payload_start..off + size });+ off += size;+ }+ out+}++#[cfg(test)]+fn read_uint(bytes: &[u8], pos: &mut usize, size: usize) -> Option<u64> {+ let mut value = 0u64;+ for _ in 0..size {+ value = (value << 8) | *bytes.get(*pos)? as u64;+ *pos += 1;+ }+ Some(value)+}++/// Reconstructs the Exif item's data (`[u32 TIFF offset][TIFF…]`) by+/// walking `meta` → `iinf` (find the `Exif` infe id) → `iloc` (that id's+/// extents into the file). `None` when the file carries no Exif item.+/// This is the spec-level proof that the mux landed: a file that merely+/// contains the bytes somewhere does not pass unless iinf/iloc agree.+#[cfg(test)]+pub fn avif_exif_item(bytes: &[u8]) -> Option<Vec<u8>> {+ let top = parse_boxes(bytes, 0..bytes.len());+ let meta = top.iter().find(|b| &b.typ == b"meta")?;+ // `meta` is a full box: children start after version/flags.+ let children = parse_boxes(bytes, (meta.payload.start + 4)..meta.payload.end);++ let iinf = children.iter().find(|b| &b.typ == b"iinf")?;+ let mut pos = iinf.payload.start + 4; // version/flags+ let version = *bytes.get(iinf.payload.start)?;+ let count = if version == 1 {+ read_uint(bytes, &mut pos, 4)? as usize+ } else {+ read_uint(bytes, &mut pos, 2)? as usize+ };+ let infes = parse_boxes(bytes, pos..iinf.payload.end);+ let _ = count;+ let exif_id = infes.iter().find_map(|infe| {+ // infe v2: version/flags(4) item_id(2) protection(2) type(4)+ let p = infe.payload.start + 4;+ if bytes.get(p + 4..p + 8)? == b"Exif" {+ Some(u16::from_be_bytes([*bytes.get(p)?, *bytes.get(p + 1)?]))+ } else {+ None+ }+ })?;++ let iloc = children.iter().find(|b| &b.typ == b"iloc")?;+ let mut pos = iloc.payload.start + 4; // version/flags+ let sizes = *bytes.get(pos)?;+ pos += 1;+ let offset_size = (sizes >> 4) as usize;+ let length_size = (sizes & 0x0F) as usize;+ let base_sizes = *bytes.get(pos)?;+ pos += 1;+ let base_offset_size = (base_sizes >> 4) as usize;+ let iloc_version = *bytes.get(iloc.payload.start)?;+ let item_count = if iloc_version == 2 {+ read_uint(bytes, &mut pos, 4)? as usize+ } else {+ read_uint(bytes, &mut pos, 2)? as usize+ };+ for _ in 0..item_count {+ let item_id = read_uint(bytes, &mut pos, 2)? as u16;+ if iloc_version == 1 || iloc_version == 2 {+ read_uint(bytes, &mut pos, 2)?; // construction_method+ }+ read_uint(bytes, &mut pos, 2)?; // data_reference_index+ let base_offset = read_uint(bytes, &mut pos, base_offset_size)?;+ let extent_count = read_uint(bytes, &mut pos, 2)? as usize;+ let mut item = Vec::new();+ let found = item_id == exif_id;+ for _ in 0..extent_count {+ if iloc_version == 1 || iloc_version == 2 {+ let index_size = (base_sizes & 0x0F) as usize;+ if index_size > 0 {+ read_uint(bytes, &mut pos, index_size)?;+ }+ }+ let offset = read_uint(bytes, &mut pos, offset_size)?;+ let length = read_uint(bytes, &mut pos, length_size)? as usize;+ if found {+ let start = (base_offset + offset) as usize;+ item.extend_from_slice(bytes.get(start..start + length)?);+ }+ }+ if found {+ return Some(item);+ }+ }+ None+}++/// The TIFF payload inside the Exif item (skips the u32 TIFF offset).+#[cfg(test)]+pub fn avif_exif_tiff(bytes: &[u8]) -> Option<Vec<u8>> {+ let item = avif_exif_item(bytes)?;+ let offset = u32::from_be_bytes(item.get(..4)?.try_into().ok()?) as usize;+ let start = 4usize.checked_add(offset)?;+ Some(item.get(start..)?.to_vec())+}+ #[cfg(test)] mod avif_tests {- use super::{avif_dimensions, encode_avif, has_avif_magic};+ use super::{avif_dimensions, avif_exif_item, avif_exif_tiff, encode_avif, encode_avif_with_exif, has_avif_magic};++ /// Minimal little-endian TIFF: IFD0 with one Orientation(=1) entry,+ /// then a marker tail so content assertions can find the payload.+ fn test_tiff() -> Vec<u8> {+ let mut tiff = Vec::new();+ tiff.extend_from_slice(b"II\x2a\0");+ tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8+ tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry+ tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation+ tiff.extend_from_slice(&3u16.to_le_bytes()); // SHORT+ tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1+ tiff.extend_from_slice(&1u16.to_le_bytes()); // value 1 (Normal)+ tiff.extend_from_slice(&[0, 0]);+ tiff.extend_from_slice(&0u32.to_le_bytes()); // no next IFD+ tiff.extend_from_slice(b"GPSMARK");+ tiff+ } fn gradient(width: usize, height: usize) -> Vec<u8> { let mut px = Vec::with_capacity(width * height * 4);@@ -128,6 +318,37 @@ mod avif_tests { assert_eq!(avif_dimensions(&bytes), Some((64, 48))); } + #[test]+ fn exif_item_round_trips_through_isobmff_boxes() {+ let rgba = gradient(64, 48);+ let tiff = test_tiff();+ let bytes = encode_avif_with_exif(&rgba, 64, 48, 80.0, 10, Some(&tiff))+ .expect("encode with exif must succeed");+ assert!(has_avif_magic(&bytes));+ assert_eq!(avif_dimensions(&bytes), Some((64, 48)));+ // Item framing: [u32 offset=0][TIFF], located via iinf+iloc.+ let item = avif_exif_item(&bytes).expect("Exif item must be present via iinf/iloc");+ assert_eq!(&item[..4], &[0, 0, 0, 0]);+ let parsed = avif_exif_tiff(&bytes).expect("TIFF payload must parse back");+ assert_eq!(parsed, tiff);+ assert!(parsed.starts_with(b"II\x2a\0"));+ assert!(parsed.windows(7).any(|w| w == b"GPSMARK"));+ }++ #[test]+ fn no_exif_item_when_no_payload_given() {+ let rgba = gradient(32, 32);+ let bytes = encode_avif(&rgba, 32, 32, 80.0, 10).expect("encode must succeed");+ assert!(avif_exif_item(&bytes).is_none());+ }++ #[test]+ fn non_tiff_exif_is_rejected_so_kotlin_falls_back_to_jpeg() {+ let rgba = gradient(32, 32);+ assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"not a tiff")).is_none());+ assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"")).is_none());+ }+ #[test] fn rejects_mismatched_and_oversized_input() { assert!(encode_avif(&[0u8; 10], 64, 48, 80.0, 10).is_none());@@ -153,6 +374,49 @@ mod avif_tests { } } +/// JNI entry for `StitchNative.encodeAvifExif`: RGBA frame + TIFF Exif+/// payload in (empty array = no payload), AVIF bytes with a muxed Exif+/// item out, null on any failure so Kotlin falls back to JPEG.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_encodeAvifExif<'l>(+ mut env: jni::EnvUnowned<'l>,+ _class: jni::objects::JClass<'l>,+ rgba: jni::objects::JByteArray<'l>,+ width: jni::sys::jint,+ height: jni::sys::jint,+ quality: jni::sys::jfloat,+ speed: jni::sys::jint,+ exif: jni::objects::JByteArray<'l>,+) -> jni::sys::jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jni::sys::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 exif_bytes = match env.convert_byte_array(&exif) {+ Ok(b) => b,+ Err(_) => return Ok(null),+ };+ let exif_ref = if exif_bytes.is_empty() { None } else { Some(exif_bytes.as_slice()) };+ let encoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ encode_avif_with_exif(&bytes, width as usize, height as usize, quality, speed.clamp(1, 10) as u8, exif_ref)+ }))+ .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>()+}+ /// JNI entry for `StitchNative.encodeAvif`: RGBA frame in, AVIF bytes out, /// null on any failure so Kotlin falls back to JPEG. #[no_mangle]
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.ktindex 3f6a941c7e..088a28b2cd 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt@@ -2,6 +2,8 @@ package com.vayunmathur.camera.domain import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue class StillFormatRoutingTest { @@ -37,6 +39,57 @@ class StillFormatRoutingTest { ) } + /** One JPEG header segment: `FF <marker> <len:u16be> <payload>` (len includes itself). */+ private fun segment(marker: Int, payload: ByteArray): ByteArray {+ val len = payload.size + 2+ return byteArrayOf(+ 0xFF.toByte(), marker.toByte(), (len shr 8).toByte(), len.toByte()+ ) + payload+ }++ /** Minimal JPEG skeleton: SOI, the given header segments, then SOS. */+ private fun jpeg(vararg segments: ByteArray): ByteArray =+ byteArrayOf(0xFF.toByte(), 0xD8.toByte()) ++ segments.fold(byteArrayOf()) { acc, s -> acc + s } ++ byteArrayOf(0xFF.toByte(), 0xDA.toByte())++ @Test+ fun plainSingleNeedsInMemoryOnlyForEffectiveAvif() {+ // AVIF plain single: must leave the JPEG file path or it lands .jpg.+ assertTrue(StillFormatRouting.plainSingleNeedsInMemory(StillFormat.AVIF, nativeAvailable = true))+ // AVIF with no native encoder honestly falls back to the JPEG file path.+ assertFalse(StillFormatRouting.plainSingleNeedsInMemory(StillFormat.AVIF, nativeAvailable = false))+ // JPEG single is unchanged: file path, EXIF/Ultra HDR preserved.+ assertFalse(StillFormatRouting.plainSingleNeedsInMemory(StillFormat.JPEG, nativeAvailable = true))+ }++ @Test+ fun ultraHdrDetectedFromGainMapHeaders() {+ val xmp = segment(+ 0xE1,+ "http://ns.adobe.com/xap/1.0/\u0000<x:xmpmeta xmlns:hdrgm=\"http://ns.adobe.com/hdr-gain-map/1.0/\"/>"+ .toByteArray(Charsets.ISO_8859_1),+ )+ assertTrue(StillFormatRouting.isUltraHdrJpeg(jpeg(xmp)))+ val mpf = segment(0xE2, "MP Extension\u0000".toByteArray(Charsets.ISO_8859_1))+ assertTrue(StillFormatRouting.isUltraHdrJpeg(jpeg(mpf)))+ // Plain JPEG, and non-JPEG bytes, are not Ultra HDR.+ assertFalse(StillFormatRouting.isUltraHdrJpeg(jpeg(segment(0xE0, "JFIF\u0000".toByteArray()))))+ assertFalse(StillFormatRouting.isUltraHdrJpeg(byteArrayOf(1, 2, 3)))+ }++ @Test+ fun exifTiffExtractedFromApp1AndMissingExifIsNull() {+ val tiff = "II*\u0000GPSMARK".toByteArray(Charsets.ISO_8859_1)+ val xmpFirst = jpeg(+ segment(0xE1, "http://ns.adobe.com/xap/1.0/\u0000<x/>".toByteArray(Charsets.ISO_8859_1)),+ segment(0xE1, "Exif\u0000\u0000".toByteArray(Charsets.ISO_8859_1) + tiff),+ )+ assertEquals(tiff.toList(), StillFormatRouting.extractExifTiff(xmpFirst)?.toList())+ assertEquals(null, StillFormatRouting.extractExifTiff(jpeg(segment(0xE0, "JFIF\u0000".toByteArray()))))+ assertEquals(null, StillFormatRouting.extractExifTiff(byteArrayOf(9, 9)))+ }+ @Test fun extensionAndMimeMatchContainer() { assertEquals("jpg", StillFormatRouting.extension(StillFormat.JPEG))
camera/src/test/java/com/vayunmathur/camera/domain/UltraHdrIntentPolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/UltraHdrIntentPolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/UltraHdrIntentPolicyTest.ktnew file mode 100644index 0000000000..f1d7b55170--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/UltraHdrIntentPolicyTest.kt@@ -0,0 +1,19 @@+package com.vayunmathur.camera.domain++import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.Test++class UltraHdrIntentPolicyTest {++ @Test fun supportedLensWantsUltraHdrLikeCameraX() {+ assertEquals(UltraHdrIntent.ULTRA_HDR, UltraHdrIntentPolicy.resolve(jpegRSupported = true))+ assertTrue(UltraHdrIntentPolicy.wantsUltraHdr(jpegRSupported = true))+ }++ @Test fun unsupportedLensFallsBackToPlainJpeg() {+ assertEquals(UltraHdrIntent.PLAIN_JPEG, UltraHdrIntentPolicy.resolve(jpegRSupported = false))+ assertFalse(UltraHdrIntentPolicy.wantsUltraHdr(jpegRSupported = false))+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.ktindex 181f2dd3d3..3edafe8ce6 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.kt@@ -27,6 +27,28 @@ class StillEncoderNativeTest { assertEquals("ftypavif", String(encoded, 4, 8, Charsets.US_ASCII)) } + @Test+ fun encodeAvifExifMuxesExifItemIntoAvif() {+ if (!StitchNative.isAvailable) return+ val width = 64+ val height = 48+ val rgba = ByteArray(width * height * 4) { 0x80.toByte() }+ // Minimal TIFF (little-endian header) with a marker tail, as+ // buildAvifExifTiff would hand over.+ val tiff = "II*\u0000\u0008\u0000\u0000\u0000GPSMARK".toByteArray(Charsets.ISO_8859_1)+ val encoded = StitchNative.encodeAvifExif(rgba, width, height, 80f, 10, tiff)+ assertNotNull(encoded)+ assertEquals("ftypavif", String(encoded, 4, 8, Charsets.US_ASCII))+ // The Exif item type and the TIFF payload must be in the file+ // (iinf `Exif` infe + mdat item data); the Rust avif_tests prove+ // the iinf/iloc structure parses back box-for-box.+ val asText = String(encoded, Charsets.ISO_8859_1)+ assertTrue("Exif" in asText, "AVIF must carry an Exif item")+ assertTrue("GPSMARK" in asText, "AVIF Exif item must carry the TIFF payload")+ // A non-TIFF payload must be rejected, never muxed silently.+ assertEquals(null, StitchNative.encodeAvifExif(rgba, width, height, 80f, 10, byteArrayOf(1, 2, 3)))+ }+ @Test fun encodeAvifRejectsMismatchedInput() { if (!StitchNative.isAvailable) return
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.ktindex c665697a5b..43a4624bd2 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacadeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacadeTest.kt@@ -135,6 +135,38 @@ class CharacteristicsFacadeTest { assertTrue(s.supportsRaw) } + @Test fun ultraHdrSupportedJpegRFromFakeMap() {+ val facade = CharacteristicsFacade.fromFakeMap(+ cameraId = "2",+ sizesByFormat = mapOf(+ ImageFormat.JPEG to listOf(Size(4032, 3024)),+ ImageFormat.JPEG_R to listOf(Size(4032, 3024)),+ ),+ )+ assertTrue(facade.snapshot.supportsJpegR)+ assertTrue(facade.ultraHdrSupportedJpegR("2"))+ assertTrue(facade.ultraHdrSupportedJpegR())+ // Another lens's support must not leak through this facade.+ assertFalse(facade.ultraHdrSupportedJpegR("9"))+ assertEquals(Size(4032, 3024), facade.snapshot.streamConfig.maxSizeFor(ImageFormat.JPEG_R))+ }++ @Test fun ultraHdrUnsupportedWithoutJpegRSizes() {+ val jpegOnly = CharacteristicsFacade.fromFakeMap(+ cameraId = "2",+ sizesByFormat = mapOf(ImageFormat.JPEG to listOf(Size(4032, 3024))),+ )+ assertFalse(jpegOnly.snapshot.supportsJpegR)+ assertFalse(jpegOnly.ultraHdrSupportedJpegR("2"))++ // JPEG_R key with no sizes is not support.+ val empty = CharacteristicsFacade.fromFakeMap(+ cameraId = "2",+ sizesByFormat = mapOf(ImageFormat.JPEG_R to emptyList()),+ )+ assertFalse(empty.ultraHdrSupportedJpegR("2"))+ }+ @Test fun streamConfigSummaryFromSizesPicksLargestArea() { val summary = StreamConfigSummary.fromSizes( mapOf(ImageFormat.YUV_420_888 to listOf(Size(640, 480), Size(1280, 720), Size(320, 240))),
camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.ktindex 6fe2d325ad..7453b3c539 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt@@ -29,16 +29,18 @@ class StillCaptureTest { lensFacingRaw: Int? = CameraMetadata.LENS_FACING_BACK, sensorOrientationDegrees: Int = 90, jpegSizes: List<Size> = listOf(Size(4000, 3000), Size(1920, 1080)),+ jpegRSizes: List<Size> = emptyList(), ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap( cameraId = "0", lensFacingRaw = lensFacingRaw, zoomRatioRange = Range(1f, 10f), hasFlashUnit = hasFlashUnit, exposureCompensationEvRange = Range(-4f, 4f),- sizesByFormat = mapOf(- ImageFormat.PRIVATE to listOf(Size(1280, 720)),- ImageFormat.JPEG to jpegSizes,- ),+ sizesByFormat = buildMap {+ put(ImageFormat.PRIVATE, listOf(Size(1280, 720)))+ put(ImageFormat.JPEG, jpegSizes)+ if (jpegRSizes.isNotEmpty()) put(ImageFormat.JPEG_R, jpegRSizes)+ }, activeArrayWidth = 4000, activeArrayHeight = 3000, sensorOrientationDegrees = sensorOrientationDegrees,@@ -196,6 +198,7 @@ class StillCaptureTest { private class FakeSessionHandle : CaptureSessionHandle { val stillRequests = mutableListOf<ResolvedStillParams>()+ val stillTargets = mutableListOf<Surface>() var stillCallback: StillResultCallback? = null var closed = false override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}@@ -205,6 +208,7 @@ class StillCaptureTest { callback: StillResultCallback, ) { stillRequests += params+ stillTargets += stillTarget stillCallback = callback } override fun close() { closed = true }@@ -228,11 +232,21 @@ class StillCaptureTest { private class FakeDriver( private val device: FakeDevice, private val output: FakeStillOutput?,+ private val ultraOutput: FakeStillOutput? = null, ) : Camera2Driver {+ val stillSizes = mutableListOf<FrameSize>()+ val ultraSizes = mutableListOf<FrameSize>() override fun openCamera(cameraId: String, callback: DeviceCallback) { callback.onOpened(device) }- override fun createStillOutput(size: FrameSize): StillOutput? = output+ override fun createStillOutput(size: FrameSize): StillOutput? {+ stillSizes += size+ return output+ }+ override fun createUltraHdrStillOutput(size: FrameSize): StillOutput? {+ ultraSizes += size+ return ultraOutput+ } } private class RecordingStillCallback : Camera2Session.StillCallback {@@ -261,6 +275,34 @@ class StillCaptureTest { return session } + private fun streamingUltraSession(+ executor: Camera2Executor,+ handle: FakeSessionHandle,+ jpeg: FakeStillOutput?,+ ultra: FakeStillOutput?,+ jpegRSizes: List<Size>,+ ): Camera2Session {+ val device = FakeDevice(handle)+ val driver = FakeDriver(device, jpeg, ultra)+ val session = Camera2Session(driver, executor, snapshot(jpegRSizes = jpegRSizes))+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ return session+ }++ private fun completeStill(+ executor: Camera2Executor,+ handle: FakeSessionHandle,+ from: FakeStillOutput,+ bytes: ByteArray,+ ) {+ from.emit(bytes)+ executor.drain()+ handle.stillCallback!!.onCompleted(RawStillMetadata(sensorTimestampNs = 99L))+ executor.drain()+ }+ @Test fun sessionCapturePairsJpegAndResultIntoOneStill() { val executor = Camera2Executor("StillCaptureTest-pair") try {@@ -341,4 +383,99 @@ class StillCaptureTest { executor.shutdown() } }++ // -- Ultra HDR (JPEG_R) routing -------------------------------------------++ @Test fun stillOutputRouterSelectsJpegROnlyWhenRequestedAndAvailable() {+ assertEquals(+ StillOutputTag.ULTRA_HDR_JPEG_R,+ StillOutputRouter.select(ultraHdrRequested = true, hasUltraHdrOutput = true),+ )+ assertEquals(+ StillOutputTag.JPEG,+ StillOutputRouter.select(ultraHdrRequested = true, hasUltraHdrOutput = false),+ )+ assertEquals(+ StillOutputTag.JPEG,+ StillOutputRouter.select(ultraHdrRequested = false, hasUltraHdrOutput = true),+ )+ assertEquals(FrameSize(4000, 3000), StreamSelection.selectJpegRSize(snapshot(jpegRSizes = listOf(Size(1920, 1080), Size(4000, 3000)))))+ assertNull(StreamSelection.selectJpegRSize(snapshot()))+ }++ @Test fun sessionCapturesToJpegRWhenSupportedAndRequested() {+ val executor = Camera2Executor("StillCaptureTest-ultra")+ try {+ val handle = FakeSessionHandle()+ val jpeg = FakeStillOutput()+ val ultra = FakeStillOutput()+ val session = streamingUltraSession(+ executor, handle, jpeg, ultra, listOf(Size(4000, 3000)),+ )+ assertTrue(session.ultraHdrSupportedJpegR)+ assertTrue(session.hasUltraHdrOutput)+ assertEquals(FrameSize(4000, 3000), session.currentUltraHdrSize())+ // Both still surfaces are in the configured session.+ val callback = RecordingStillCallback()+ session.capture(callback, ultraHdrRequested = true)+ executor.drain()+ assertEquals(1, handle.stillRequests.size)+ assertEquals(ultra.surface, handle.stillTargets.single())+ completeStill(executor, handle, ultra, byteArrayOf(7, 8))+ assertEquals(1, callback.captured.size)+ assertEquals(StillOutputTag.ULTRA_HDR_JPEG_R, callback.captured.single().tag)+ assertTrue(callback.captured.single().jpegBytes.contentEquals(byteArrayOf(7, 8)))+ assertTrue(callback.failures.isEmpty())+ session.close()+ executor.drain()+ assertTrue(ultra.closed)+ } finally {+ executor.shutdown()+ }+ }++ @Test fun sessionFallsBackToJpegWhenUltraRequestedButUnsupported() {+ val executor = Camera2Executor("StillCaptureTest-ultra-fallback")+ try {+ val handle = FakeSessionHandle()+ val jpeg = FakeStillOutput()+ // No JPEG_R sizes: no Ultra HDR output is ever created.+ val session = streamingUltraSession(executor, handle, jpeg, FakeStillOutput(), emptyList())+ assertFalse(session.ultraHdrSupportedJpegR)+ assertFalse(session.hasUltraHdrOutput)+ val callback = RecordingStillCallback()+ session.capture(callback, ultraHdrRequested = true)+ executor.drain()+ assertEquals(jpeg.surface, handle.stillTargets.single())+ completeStill(executor, handle, jpeg, byteArrayOf(1))+ assertEquals(StillOutputTag.JPEG, callback.captured.single().tag)+ assertTrue(callback.failures.isEmpty())+ session.close()+ executor.drain()+ } finally {+ executor.shutdown()+ }+ }++ @Test fun sessionUsesJpegWhenUltraSupportedButNotRequested() {+ val executor = Camera2Executor("StillCaptureTest-ultra-not-requested")+ try {+ val handle = FakeSessionHandle()+ val jpeg = FakeStillOutput()+ val session = streamingUltraSession(+ executor, handle, jpeg, FakeStillOutput(), listOf(Size(4000, 3000)),+ )+ assertTrue(session.hasUltraHdrOutput)+ val callback = RecordingStillCallback()+ session.capture(callback, ultraHdrRequested = false)+ executor.drain()+ assertEquals(jpeg.surface, handle.stillTargets.single())+ completeStill(executor, handle, jpeg, byteArrayOf(2))+ assertEquals(StillOutputTag.JPEG, callback.captured.single().tag)+ session.close()+ executor.drain()+ } finally {+ executor.shutdown()+ }+ } }