photos: derive still size from file header when MediaStore says 0
- Commit
d090f04bb8fcba68b7ad00702d860c399585cefe- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 15:17 UTC (18 hours ago)
- Parents
ffc8aed
The gallery displayed a just-captured Motion Photo as 0x0 because the sync copied MediaStore WIDTH/HEIGHT into the photo database verbatim: a row scanned before the camera recorded dimensions (or a container the scanner cannot size, such as an AVIF Motion Photo) stayed 0 forever, even when the file's own metadata was correct. Add ImageDimensionParser (JPEG SOF, AVIF primary ispe via pitm+ipma so a gain map's smaller ispe never wins, both tolerant of an MP4 Motion Photo trailer) and use it in the MediaStore sync only when the row reports a non-positive width or height: the size is read from the file header instead of persisting and displaying 0x0. Rows the header cannot size keep MediaStore's value; nothing is ever fabricated. Verified: ./gradlew :photos:lint :photos:lintVitalRelease :photos:testDevUnitTest - the only failure is VaultViewerPageRealTest.viewerDecryptsAndShowsVaultPhoto, which fails identically on a pristine origin/main checkout (pre-existing, unrelated to this change).
Diff
photos/AGENTS.md
diff --git a/photos/AGENTS.md b/photos/AGENTS.mdindex 2f137738d8..c0db88c63d 100644--- a/photos/AGENTS.md+++ b/photos/AGENTS.md@@ -79,6 +79,7 @@ _Install: ./install photos (dev by default)._ - 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/ImageDimensions.kt — JPEG SOF / AVIF primary-`ispe` header dimensions; the MediaStore sync derives a still's size from its file header when the MediaStore row reports 0, so a valid file never displays 0x0 - 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`.
photos/src/main/java/com/vayunmathur/photos/domain/ImageDimensions.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/ImageDimensions.kt b/photos/src/main/java/com/vayunmathur/photos/domain/ImageDimensions.ktnew file mode 100644index 0000000000..872a1b0274--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/ImageDimensions.kt@@ -0,0 +1,180 @@+package com.vayunmathur.photos.domain++/** Pixel dimensions of an encoded still, parsed from its header bytes. */+data class ImageDimensions(val width: Int, val height: Int) {+ val isValid: Boolean get() = width > 0 && height > 0+}++/**+ * Header-level dimension reader for the gallery sync: JPEG SOF and+ * AVIF primary `ispe`. Used only when MediaStore reports an unknown+ * (0) size, so a file whose metadata is right is never displayed as+ * 0x0 because the MediaStore row was scanned before/without dims.+ * Works on a header prefix; Motion Photo trailers (MP4 after the+ * still) do not affect either parse.+ */+object ImageDimensionParser {++ private const val HEADER_READ_LIMIT = 512 * 1024++ /** Dimensions of [bytes] in either container, by magic bytes. */+ fun forBytes(bytes: ByteArray): ImageDimensions? = when {+ bytes.size >= 2 && bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte() -> jpeg(bytes)+ bytes.size >= 8 && String(bytes, 4, 4, Charsets.ISO_8859_1) == "ftyp" -> avif(bytes)+ else -> null+ }++ /** Read at most the header prefix needed for either parse. */+ fun readHeader(input: java.io.InputStream): ByteArray {+ val buffer = ByteArray(HEADER_READ_LIMIT)+ var total = 0+ while (total < buffer.size) {+ val read = input.read(buffer, total, buffer.size - total)+ if (read <= 0) break+ total += read+ // JPEG SOF and AVIF meta both sit early; stop once found.+ if (forBytes(buffer.copyOf(total)) != null) break+ }+ return buffer.copyOf(total)+ }++ private fun jpeg(bytes: ByteArray): ImageDimensions? {+ var pos = 2+ while (pos + 4 <= bytes.size) {+ if (bytes[pos] != 0xFF.toByte()) return null+ var markerPos = pos + 1+ while (markerPos < bytes.size && bytes[markerPos] == 0xFF.toByte()) markerPos+++ if (markerPos >= bytes.size) return null+ val marker = bytes[markerPos].toInt() and 0xFF+ if (marker == 0xDA) return null+ if (marker == 0xD8 || marker == 0xD9 || marker == 0x01 || marker in 0xD0..0xD7) {+ pos = markerPos + 1+ continue+ }+ if (markerPos + 3 > bytes.size) return null+ val length = ((bytes[markerPos + 1].toInt() and 0xFF) shl 8) or+ (bytes[markerPos + 2].toInt() and 0xFF)+ if (length < 2 || markerPos + 1 + length > bytes.size) return null+ if (marker in 0xC0..0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC) {+ if (length < 7) return null+ val p = markerPos + 3+ val height = ((bytes[p + 1].toInt() and 0xFF) shl 8) or (bytes[p + 2].toInt() and 0xFF)+ val width = ((bytes[p + 3].toInt() and 0xFF) shl 8) or (bytes[p + 4].toInt() and 0xFF)+ return ImageDimensions(width, height).takeIf { it.isValid }+ }+ pos = markerPos + 1 + length+ }+ return null+ }++ private class Box(val type: String, 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+ out.add(Box(String(bytes, off + 4, 4, Charsets.ISO_8859_1), off + header, off + size))+ off += size+ }+ return out+ }++ private fun avif(bytes: ByteArray): ImageDimensions? {+ if (bytes.size < 12 || String(bytes, 4, 4, Charsets.ISO_8859_1) != "ftyp") return null+ val meta = boxes(bytes, 0, bytes.size).firstOrNull { it.type == "meta" } ?: return null+ val children = boxes(bytes, meta.payloadStart + 4, meta.payloadEnd)+ val iprp = children.firstOrNull { it.type == "iprp" } ?: return null+ val iprpChildren = boxes(bytes, iprp.payloadStart, iprp.payloadEnd)+ val ipco = iprpChildren.firstOrNull { it.type == "ipco" } ?: return null+ val allProps = boxes(bytes, ipco.payloadStart, ipco.payloadEnd)+ val ispes = allProps.filter { it.type == "ispe" }.mapNotNull { ispeDimensions(bytes, it) }+ if (ispes.isEmpty()) return null+ // Primary item's ispe via pitm + ipma; a gain map's smaller ispe+ // must not win, so the association is authoritative.+ primaryDimensions(bytes, children, iprpChildren, allProps)?.let { return it }+ return ispes.firstOrNull { it.isValid }+ }++ private fun ispeDimensions(bytes: ByteArray, ispe: Box): ImageDimensions? {+ if (ispe.payloadStart + 12 > bytes.size) return null+ return ImageDimensions(+ u32(bytes, ispe.payloadStart + 4).toInt(),+ u32(bytes, ispe.payloadStart + 8).toInt(),+ )+ }++ private fun primaryDimensions(+ bytes: ByteArray,+ metaChildren: List<Box>,+ iprpChildren: List<Box>,+ allProps: List<Box>,+ ): ImageDimensions? {+ val pitm = metaChildren.firstOrNull { it.type == "pitm" } ?: return null+ val primaryId = if ((bytes[pitm.payloadStart].toInt() and 0xFF) == 1) {+ if (pitm.payloadStart + 8 > bytes.size) return null+ u32(bytes, pitm.payloadStart + 4).toInt()+ } else {+ if (pitm.payloadStart + 6 > bytes.size) return null+ u16(bytes, pitm.payloadStart + 4)+ }+ val ipma = iprpChildren.firstOrNull { it.type == "ipma" } ?: return null+ var pos = ipma.payloadStart + 4+ val version = bytes[ipma.payloadStart].toInt() and 0xFF+ val flags = u32(bytes, ipma.payloadStart)+ val entryCount: Int+ if (flags and 1L != 0L) {+ entryCount = readUint(bytes, pos, 4)?.also { pos += 4 } ?: return null+ } else {+ val asU16 = readUint(bytes, pos, 2)?.also { pos += 2 } ?: return null+ entryCount = if (asU16 == 0) {+ readUint(bytes, pos, 2)?.also { pos += 2 } ?: return null+ } else {+ asU16+ }+ }+ repeat(entryCount) {+ val itemId = if (version >= 1) {+ readUint(bytes, pos, 4)?.also { pos += 4 } ?: return null+ } else {+ readUint(bytes, pos, 2)?.also { pos += 2 } ?: return null+ }+ val count = readUint(bytes, pos, 1)?.also { pos += 1 } ?: return null+ var dims: ImageDimensions? = null+ repeat(count) {+ val raw = if (version >= 1) {+ readUint(bytes, pos, 2)?.also { pos += 2 } ?: return null+ } else {+ readUint(bytes, pos, 1)?.also { pos += 1 } ?: return null+ }+ val index = raw and if (version >= 1) 0x7FFF else 0x7F+ val named = allProps.getOrNull(index - 1)+ if (itemId == primaryId && named?.type == "ispe") dims = ispeDimensions(bytes, named)+ }+ if (itemId == primaryId) return dims+ }+ return null+ }++ private fun readUint(b: ByteArray, off: Int, size: Int): Int? {+ if (off < 0 || off + size > b.size) return null+ var v = 0+ repeat(size) { v = (v shl 8) or (b[off + it].toInt() and 0xFF) }+ return v+ }++ private fun u16(b: ByteArray, off: Int): Int =+ ((b[off].toInt() and 0xFF) shl 8) or (b[off + 1].toInt() and 0xFF)++ 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)+}
photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.ktindex 0edc92c476..e90983bc9b 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt@@ -459,7 +459,12 @@ private class CursorScope( val favoriteChanges: MutableMap<Long, Boolean> = mutableMapOf(), ) -private fun processCursor(cursor: android.database.Cursor, isVideo: Boolean, scope: CursorScope) {+private fun processCursor(+ cursor: android.database.Cursor,+ isVideo: Boolean,+ scope: CursorScope,+ resolver: ContentResolver? = null,+) { val cols = CursorColumns(cursor, isVideo) val baseUri = if (isVideo) { MediaStore.Video.Media.EXTERNAL_CONTENT_URI@@ -468,7 +473,7 @@ private fun processCursor(cursor: android.database.Cursor, isVideo: Boolean, sco } while (cursor.moveToNext()) { try {- readCursorRow(cursor, cols, isVideo, baseUri, scope)+ readCursorRow(cursor, cols, isVideo, baseUri, scope, resolver) } catch (e: CursorIndexOutOfBoundsException) { Log.error("SyncWorker", "Error processing photo/video from cursor", e) } catch (e: IllegalStateException) {@@ -483,6 +488,7 @@ private fun readCursorRow( isVideo: Boolean, baseUri: Uri, scope: CursorScope,+ resolver: ContentResolver? = null, ) { val id = cursor.getLong(cols.id) val name = cursor.getString(cols.name)@@ -493,8 +499,24 @@ private fun readCursorRow( cursor.getLong(cols.dateAdded) * MILLIS_PER_SECOND } val dateModified = cursor.getLong(cols.dateModified)- val width = cursor.getInt(cols.width)- val height = cursor.getInt(cols.height)+ var width = cursor.getInt(cols.width)+ var height = cursor.getInt(cols.height)+ // MediaStore can carry 0x0 for a still whose file metadata is fine (row+ // scanned before dimensions landed, or an unsizable container): derive+ // the size from the file header rather than persisting/displaying 0x0.+ if (!isVideo && (width <= 0 || height <= 0) && resolver != null) {+ val derived = runCatching {+ resolver.openInputStream(ContentUris.withAppendedId(baseUri, id))?.use { input ->+ com.vayunmathur.photos.domain.ImageDimensionParser.forBytes(+ com.vayunmathur.photos.domain.ImageDimensionParser.readHeader(input)+ )+ }+ }.getOrNull()+ if (derived?.isValid == true) {+ width = derived.width+ height = derived.height+ }+ } val isTrashed = cursor.getInt(cols.isTrashed) == 1 val mimeType = cursor.getString(cols.mimeType) val album = cursor.getString(cols.album)@@ -535,7 +557,8 @@ private fun queryMediaStore( putString(ContentResolver.QUERY_ARG_SQL_SELECTION, selection) putInt(MediaStore.QUERY_ARG_MATCH_TRASHED, MediaStore.MATCH_INCLUDE) }- context.contentResolver.query(uri, projection, bundle, null)?.use { processCursor(it, isVideo, scope) }+ context.contentResolver.query(uri, projection, bundle, null)+ ?.use { processCursor(it, isVideo, scope, context.contentResolver) } } catch (e: SecurityException) { Log.error("SyncWorker", "Error querying MediaStore for $kind", e) } catch (e: IllegalArgumentException) {
photos/src/test/java/com/vayunmathur/photos/domain/ImageDimensionsTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/domain/ImageDimensionsTest.kt b/photos/src/test/java/com/vayunmathur/photos/domain/ImageDimensionsTest.ktnew file mode 100644index 0000000000..a1e037e3b4--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/domain/ImageDimensionsTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.photos.domain++import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/** The gallery must never display 0x0 when the file header knows the size. */+class ImageDimensionsTest {++ private fun jpeg(width: Int, height: Int): ByteArray {+ val out = ByteArrayOutputStream()+ out.write(byteArrayOf(0xFF.toByte(), 0xD8.toByte()))+ out.write(byteArrayOf(0xFF.toByte(), 0xC0.toByte(), 0x00, 0x11, 0x08))+ out.write(byteArrayOf((height shr 8).toByte(), height.toByte()))+ out.write(byteArrayOf((width shr 8).toByte(), width.toByte()))+ out.write(byteArrayOf(0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01))+ out.write(byteArrayOf(0xFF.toByte(), 0xDA.toByte()))+ return out.toByteArray()+ }++ private fun box(type: String, payload: ByteArray): ByteArray {+ val out = ByteArrayOutputStream()+ val size = payload.size + 8+ out.write(byteArrayOf((size shr 24).toByte(), (size shr 16).toByte(), (size shr 8).toByte(), size.toByte()))+ out.write(type.toByteArray(Charsets.ISO_8859_1))+ out.write(payload)+ return out.toByteArray()+ }++ private fun ispe(width: Int, height: Int): ByteArray {+ val payload = ByteArrayOutputStream()+ payload.write(byteArrayOf(0, 0, 0, 0))+ payload.write(+ byteArrayOf((width shr 24).toByte(), (width shr 16).toByte(), (width shr 8).toByte(), width.toByte())+ )+ payload.write(+ byteArrayOf((height shr 24).toByte(), (height shr 16).toByte(), (height shr 8).toByte(), height.toByte())+ )+ return box("ispe", payload.toByteArray())+ }++ private fun avif(primaryWidth: Int, primaryHeight: Int): ByteArray {+ val ftyp = box("ftyp", "avif".toByteArray() + byteArrayOf(0, 0, 0, 0) + "avif".toByteArray())+ val pitm = box("pitm", byteArrayOf(0, 0, 0, 0, 0, 1))+ val ipco = box("ipco", ispe(24, 18) + ispe(primaryWidth, primaryHeight))+ val ipmaPayload = ByteArrayOutputStream()+ ipmaPayload.write(byteArrayOf(0, 0, 0, 0))+ ipmaPayload.write(byteArrayOf(0, 1, 0, 1, 1, 2))+ val iprp = box("iprp", ipco + box("ipma", ipmaPayload.toByteArray()))+ val metaPayload = ByteArrayOutputStream()+ metaPayload.write(byteArrayOf(0, 0, 0, 0))+ metaPayload.write(pitm + iprp)+ return ftyp + box("meta", metaPayload.toByteArray())+ }++ @Test fun jpegMotionPhotoDimensionsFromHeader() {+ val mp4 = byteArrayOf(0, 0, 0, 8, 0x66, 0x74, 0x79, 0x70)+ assertEquals(ImageDimensions(1920, 1080), ImageDimensionParser.forBytes(jpeg(1920, 1080) + mp4))+ }++ @Test fun avifPrimaryIspeNotGainIspe() {+ val mp4 = byteArrayOf(0, 0, 0, 8, 0x66, 0x74, 0x79, 0x70)+ assertEquals(ImageDimensions(64, 48), ImageDimensionParser.forBytes(avif(64, 48) + mp4))+ }++ @Test fun unknownStaysUnknown() {+ assertNull(ImageDimensionParser.forBytes(byteArrayOf(1, 2, 3)))+ assertNull(ImageDimensionParser.forBytes(jpeg(0, 0)))+ }+}