Modern Apps git

← Modern-Apps.git

photos: play motion photos stored in AVIF files

Commit
1f13e91ee2a0873e279ac6c2d8b27ff4ffd817ba
Author
Vayun Mathur <[email protected]>
When
2026-12-05 14:35 UTC (21 hours ago)
Parents
0fba9e2
The viewer only recognised JPEG motion photos (XMP from the
Exif APP1, via MotionPhotoVideo). AVIF motion photos carry the
same GCamera packet in the ISOBMFF XMP item, so a new pure
domain parser (AvifMotionPhoto) walks meta -> iinf (mime /
application/rdf+xml infe) -> iloc extents to read it, and
MotionPhotoVideo branches on the ftyp header: AVIF files are
parsed and their trailing MP4 extracted to the same cache the
JPEG path uses, so the existing viewer toggle plays them
unchanged.

MotionPhotoXmp now documents that MicroVideoOffset is the clip
length counted back from EOF (what the camera writer writes)
and gains motionVideoStart(fileSize, offset); the JPEG
extraction uses it too, converting with the MediaStore file
length instead of skipping the raw value as an absolute offset.

Tests: synthetic-AVIF parse/extract round-trip, plain-AVIF and
non-motion rejection, motionVideoStart conversions.
Verified: :photos:lint :photos:lintVitalRelease green;
AvifMotionPhotoTest + PhotosSlice3JvmTest green. Full
:photos:testDevUnitTest has 2 pre-existing failures
(VaultViewerPageRealTest, GalleryViewModelRealRepoTest) that
reproduce identically on a clean origin/main worktree.

Diff

photos/AGENTS.md
diff --git a/photos/AGENTS.md b/photos/AGENTS.mdindex a34b5b6804..417cba8e57 100644--- a/photos/AGENTS.md+++ b/photos/AGENTS.md@@ -72,7 +72,8 @@ _Install: ./install photos (dev by default)._ - com/vayunmathur/photos/data/BitmapExtensions.kt ### domain/ — OCR, motion-photo and face-grouping logic (pure) - com/vayunmathur/photos/domain/PhotoOcr.kt-- com/vayunmathur/photos/domain/MotionPhotoXmp.kt+- com/vayunmathur/photos/domain/MotionPhotoXmp.kt — GCamera MicroVideo XMP parsing (clip length from EOF) for JPEG and AVIF motion photos+- com/vayunmathur/photos/domain/AvifMotionPhoto.kt — ISOBMFF XMP-item parsing + trailer extraction for AVIF motion photos - com/vayunmathur/photos/domain/FaceAlignment.kt — five-point ArcFace alignment - com/vayunmathur/photos/domain/FaceQuality.kt — which faces may form people - com/vayunmathur/photos/domain/FaceClustering.kt — batch average-linkage grouping
photos/src/main/java/com/vayunmathur/photos/domain/AvifMotionPhoto.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/AvifMotionPhoto.kt b/photos/src/main/java/com/vayunmathur/photos/domain/AvifMotionPhoto.ktnew file mode 100644index 0000000000..2dcb9bd715--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/AvifMotionPhoto.kt@@ -0,0 +1,154 @@+package com.vayunmathur.photos.domain++/**+ * Detects and extracts AVIF Motion Photos: an AVIF still whose XMP item+ * (`mime` / `application/rdf+xml` in the ISOBMFF `meta` box) carries the+ * GCamera MicroVideo packet, with the MP4 clip appended as a trailer.+ * This is the same layout the camera writes for JPEG (still + XMP ++ * trailing MP4, clip length counted back from EOF), carried in AVIF's+ * native item metadata instead of a JPEG APP1 segment. Pure logic over+ * bytes — no Android, no IO — so it unit-tests anywhere.+ */+object AvifMotionPhoto {++    /** One parsed AVIF Motion Photo: the XMP packet and the clip length. */+    data class Info(val xmp: String, val videoLength: Long) {+        /** Absolute byte offset where the clip starts in a file of [fileSize]. */+        fun videoStart(fileSize: Long): Long? =+            MotionPhotoXmp.motionVideoStart(fileSize, videoLength)+    }++    /** True when [bytes] start with an AVIF file-type box. */+    fun isAvif(bytes: ByteArray): Boolean =+        bytes.size >= 12 && String(bytes, 4, 4, Charsets.US_ASCII) == "ftyp" &&+            String(bytes, 8, 4, Charsets.US_ASCII).let { it == "avif" || it == "avis" }++    /** Parses the XMP item + declared clip, or null when not a motion AVIF. */+    fun parse(bytes: ByteArray): Info? {+        if (!isAvif(bytes)) return null+        val xmp = xmpItem(bytes) ?: return null+        val length = MotionPhotoXmp.parseMicroVideoOffset(xmp) ?: return null+        val info = Info(xmp, length)+        if (info.videoStart(bytes.size.toLong()) == null) return null+        return info+    }++    /** The embedded MP4 bytes, or null when [bytes] is not a motion AVIF. */+    fun extractVideo(bytes: ByteArray): ByteArray? {+        val info = parse(bytes) ?: return null+        val start = info.videoStart(bytes.size.toLong())?.toInt() ?: return null+        return bytes.copyOfRange(start, bytes.size)+    }++    // -- ISOBMFF walk: meta -> iinf (mime infe) -> iloc extents --++    private data class Box(val type: String, val start: Int, val payloadStart: Int, val end: Int)++    private fun boxes(bytes: ByteArray, from: Int, until: Int): List<Box> {+        val out = mutableListOf<Box>()+        var off = from+        while (off + 8 <= until && off + 8 <= bytes.size) {+            val size32 = u32(bytes, off) ?: break+            val (size, header) = when {+                size32 == 1L && off + 16 <= bytes.size -> (u64(bytes, off + 8) ?: break) to 16+                size32 == 0L -> (until - off).toLong() to 8+                else -> size32 to 8+            }+            if (size < header || off + size > bytes.size) break+            val type = String(bytes, off + 4, 4, Charsets.US_ASCII)+            out.add(Box(type, off, off + header.toInt(), (off + size).toInt()))+            off += size.toInt()+        }+        return out+    }++    private fun u32(bytes: ByteArray, off: Int): Long? {+        if (off + 4 > bytes.size) return null+        return ((bytes[off].toLong() and 0xFF) shl 24) or ((bytes[off + 1].toLong() and 0xFF) shl 16) or+            ((bytes[off + 2].toLong() and 0xFF) shl 8) or (bytes[off + 3].toLong() and 0xFF)+    }++    private fun u64(bytes: ByteArray, off: Int): Long? {+        val hi = u32(bytes, off) ?: return null+        val lo = u32(bytes, off + 4) ?: return null+        return (hi shl 32) or lo+    }++    private fun u16(bytes: ByteArray, off: Int): Int? {+        if (off + 2 > bytes.size) return null+        return ((bytes[off].toInt() and 0xFF) shl 8) or (bytes[off + 1].toInt() and 0xFF)+    }++    private fun xmpItem(bytes: ByteArray): String? {+        val meta = boxes(bytes, 0, bytes.size).firstOrNull { it.type == "meta" } ?: return null+        val children = boxes(bytes, meta.payloadStart + 4, meta.end)+        val iinf = children.firstOrNull { it.type == "iinf" } ?: return null+        val countLen = if (bytes.getOrNull(iinf.payloadStart)?.toInt() == 1) 4 else 2+        val infes = boxes(bytes, iinf.payloadStart + 4 + countLen, iinf.end)+        var xmpId: Int? = null+        for (infe in infes) {+            val p = infe.payloadStart + 4+            if (String(bytes, p + 4, 4, Charsets.US_ASCII) != "mime") continue+            // mime infe: name (null-terminated), then content type.+            var pos = p + 8+            while (pos < infe.end && bytes[pos].toInt() != 0) pos+++            pos+++            val typeStart = pos+            while (pos < infe.end && bytes[pos].toInt() != 0) pos+++            val contentType = String(bytes, typeStart, pos - typeStart, Charsets.US_ASCII)+            if (!contentType.startsWith("application/rdf+xml")) continue+            xmpId = u16(bytes, p) ?: return null+            break+        }+        val id = xmpId ?: return null+        val iloc = children.firstOrNull { it.type == "iloc" } ?: return null+        return readIlocItem(bytes, iloc, id)?.let { String(it, Charsets.UTF_8) }+    }++    private fun readIlocItem(bytes: ByteArray, iloc: Box, wantedId: Int): ByteArray? {+        var pos = iloc.payloadStart + 4+        val version = bytes.getOrNull(iloc.payloadStart)?.toInt() ?: return null+        val sizes = bytes.getOrNull(pos)?.toInt() ?: return null+        pos+++        val offsetSize = sizes shr 4+        val lengthSize = sizes and 0x0F+        val baseSizes = bytes.getOrNull(pos)?.toInt() ?: return null+        pos+++        val baseOffsetSize = baseSizes shr 4+        val indexSize = baseSizes and 0x0F+        fun read(size: Int): Long? {+            var value = 0L+            repeat(size) {+                val b = bytes.getOrNull(pos) ?: return null+                value = (value shl 8) or (b.toLong() and 0xFF)+                pos+++            }+            return value+        }+        val count = read(if (version == 2) 4 else 2)?.toInt() ?: return null+        repeat(count) {+            val itemId = read(2)?.toInt() ?: return null+            if (version == 1 || version == 2) read(2) ?: return null+            read(2) ?: return null+            val base = read(baseOffsetSize) ?: return null+            val extentCount = read(2)?.toInt() ?: return null+            val extents = mutableListOf<Pair<Long, Long>>()+            repeat(extentCount) {+                if ((version == 1 || version == 2) && indexSize > 0) read(indexSize) ?: return null+                val offset = read(offsetSize) ?: return null+                val length = read(lengthSize) ?: return null+                extents.add(base + offset to length)+            }+            if (itemId == wantedId) {+                val out = java.io.ByteArrayOutputStream()+                for ((offset, length) in extents) {+                    val end = offset + length+                    if (offset < 0 || end > bytes.size) return null+                    out.write(bytes, offset.toInt(), length.toInt())+                }+                return out.toByteArray()+            }+        }+        return null+    }+}
photos/src/main/java/com/vayunmathur/photos/domain/MotionPhotoXmp.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/MotionPhotoXmp.kt b/photos/src/main/java/com/vayunmathur/photos/domain/MotionPhotoXmp.ktindex bb63b8af52..9ad33c4bd9 100644--- a/photos/src/main/java/com/vayunmathur/photos/domain/MotionPhotoXmp.kt+++ b/photos/src/main/java/com/vayunmathur/photos/domain/MotionPhotoXmp.kt@@ -4,11 +4,14 @@ package com.vayunmathur.photos.domain  * Detects Google motion photos ("MicroVideo") from a photo's XMP packet (as  * exposed by ExifInterface's TAG_XMP), without touching the file's video bytes.  *- * A motion photo is a still JPEG with the clip appended after the image data:- * `GCamera:MicroVideo="1"` marks the container and `GCamera:MicroVideoOffset`- * gives the byte offset where the embedded MP4 starts. Returns that offset, or- * null when the packet is absent, isn't a motion photo, or carries no usable- * offset. Pure logic — no Android, no IO — so it unit-tests anywhere.+ * A motion photo is a still (JPEG or AVIF) with the clip appended after+ * the image data: `GCamera:MicroVideo="1"` marks the container and+ * `GCamera:MicroVideoOffset` gives the clip length in bytes, counted+ * back from the end of the file (the MP4 is the final segment).+ * [parseMicroVideoOffset] returns that raw length, or null when the+ * packet is absent, isn't a motion photo, or carries no usable value;+ * [motionVideoStart] converts it to an absolute start offset. Pure+ * logic — no Android, no IO — so it unit-tests anywhere.  *  * Samsung (SEF) motion photos use a different container and are out of scope.  */@@ -20,6 +23,12 @@ object MotionPhotoXmp {         return attr(xmp, "MicroVideoOffset")?.trim()?.toLongOrNull()?.takeIf { it > 0 }     } +    /** Absolute clip start for a file of [fileSize], or null when unusable. */+    fun motionVideoStart(fileSize: Long, microVideoOffset: Long): Long? {+        if (fileSize < 0 || microVideoOffset <= 0 || microVideoOffset >= fileSize) return null+        return fileSize - microVideoOffset+    }+     // MicroVideo fields appear either as attributes     // (GCamera:MicroVideoOffset="123") or as child elements     // (<GCamera:MicroVideoOffset>123</...>); handle both, namespace-agnostic.
photos/src/main/java/com/vayunmathur/photos/platform/MotionPhotoVideo.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/MotionPhotoVideo.kt b/photos/src/main/java/com/vayunmathur/photos/platform/MotionPhotoVideo.ktindex bb0a1218bb..f7419b7c0c 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/MotionPhotoVideo.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/MotionPhotoVideo.kt@@ -5,6 +5,7 @@ import android.net.Uri import android.provider.MediaStore import androidx.core.net.toUri import androidx.exifinterface.media.ExifInterface+import com.vayunmathur.photos.domain.AvifMotionPhoto import com.vayunmathur.photos.domain.MotionPhotoXmp import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext@@ -12,33 +13,41 @@ import java.io.File import java.io.InputStream  /**- * Extracts the embedded MicroVideo clip from a Google motion photo into the+ * Extracts the embedded MicroVideo clip from a motion photo into the  * app cache, so the viewer can play it with the shared video player.  *- * The still JPEG and the MP4 live in one file back to back; [MotionPhotoXmp]- * reads the XMP-declared byte offset where the video starts, and this copies- * everything from there to end-of-file. Results are cached per photo id under- * `cacheDir/motion/` (skipped when already extracted); nothing here touches- * the database or the sync pipeline. Returns null on any failure — callers- * stay on the still and report it.+ * Both containers carry the still first and the MP4 as a trailer, with+ * the GCamera XMP declaring the clip length counted back from EOF:+ * JPEG keeps that XMP in its Exif APP1, AVIF in its ISOBMFF XMP item+ * (parsed by [AvifMotionPhoto]). Results are cached per photo id under+ * `cacheDir/motion/` (skipped when already extracted); nothing here+ * touches the database or the sync pipeline. Returns null on any+ * failure — callers stay on the still and report it.  */ object MotionPhotoVideo {      /**-     * True when the photo's XMP declares an embedded MicroVideo clip. Opens-     * only the original bytes' EXIF header (mirrors SyncWorker.setExifData);-     * any failure reads as not-motion so the viewer just shows the still.+     * True when the photo declares an embedded MicroVideo clip. Opens+     * only the original bytes (mirrors SyncWorker.setExifData); any+     * failure reads as not-motion so the viewer just shows the still.      */     suspend fun isMotionPhoto(context: Context, photoUri: String): Boolean =         withContext(Dispatchers.IO) {             runCatching {-                context.contentResolver.openInputStream(-                    MediaStore.setRequireOriginal(photoUri.toUri())-                )?.use { stream ->-                    MotionPhotoXmp.parseMicroVideoOffset(-                        ExifInterface(stream).getAttribute(ExifInterface.TAG_XMP)-                    ) != null-                } ?: false+                val uri = MediaStore.setRequireOriginal(photoUri.toUri())+                val head = context.contentResolver.openInputStream(uri)?.use { readHead(it) } ?: return@runCatching false+                if (AvifMotionPhoto.isAvif(head)) {+                    val bytes = context.contentResolver.openInputStream(uri)?.use {+                        it.readBytes()+                    } ?: return@runCatching false+                    AvifMotionPhoto.parse(bytes) != null+                } else {+                    context.contentResolver.openInputStream(uri)?.use { stream ->+                        MotionPhotoXmp.parseMicroVideoOffset(+                            ExifInterface(stream).getAttribute(ExifInterface.TAG_XMP)+                        ) != null+                    } ?: false+                }             }.getOrDefault(false)         } @@ -47,29 +56,41 @@ object MotionPhotoVideo {             runCatching {                 val uri = photoUri.toUri()                 val original = MediaStore.setRequireOriginal(uri)-                val offset = context.contentResolver.openInputStream(original)?.use { stream ->-                    MotionPhotoXmp.parseMicroVideoOffset(-                        ExifInterface(stream).getAttribute(ExifInterface.TAG_XMP)-                    )-                } ?: return@runCatching null-                 val dir = File(context.cacheDir, "motion").apply { mkdirs() }                 val out = File(dir, "$photoId.mp4")                 if (out.exists() && out.length() > 0) return@runCatching out -                // Sanity-check the offset against the file length when known;-                // an unknown length (-1) just means the check is skipped.-                val total = contentLength(context, uri)-                if (total >= 0 && offset >= total) return@runCatching null+                val head = context.contentResolver.openInputStream(original)?.use { readHead(it) } ?: return@runCatching null                  // Copy to a temp file first so a cancelled run can't leave a                 // truncated .mp4 that the cache check above would trust.                 val tmp = File(dir, "$photoId.tmp")-                context.contentResolver.openInputStream(original)?.use { stream ->-                    if (!skipFully(stream, offset)) return@runCatching null-                    tmp.outputStream().use { outStream -> stream.copyTo(outStream) }-                } ?: return@runCatching null-                if (tmp.length() == 0L || !tmp.renameTo(out)) {+                val written = if (AvifMotionPhoto.isAvif(head)) {+                    val bytes = context.contentResolver.openInputStream(original)?.use {+                        it.readBytes()+                    } ?: return@runCatching null+                    val video = AvifMotionPhoto.extractVideo(bytes)+                        ?: return@runCatching null+                    tmp.outputStream().use { it.write(video) }+                    true+                } else {+                    val offset = context.contentResolver.openInputStream(original)?.use { stream ->+                        MotionPhotoXmp.parseMicroVideoOffset(+                            ExifInterface(stream).getAttribute(ExifInterface.TAG_XMP)+                        )+                    } ?: return@runCatching null+                    // The declared value is the clip length from EOF; the+                    // file length converts it to an absolute start.+                    val total = contentLength(context, uri)+                    val start = MotionPhotoXmp.motionVideoStart(total, offset)+                        ?: return@runCatching null+                    context.contentResolver.openInputStream(original)?.use { stream ->+                        if (!skipFully(stream, start)) return@runCatching null+                        tmp.outputStream().use { outStream -> stream.copyTo(outStream) }+                    } ?: return@runCatching null+                    true+                }+                if (!written || tmp.length() == 0L || !tmp.renameTo(out)) {                     tmp.delete()                     return@runCatching null                 }@@ -77,6 +98,18 @@ object MotionPhotoVideo {             }.getOrNull()         } +    /** Up to 16 header bytes, read without newer-API helpers. */+    private fun readHead(stream: InputStream): ByteArray {+        val buf = ByteArray(16)+        var read = 0+        while (read < buf.size) {+            val n = stream.read(buf, read, buf.size - read)+            if (n < 0) break+            read += n+        }+        return buf.copyOf(read)+    }+     private fun contentLength(context: Context, uri: Uri): Long {         context.contentResolver.query(             uri, arrayOf(MediaStore.MediaColumns.SIZE), null, null, null
photos/src/test/java/com/vayunmathur/photos/domain/AvifMotionPhotoTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/domain/AvifMotionPhotoTest.kt b/photos/src/test/java/com/vayunmathur/photos/domain/AvifMotionPhotoTest.ktnew file mode 100644index 0000000000..16ecf1e302--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/domain/AvifMotionPhotoTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.photos.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Pure-JVM tests for [AvifMotionPhoto]: ISOBMFF XMP item + MP4 trailer. */+class AvifMotionPhotoTest {++    private fun box(type: String, payload: ByteArray): ByteArray {+        val out = ByteArray(8 + payload.size)+        val size = out.size+        out[0] = (size shr 24).toByte(); out[1] = (size shr 16).toByte()+        out[2] = (size shr 8).toByte(); out[3] = size.toByte()+        type.toByteArray(Charsets.US_ASCII).copyInto(out, 4)+        payload.copyInto(out, 8)+        return out+    }++    private fun u16(v: Int) = byteArrayOf((v shr 8).toByte(), v.toByte())+    private fun u32(v: Int) =+        byteArrayOf((v shr 24).toByte(), (v shr 16).toByte(), (v shr 8).toByte(), v.toByte())++    /** Minimal AVIF: ftyp + meta(iinf mime XMP id=2, iloc) + mdat(XMP) + MP4 trailer. */+    private fun avifMotion(mp4: ByteArray, xmpOverride: String? = null): ByteArray {+        val xmp = (xmpOverride+            ?: """<x:xmpmeta><rdf:RDF><rdf:Description GCamera:MotionPhoto="1" """ ++            """GCamera:MicroVideo="1" GCamera:MicroVideoOffset="${mp4.size}"/></rdf:RDF></x:xmpmeta>"""+            ).toByteArray(Charsets.UTF_8)+        // Layout sizes first: ftyp(16) + meta header, so XMP extent offset is+        // computed after building meta with a placeholder iloc, then rebuilt.+        fun build(xmpOffset: Int): ByteArray {+            val infe = box(+                "infe",+                byteArrayOf(2, 0, 0, 0) + u16(2) + u16(0) + "mime".toByteArray() + byteArrayOf(0) ++                    "application/rdf+xml".toByteArray() + byteArrayOf(0) + byteArrayOf(0),+            )+            val iinf = box("iinf", u32(0) + u16(1) + infe)+            val ilocPayload = byteArrayOf(1, 0, 0, 0) + byteArrayOf(0x44, 0) + u16(1) ++                u16(2) + u16(0) + u16(0) + u16(1) + u32(xmpOffset) + u32(xmp.size)+            val iloc = box("iloc", ilocPayload)+            val meta = box("meta", u32(0) + iinf + iloc)+            val ftyp = box("ftyp", "avif".toByteArray() + u32(0) + "avifmif1".toByteArray())+            val mdat = box("mdat", xmp)+            return ftyp + meta + mdat + mp4+        }+        val probe = build(0)+        val xmpOffset = probe.size - mp4.size - xmp.size+        return build(xmpOffset)+    }++    private val mp4 = byteArrayOf(0, 0, 0, 24) + "ftypmp42".toByteArray() + "FAKECLIP".toByteArray()++    @Test fun parsesXmpItemAndExtractsTrailer() {+        val bytes = avifMotion(mp4)+        val info = AvifMotionPhoto.parse(bytes)+        assertTrue(info != null, "AVIF motion photo must parse")+        assertEquals(mp4.size.toLong(), info.videoLength)+        assertEquals((bytes.size - mp4.size).toLong(), info.videoStart(bytes.size.toLong()))+        assertTrue(AvifMotionPhoto.extractVideo(bytes)!!.contentEquals(mp4))+        assertTrue(AvifMotionPhoto.isAvif(bytes))+    }++    @Test fun rejectsPlainAvifAndNonMotionXmp() {+        assertNull(AvifMotionPhoto.parse(avifMotion(mp4, "<x:xmpmeta/>")))+        assertNull(AvifMotionPhoto.parse(byteArrayOf(1, 2, 3)))+        assertNull(AvifMotionPhoto.extractVideo(byteArrayOf(1, 2, 3)))+    }++    @Test fun motionVideoStartIsFromEndOfFile() {+        // MicroVideoOffset is the clip length (bytes from EOF), not an+        // absolute start: a 1000-byte file with a 200-byte clip starts at 800.+        assertEquals(800L, MotionPhotoXmp.motionVideoStart(fileSize = 1000L, microVideoOffset = 200L))+        assertNull(MotionPhotoXmp.motionVideoStart(fileSize = 100L, microVideoOffset = 200L))+        assertNull(MotionPhotoXmp.motionVideoStart(fileSize = -1L, microVideoOffset = 200L))+    }+}