camera: add Ultra HDR gain map for AVIF stills
- Commit
ad587e6891a3190732e0aeb96556ab1dda2a9522- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 14:36 UTC (21 hours ago)
- Parents
a5e8a34
Ultra HDR (ISO 21496-1 gain map) existed only as JPEG_R: an Ultra HDR source under an AVIF selection stayed JPEG_R because decoding it would discard the gain map and the AVIF gain-map mux was not built. AVIF stills therefore had no HDR rendition. Add the AVIF tmap mux in Rust (avif_gainmap.rs + avif_gainmap_parse.rs): the gain map is encoded with the same ravif encoder as the base, spliced in as a hidden av01 item, and referenced by a derived tmap item (dimg [gain, base]) whose extent carries the single-channel gain-map metadata fractions. One JNI call (StitchNative.encodeAvifUltraHdr) encodes base + Exif + gain map. Host tests prove the tmap/infe/iref/iloc round-trip, metadata fraction round-trip, and Exif coexistence. Capture routing follows the existing format selection with no new setting: StillFormatRouting sends Ultra HDR sources under AVIF to the new AVIF_GAINMAP route, JPEG stays JPEG_R. The Camera2 and plain-single paths extract the HAL gain map from the decoded JPEG_R (Bitmap.gainmap, API 34+) via GainMapExtractor and encode through saveProcessedStill; any extraction or mux failure falls back to the JPEG_R bytes, so an HDR shot never lands SDR-only. GainMapMath holds the pure encode/decode math shared with the metadata defaults. The AVIF settings text no longer claims Ultra HDR stays JPEG. Motion Photos coexist with Ultra HDR: captureMotionPhoto now requests the JPEG_R output like the direct still path, and assembleAndSaveMotionPhoto encodes the gain map first (encodeGainMapStill) and only then muxes the motion clip (StitchNative.muxAvifMotionPhoto appends the MP4 as the true EOF trailer), so a still can be both AVIF Ultra HDR and a Motion Photo and both Photos detectors (tmap iloc, XMP iloc + trailer-from-EOF) still parse it — proven by the Rust ultra_hdr_then_motion_mux_keeps_both round-trip. Gain-map extraction/encode failure falls back to a JPEG_R Motion Photo (HDR wins over the AVIF container); motion-mux failure keeps the plain AVIF Ultra HDR still. Rebased onto AVIF Motion Photos (muxAvifMotionPhoto): both JNI entry points kept in StitchNative, both AGENTS.md descriptions merged. Verified: cargo test -p camera_stitch (see rebase verification); ./gradlew :camera:lint :camera:lintVitalRelease :camera:testDevUnitTest (with the Photos verification run).
Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex c63fc1f2aa..7748ea06f0 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -79,7 +79,8 @@ for a direct open-on-phone broadcast. - com/vayunmathur/camera/domain/AnalysisRotation.kt — analysis-frame rotation (same formula as CaptureRotation) - com/vayunmathur/camera/domain/PanoXmp.kt - com/vayunmathur/camera/domain/SphereWaypoints.kt — FOV-derived photo-sphere waypoint layout + fused-orientation yaw/pitch math-- com/vayunmathur/camera/domain/MotionPhotoWriter.kt — GCamera XMP + assembly for both containers: JPEG (XMP injected, MP4 trailer) and AVIF (XMP item + MP4 trailer via the Rust mux)+- com/vayunmathur/camera/domain/MotionPhotoWriter.kt — GCamera XMP + assembly for both containers: JPEG (XMP injected, MP4 trailer) and AVIF (XMP item + MP4 trailer via the Rust mux); an AVIF still carries both a `tmap` gain map and a motion clip (gain-map encode first, motion mux appends the MP4 as the EOF trailer; JPEG_R Motion Photo bytes on any gain-map failure)+- com/vayunmathur/camera/domain/GainMapMath.kt — ISO 21496-1 gain-map params + encode/decode math for AVIF Ultra HDR; `StillFormatRouting.stillSaveRoute` sends Ultra HDR sources under AVIF to the `tmap` encoder (JPEG_R bytes on any gain-map failure) ### platform/ — capability queries - com/vayunmathur/camera/platform/CameraCapabilities.kt - com/vayunmathur/camera/platform/WearCameraSync.kt — phone conduit client node; mirrored state/thumbnail publish, op handling, preview streaming; wire protocol `com.vayunmathur.library.wearlink.camera.WearCameraProtocol` (WCF1 frames) in `:library:wearlink`; this module's `WearCameraProtocolTest` pins the golden JSON/frame bytes@@ -134,6 +135,7 @@ for a direct open-on-phone broadcast. - com/vayunmathur/camera/platform/MotionPhotoEncoder.kt - com/vayunmathur/camera/platform/VideoProcessor.kt - com/vayunmathur/camera/platform/CodecSupport.kt+- com/vayunmathur/camera/platform/GainMapExtractor.kt — extracts the HAL JPEG_R gain map (`Bitmap.gainmap`, API 34+) as a grayscale `GainMapFrame` for the AVIF `tmap` mux in Rust (`src/main/rust/src/avif_gainmap.rs` + `avif_gainmap_parse.rs`, via `StitchNative.encodeAvifUltraHdr`) ### platform/camera2/ — Camera2 driver - com/vayunmathur/camera/platform/camera2/Camera2Driver.kt - com/vayunmathur/camera/platform/camera2/Camera2Session.kt
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 db7dffb43e..f585b6ba05 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt@@ -11,7 +11,9 @@ 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.GainMapFrame import com.vayunmathur.camera.platform.StillEncoder.encode+import com.vayunmathur.camera.platform.StillEncoder.encodeGainMapStill import com.vayunmathur.camera.platform.buildAvifExifTiff /**@@ -83,6 +85,12 @@ internal fun CameraViewModel.saveProcessedStill( * honour it; callers whose bitmap is already mirrored pass false. */ mirrored: Boolean = false,+ /**+ * Ultra HDR gain map extracted from the source JPEG_R, when the+ * still is an HDR capture under AVIF. Null on encode failure so+ * the caller falls back to JPEG_R (HDR is never dropped silently).+ */+ gainMap: GainMapFrame? = null, ): SavedStill? { val started = android.os.SystemClock.elapsedRealtime() val exifTiff = if (photoFormatMutable.value == com.vayunmathur.camera.platform.PhotoFormat.AVIF) {@@ -96,7 +104,12 @@ internal fun CameraViewModel.saveProcessedStill( } val exifMs = android.os.SystemClock.elapsedRealtime() - started val encodeStarted = android.os.SystemClock.elapsedRealtime()- val encoded: EncodedStill = encode(bitmap, rotationDegrees, exifTiff, mirrored)+ val encoded: EncodedStill = if (gainMap != null) {+ if (exifTiff == null) return null+ encodeGainMapStill(bitmap, rotationDegrees, exifTiff, mirrored, gainMap) ?: return null+ } else {+ encode(bitmap, rotationDegrees, exifTiff, mirrored)+ } // StillSave breadcrumb: the two segments a processed still spends // before MediaStore — EXIF TIFF build (full-res JPEG carrier encode // + tag copy) and the container encode itself (ravif segment is
camera/src/main/java/com/vayunmathur/camera/domain/GainMapMath.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/GainMapMath.kt b/camera/src/main/java/com/vayunmathur/camera/domain/GainMapMath.ktnew file mode 100644index 0000000000..f20520e579--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/GainMapMath.kt@@ -0,0 +1,62 @@+package com.vayunmathur.camera.domain++import kotlin.math.pow+import kotlin.math.roundToInt++/**+ * ISO 21496-1 gain-map parameters for one (single-channel) gain map.+ *+ * The gain map stores, per pixel, the log-ratio between the HDR and+ * SDR renditions: `gain = ((log2(hdr / sdr) - min) / (max - min)) ^+ * (1 / gamma)`, quantised to one byte. Reconstruction inverts it:+ * `hdr = sdr * 2 ^ (min + gain ^ gamma * (max - min))`, with the+ * exponent scaled by the display's available headroom relative to+ * [hdrCapacityMax]. The defaults give a 4x (2-stop) boost ceiling,+ * which matches the `tmap` metadata the Rust mux writes.+ */+data class GainMapParams(+ val min: Float = 0f,+ val max: Float = 2f,+ val gamma: Float = 1f,+ val offsetSdr: Float = 0f,+ val offsetHdr: Float = 0f,+ val hdrCapacityMin: Float = 0f,+ val hdrCapacityMax: Float = 2f,+) {+ companion object {+ val DEFAULT = GainMapParams()+ }+}++/** Pure gain-map encode/decode math (host-testable, no Android types). */+object GainMapMath {++ /** Encoded gain byte for one pixel from its HDR and SDR luminance. */+ fun encodeGainByte(hdr: Float, sdr: Float, params: GainMapParams = GainMapParams.DEFAULT): Int {+ val range = params.max - params.min+ if (range <= 0f) return 0+ val ratio = (hdr + params.offsetHdr) / (sdr + params.offsetSdr).coerceAtLeast(1e-6f)+ val logRatio = (kotlin.math.ln(ratio.coerceAtLeast(1e-6f)) / kotlin.math.ln(2f)).toFloat()+ val normalised = ((logRatio - params.min) / range).coerceIn(0f, 1f)+ val gammaEncoded = if (params.gamma == 1f) {+ normalised+ } else {+ normalised.pow(1f / params.gamma)+ }+ return (gammaEncoded * 255f).roundToInt().coerceIn(0, 255)+ }++ /** Linear multiplier the gain byte applies to the SDR pixel. */+ fun decodeRatio(gainByte: Int, params: GainMapParams = GainMapParams.DEFAULT, headroom: Float = 1f): Float {+ val normalised = gainByte.coerceIn(0, 255) / 255f+ val linear = if (params.gamma == 1f) normalised else normalised.pow(params.gamma)+ val stops = (params.min + linear * (params.max - params.min)) * headroom.coerceIn(0f, 1f)+ return 2f.pow(stops)+ }++ /** Grayscale gain bytes for paired HDR/SDR luminance planes. */+ fun encodeGainMap(hdrLuma: FloatArray, sdrLuma: FloatArray, params: GainMapParams = GainMapParams.DEFAULT): ByteArray {+ require(hdrLuma.size == sdrLuma.size) { "HDR/SDR planes must match" }+ return ByteArray(hdrLuma.size) { i -> encodeGainByte(hdrLuma[i], sdrLuma[i], params).toByte() }+ }+}
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 a22c11a614..0ae2936f62 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt@@ -86,14 +86,21 @@ object StillFormatRouting { /** Ultra HDR (JPEG_R) source: write the bytes unchanged, gain map intact. */ ULTRA_HDR_JPEG_BYTES,++ /** Ultra HDR source under AVIF: re-encode with an AVIF `tmap` gain map. */+ AVIF_GAINMAP, } /**- * The landing for a pre-encoded still under [requested]. An Ultra HDR- * source always stays JPEG_R (the AVIF gain-map mux is not built);- * AVIF otherwise routes through the encoder; JPEG stays JPEG bytes.+ * The landing for a pre-encoded still under [requested]. An Ultra+ * HDR source under AVIF goes through the gain-map encoder (the+ * caller falls back to [ULTRA_HDR_JPEG_BYTES] when no gain map can+ * be extracted or the mux fails, so HDR is never silently lost);+ * under JPEG it stays JPEG_R; AVIF otherwise routes through the+ * encoder; JPEG stays JPEG bytes. */ fun stillSaveRoute(requested: StillFormat, ultraHdrSource: Boolean): StillSaveRoute = when {+ ultraHdrSource && requested == StillFormat.AVIF -> StillSaveRoute.AVIF_GAINMAP ultraHdrSource -> StillSaveRoute.ULTRA_HDR_JPEG_BYTES requested == StillFormat.AVIF -> StillSaveRoute.PROCESSED_ENCODER else -> StillSaveRoute.JPEG_BYTES@@ -122,8 +129,8 @@ object StillFormatRouting { * 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.+ * data can never false-positive. Such stills route to the AVIF+ * gain-map encoder when AVIF is selected (see [stillSaveRoute]). */ fun isUltraHdrJpeg(jpeg: ByteArray): Boolean { if (jpeg.size < 4 || jpeg[0] != 0xFF.toByte() || jpeg[1] != 0xD8.toByte()) return false
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 b0cc06ec33..a3d0b509c8 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -155,8 +155,9 @@ internal fun CameraViewModel.requestedStillFormat(): StillFormat = * reprocess and direct-encode fallbacks, and the night extension — so * this one decision covers them all: AVIF goes through the EXIF-carrying * `StillEncoder` via [saveProcessedStill]; an Ultra HDR source (the- * JPEG_R output tag, or a gain map sniffed in the bytes) stays JPEG_R;- * JPEG-selected shots keep the stamped-JPEG landing untouched.+ * JPEG_R output tag, or a gain map sniffed in the bytes) under AVIF+ * lands as an AVIF `tmap` Ultra HDR (JPEG_R bytes on any gain-map+ * failure); JPEG-selected shots keep the stamped-JPEG landing untouched. */ internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? { // Aspect-ratio crop: the selected ratio must shape the saved still@@ -219,11 +220,34 @@ internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? { StillFormatRouting.isUltraHdrJpeg(still.jpegBytes) return when (StillFormatRouting.stillSaveRoute(requestedStillFormat(), ultraHdrSource)) { StillFormatRouting.StillSaveRoute.PROCESSED_ENCODER -> saveCamera2EncodedStill(still)+ StillFormatRouting.StillSaveRoute.AVIF_GAINMAP -> saveCamera2GainMapStill(still) StillFormatRouting.StillSaveRoute.JPEG_BYTES, StillFormatRouting.StillSaveRoute.ULTRA_HDR_JPEG_BYTES -> saveJpegStill(still) } } +/**+ * The Ultra HDR AVIF landing: decode the JPEG_R once, extract the+ * gain map the HAL embedded, and encode base + gain map (`tmap`)+ * through the Rust mux. Any step that cannot produce a gain map+ * (older platform decode, mux failure) falls back to the JPEG_R+ * bytes, so an HDR shot never lands as an SDR-only AVIF.+ */+private fun CameraViewModel.saveCamera2GainMapStill(still: CapturedStill): Uri? {+ val bitmap = BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size)+ ?: return saveJpegStill(still)+ try {+ val gainMap = extractGainMapFrame(bitmap) ?: return saveJpegStill(still)+ val saved = saveProcessedStill(+ bitmap, still.metadata.rotationDegrees, still.jpegBytes,+ mirrored = still.metadata.mirrored, gainMap = gainMap,+ ) ?: return saveJpegStill(still)+ return saved.uri+ } finally {+ bitmap.recycle()+ }+}+ /** * Lands one captured Camera2 still, releasing the shutter first when the * landing is an AVIF encode. Once [still] is in memory its source JPEG@@ -243,9 +267,9 @@ internal fun CameraViewModel.onCamera2StillCaptured( ) { val ultraHdrSource = still.tag == StillOutputTag.ULTRA_HDR_JPEG_R || StillFormatRouting.isUltraHdrJpeg(still.jpegBytes)- val avifEncode = StillFormatRouting.stillSaveRoute(- requestedStillFormat(), ultraHdrSource,- ) == StillFormatRouting.StillSaveRoute.PROCESSED_ENCODER+ val avifRoute = StillFormatRouting.stillSaveRoute(requestedStillFormat(), ultraHdrSource)+ val avifEncode = avifRoute == StillFormatRouting.StillSaveRoute.PROCESSED_ENCODER ||+ avifRoute == StillFormatRouting.StillSaveRoute.AVIF_GAINMAP if (avifEncode && stillSaveQueue.tryReserve()) { finishCapture(null) stillSaveScope.launch(stillSaveDispatcher) {
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 0ed2e10efa..4859f7f6df 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -344,8 +344,17 @@ internal fun CameraViewModel.captureMotionPhoto() { ), ) val mirrored = mirrorCaptures+ // Ask for the JPEG_R output exactly like the direct still path, so a+ // Motion Photo shot can also be Ultra HDR: the gain map is extracted+ // from these bytes in [assembleAndSaveMotionPhoto] (AVIF gain-map+ // encode first, motion trailer appended last) and is never dropped+ // for the clip.+ val ultraHdrRequested = com.vayunmathur.camera.domain.UltraHdrIntentPolicy.wantsUltraHdr(+ session.ultraHdrSupportedJpegR,+ ) session.capture( mirrored = mirrored,+ ultraHdrRequested = ultraHdrRequested, callback = object : com.vayunmathur.camera.platform.camera2.Camera2Session.StillCallback { override fun onStillCaptured(still: com.vayunmathur.camera.platform.camera2.CapturedStill) { emitShutterFeedback()@@ -447,8 +456,48 @@ internal fun CameraViewModel.assembleAndSaveMotionPhoto(request: MotionSaveReque } val exifTiff = buildAvifExifTiff(stillBytes, carrier) if (exifTiff != null) {- val encoded = with(StillEncoder) {- encode(bitmap, request.rotationDegrees, exifTiff, request.mirrored)+ // Combined Motion Photo + Ultra HDR (priority order):+ // the gain map wins over the AVIF container, and the+ // clip wins over nothing — a still is both when the+ // pipeline produces both. Gain-map encode runs FIRST+ // (encodeGainMapStill), then muxAvifMotionPhoto+ // splices the XMP item and appends the MP4 as the+ // true EOF trailer; the reverse order would strand+ // the gain-map mdat after the trailer and break the+ // clip-length-from-EOF rule both Photos parsers use.+ // When no gain map can be extracted or encoded, the+ // shot stays a JPEG_R Motion Photo (HDR + clip in+ // JPEG), never an SDR-only AVIF.+ val ultraHdrSource =+ com.vayunmathur.camera.domain.StillFormatRouting.isUltraHdrJpeg(stillBytes)+ val gainFrame = if (ultraHdrSource) extractGainMapFrame(bitmap) else null+ if (ultraHdrSource && gainFrame == null) {+ val bytes = if (mp4 != null) {+ MotionPhotoWriter.assemble(stillBytes, mp4)+ } else {+ stillBytes+ }+ return saveStillBytes("$stem.jpg", bytes)+ }+ val encoded = if (gainFrame != null) {+ val gainEncoded = with(StillEncoder) {+ encodeGainMapStill(+ bitmap, request.rotationDegrees, exifTiff, request.mirrored, gainFrame,+ )+ }+ if (gainEncoded == null) {+ val bytes = if (mp4 != null) {+ MotionPhotoWriter.assemble(stillBytes, mp4)+ } else {+ stillBytes+ }+ return saveStillBytes("$stem.jpg", bytes)+ }+ gainEncoded+ } else {+ with(StillEncoder) {+ encode(bitmap, request.rotationDegrees, exifTiff, request.mirrored)+ } } if (encoded.format == com.vayunmathur.camera.domain.StillFormat.AVIF) { val bytes = if (mp4 != null) {
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 1abe007a57..18df598b93 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt@@ -150,14 +150,28 @@ private fun CameraViewModel.processSingleFrame( sourceJpeg: ByteArray, 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) trade HDR for the effect, as before.+ // Plain AVIF single + Ultra HDR source: decode once, extract the+ // gain map and land as AVIF `tmap` Ultra HDR; when no gain map can+ // be extracted or the mux fails the shot stays JPEG_R — stamped+ // (orientation/GPS, gain map preserved by ExifInterface) exactly+ // like the Motion Photo still. Processed shots (bokeh/colour)+ // 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 decodedHdr = BitmapFactory.decodeByteArray(sourceJpeg, 0, sourceJpeg.size)+ val gainMap = decodedHdr?.let { extractGainMapFrame(it) }+ if (decodedHdr != null && gainMap != null) {+ try {+ saveProcessedStill(+ decodedHdr, degrees, sourceJpeg, mirrored = plan.mirror, gainMap = gainMap,+ )?.let { return it.uri }+ } finally {+ decodedHdr.recycle()+ }+ } else {+ decodedHdr?.recycle()+ } val stamped = stampStillBytes(sourceJpeg, degrees, plan.mirror) val name = com.vayunmathur.camera.domain.StillFormatRouting.displayName( MediaStoreSaver.timestamp(), com.vayunmathur.camera.domain.StillFormat.JPEG
camera/src/main/java/com/vayunmathur/camera/platform/GainMapExtractor.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/GainMapExtractor.kt b/camera/src/main/java/com/vayunmathur/camera/platform/GainMapExtractor.ktnew file mode 100644index 0000000000..34d4b6af24--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/GainMapExtractor.kt@@ -0,0 +1,37 @@+package com.vayunmathur.camera.platform++import android.graphics.Bitmap+import android.os.Build++/**+ * Extracts the gain map the HAL embedded in a JPEG_R still.+ *+ * Decoding a JPEG_R on API 34+ yields a [Bitmap] whose+ * `gainmap.gainmapContents` is the gain-map image the platform+ * parsed from the ISO 21496-1 container. Its pixels are the encoded+ * gain (luma), which the Rust AVIF mux re-encodes as the `tmap`+ * gain-map item. Returns null where the platform exposes no gain+ * map (older API, plain JPEG, host tests) — callers then keep the+ * JPEG_R bytes so HDR is never silently dropped.+ */+internal fun extractGainMapFrame(bitmap: Bitmap): GainMapFrame? {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return null+ return runCatching {+ if (!bitmap.hasGainmap()) return null+ val contents = bitmap.gainmap?.gainmapContents ?: return null+ val width = contents.width+ val height = contents.height+ if (width <= 0 || height <= 0) return null+ val pixels = IntArray(width * height)+ contents.getPixels(pixels, 0, width, 0, 0, width, height)+ val gray = ByteArray(pixels.size)+ for (i in pixels.indices) {+ val px = pixels[i]+ val r = px shr 16 and 0xFF+ val g = px shr 8 and 0xFF+ val b = px and 0xFF+ gray[i] = ((r * 299 + g * 587 + b * 114) / 1000).toByte()+ }+ GainMapFrame(gray, width, height)+ }.getOrNull()+}
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 6ac708431d..456a7a2cd3 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt@@ -6,6 +6,18 @@ import com.vayunmathur.camera.domain.StillFormatRouting import com.vayunmathur.library.log.Log import java.io.ByteArrayOutputStream +/** One grayscale gain-map frame: one encoded gain byte per pixel. */+internal data class GainMapFrame(+ val gray: ByteArray,+ val width: Int,+ val height: Int,+) {+ override fun equals(other: Any?): Boolean =+ other is GainMapFrame && width == other.width && height == other.height && gray.contentEquals(other.gray)++ override fun hashCode(): Int = 31 * (31 * gray.contentHashCode() + width) + height+}+ /** One encoded still plus the container it actually landed in. */ internal data class EncodedStill( val bytes: ByteArray,@@ -101,6 +113,55 @@ internal object StillEncoder { return EncodedStill(encodeJpeg(bitmap), StillFormat.JPEG) } + /**+ * Ultra HDR AVIF for [bitmap] + [gainMap]: base encode plus the+ * Rust `tmap` gain-map mux in one native call. Null on any+ * failure — the caller must fall back to JPEG_R, never to an+ * SDR-only AVIF or JPEG, so the HDR rendition is not lost.+ */+ fun CameraViewModel.encodeGainMapStill(+ bitmap: Bitmap,+ rotationDegrees: Int = 0,+ exifTiff: ByteArray,+ mirrored: Boolean = false,+ gainMap: GainMapFrame,+ ): EncodedStill? {+ if (!StitchNative.isAvailable) return null+ val upright = uprightCopy(bitmap, rotationDegrees, 0, mirrored)+ try {+ val width = upright.width+ val height = upright.height+ if (width <= 0 || height <= 0) return null+ val pixels = IntArray(width * height)+ upright.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()+ }+ val params = com.vayunmathur.camera.domain.GainMapParams.DEFAULT+ val encoded = try {+ StitchNative.encodeAvifUltraHdr(+ rgba, width, height,+ StillFormatRouting.AVIF_QUALITY, StillFormatRouting.AVIF_SPEED,+ exifTiff, gainMap.gray, gainMap.width, gainMap.height,+ params.min, params.max, params.gamma,+ params.offsetSdr, params.offsetHdr,+ params.hdrCapacityMin, params.hdrCapacityMax,+ )+ } catch (e: UnsatisfiedLinkError) {+ Log.status("StillEncoder", "AVIF Ultra HDR native call failed; JPEG_R fallback", e)+ null+ } ?: return null+ return EncodedStill(encoded, StillFormat.AVIF, orientationBaked = true)+ } finally {+ if (upright !== bitmap) upright.recycle()+ }+ }+ private fun encodeAvif(bitmap: Bitmap, exifTiff: ByteArray): ByteArray? { if (!StitchNative.isAvailable) return null val width = bitmap.width
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 db6c1e1f6b..5d1457c40c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt@@ -115,6 +115,21 @@ object StitchNative { */ external fun muxAvifMotionPhoto(avif: ByteArray, xmp: ByteArray, mp4: ByteArray): ByteArray? + /**+ * Encodes an Ultra HDR AVIF: [rgba] base + [exif] TIFF (empty =+ * none) + grayscale gain map ([gainGray], one byte per pixel at+ * [gainWidth]x[gainHeight]) + ISO 21496-1 gain-map metadata,+ * muxed as an AVIF `tmap` item. Null on any failure — callers+ * fall back to JPEG_R so an HDR shot never lands SDR-only.+ */+ external fun encodeAvifUltraHdr(+ rgba: ByteArray, width: Int, height: Int, quality: Float, speed: Int,+ exif: ByteArray, gainGray: ByteArray, gainWidth: Int, gainHeight: Int,+ gainMin: Float, gainMax: Float, gainGamma: Float,+ offsetSdr: Float, offsetHdr: Float,+ hdrCapacityMin: Float, hdrCapacityMax: Float,+ ): ByteArray?+ // --- Zero-copy luma on-ramp (Camera2 migration Phase 3) --- /**
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 33191503a4..3565c1b75d 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -89,7 +89,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; Ultra HDR and Motion Photos stay JPEG</string>+ <string name="photo_format_avif_description">Smaller files, slower to save; Motion Photos stay JPEG</string> <!-- Motion-Photo settings (SettingsPage, issue #712) --> <!-- SettingsPage: section header for the motion-photo on/off toggle -->
camera/src/main/rust/src/avif_gainmap.rs
diff --git a/camera/src/main/rust/src/avif_gainmap.rs b/camera/src/main/rust/src/avif_gainmap.rsnew file mode 100644index 0000000000..af2dcc6bc4--- /dev/null+++ b/camera/src/main/rust/src/avif_gainmap.rs@@ -0,0 +1,417 @@+//! AVIF Ultra HDR gain-map mux (ISO 21496-1 gain map, AVIF `tmap`).+//!+//! An Ultra HDR AVIF carries three image items: the SDR base (the+//! existing primary `av01` item), a hidden grayscale gain-map `av01`+//! item, and a derived `tmap` item. The `tmap` item's `dimg` reference+//! lists `[gain-map item, base item]` and its extent holds the+//! single-channel gain-map metadata as seven fractions+//! (min, max, gamma, offsetSdr, offsetHdr, hdrCapacityMin,+//! hdrCapacityMax), each an `i32`/`u32` numerator over a `u32`+//! denominator, followed by one byte `useBaseColourSpace` (1). A+//! viewer that understands `tmap` reconstructs HDR as+//! `hdr = sdr * 2^(min + gain^gamma * (max - min))` (per channel, in+//! linear light, scaled by the display headroom); every other viewer+//! shows the base item unchanged, which is the SDR fallback.+//!+//! The mux splices the gain-map image (encoded here with the same+//! ravif encoder as the base) into an already-encoded base AVIF,+//! following the same rebuild rules as the Exif mux in+//! [`crate::avif_mux`]: `iinf`/`iloc`/`iref`/`iprp` are rebuilt,+//! post-`meta` extents shift by the `meta` growth, and new item data+//! lands in a trailing `mdat`. Anything unrecognised returns `None`+//! so Kotlin falls back to JPEG_R rather than shipping a bad file.++use crate::avif::{encode_avif, encode_avif_with_exif};+use crate::avif_gainmap_parse::{+ build_ipma, infe_id_and_type, parse_iprp, primary_id_of, GainMapParams, IpmaEntry,+};+use crate::avif_mux::{parse_boxes, read_uint, BoxSpan};+use jni_bridge::jni_fn;++use crate::avif_gainmap_parse::item_extents;+pub use crate::avif_gainmap_parse::{+ avif_gain_map, gain_map_metadata_bytes, parse_gain_map_metadata,+};++fn box_bytes(typ: &[u8; 4], payload: &[u8]) -> Option<Vec<u8>> {+ let size = u32::try_from(payload.len().checked_add(8)?).ok()?;+ let mut out = Vec::with_capacity(size as usize);+ out.extend_from_slice(&size.to_be_bytes());+ out.extend_from_slice(typ);+ out.extend_from_slice(payload);+ Some(out)+}++/// Muxes a grayscale gain map into an already-encoded base AVIF.+/// `gain_gray.len() == gain_width * gain_height` (one byte per pixel:+/// the encoded gain, see `GainMapParams`). Returns `None` on any+/// layout this mux does not understand.+pub fn mux_avif_gain_map(+ base_avif: &[u8],+ gain_gray: &[u8],+ gain_width: usize,+ gain_height: usize,+ params: &GainMapParams,+ quality: f32,+ speed: u8,+) -> Option<Vec<u8>> {+ if base_avif.len() < 12 || &base_avif[4..8] != b"ftyp" {+ return None;+ }+ if gain_width == 0 || gain_height == 0 || gain_gray.len() != gain_width * gain_height {+ return None;+ }+ if avif_gain_map(base_avif).is_some() {+ return None; // already Ultra HDR+ }+ // Encode the gain map as its own AVIF, then harvest its bitstream+ // and property boxes for splicing into the base file.+ let gain_rgba: Vec<u8> = gain_gray.iter().flat_map(|g| [*g, *g, *g, 255u8]).collect();+ let gain_avif = encode_avif(&gain_rgba, gain_width, gain_height, quality, speed)?;+ let (gain_bitstream, gain_props) = harvest_gain_item(&gain_avif)?;++ let top = parse_boxes(base_avif, 0..base_avif.len());+ let meta = top.iter().find(|b| &b.typ == b"meta")?;+ let children = parse_boxes(base_avif, (meta.payload.start + 4)..meta.payload.end);+ let raw_child = |b: &BoxSpan| base_avif[b.start..b.payload.end].to_vec();+ let primary_id = primary_id_of(base_avif, &children)?;++ // --- iinf: new ids, infe entries for gain (hidden av01) + tmap.+ let iinf = children.iter().find(|b| &b.typ == b"iinf")?;+ let iinf_version = *base_avif.get(iinf.payload.start)?;+ let (count_len, entry_count) = if iinf_version == 1 {+ (+ 4usize,+ u32::from_be_bytes(+ base_avif.get(iinf.payload.start + 4..iinf.payload.start + 8)?.try_into().ok()?,+ ) as usize,+ )+ } else {+ (+ 2usize,+ u16::from_be_bytes(+ base_avif.get(iinf.payload.start + 4..iinf.payload.start + 6)?.try_into().ok()?,+ ) as usize,+ )+ };+ let infes = parse_boxes(base_avif, (iinf.payload.start + 4 + count_len)..iinf.payload.end);+ let mut max_id: u32 = primary_id;+ for infe in &infes {+ let (id, typ) = infe_id_and_type(base_avif, infe)?;+ if &typ == b"tmap" {+ return None;+ }+ max_id = max_id.max(id);+ }+ let gain_id = max_id.checked_add(1)?;+ let tmap_id = max_id.checked_add(2)?;+ if tmap_id > u16::MAX as u32 {+ return None;+ }+ let make_infe = |id: u32, typ: &[u8; 4], hidden: bool| -> Option<Vec<u8>> {+ let mut payload = Vec::new();+ payload.extend_from_slice(&(2u32 | if hidden { 1 } else { 0 }).to_be_bytes());+ payload.extend_from_slice(&(id as u16).to_be_bytes());+ payload.extend_from_slice(&0u16.to_be_bytes());+ payload.extend_from_slice(typ);+ payload.push(0);+ box_bytes(b"infe", &payload)+ };+ let mut iinf_payload = Vec::new();+ iinf_payload.extend_from_slice(base_avif.get(iinf.payload.start..iinf.payload.start + 4)?);+ if iinf_version == 1 {+ iinf_payload.extend_from_slice(&((entry_count + 2) as u32).to_be_bytes());+ } else {+ iinf_payload.extend_from_slice(&((entry_count + 2) as u16).to_be_bytes());+ }+ for infe in &infes {+ iinf_payload.extend_from_slice(&raw_child(infe));+ }+ iinf_payload.extend_from_slice(&make_infe(gain_id, b"av01", true)?);+ iinf_payload.extend_from_slice(&make_infe(tmap_id, b"tmap", false)?);+ let iinf_box = box_bytes(b"iinf", &iinf_payload)?;++ // --- iprp: append gain properties, add ipma entries.+ let iprp = children.iter().find(|b| &b.typ == b"iprp")?;+ let (mut ipco_boxes, mut ipma_entries, ipma_version, ipma_flags) = parse_iprp(base_avif, iprp)?;+ let base_ipco_count = ipco_boxes.len() as u16;+ let essential_mask: u16 = if ipma_version >= 1 { 0x8000 } else { 0x80 };+ let index_mask: u16 = if ipma_version >= 1 { 0x7FFF } else { 0x7F };+ let mut gain_indices = Vec::new();+ for (i, pair) in gain_props.iter().enumerate() {+ ipco_boxes.push(pair.1.clone());+ gain_indices.push((pair.0 & essential_mask) | (base_ipco_count + 1 + i as u16));+ }+ let _ = index_mask;+ // tmap shares the base item's ispe (same dimensions).+ let base_entry = ipma_entries.iter().find(|e| e.item_id == primary_id)?;+ let mut tmap_indices = Vec::new();+ for raw_assoc in &base_entry.properties {+ let index = raw_assoc & 0x7F;+ let raw = ipco_boxes.get((index as usize).checked_sub(1)?)?;+ if raw.len() >= 8 && &raw[4..8] == b"ispe" {+ tmap_indices.push(*raw_assoc);+ }+ }+ if tmap_indices.is_empty() {+ return None;+ }+ ipma_entries.push(IpmaEntry { item_id: gain_id, properties: gain_indices });+ ipma_entries.push(IpmaEntry { item_id: tmap_id, properties: tmap_indices });+ let mut ipco_payload = Vec::new();+ for raw in &ipco_boxes {+ ipco_payload.extend_from_slice(raw);+ }+ let iprp_box = {+ let mut payload = Vec::new();+ payload.extend_from_slice(&box_bytes(b"ipco", &ipco_payload)?);+ payload.extend_from_slice(&build_ipma(&ipma_entries, ipma_version, ipma_flags & 1 != 0)?);+ box_bytes(b"iprp", &payload)?+ };++ // --- iref: dimg tmap -> [gain, base]+ let make_dimg = |id_bytes: usize| -> Option<Vec<u8>> {+ // SingleItemTypeReferenceBox payload: from_item_ID,+ // reference_count, to_item_IDs — no version/flags of its own.+ let mut payload = Vec::new();+ if id_bytes == 4 {+ payload.extend_from_slice(&tmap_id.to_be_bytes());+ payload.extend_from_slice(&2u16.to_be_bytes());+ payload.extend_from_slice(&gain_id.to_be_bytes());+ payload.extend_from_slice(&primary_id.to_be_bytes());+ } else {+ payload.extend_from_slice(&(tmap_id as u16).to_be_bytes());+ payload.extend_from_slice(&2u16.to_be_bytes());+ payload.extend_from_slice(&(gain_id as u16).to_be_bytes());+ payload.extend_from_slice(&(primary_id as u16).to_be_bytes());+ }+ box_bytes(b"dimg", &payload)+ };+ let (iref_box, iref_is_new) = match children.iter().find(|b| &b.typ == b"iref") {+ Some(iref) => {+ let version = *base_avif.get(iref.payload.start)?;+ let id_bytes = if version == 1 { 4 } else { 2 };+ let mut payload = base_avif.get(iref.payload.start..iref.payload.end)?.to_vec();+ payload.extend_from_slice(&make_dimg(id_bytes)?);+ (box_bytes(b"iref", &payload)?, false)+ }+ None => {+ let mut payload = Vec::new();+ payload.extend_from_slice(&0u32.to_be_bytes());+ payload.extend_from_slice(&make_dimg(2)?);+ (box_bytes(b"iref", &payload)?, true)+ }+ };++ // --- iloc: rebuilt at fixed layout, existing extents shifted.+ let iloc_old = children.iter().find(|b| &b.typ == b"iloc")?;+ let iloc_items = parse_iloc_items(base_avif, iloc_old)?;+ if iloc_items.iter().any(|i| i.construction_method != 0) {+ return None;+ }+ let tmap_metadata = gain_map_metadata_bytes(params);+ let new_items_len = iloc_items.len() + 2;+ let iloc_payload_len = 8usize+ + iloc_items.iter().map(|i| 8 + i.extents.len() * 8).sum::<usize>()+ + (8 + 8) // gain item, one extent+ + (8 + 8); // tmap item, one extent+ let _ = new_items_len;+ let iloc_box_len = iloc_payload_len + 8;++ let mut meta_len = 4usize;+ for child in &children {+ meta_len += match &child.typ {+ b"iinf" => iinf_box.len(),+ b"iloc" => iloc_box_len,+ b"iref" => iref_box.len(),+ b"iprp" => iprp_box.len(),+ _ => child.payload.end - child.start,+ };+ }+ if iref_is_new {+ meta_len += iref_box.len();+ }+ let new_meta_total = meta_len + 8;+ let old_meta_total = meta.payload.end - meta.start;+ let delta = new_meta_total as i64 - old_meta_total as i64;+ let mdat_start = (base_avif.len() as i64 + delta) as usize;+ let gain_offset = mdat_start + 8;+ let tmap_offset = gain_offset + gain_bitstream.len();++ let mut iloc_payload = Vec::new();+ iloc_payload.extend_from_slice(&[1u8, 0, 0, 0]);+ iloc_payload.push((4 << 4) | 4);+ iloc_payload.push(0);+ iloc_payload.extend_from_slice(&((iloc_items.len() + 2) as u16).to_be_bytes());+ let shift = |offset: u64| -> Option<u32> {+ let adjusted =+ if offset as usize >= meta.payload.end { offset as i64 + delta } else { offset as i64 };+ u32::try_from(adjusted).ok()+ };+ for item in &iloc_items {+ iloc_payload.extend_from_slice(&(item.item_id as u16).to_be_bytes());+ iloc_payload.extend_from_slice(&0u16.to_be_bytes());+ iloc_payload.extend_from_slice(&0u16.to_be_bytes());+ iloc_payload.extend_from_slice(&(item.extents.len() as u16).to_be_bytes());+ for &(offset, length) in &item.extents {+ iloc_payload.extend_from_slice(&shift(offset)?.to_be_bytes());+ iloc_payload.extend_from_slice(&(length as u32).to_be_bytes());+ }+ }+ for (id, offset, len) in+ [(gain_id, gain_offset, gain_bitstream.len()), (tmap_id, tmap_offset, tmap_metadata.len())]+ {+ iloc_payload.extend_from_slice(&(id as u16).to_be_bytes());+ iloc_payload.extend_from_slice(&0u16.to_be_bytes());+ iloc_payload.extend_from_slice(&0u16.to_be_bytes());+ iloc_payload.extend_from_slice(&1u16.to_be_bytes());+ iloc_payload.extend_from_slice(&(offset as u32).to_be_bytes());+ iloc_payload.extend_from_slice(&(len as u32).to_be_bytes());+ }+ let iloc_box = box_bytes(b"iloc", &iloc_payload)?;+ debug_assert_eq!(iloc_box.len(), iloc_box_len);++ // --- Reassemble.+ let mut out = Vec::with_capacity(tmap_offset + tmap_metadata.len());+ out.extend_from_slice(&base_avif[..meta.start]);+ let meta_box = {+ let mut payload = Vec::with_capacity(meta_len);+ payload.extend_from_slice(base_avif.get(meta.payload.start..meta.payload.start + 4)?);+ for child in &children {+ match &child.typ {+ b"iinf" => payload.extend_from_slice(&iinf_box),+ b"iloc" => payload.extend_from_slice(&iloc_box),+ b"iref" => payload.extend_from_slice(&iref_box),+ b"iprp" => payload.extend_from_slice(&iprp_box),+ _ => payload.extend_from_slice(&raw_child(child)),+ }+ }+ if iref_is_new {+ payload.extend_from_slice(&iref_box);+ }+ box_bytes(b"meta", &payload)?+ };+ out.extend_from_slice(&meta_box);+ out.extend_from_slice(&base_avif[meta.payload.end..]);+ debug_assert_eq!(out.len(), mdat_start);+ let mut mdat_payload = Vec::with_capacity(gain_bitstream.len() + tmap_metadata.len());+ mdat_payload.extend_from_slice(&gain_bitstream);+ mdat_payload.extend_from_slice(&tmap_metadata);+ out.extend_from_slice(&box_bytes(b"mdat", &mdat_payload)?);+ Some(out)+}++/// Extracts (bitstream, property boxes) of the primary item of a+/// standalone ravif-encoded gain-map AVIF.+fn harvest_gain_item(gain_avif: &[u8]) -> Option<(Vec<u8>, Vec<(u16, Vec<u8>)>)> {+ let top = parse_boxes(gain_avif, 0..gain_avif.len());+ let meta = top.iter().find(|b| &b.typ == b"meta")?;+ let children = parse_boxes(gain_avif, (meta.payload.start + 4)..meta.payload.end);+ let primary_id = primary_id_of(gain_avif, &children)?;+ let iloc = children.iter().find(|b| &b.typ == b"iloc")?;+ let bitstream = item_extents(gain_avif, iloc, primary_id)?;+ let iprp = children.iter().find(|b| &b.typ == b"iprp")?;+ let (ipco_boxes, ipma_entries, _, _) = parse_iprp(gain_avif, iprp)?;+ let entry = ipma_entries.iter().find(|e| e.item_id == primary_id)?;+ let index_mask: u16 = 0x7FFF;+ let mut props = Vec::new();+ for raw in &entry.properties {+ let index = raw & index_mask;+ // version-0 files use a 7-bit index; masking with 0x7FFF still+ // yields the right slot because essential is the top bit and+ // indices here are < 128 in both encodings we produce/consume.+ let index = if index > 0x7F && ipco_boxes.len() <= 0x7F { raw & 0x7F } else { index };+ props.push((*raw, ipco_boxes.get((index as usize).checked_sub(1)?)?.clone()));+ }+ Some((bitstream, props))+}++struct SimpleIlocItem {+ item_id: u32,+ construction_method: u16,+ extents: Vec<(u64, u64)>,+}++fn parse_iloc_items(bytes: &[u8], iloc: &BoxSpan) -> Option<Vec<SimpleIlocItem>> {+ let mut pos = iloc.payload.start + 4;+ let version = *bytes.get(iloc.payload.start)?;+ 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 index_size = (base_sizes & 0x0F) as usize;+ let item_count = if version == 2 {+ read_uint(bytes, &mut pos, 4)? as usize+ } else {+ read_uint(bytes, &mut pos, 2)? as usize+ };+ let mut items = Vec::with_capacity(item_count);+ for _ in 0..item_count {+ let item_id = read_uint(bytes, &mut pos, 2)? as u32;+ let construction =+ if version == 1 || version == 2 { read_uint(bytes, &mut pos, 2)? as u16 } else { 0 };+ read_uint(bytes, &mut pos, 2)?;+ let base_offset = read_uint(bytes, &mut pos, base_offset_size)?;+ let extent_count = read_uint(bytes, &mut pos, 2)? as usize;+ let mut extents = Vec::with_capacity(extent_count);+ for _ in 0..extent_count {+ if (version == 1 || version == 2) && 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)?;+ extents.push((base_offset + offset, length));+ }+ items.push(SimpleIlocItem { item_id, construction_method: construction, extents });+ }+ Some(items)+}++/// Encodes an Ultra HDR AVIF in one call: SDR base (with Exif) plus+/// the gain map from `gain_gray`, muxed as a `tmap` item.+#[allow(clippy::too_many_arguments)]+pub fn encode_avif_ultra_hdr(+ rgba: &[u8],+ width: usize,+ height: usize,+ quality: f32,+ speed: u8,+ exif: Option<&[u8]>,+ gain_gray: &[u8],+ gain_width: usize,+ gain_height: usize,+ params: &GainMapParams,+) -> Option<Vec<u8>> {+ let base = encode_avif_with_exif(rgba, width, height, quality, speed, exif)?;+ mux_avif_gain_map(&base, gain_gray, gain_width, gain_height, params, quality, speed)+}++#[cfg(test)]+#[path = "avif_gainmap_tests.rs"]+mod avif_gainmap_tests;++jni_fn! { /// JNI entry for `StitchNative.encodeAvifUltraHdr`: base RGBA ++/// Exif TIFF (empty = none) + grayscale gain map + seven metadata+/// floats in, Ultra HDR AVIF bytes out; null on any failure so Kotlin+/// falls back to JPEG_R (never an SDR-only AVIF for an HDR shot).+Java_com_vayunmathur_camera_platform_StitchNative_encodeAvifUltraHdr -> jni::sys::jbyteArray; (_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>, gain_gray: jni::objects::JByteArray<'l>, gain_width: jni::sys::jint, gain_height: jni::sys::jint, gain_min: jni::sys::jfloat, gain_max: jni::sys::jfloat, gain_gamma: jni::sys::jfloat, offset_sdr: jni::sys::jfloat, offset_hdr: jni::sys::jfloat, hdr_capacity_min: jni::sys::jfloat, hdr_capacity_max: jni::sys::jfloat) |env| {+ let null = std::ptr::null_mut();+ if width <= 0 || height <= 0 || gain_width <= 0 || gain_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 gain_bytes = match env.convert_byte_array(&gain_gray) { Ok(b) => b, Err(_) => return Ok(null) };+ let exif_ref = if exif_bytes.is_empty() { None } else { Some(exif_bytes.as_slice()) };+ let params = GainMapParams { min: gain_min, max: gain_max, gamma: gain_gamma, offset_sdr, offset_hdr, hdr_capacity_min, hdr_capacity_max };+ let encoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ encode_avif_ultra_hdr(&bytes, width as usize, height as usize, quality, speed.clamp(1, 10) as u8, exif_ref, &gain_bytes, gain_width as usize, gain_height as usize, ¶ms)+ })).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),+ }+ } }
camera/src/main/rust/src/avif_gainmap_parse.rs
diff --git a/camera/src/main/rust/src/avif_gainmap_parse.rs b/camera/src/main/rust/src/avif_gainmap_parse.rsnew file mode 100644index 0000000000..a704054c35--- /dev/null+++ b/camera/src/main/rust/src/avif_gainmap_parse.rs@@ -0,0 +1,338 @@+//! Parsing half of the AVIF gain-map support: ISO 21496-1 metadata+//! fractions, `iprp` (`ipco`/`ipma`) parsing/building, `iloc` extent+//! lookup, and the `tmap` detector used by tests and the viewer+//! contract. The mux itself lives in [`crate::avif_gainmap`].++use crate::avif_mux::{parse_boxes, read_uint, BoxSpan};++/// Gain-map metadata (single channel), mirroring+/// `com.vayunmathur.camera.domain.GainMapParams` on the Kotlin side.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct GainMapParams {+ pub min: f32,+ pub max: f32,+ pub gamma: f32,+ pub offset_sdr: f32,+ pub offset_hdr: f32,+ pub hdr_capacity_min: f32,+ pub hdr_capacity_max: f32,+}++impl Default for GainMapParams {+ fn default() -> Self {+ Self {+ min: 0.0,+ max: 2.0,+ gamma: 1.0,+ offset_sdr: 0.0,+ offset_hdr: 0.0,+ hdr_capacity_min: 0.0,+ hdr_capacity_max: 2.0,+ }+ }+}++const FRACTION_DENOMINATOR: f32 = 1_000_000.0;++fn write_fraction(out: &mut Vec<u8>, value: f32, signed: bool) {+ let numerator = (value * FRACTION_DENOMINATOR).round();+ if signed {+ out.extend_from_slice(&(numerator as i32).to_be_bytes());+ } else {+ out.extend_from_slice(&(numerator.max(0.0) as u32).to_be_bytes());+ }+ out.extend_from_slice(&(FRACTION_DENOMINATOR as u32).to_be_bytes());+}++fn read_fraction(bytes: &[u8], pos: &mut usize, signed: bool) -> Option<f32> {+ let numerator = if signed {+ i32::from_be_bytes(bytes.get(*pos..*pos + 4)?.try_into().ok()?) as f32+ } else {+ u32::from_be_bytes(bytes.get(*pos..*pos + 4)?.try_into().ok()?) as f32+ };+ *pos += 4;+ let denominator = u32::from_be_bytes(bytes.get(*pos..*pos + 4)?.try_into().ok()?) as f32;+ *pos += 4;+ if denominator == 0.0 {+ return None;+ }+ Some(numerator / denominator)+}++/// Serialises the `tmap` item payload (57 bytes).+pub fn gain_map_metadata_bytes(params: &GainMapParams) -> Vec<u8> {+ let mut out = Vec::with_capacity(57);+ write_fraction(&mut out, params.min, true);+ write_fraction(&mut out, params.max, true);+ write_fraction(&mut out, params.gamma, false);+ write_fraction(&mut out, params.offset_sdr, true);+ write_fraction(&mut out, params.offset_hdr, true);+ write_fraction(&mut out, params.hdr_capacity_min, false);+ write_fraction(&mut out, params.hdr_capacity_max, false);+ out.push(1); // use_base_colour_space+ out+}++/// Parses a `tmap` item payload written by [`gain_map_metadata_bytes`].+pub fn parse_gain_map_metadata(bytes: &[u8]) -> Option<GainMapParams> {+ let mut pos = 0usize;+ let params = GainMapParams {+ min: read_fraction(bytes, &mut pos, true)?,+ max: read_fraction(bytes, &mut pos, true)?,+ gamma: read_fraction(bytes, &mut pos, false)?,+ offset_sdr: read_fraction(bytes, &mut pos, true)?,+ offset_hdr: read_fraction(bytes, &mut pos, true)?,+ hdr_capacity_min: read_fraction(bytes, &mut pos, false)?,+ hdr_capacity_max: read_fraction(bytes, &mut pos, false)?,+ };+ Some(params)+}++/// One parsed `iprp` association entry.+pub(crate) struct IpmaEntry {+ pub(crate) item_id: u32,+ pub(crate) properties: Vec<u16>, // raw associations, essential bit kept+}++/// Parses `ipco` (raw child boxes) and `ipma` (entries) of an `iprp`.+pub(crate) fn parse_iprp(+ bytes: &[u8],+ iprp: &BoxSpan,+) -> Option<(Vec<Vec<u8>>, Vec<IpmaEntry>, u8, u32)> {+ let children = parse_boxes(bytes, iprp.payload.clone());+ let ipco = children.iter().find(|b| &b.typ == b"ipco")?;+ let ipma = children.iter().find(|b| &b.typ == b"ipma")?;+ let ipco_boxes: Vec<Vec<u8>> = parse_boxes(bytes, ipco.payload.clone())+ .iter()+ .map(|b| bytes[b.start..b.payload.end].to_vec())+ .collect();+ let version = *bytes.get(ipma.payload.start)?;+ let flags =+ u32::from_be_bytes(bytes.get(ipma.payload.start..ipma.payload.start + 4)?.try_into().ok()?);+ let mut pos = ipma.payload.start + 4;+ // ravif writes the entry count as u32 even with flags 0; accept the+ // u32 reading when the u16 reading would be zero.+ let entry_count = if flags & 1 != 0 {+ read_uint(bytes, &mut pos, 4)? as usize+ } else {+ let as_u16 = read_uint(bytes, &mut pos, 2)? as usize;+ if as_u16 == 0 {+ read_uint(bytes, &mut pos, 2)? as usize+ } else {+ as_u16+ }+ };+ let mut entries = Vec::with_capacity(entry_count);+ for _ in 0..entry_count {+ let item_id = if version >= 1 {+ read_uint(bytes, &mut pos, 4)? as u32+ } else {+ read_uint(bytes, &mut pos, 2)? as u32+ };+ let count = read_uint(bytes, &mut pos, 1)? as usize;+ let mut properties = Vec::with_capacity(count);+ for _ in 0..count {+ let raw = if version >= 1 {+ read_uint(bytes, &mut pos, 2)? as u16+ } else {+ read_uint(bytes, &mut pos, 1)? as u16+ };+ properties.push(raw);+ }+ entries.push(IpmaEntry { item_id, properties });+ }+ Some((ipco_boxes, entries, version, flags))+}++pub(crate) fn build_ipma(entries: &[IpmaEntry], version: u8, large_count: bool) -> Option<Vec<u8>> {+ let mut payload = Vec::new();+ payload.push(version);+ payload.extend_from_slice(&[0, 0, if large_count { 1 } else { 0 }]);+ if large_count {+ payload.extend_from_slice(&(entries.len() as u32).to_be_bytes());+ } else {+ payload.extend_from_slice(&(entries.len() as u16).to_be_bytes());+ }+ for entry in entries {+ if version >= 1 {+ payload.extend_from_slice(&entry.item_id.to_be_bytes());+ } else {+ payload.extend_from_slice(&(entry.item_id as u16).to_be_bytes());+ }+ payload.push(entry.properties.len() as u8);+ for index in &entry.properties {+ if version >= 1 {+ payload.extend_from_slice(&index.to_be_bytes());+ } else {+ payload.push(*index as u8);+ }+ }+ }+ box_bytes(b"ipma", &payload)+}++/// Locates one item's extents via `iloc` (absolute offset/length pairs).+pub(crate) fn item_extents(bytes: &[u8], iloc: &BoxSpan, want_id: u32) -> Option<Vec<u8>> {+ let mut pos = iloc.payload.start + 4;+ let version = *bytes.get(iloc.payload.start)?;+ 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 index_size = (base_sizes & 0x0F) as usize;+ let item_count = if 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 u32;+ if version == 1 || version == 2 {+ read_uint(bytes, &mut pos, 2)?;+ }+ read_uint(bytes, &mut pos, 2)?;+ let base_offset = read_uint(bytes, &mut pos, base_offset_size)?;+ let extent_count = read_uint(bytes, &mut pos, 2)? as usize;+ let mut data = Vec::new();+ let found = item_id == want_id;+ for _ in 0..extent_count {+ if (version == 1 || version == 2) && 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;+ data.extend_from_slice(bytes.get(start..start + length)?);+ }+ }+ if found {+ return Some(data);+ }+ }+ None+}++pub(crate) fn primary_id_of(bytes: &[u8], children: &[BoxSpan]) -> Option<u32> {+ let pitm = children.iter().find(|b| &b.typ == b"pitm")?;+ let version = *bytes.get(pitm.payload.start)?;+ if version == 1 {+ Some(u32::from_be_bytes(+ bytes.get(pitm.payload.start + 4..pitm.payload.start + 8)?.try_into().ok()?,+ ))+ } else {+ Some(u16::from_be_bytes(+ bytes.get(pitm.payload.start + 4..pitm.payload.start + 6)?.try_into().ok()?,+ ) as u32)+ }+}++pub(crate) fn infe_id_and_type(bytes: &[u8], infe: &BoxSpan) -> Option<(u32, [u8; 4])> {+ let p = infe.payload.start + 4;+ let id = u16::from_be_bytes(bytes.get(p..p + 2)?.try_into().ok()?) as u32;+ let typ: [u8; 4] = bytes.get(p + 4..p + 8)?.try_into().ok()?;+ Some((id, typ))+}++/// What the gain-map parser found in a file (test + viewer proof).+#[derive(Debug, Clone, PartialEq)]+pub struct GainMapInfo {+ pub primary_id: u32,+ pub gain_item_id: u32,+ pub tmap_item_id: u32,+ pub params: GainMapParams,+ pub gain_width: u32,+ pub gain_height: u32,+ pub gain_bitstream_len: usize,+ pub tmap_refs: Vec<u32>,+}++/// Parses an AVIF for its `tmap` gain map. `None` when absent/broken.+pub fn avif_gain_map(bytes: &[u8]) -> Option<GainMapInfo> {+ let top = parse_boxes(bytes, 0..bytes.len());+ let meta = top.iter().find(|b| &b.typ == b"meta")?;+ let children = parse_boxes(bytes, (meta.payload.start + 4)..meta.payload.end);+ let primary_id = primary_id_of(bytes, &children)?;+ let iinf = children.iter().find(|b| &b.typ == b"iinf")?;+ let mut pos = iinf.payload.start + 4;+ let version = *bytes.get(iinf.payload.start)?;+ if version == 1 {+ read_uint(bytes, &mut pos, 4)?;+ } else {+ read_uint(bytes, &mut pos, 2)?;+ }+ let infes = parse_boxes(bytes, pos..iinf.payload.end);+ let mut tmap_item_id = None;+ // Gain item is identified via the tmap dimg refs below; first find tmap.+ for infe in &infes {+ let (id, typ) = infe_id_and_type(bytes, infe)?;+ if &typ == b"tmap" {+ tmap_item_id = Some(id);+ }+ }+ let tmap_item_id = tmap_item_id?;+ // iref dimg from tmap: [gain, base]+ let iref = children.iter().find(|b| &b.typ == b"iref")?;+ let iref_version = *bytes.get(iref.payload.start)?;+ let id_bytes = if iref_version == 1 { 4 } else { 2 };+ let ref_boxes = parse_boxes(bytes, (iref.payload.start + 4)..iref.payload.end);+ let mut tmap_refs = Vec::new();+ for rb in &ref_boxes {+ if &rb.typ != b"dimg" {+ continue;+ }+ let mut p = rb.payload.start;+ let from = read_uint(bytes, &mut p, id_bytes)? as u32;+ if from != tmap_item_id {+ continue;+ }+ let count = read_uint(bytes, &mut p, 2)? as usize;+ for _ in 0..count {+ tmap_refs.push(read_uint(bytes, &mut p, id_bytes)? as u32);+ }+ }+ if tmap_refs.len() != 2 || tmap_refs[1] != primary_id {+ return None;+ }+ let gain_item_id = tmap_refs[0];+ let iloc = children.iter().find(|b| &b.typ == b"iloc")?;+ let tmap_data = item_extents(bytes, iloc, tmap_item_id)?;+ let params = parse_gain_map_metadata(&tmap_data)?;+ let gain_data = item_extents(bytes, iloc, gain_item_id)?;+ // Gain dimensions from its ispe property via iprp.+ let iprp = children.iter().find(|b| &b.typ == b"iprp")?;+ let (ipco_boxes, ipma_entries, _, _) = parse_iprp(bytes, iprp)?;+ let gain_entry = ipma_entries.iter().find(|e| e.item_id == gain_item_id)?;+ let mut gain_width = 0u32;+ let mut gain_height = 0u32;+ for raw_assoc in &gain_entry.properties {+ let index = raw_assoc & 0x7F;+ let raw = ipco_boxes.get((index as usize).checked_sub(1)?)?;+ if raw.len() >= 8 && &raw[4..8] == b"ispe" {+ gain_width = u32::from_be_bytes(raw.get(12..16)?.try_into().ok()?);+ gain_height = u32::from_be_bytes(raw.get(16..20)?.try_into().ok()?);+ }+ }+ Some(GainMapInfo {+ primary_id,+ gain_item_id,+ tmap_item_id,+ params,+ gain_width,+ gain_height,+ gain_bitstream_len: gain_data.len(),+ tmap_refs,+ })+}++pub(crate) fn box_bytes(typ: &[u8; 4], payload: &[u8]) -> Option<Vec<u8>> {+ let size = u32::try_from(payload.len().checked_add(8)?).ok()?;+ let mut out = Vec::with_capacity(size as usize);+ out.extend_from_slice(&size.to_be_bytes());+ out.extend_from_slice(typ);+ out.extend_from_slice(payload);+ Some(out)+}
camera/src/main/rust/src/avif_gainmap_tests.rs
diff --git a/camera/src/main/rust/src/avif_gainmap_tests.rs b/camera/src/main/rust/src/avif_gainmap_tests.rsnew file mode 100644index 0000000000..8ac9e30b60--- /dev/null+++ b/camera/src/main/rust/src/avif_gainmap_tests.rs@@ -0,0 +1,136 @@+use super::{+ avif_gain_map, encode_avif_ultra_hdr, gain_map_metadata_bytes, mux_avif_gain_map,+ parse_gain_map_metadata, GainMapParams,+};+use crate::avif::{avif_dimensions, avif_exif_tiff, encode_avif, has_avif_magic};+use crate::avif_mux::{avif_motion_video, mux_avif_motion_photo};++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+}++fn gain_map(width: usize, height: usize) -> Vec<u8> {+ (0..width * height).map(|i| (i % 256) as u8).collect()+}++#[test]+fn metadata_fractions_round_trip() {+ let params = GainMapParams {+ min: -0.5,+ max: 3.25,+ gamma: 1.5,+ offset_sdr: 0.0625,+ offset_hdr: 0.125,+ hdr_capacity_min: 0.0,+ hdr_capacity_max: 3.25,+ };+ let bytes = gain_map_metadata_bytes(¶ms);+ assert_eq!(bytes.len(), 57);+ let parsed = parse_gain_map_metadata(&bytes).expect("metadata must parse");+ assert!((parsed.min - params.min).abs() < 1e-5);+ assert!((parsed.max - params.max).abs() < 1e-5);+ assert!((parsed.gamma - params.gamma).abs() < 1e-5);+ assert!((parsed.hdr_capacity_max - params.hdr_capacity_max).abs() < 1e-5);+}++#[test]+fn gain_map_mux_round_trips_through_boxes() {+ let rgba = gradient(64, 48);+ let base = encode_avif(&rgba, 64, 48, 80.0, 10).expect("base encode");+ assert!(avif_gain_map(&base).is_none(), "plain AVIF has no gain map");+ let params = GainMapParams::default();+ let muxed = mux_avif_gain_map(&base, &gain_map(64, 48), 64, 48, ¶ms, 80.0, 10)+ .expect("gain-map mux must succeed");+ assert!(has_avif_magic(&muxed));+ assert_eq!(avif_dimensions(&muxed), Some((64, 48)), "base item intact");+ let info = avif_gain_map(&muxed).expect("tmap must be found via iinf/iref/iloc");+ assert_eq!(info.tmap_refs, vec![info.gain_item_id, info.primary_id]);+ assert_ne!(info.gain_item_id, info.primary_id);+ assert_ne!(info.tmap_item_id, info.primary_id);+ assert_eq!((info.gain_width, info.gain_height), (64, 48));+ assert!(info.gain_bitstream_len > 0, "gain AV1 bitstream present");+ assert!((info.params.max - 2.0).abs() < 1e-5);+ assert!((info.params.hdr_capacity_max - 2.0).abs() < 1e-5);+ // Second mux refuses (already Ultra HDR); bad inputs refuse.+ assert!(mux_avif_gain_map(&muxed, &gain_map(64, 48), 64, 48, ¶ms, 80.0, 10).is_none());+ assert!(mux_avif_gain_map(&base, &[0u8; 3], 64, 48, ¶ms, 80.0, 10).is_none());+ assert!(mux_avif_gain_map(b"not an avif", &gain_map(4, 4), 4, 4, ¶ms, 80.0, 10).is_none());+}++#[test]+fn ultra_hdr_encode_keeps_exif_and_gain_map() {+ let rgba = gradient(48, 32);+ let mut tiff = Vec::new();+ tiff.extend_from_slice(b"II\x2a\0");+ tiff.extend_from_slice(&8u32.to_le_bytes());+ tiff.extend_from_slice(&0u16.to_le_bytes());+ tiff.extend_from_slice(&0u32.to_le_bytes());+ let bytes = encode_avif_ultra_hdr(+ &rgba,+ 48,+ 32,+ 80.0,+ 10,+ Some(&tiff),+ &gain_map(48, 32),+ 48,+ 32,+ &GainMapParams::default(),+ )+ .expect("ultra hdr encode must succeed");+ assert!(has_avif_magic(&bytes));+ assert_eq!(avif_exif_tiff(&bytes).expect("exif survives"), tiff);+ let info = avif_gain_map(&bytes).expect("gain map survives beside exif");+ assert_eq!((info.gain_width, info.gain_height), (48, 32));+}++#[test]+fn ultra_hdr_then_motion_mux_keeps_both() {+ // Combined Motion Photo + Ultra HDR, in production order: the+ // gain-map encode lands first, then the motion mux splices the+ // XMP item and appends the MP4 as the true EOF trailer. Both+ // detectors must still find their payload on the result — the+ // gain-map (tmap/iloc) walk and the motion (XMP iloc + trailer+ // counted back from EOF) walk the Photos parsers mirror.+ let rgba = gradient(48, 32);+ let ultra = encode_avif_ultra_hdr(+ &rgba,+ 48,+ 32,+ 80.0,+ 10,+ None,+ &gain_map(48, 32),+ 48,+ 32,+ &GainMapParams::default(),+ )+ .expect("ultra hdr encode must succeed");+ let before = avif_gain_map(&ultra).expect("gain map before motion mux");+ let mp4: Vec<u8> = (0..512u32).map(|i| (i % 251) as u8).collect();+ let xmp = format!(+ "<x:xmpmeta><rdf:RDF><rdf:Description GCamera:MotionPhoto=\"1\" \+ GCamera:MicroVideo=\"1\" GCamera:MicroVideoOffset=\"{}\"/></rdf:RDF></x:xmpmeta>",+ mp4.len()+ )+ .into_bytes();+ let combined = mux_avif_motion_photo(&ultra, &xmp, &mp4).expect("motion mux must succeed");+ assert!(has_avif_magic(&combined));+ assert_eq!(avif_dimensions(&combined), Some((48, 32)), "base item intact");+ let after = avif_gain_map(&combined).expect("tmap must survive the motion mux");+ assert_eq!(after.tmap_refs, before.tmap_refs);+ assert_eq!((after.gain_width, after.gain_height), (48, 32));+ assert!(after.gain_bitstream_len > 0);+ assert_eq!(+ avif_motion_video(&combined),+ Some(mp4.as_slice()),+ "clip is the trailing bytes, counted back from EOF"+ );+ assert!(combined.ends_with(&mp4));+}
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 fff079255d..d77e7c2d4e 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -9,6 +9,8 @@ pub use vision_core::{camera, features, geometry, imgbuf, linalg}; mod avif;+mod avif_gainmap;+mod avif_gainmap_parse; mod avif_mux; mod blend; mod bundle;
camera/src/test/java/com/vayunmathur/camera/domain/GainMapMathTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/GainMapMathTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/GainMapMathTest.ktnew file mode 100644index 0000000000..1de8bcf3c9--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/GainMapMathTest.kt@@ -0,0 +1,47 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class GainMapMathTest {++ @Test+ fun identicalHdrAndSdrEncodeZeroGain() {+ assertEquals(0, GainMapMath.encodeGainByte(hdr = 0.5f, sdr = 0.5f))+ assertEquals(1f, GainMapMath.decodeRatio(0), 1e-6f)+ }++ @Test+ fun fourTimesBrighterIsFullGainAtDefaultParams() {+ // Default max is 2 stops: log2(4) = 2 -> normalised 1 -> 255.+ assertEquals(255, GainMapMath.encodeGainByte(hdr = 1.0f, sdr = 0.25f))+ assertEquals(4f, GainMapMath.decodeRatio(255), 1e-3f)+ }++ @Test+ fun encodeDecodeRoundTripsWithinQuantisation() {+ for (ratio in listOf(1.0f, 1.5f, 2.0f, 3.0f, 4.0f)) {+ val byte = GainMapMath.encodeGainByte(hdr = ratio * 0.2f, sdr = 0.2f)+ val decoded = GainMapMath.decodeRatio(byte)+ assertTrue(kotlin.math.abs(decoded - ratio) / ratio < 0.03f, "ratio $ratio -> $byte -> $decoded")+ }+ }++ @Test+ fun headroomScalesTheBoost() {+ // Half headroom applies half the stops: 2^(2 * 0.5) = 2x.+ assertEquals(2f, GainMapMath.decodeRatio(255, headroom = 0.5f), 1e-3f)+ assertEquals(1f, GainMapMath.decodeRatio(255, headroom = 0f), 1e-6f)+ }++ @Test+ fun planeEncodeMatchesPerPixelEncode() {+ val hdr = floatArrayOf(0.2f, 0.4f, 0.8f)+ val sdr = floatArrayOf(0.2f, 0.2f, 0.2f)+ val bytes = GainMapMath.encodeGainMap(hdr, sdr)+ assertEquals(3, bytes.size)+ assertEquals(0, bytes[0].toInt() and 0xFF)+ assertEquals(255, bytes[2].toInt() and 0xFF)+ }+}
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 9d0c59b344..14827af23e 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt@@ -114,9 +114,10 @@ class StillFormatRoutingTest { StillFormatRouting.StillSaveRoute.PROCESSED_ENCODER, StillFormatRouting.stillSaveRoute(StillFormat.AVIF, ultraHdrSource = false), )- // Ultra HDR sources stay JPEG_R under either selection.+ // Ultra HDR sources under AVIF route to the tmap gain-map+ // encoder; under JPEG they stay JPEG_R. assertEquals(- StillFormatRouting.StillSaveRoute.ULTRA_HDR_JPEG_BYTES,+ StillFormatRouting.StillSaveRoute.AVIF_GAINMAP, StillFormatRouting.stillSaveRoute(StillFormat.AVIF, ultraHdrSource = true), ) assertEquals(
camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.ktindex 7e84fecfce..f576c59e0a 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt@@ -112,11 +112,13 @@ class Camera2AvifRoutingTest { assertEquals("image/jpeg", savedMime(uri)) } - @Test fun ultraHdrTaggedStillStaysJpegRUnderAvif() {+ @Test fun ultraHdrTaggedStillFallsBackToJpegRWhenNoGainMapExtractable() { val viewModel = vm() viewModel.photoFormatMutable.value = PhotoFormat.AVIF // Plain header bytes: only the JPEG_R output tag marks this Ultra- // HDR, so a header-sniff-only check would wrongly encode it.+ // HDR. Under AVIF it routes to the tmap gain-map encoder, but the+ // host bitmap carries no platform gain map, so it must fall back+ // to JPEG_R bytes rather than landing as an SDR-only AVIF. val uri = viewModel.saveCamera2Still( still(jpegBytes(), StillOutputTag.ULTRA_HDR_JPEG_R), )