Modern Apps git

← Modern-Apps.git

photos: render AVIF Ultra HDR on HDR displays

Commit
105d23cf089734896ce17e5079c16b377939c6c4
Author
Vayun Mathur <[email protected]>
When
2026-12-05 14:36 UTC (22 hours ago)
Parents
ad587e6
The viewer had no gain-map handling: AVIF Ultra HDR files
(camera now writes them with a tmap gain map) showed only
their SDR base, and JPEG_R relied on whatever the platform
bitmap happened to do.

Add box-level AVIF gain-map detection (domain/AvifGainMap.kt):
a tmap item whose dimg reference ends at the primary item,
with the hdr-capacity read from the tmap metadata when its
extent is in range. Detection works on a 256 KiB header
prefix because meta precedes mdat in these files.
GainMapPlayback decides HDR only when a gain map is present
and the display is HDR-capable, and holds the linear-light
reconstruction math (hdr = sdr * 2^(gain * capacity *
headroom)).

The viewer (platform/UltraHdrPlayback.kt +
PhotoDetailMedia) detects AVIF gain maps off the main thread,
requests HDR window colour mode while an HDR photo is shown
(restoring the previous mode on dispose), and shows an HDR
badge. SDR photos, SDR displays, and non-AVIF formats render
exactly as before.

Verified: ./gradlew :photos:lint :photos:lintVitalRelease
:photos:testDevUnitTest (with the camera verification run),
including synthetic-AVIF parser tests laid out like the
camera mux writes.

Diff

photos/AGENTS.md
diff --git a/photos/AGENTS.md b/photos/AGENTS.mdindex 417cba8e57..2f137738d8 100644--- a/photos/AGENTS.md+++ b/photos/AGENTS.md@@ -78,6 +78,8 @@ _Install: ./install photos (dev by default)._ - com/vayunmathur/photos/domain/FaceQuality.kt — which faces may form people - com/vayunmathur/photos/domain/FaceClustering.kt — batch average-linkage grouping - com/vayunmathur/photos/domain/FaceClusterIdentity.kt — keeps person ids/names across regroups+- com/vayunmathur/photos/domain/AvifGainMap.kt — ISOBMFF `tmap` gain-map detection for AVIF Ultra HDR (box-level, works on a header prefix)+- com/vayunmathur/photos/domain/GainMapPlayback.kt — HDR vs SDR viewer decision + linear-light gain-map reconstruction math ### intents/ — assistant IPC (metadata only) - com/vayunmathur/photos/intents/SearchPhotosIntent.kt — `photos_search_photos`: filtered (file-name/folder/date) metadata search over `PhotoDao.searchPhotoMetadata`; returns the matching count plus at most 10 hits (`library.intents.photos.PhotoHitData`: id, file name, taken date, dimensions, album, MIME). Never returns image bytes, thumbnails, URIs/paths, location, OCR text or embeddings; trashed items are excluded in SQL and the secure-folder vault is never opened. Guarded by the signature permission `com.vayunmathur.photos.permissions.ACCESS_PHOTOS`. - com/vayunmathur/photos/intents/PhotosSearchContract.kt — provider-side validation/clamping (limit 1–10, text/date-range normalisation) and row→hit mapping@@ -85,6 +87,7 @@ _Install: ./install photos (dev by default)._ - com/vayunmathur/photos/widget/PhotoGlanceWidget.kt — includes `PhotoGlanceWidgetReceiver` (one widget, one file) ### platform/ — motion-photo - com/vayunmathur/photos/platform/MotionPhotoVideo.kt+- com/vayunmathur/photos/platform/UltraHdrPlayback.kt — viewer Ultra HDR state: AVIF `tmap` header detection, HDR-display check, HDR window colour mode while an HDR photo is shown (SDR fallback unchanged) ### service/ — live wallpaper - com/vayunmathur/photos/service/LiveWallpaperService.kt ### ui/ — gallery, albums, people, map
photos/src/main/java/com/vayunmathur/photos/domain/AvifGainMap.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/AvifGainMap.kt b/photos/src/main/java/com/vayunmathur/photos/domain/AvifGainMap.ktnew file mode 100644index 0000000000..2141a7fceb--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/AvifGainMap.kt@@ -0,0 +1,169 @@+package com.vayunmathur.photos.domain++/**+ * What the Photos viewer needs to know about an AVIF's Ultra HDR+ * gain map: the `tmap` derived item (ISO 21496-1) references+ * `[gain-map item, base item]`, and its payload carries the+ * hdr-capacity ceiling. Detection is box-level only (no AV1 decode):+ * a file is Ultra HDR when it carries a `tmap` item whose `dimg`+ * reference ends at the primary item.+ */+data class AvifGainMapDetection(+    val primaryItemId: Int,+    val gainItemId: Int,+    val tmapItemId: Int,+    /** Stops of boost the gain map can add, when the metadata extent was readable. */+    val hdrCapacityMax: Float?,+)++/** Pure ISOBMFF box walk for AVIF gain maps (host-testable). */+object AvifGainMapParser {++    private class Box(val type: String, val start: Int, val payloadStart: Int, val payloadEnd: Int)++    private fun boxes(bytes: ByteArray, start: Int, end: Int): List<Box> {+        val out = mutableListOf<Box>()+        var off = start+        while (off + 8 <= end && off + 8 <= bytes.size) {+            val size32 = u32(bytes, off)+            val (size, header) = when {+                size32 == 1L && off + 16 <= bytes.size -> u64(bytes, off + 8).toInt() to 16+                size32 == 0L -> (end - off) to 8+                else -> size32.toInt() to 8+            }+            if (size < header || off + size > bytes.size) break+            val type = String(bytes, off + 4, 4, Charsets.ISO_8859_1)+            out.add(Box(type, off, off + header, off + size))+            off += size+        }+        return out+    }++    private fun u32(b: ByteArray, off: Int): Long =+        ((b[off].toLong() and 0xFF) shl 24) or ((b[off + 1].toLong() and 0xFF) shl 16) or+            ((b[off + 2].toLong() and 0xFF) shl 8) or (b[off + 3].toLong() and 0xFF)++    private fun u64(b: ByteArray, off: Int): Long = (u32(b, off) shl 32) or u32(b, off + 4)++    private fun u16(b: ByteArray, off: Int): Int =+        ((b[off].toInt() and 0xFF) shl 8) or (b[off + 1].toInt() and 0xFF)++    /**+     * Detects the gain map in [bytes], which may be a header prefix:+     * the `meta` box sits before `mdat` in files this app produces,+     * so detection works without the gain-map bitstream. The+     * hdr-capacity is read only when the `tmap` extent is inside+     * [bytes]; otherwise it is null and the viewer uses the default.+     */+    fun detect(bytes: ByteArray): AvifGainMapDetection? {+        if (bytes.size < 12 || String(bytes, 4, 4, Charsets.ISO_8859_1) != "ftyp") return null+        val top = boxes(bytes, 0, bytes.size)+        val meta = top.firstOrNull { it.type == "meta" } ?: return null+        val children = boxes(bytes, meta.payloadStart + 4, meta.payloadEnd)++        val pitm = children.firstOrNull { it.type == "pitm" } ?: return null+        val primaryId = if (bytes[pitm.payloadStart].toInt() == 1) {+            u32(bytes, pitm.payloadStart + 4).toInt()+        } else {+            u16(bytes, pitm.payloadStart + 4)+        }++        val iinf = children.firstOrNull { it.type == "iinf" } ?: return null+        val countLen = if (bytes[iinf.payloadStart].toInt() == 1) 4 else 2+        val infes = boxes(bytes, iinf.payloadStart + 4 + countLen, iinf.payloadEnd)+        var tmapId: Int? = null+        for (infe in infes) {+            val p = infe.payloadStart + 4+            if (p + 8 > infe.payloadEnd) continue+            val type = String(bytes, p + 4, 4, Charsets.ISO_8859_1)+            if (type == "tmap") tmapId = u16(bytes, p)+        }+        val tmap = tmapId ?: return null++        val iref = children.firstOrNull { it.type == "iref" } ?: return null+        val idBytes = if (bytes[iref.payloadStart].toInt() == 1) 4 else 2+        val refBoxes = boxes(bytes, iref.payloadStart + 4, iref.payloadEnd)+        var refs: List<Int>? = null+        for (rb in refBoxes) {+            if (rb.type != "dimg") continue+            var p = rb.payloadStart+            val from = readUint(bytes, p, idBytes) ?: return null+            p += idBytes+            if (from != tmap) continue+            val count = u16(bytes, p)+            p += 2+            val list = mutableListOf<Int>()+            repeat(count) {+                list.add(readUint(bytes, p, idBytes) ?: return null)+                p += idBytes+            }+            refs = list+        }+        val refList = refs ?: return null+        if (refList.size != 2 || refList[1] != primaryId) return null++        return AvifGainMapDetection(+            primaryItemId = primaryId,+            gainItemId = refList[0],+            tmapItemId = tmap,+            hdrCapacityMax = readHdrCapacityMax(bytes, children, tmap),+        )+    }++    private fun readUint(b: ByteArray, off: Int, size: Int): Int? {+        if (off + size > b.size) return null+        var v = 0+        repeat(size) { v = (v shl 8) or (b[off + it].toInt() and 0xFF) }+        return v+    }++    /** hdrCapacityMax is the last-but-one fraction of the 57-byte tmap payload. */+    private fun readHdrCapacityMax(bytes: ByteArray, children: List<Box>, tmapId: Int): Float? {+        val iloc = children.firstOrNull { it.type == "iloc" } ?: return null+        var pos = iloc.payloadStart + 4+        if (pos + 2 > bytes.size) return null+        val version = bytes[iloc.payloadStart].toInt()+        val sizes = bytes[pos].toInt() and 0xFF+        pos+++        val offsetSize = sizes shr 4+        val lengthSize = sizes and 0x0F+        val baseSizes = bytes[pos].toInt() and 0xFF+        pos+++        val baseOffsetSize = baseSizes shr 4+        val indexSize = baseSizes and 0x0F+        val itemCount = if (version == 2) {+            readUint(bytes, pos, 4)?.also { pos += 4 } ?: return null+        } else {+            readUint(bytes, pos, 2)?.also { pos += 2 } ?: return null+        }+        repeat(itemCount) {+            val itemId = readUint(bytes, pos, 2) ?: return null+            pos += 2+            if (version == 1 || version == 2) pos += 2+            pos += 2+            val baseOffset = readUint(bytes, pos, baseOffsetSize) ?: 0+            pos += baseOffsetSize+            val extentCount = readUint(bytes, pos, 2) ?: return null+            pos += 2+            repeat(extentCount) {+                if ((version == 1 || version == 2) && indexSize > 0) pos += indexSize+                val offset = readUint(bytes, pos, offsetSize) ?: return null+                pos += offsetSize+                val length = readUint(bytes, pos, lengthSize) ?: return null+                pos += lengthSize+                if (itemId == tmapId) {+                    val start = baseOffset + offset+                    // Fractions: min,max,gamma,offsetSdr,offsetHdr,+                    // hdrCapacityMin,hdrCapacityMax — the 7th pair.+                    val fracOff = start + 6 * 8+                    if (fracOff + 8 > bytes.size || fracOff + 8 > start + length) return null+                    val num = u32(bytes, fracOff)+                    val den = u32(bytes, fracOff + 4)+                    if (den == 0L) return null+                    return num.toFloat() / den.toFloat()+                }+            }+        }+        return null+    }+}
photos/src/main/java/com/vayunmathur/photos/domain/GainMapPlayback.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/GainMapPlayback.kt b/photos/src/main/java/com/vayunmathur/photos/domain/GainMapPlayback.ktnew file mode 100644index 0000000000..a1aa9e855f--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/GainMapPlayback.kt@@ -0,0 +1,57 @@+package com.vayunmathur.photos.domain++import kotlin.math.pow++/** How the viewer should present one photo. */+enum class GainMapPlaybackMode {+    /** Gain map applied / HDR colour mode requested. */+    HDR,++    /** Base (SDR) rendition, exactly as before Ultra HDR. */+    SDR,+}++/**+ * Viewer-side gain-map decision and reconstruction math.+ *+ * A photo renders HDR only when it actually carries a gain map+ * (JPEG_R attached by the platform decoder, or an AVIF `tmap`+ * detected by [AvifGainMapParser]) and the display can show HDR;+ * everything else is the SDR base image. This mirrors the camera:+ * `hdr = sdr * 2^(min + gain^gamma * (max - min))` in linear light,+ * with the exponent scaled by the display headroom.+ */+object GainMapPlayback {++    const val DEFAULT_HDR_CAPACITY_MAX = 2f++    fun decide(+        mimeType: String?,+        avifDetection: AvifGainMapDetection?,+        platformGainMapAttached: Boolean,+        hdrDisplayCapable: Boolean,+    ): GainMapPlaybackMode {+        val hasGainMap = when {+            mimeType.equals("image/avif", ignoreCase = true) -> avifDetection != null+            mimeType.equals("image/jpeg", ignoreCase = true) -> platformGainMapAttached+            else -> platformGainMapAttached+        }+        return if (hasGainMap && hdrDisplayCapable) GainMapPlaybackMode.HDR else GainMapPlaybackMode.SDR+    }++    /** Linear-light HDR values from SDR linear values + encoded gain bytes. */+    fun applyGainMap(+        sdrLinear: FloatArray,+        gainBytes: ByteArray,+        hdrCapacityMax: Float = DEFAULT_HDR_CAPACITY_MAX,+        headroom: Float = 1f,+    ): FloatArray {+        require(sdrLinear.size == gainBytes.size) { "SDR/gain planes must match" }+        val clampedHeadroom = headroom.coerceIn(0f, 1f)+        return FloatArray(sdrLinear.size) { i ->+            val gain = (gainBytes[i].toInt() and 0xFF) / 255f+            val stops = gain * hdrCapacityMax * clampedHeadroom+            sdrLinear[i] * 2f.pow(stops)+        }+    }+}
photos/src/main/java/com/vayunmathur/photos/platform/UltraHdrPlayback.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/UltraHdrPlayback.kt b/photos/src/main/java/com/vayunmathur/photos/platform/UltraHdrPlayback.ktnew file mode 100644index 0000000000..109b19cc61--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/platform/UltraHdrPlayback.kt@@ -0,0 +1,100 @@+package com.vayunmathur.photos.platform++import android.app.Activity+import android.content.Context+import android.content.pm.ActivityInfo+import android.net.Uri+import android.os.Build+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import androidx.core.net.toUri+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.domain.AvifGainMapDetection+import com.vayunmathur.photos.domain.AvifGainMapParser+import com.vayunmathur.photos.domain.GainMapPlayback+import com.vayunmathur.photos.domain.GainMapPlaybackMode+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/** Bytes read from the file head for gain-map detection (meta precedes mdat). */+private const val HEADER_BYTES = 256 * 1024++/** True when this display advertises HDR capabilities. */+internal fun Context.isHdrDisplayCapable(): Boolean = runCatching {+    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+        display?.hdrCapabilities?.supportedHdrTypes?.isNotEmpty() == true+    } else {+        false+    }+}.getOrDefault(false)++internal fun readAvifHeader(context: Context, uri: Uri): ByteArray? = runCatching {+    context.contentResolver.openInputStream(uri)?.use { input ->+        val buffer = ByteArray(HEADER_BYTES)+        var read = 0+        while (read < HEADER_BYTES) {+            val n = input.read(buffer, read, HEADER_BYTES - read)+            if (n < 0) break+            read += n+        }+        buffer.copyOfRange(0, read)+    }+}.getOrNull()++/**+ * Viewer Ultra HDR state for [photo]: detects an AVIF `tmap` gain+ * map from the file header (JPEG_R keeps the platform decoder's+ * gain map), decides HDR vs SDR with [GainMapPlayback], and while+ * HDR is active asks the window for HDR colour mode so the system+ * compositor can tone-map the wide-gamut surface. SDR photos and+ * SDR displays keep the exact previous rendering.+ */+@Composable+internal fun rememberUltraHdrPlayback(photo: Photo): GainMapPlaybackMode {+    val context = LocalContext.current+    var detection by remember(photo.id, photo.dateModified) {+        mutableStateOf<AvifGainMapDetection?>(null)+    }+    val hdrCapable = remember(context) { context.isHdrDisplayCapable() }++    LaunchedEffect(photo.id, photo.dateModified) {+        if (photo.mimeType.equals("image/avif", ignoreCase = true)) {+            val uri = photo.uri.toUri()+            detection = withContext(Dispatchers.IO) {+                readAvifHeader(context, uri)?.let { AvifGainMapParser.detect(it) }+            }+        }+    }++    val mode = GainMapPlayback.decide(+        mimeType = photo.mimeType,+        avifDetection = detection,+        platformGainMapAttached = false,+        hdrDisplayCapable = hdrCapable,+    )++    val activity = remember(context) { context as? Activity }+    DisposableEffect(mode, activity) {+        val window = activity?.window+        if (mode == GainMapPlaybackMode.HDR && window != null &&+            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O+        ) {+            val previous = window.attributes.colorMode+            window.attributes = window.attributes.apply {+                colorMode = ActivityInfo.COLOR_MODE_HDR+            }+            onDispose {+                window.attributes = window.attributes.apply { colorMode = previous }+            }+        } else {+            onDispose { }+        }+    }+    return mode+}
photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailMedia.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailMedia.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailMedia.ktindex c69aea9a54..5c03c67cd5 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailMedia.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailMedia.kt@@ -2,10 +2,17 @@ package com.vayunmathur.photos.ui  import android.content.Context import android.net.Uri+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Text import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.dp import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.unit.IntSize import androidx.core.net.toUri@@ -14,6 +21,8 @@ import com.vayunmathur.library.image.compose.AnimatedImage import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.util.sharedContainer import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.domain.GainMapPlaybackMode+import com.vayunmathur.photos.platform.rememberUltraHdrPlayback import java.io.File  /**@@ -38,6 +47,14 @@ fun PhotoDetailMedia(     modifier: Modifier,     onSizeChanged: (IntSize) -> Unit, ) {+    // Ultra HDR: AVIF `tmap` gain-map photos request HDR colour mode+    // on HDR displays (see rememberUltraHdrPlayback); SDR falls back+    // to the base image exactly as before.+    val ultraHdrMode = if (photo.videoData == null) {+        rememberUltraHdrPlayback(photo)+    } else {+        GainMapPlaybackMode.SDR+    }     if (photo.videoData == null && !(motionPlaying && motionFile != null)) {         val imageModifier =             Modifier.fillMaxSize()@@ -49,6 +66,7 @@ fun PhotoDetailMedia(                     if (sharedKey == null) Modifier                     else Modifier.sharedContainer("photo-image-$sharedKey")                 )+        Box(modifier = Modifier.fillMaxSize()) {         if (photo.isGif) {             AnimatedImage(                 uri = photo.uri.toUri(),@@ -79,6 +97,18 @@ fun PhotoDetailMedia(                 contentScale = ContentScale.Fit             )         }+            if (ultraHdrMode == GainMapPlaybackMode.HDR) {+                Text(+                    text = "HDR",+                    color = Color.White,+                    modifier = Modifier+                        .align(Alignment.TopEnd)+                        .padding(12.dp)+                        .background(Color.Black.copy(alpha = 0.55f))+                        .padding(horizontal = 8.dp, vertical = 4.dp),+                )+            }+        }     } else if (motionPlaying && motionFile != null) {         // Motion-photo playback. The seek bar is the frame inspector:         // scrubbing pauses polling and seeks on release, like videos.
photos/src/test/java/com/vayunmathur/photos/domain/AvifGainMapTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/domain/AvifGainMapTest.kt b/photos/src/test/java/com/vayunmathur/photos/domain/AvifGainMapTest.ktnew file mode 100644index 0000000000..9f09d7c9e2--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/domain/AvifGainMapTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.photos.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class AvifGainMapTest {++    private fun box(type: String, payload: ByteArray): ByteArray {+        val size = payload.size + 8+        return byteArrayOf(+            (size shr 24).toByte(), (size shr 16).toByte(), (size shr 8).toByte(), size.toByte(),+        ) + type.toByteArray(Charsets.ISO_8859_1) + payload+    }++    private fun infe(id: Int, type: String): ByteArray {+        val payload = byteArrayOf(0, 0, 0, 2, (id shr 8).toByte(), id.toByte(), 0, 0) ++            type.toByteArray(Charsets.ISO_8859_1) + byteArrayOf(0)+        return box("infe", payload)+    }++    private fun fraction(value: Float): ByteArray {+        val den = 1_000_000+        val num = (value * den).toInt()+        return byteArrayOf(+            (num shr 24).toByte(), (num shr 16).toByte(), (num shr 8).toByte(), num.toByte(),+            (den shr 24).toByte(), (den shr 16).toByte(), (den shr 8).toByte(), den.toByte(),+        )+    }++    /** Minimal AVIF carrying a tmap gain map, laid out like the camera mux writes. */+    private fun ultraHdrAvif(hdrCapacityMax: Float = 2f): ByteArray {+        val tmapMetadata = fraction(0f) + fraction(2f) + fraction(1f) + fraction(0f) ++            fraction(0f) + fraction(0f) + fraction(hdrCapacityMax) + byteArrayOf(1)+        fun build(tmapOffset: Int): ByteArray {+            val pitm = box("pitm", byteArrayOf(0, 0, 0, 0, 0, 1))+            val iinfPayload = byteArrayOf(0, 0, 0, 0, 0, 3) ++                infe(1, "av01") + infe(2, "av01") + infe(3, "tmap")+            val iinf = box("iinf", iinfPayload)+            val dimgPayload = byteArrayOf(0, 3, 0, 2, 0, 2, 0, 1)+            val iref = box("iref", byteArrayOf(0, 0, 0, 0) + box("dimg", dimgPayload))+            val ilocPayload = byteArrayOf(1, 0, 0, 0, 0x44, 0, 0, 1, 0, 3, 0, 0, 0, 0, 0, 1) ++                byteArrayOf(+                    (tmapOffset shr 24).toByte(), (tmapOffset shr 16).toByte(),+                    (tmapOffset shr 8).toByte(), tmapOffset.toByte(),+                    0, 0, 0, tmapMetadata.size.toByte(),+                )+            val iloc = box("iloc", ilocPayload)+            val meta = box("meta", byteArrayOf(0, 0, 0, 0) + pitm + iinf + iref + iloc)+            val ftyp = box("ftyp", "avif".toByteArray() + byteArrayOf(0, 0, 0, 0) + "avifmif1".toByteArray())+            return ftyp + meta + box("mdat", tmapMetadata)+        }+        // Two passes: measure the mdat payload offset, then rebuild with it.+        val probe = build(0)+        val metaEnd = probe.size - (tmapMetadata.size + 8)+        return build(metaEnd + 8)+    }++    @Test+    fun detectsTmapGainMapAndCapacity() {+        val detection = AvifGainMapParser.detect(ultraHdrAvif(hdrCapacityMax = 3f))+        assertNotNull(detection)+        assertEquals(1, detection.primaryItemId)+        assertEquals(2, detection.gainItemId)+        assertEquals(3, detection.tmapItemId)+        assertEquals(3f, detection.hdrCapacityMax!!, 1e-5f)+    }++    @Test+    fun plainAvifAndNonAvifAreNotUltraHdr() {+        assertNull(AvifGainMapParser.detect(byteArrayOf(1, 2, 3)))+        val ftypOnly = box("ftyp", "avif".toByteArray() + ByteArray(8))+        assertNull(AvifGainMapParser.detect(ftypOnly))+    }++    @Test+    fun headerPrefixStillDetectsWithoutCapacity() {+        val full = ultraHdrAvif()+        val prefix = full.copyOfRange(0, full.size - 65) // drop mdat payload+        val detection = AvifGainMapParser.detect(prefix)+        assertNotNull(detection)+        assertNull(detection.hdrCapacityMax)+    }++    @Test+    fun playbackDecidesHdrOnlyWithGainMapAndHdrDisplay() {+        val detection = AvifGainMapParser.detect(ultraHdrAvif())+        assertEquals(+            GainMapPlaybackMode.HDR,+            GainMapPlayback.decide("image/avif", detection, platformGainMapAttached = false, hdrDisplayCapable = true),+        )+        assertEquals(+            GainMapPlaybackMode.SDR,+            GainMapPlayback.decide("image/avif", detection, platformGainMapAttached = false, hdrDisplayCapable = false),+        )+        assertEquals(+            GainMapPlaybackMode.SDR,+            GainMapPlayback.decide("image/avif", null, platformGainMapAttached = false, hdrDisplayCapable = true),+        )+        // JPEG_R keeps its existing platform-gainmap route.+        assertEquals(+            GainMapPlaybackMode.HDR,+            GainMapPlayback.decide("image/jpeg", null, platformGainMapAttached = true, hdrDisplayCapable = true),+        )+    }++    @Test+    fun applyGainMapBoostsLinearLight() {+        val out = GainMapPlayback.applyGainMap(+            floatArrayOf(0.25f, 0.5f), byteArrayOf(0, -1), hdrCapacityMax = 2f,+        )+        assertEquals(0.25f, out[0], 1e-6f)+        assertEquals(2.0f, out[1], 1e-3f) // 0.5 * 2^2+        assertTrue(out[1] > 1f, "HDR values exceed SDR white")+    }+}