camera: record true still dimensions, never 0x0
- Commit
ffc8aed132f8b85e48d42b85cf95e9fbad96f045- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 15:17 UTC (18 hours ago)
- Parents
beb5e87
A Motion Photo (and any AVIF still) could land with resolution 0x0: MediaStoreSaver inserted image rows with no WIDTH/HEIGHT/ SIZE at all, so the row depended on a scanner pass that cannot size an AVIF container or a JPEG/AVIF carrying an MP4 trailer; the AVIF Exif item built from a clean carrier JPEG carried no ImageWidth/PixelXDimension tags; and the Rust motion mux (mux_avif_item) sized the rebuilt iloc as if every existing item had exactly one extent, so on Ultra HDR stills (whose items use two extents) the rebuilt meta size and every shifted extent offset landed 8 bytes short in release builds, corrupting item offsets even though ispe itself was intact. Fix all three layers. StillDimensions/StillDimensionParser derive a still's true size from the actual buffer (JPEG SOF, AVIF primary ispe via pitm+ipma so a smaller gain-map ispe never wins, TIFF tags), and saveJpegBytes/saveBitmap write WIDTH/HEIGHT (and SIZE for bytes) at insert time only when a valid size was derived - 0 is never written. buildAvifExifTiff now stamps the upright bitmap dimensions into the AVIF Exif item, writeCaptureExif and stampStillBytes fill JPEG dimension tags from the saved file's own SOF when missing/zero, and saveCamera2Still derives crop dimensions from the JPEG buffer when a ring/direct still reports 0. The Rust iloc rebuild counts 8 bytes per extent per item. Verified: cargo test -p camera_stitch (incl. new ultra_hdr_motion_keeps_ispe_and_exif_dimension_tags, which failed before the mux fix); ./gradlew :camera:lint :camera:lintVitalRelease :camera:testDevUnitTest green.
Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex a8c9039f07..e09e6a5fb9 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -81,6 +81,7 @@ for a direct open-on-phone broadcast. - 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); 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)+- com/vayunmathur/camera/domain/StillDimensions.kt — true still dimensions parsed from the image buffer (JPEG SOF, AVIF primary `ispe`, TIFF tags); every save path derives dimensions from the actual buffer so file metadata and MediaStore never record 0x0 ### 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
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 f585b6ba05..789c8ee082 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt@@ -98,7 +98,12 @@ internal fun CameraViewModel.saveProcessedStill( bitmap.compress(Bitmap.CompressFormat.JPEG, StillFormatRouting.JPEG_QUALITY, out) out.toByteArray() }- buildAvifExifTiff(sourceJpeg, carrier)+ buildAvifExifTiff(+ sourceJpeg, carrier,+ com.vayunmathur.camera.domain.StillDimensions.upright(+ bitmap.width, bitmap.height, rotationDegrees,+ ),+ ) } else { null }
camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.kt b/camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.ktindex 7702947dd5..5ab58e7072 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/MediaStoreSaver.kt@@ -15,6 +15,8 @@ import android.graphics.Bitmap import android.net.Uri import android.os.Environment import android.provider.MediaStore+import com.vayunmathur.camera.domain.StillDimensionParser+import com.vayunmathur.camera.domain.StillDimensions import java.io.File /** Centralizes the DCIM/Camera MediaStore writes shared by photo, video and panorama capture. */@@ -39,6 +41,20 @@ object MediaStoreSaver { fun imageValues(displayName: String, mimeType: String): ContentValues = contentValues(displayName, mimeType) + /**+ * Image values carrying the still's true [dimensions]. A dimension+ * is written only when known-valid: an unknown/zero dimension stays+ * absent so MediaStore (and gallery readers trusting it) can never+ * record a 0x0 still from this insert.+ */+ fun imageValues(displayName: String, mimeType: String, dimensions: StillDimensions?): ContentValues =+ contentValues(displayName, mimeType).apply {+ if (dimensions?.isValid == true) {+ put(MediaStore.MediaColumns.WIDTH, dimensions.width)+ put(MediaStore.MediaColumns.HEIGHT, dimensions.height)+ }+ }+ fun videoValues(displayName: String): ContentValues = contentValues(displayName, "video/mp4") private fun contentValues(displayName: String, mimeType: String) = ContentValues().apply {@@ -53,6 +69,12 @@ object MediaStoreSaver { bitmap: Bitmap, quality: Int = 95, ): Uri? {+ // The bitmap is the actual image buffer: its dimensions are the+ // still's dimensions, recorded at insert (never 0).+ if (bitmap.width > 0 && bitmap.height > 0) {+ values.put(MediaStore.MediaColumns.WIDTH, bitmap.width)+ values.put(MediaStore.MediaColumns.HEIGHT, bitmap.height)+ } val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return null val ok = try { resolver.openOutputStream(uri)?.use { os ->@@ -82,6 +104,24 @@ object MediaStoreSaver { values: ContentValues, bytes: ByteArray, ): Uri? {+ // Derive dimensions from the actual encoded buffer (JPEG SOF /+ // AVIF ispe) before insert. Without this the row lands with no+ // WIDTH/HEIGHT and a scanner that cannot extract them from the+ // file (AVIF, or a Motion Photo's MP4 trailer) leaves it 0x0.+ // Unknown dimensions stay absent — 0 is never written.+ val dimensions = StillDimensions.firstValid(+ StillDimensionParser.forBytes(bytes),+ values.getAsInteger(MediaStore.MediaColumns.WIDTH)?.let { w ->+ values.getAsInteger(MediaStore.MediaColumns.HEIGHT)?.let { h ->+ StillDimensions(w, h)+ }+ },+ )+ if (dimensions?.isValid == true) {+ values.put(MediaStore.MediaColumns.WIDTH, dimensions.width)+ values.put(MediaStore.MediaColumns.HEIGHT, dimensions.height)+ }+ values.put(MediaStore.MediaColumns.SIZE, bytes.size.toLong()) val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return null val ok = try { resolver.openOutputStream(uri)?.use { os ->
camera/src/main/java/com/vayunmathur/camera/domain/StillDimensions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/StillDimensions.kt b/camera/src/main/java/com/vayunmathur/camera/domain/StillDimensions.ktnew file mode 100644index 0000000000..06aa7fccc1--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/StillDimensions.kt@@ -0,0 +1,295 @@+package com.vayunmathur.camera.domain++/**+ * True pixel dimensions of an encoded still, parsed from the image+ * bytes themselves (JPEG SOF, AVIF `ispe`, TIFF/EXIF tags). Pure and+ * Android-free so every save path can guard against recording a+ * 0x0 still: a dimension is only ever written to file metadata or+ * MediaStore when it was derived from an actual image buffer, and+ * an unknown dimension stays absent rather than becoming 0.+ */+data class StillDimensions(val width: Int, val height: Int) {+ val isValid: Boolean get() = width > 0 && height > 0++ companion object {+ /** First valid candidate, or null when every source is unknown/zero. */+ fun firstValid(vararg candidates: StillDimensions?): StillDimensions? =+ candidates.firstOrNull { it?.isValid == true }++ /** Dimensions after baking a [rotationDegrees] rotation into the pixels. */+ fun upright(width: Int, height: Int, rotationDegrees: Int): StillDimensions {+ val rotated = ((rotationDegrees % 360) + 360) % 360+ return if (rotated == 90 || rotated == 270) {+ StillDimensions(height, width)+ } else {+ StillDimensions(width, height)+ }+ }+ }+}++/** Dimension parsers over encoded still bytes / TIFF payloads. */+object StillDimensionParser {++ /** JPEG dimensions from the first SOF segment, or null. MP4 trailers are ignored. */+ fun jpeg(bytes: ByteArray): StillDimensions? {+ if (bytes.size < 4 || bytes[0] != 0xFF.toByte() || bytes[1] != 0xD8.toByte()) return null+ 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 // SOS: no SOF before compressed data+ 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+ // SOF0..SOF15 except DHT (C4), JPG (C8) and DAC (CC).+ if (marker in 0xC0..0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC) {+ if (length < 7) return null+ val p = markerPos + 3 // payload: precision(1), height(2), width(2)+ 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 StillDimensions(width, height).takeIf { it.isValid }+ }+ pos = markerPos + 1 + length+ }+ return null+ }++ /**+ * AVIF dimensions: the primary item's `ispe` (via `pitm` + `ipma`),+ * falling back to the first non-zero `ispe` in `ipco`. Works on a+ * header prefix and tolerates a trailing MP4 (Motion Photo) after+ * the AVIF boxes. With a gain map, `ipco` also holds the gain+ * item's smaller `ispe`, so the primary association is authoritative.+ */+ fun avif(bytes: ByteArray): StillDimensions? {+ 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 ispes = boxes(bytes, ipco.payloadStart, ipco.payloadEnd)+ .filter { it.type == "ispe" }+ .mapNotNull { ispeDimensions(bytes, it) }+ if (ispes.isEmpty()) return null+ val primary = primaryIspe(bytes, children, iprpChildren, ispes.size)+ return primary ?: ispes.firstOrNull { it.isValid }+ }++ /** Dimensions declared by a TIFF payload (EXIF ImageWidth/Length, then PixelX/Y). */+ fun tiff(tiff: ByteArray): StillDimensions? {+ val reader = TiffReader.create(tiff) ?: return null+ val ifd0 = reader.readIfd(reader.firstIfdOffset) ?: return null+ var width = ifd0.intValue(256) // ImageWidth+ var height = ifd0.intValue(257) // ImageLength+ if (width == null || height == null) {+ val exifOffset = ifd0.intValue(34665) // ExifIFD pointer+ if (exifOffset != null) {+ val exif = reader.readIfd(exifOffset)+ if (exif != null) {+ width = width ?: exif.intValue(40962) // PixelXDimension+ height = height ?: exif.intValue(40963) // PixelYDimension+ }+ }+ }+ val w = width ?: return null+ val h = height ?: return null+ return StillDimensions(w, h).takeIf { it.isValid }+ }++ /** Dimensions of [bytes] in either still container, by magic bytes. */+ fun forBytes(bytes: ByteArray): StillDimensions? = 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+ }++ 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 ispeDimensions(bytes: ByteArray, ispe: Box): StillDimensions? {+ // ispe payload: version/flags(4), width(4), height(4).+ if (ispe.payloadStart + 12 > ispe.payloadEnd || ispe.payloadStart + 12 > bytes.size) return null+ val width = u32(bytes, ispe.payloadStart + 4).toInt()+ val height = u32(bytes, ispe.payloadStart + 8).toInt()+ return StillDimensions(width, height)+ }++ private fun primaryIspe(+ bytes: ByteArray,+ metaChildren: List<Box>,+ iprpChildren: List<Box>,+ ispeCount: Int,+ ): StillDimensions? {+ if (ispeCount == 0) return null+ 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+ val ipco = iprpChildren.firstOrNull { it.type == "ipco" } ?: return null+ // ipma property indexes are 1-based into the full ipco box list.+ val allProps = boxes(bytes, ipco.payloadStart, ipco.payloadEnd)+ var pos = ipma.payloadStart + 4+ if (pos > bytes.size) return null+ 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 primaryDims: StillDimensions? = 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") {+ primaryDims = ispeDimensions(bytes, named)+ }+ }+ if (itemId == primaryId) return primaryDims+ }+ 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)++ /** Minimal little/big-endian TIFF IFD reader for dimension tags. */+ private class TiffReader private constructor(+ private val bytes: ByteArray,+ private val littleEndian: Boolean,+ val firstIfdOffset: Int,+ ) {+ class Ifd(private val values: Map<Int, Int>) {+ fun intValue(tag: Int): Int? = values[tag]+ }++ fun readIfd(offset: Int): Ifd? {+ if (offset < 0 || offset + 2 > bytes.size) return null+ val count = uint16(offset)+ val values = mutableMapOf<Int, Int>()+ var pos = offset + 2+ repeat(count) {+ if (pos + 12 > bytes.size) return null+ val tag = uint16(pos)+ val type = uint16(pos + 2)+ val num = uint32(pos + 4)+ val valueField = pos + 8+ val typeSize = when (type) {+ 1, 2, 6, 7 -> 1+ 3, 8 -> 2+ 4, 9, 11 -> 4+ 5, 10, 12 -> 8+ else -> return null+ }+ val total = typeSize.toLong() * num+ val dataPos = if (total <= 4) valueField else uint32(valueField).toInt()+ if (dataPos < 0 || dataPos + typeSize > bytes.size) {+ pos += 12+ return@repeat+ }+ val value = when (type) {+ 3 -> uint16(dataPos)+ 4 -> uint32(dataPos).toInt()+ 1 -> bytes[dataPos].toInt() and 0xFF+ else -> null+ }+ if (value != null) values[tag] = value+ pos += 12+ }+ return Ifd(values)+ }++ private fun uint16(off: Int): Int {+ val a = bytes[off].toInt() and 0xFF+ val b = bytes[off + 1].toInt() and 0xFF+ return if (littleEndian) a or (b shl 8) else (a shl 8) or b+ }++ private fun uint32(off: Int): Long {+ var v = 0L+ if (littleEndian) {+ for (i in 3 downTo 0) v = (v shl 8) or (bytes[off + i].toLong() and 0xFF)+ } else {+ for (i in 0 until 4) v = (v shl 8) or (bytes[off + i].toLong() and 0xFF)+ }+ return v+ }++ companion object {+ fun create(bytes: ByteArray): TiffReader? {+ if (bytes.size < 8) return null+ val little = when {+ bytes[0] == 'I'.code.toByte() && bytes[1] == 'I'.code.toByte() -> true+ bytes[0] == 'M'.code.toByte() && bytes[1] == 'M'.code.toByte() -> false+ else -> return null+ }+ val reader = TiffReader(bytes, little, 0)+ if (reader.uint16(2) != 42) return null+ val first = reader.uint32(4).toInt()+ return TiffReader(bytes, little, first)+ }+ }+ }+}
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 a3d0b509c8..812ae5e4ac 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -167,18 +167,24 @@ internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? { // selection keeps the byte-preserving routes below untouched. An // Ultra HDR (JPEG_R) still that needs cropping trades its gain map // for the crop, the same trade processed (bokeh/colour) stills make.+ // Guard: a ring/direct still whose reported size is unknown/zero+ // derives its dimensions from the actual JPEG buffer, never 0.+ val stillDims = com.vayunmathur.camera.domain.StillDimensions.firstValid(+ com.vayunmathur.camera.domain.StillDimensions(still.jpegWidth, still.jpegHeight),+ com.vayunmathur.camera.domain.StillDimensionParser.jpeg(still.jpegBytes),+ ) val needsCrop = run { if (cameraModeMutable.value != CameraMode.PHOTO &&- cameraModeMutable.value != CameraMode.PORTRAIT+ cameraModeMutable.value != CameraMode.PORTRAIT || stillDims == null ) { false } else { val ratio = currentCropAspectRatio() val rect = com.vayunmathur.camera.domain.AspectCrop.centerCropRect(- still.jpegWidth, still.jpegHeight,+ stillDims.width, stillDims.height, still.metadata.rotationDegrees, ratio.numerator, ratio.denominator, )- rect != null && !rect.isFullFrame(still.jpegWidth, still.jpegHeight)+ rect != null && !rect.isFullFrame(stillDims.width, stillDims.height) } } val decoded = if (needsCrop) {
camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.ktindex e48eeca98d..b495547ee3 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt@@ -186,7 +186,11 @@ internal fun CameraViewModel.writeRawCaptureExif( * failure: the caller then falls back to JPEG instead of shipping an * EXIF-less AVIF. Blocking (file I/O): call off the main thread. */-internal fun CameraViewModel.buildAvifExifTiff(sourceJpeg: ByteArray?, carrierJpeg: ByteArray): ByteArray? {+internal fun CameraViewModel.buildAvifExifTiff(+ sourceJpeg: ByteArray?,+ carrierJpeg: ByteArray,+ dimensions: com.vayunmathur.camera.domain.StillDimensions? = null,+): ByteArray? { updateLocation() var tmp: java.io.File? = null return try {@@ -194,6 +198,21 @@ internal fun CameraViewModel.buildAvifExifTiff(sourceJpeg: ByteArray?, carrierJp tmp.writeBytes(carrierJpeg) val dest = ExifInterface(tmp.absolutePath) copyExifTags(sourceJpeg?.let { ExifInterface(ByteArrayInputStream(it)) }, dest)+ // Dimension tags must describe the AVIF pixels being saved (the+ // upright bitmap), never the sensor-oriented source: derive them+ // from the caller's upright size, falling back to the carrier's+ // own SOF. Without this the Exif item carries no dimensions at+ // all and EXIF readers report 0x0.+ val dims = com.vayunmathur.camera.domain.StillDimensions.firstValid(+ dimensions,+ com.vayunmathur.camera.domain.StillDimensionParser.jpeg(carrierJpeg),+ )+ if (dims?.isValid == true) {+ dest.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, dims.width.toString())+ dest.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, dims.height.toString())+ dest.setAttribute(ExifInterface.TAG_PIXEL_X_DIMENSION, dims.width.toString())+ dest.setAttribute(ExifInterface.TAG_PIXEL_Y_DIMENSION, dims.height.toString())+ } dest.setAttribute( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL.toString()@@ -219,9 +238,27 @@ private fun CameraViewModel.writeExifAttributes( orientation: String ) { val source = sourceJpeg?.let { ExifInterface(ByteArrayInputStream(it)) }+ // Dimensions come from the saved file's own buffer (its SOF), so a+ // cropped/processed still records its cropped size, not the source+ // frame's. Never write a dimension that could not be derived.+ val savedDims = try {+ app.contentResolver.openInputStream(uri)?.use { input ->+ com.vayunmathur.camera.domain.StillDimensionParser.forBytes(input.readBytes())+ }+ } catch (e: java.io.IOException) {+ null+ } catch (e: SecurityException) {+ null+ } app.contentResolver.openFileDescriptor(uri, "rw")?.use { pfd -> val dest = ExifInterface(pfd.fileDescriptor) copyExifTags(source, dest)+ if (savedDims?.isValid == true) {+ dest.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, savedDims.width.toString())+ dest.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, savedDims.height.toString())+ dest.setAttribute(ExifInterface.TAG_PIXEL_X_DIMENSION, savedDims.width.toString())+ dest.setAttribute(ExifInterface.TAG_PIXEL_Y_DIMENSION, savedDims.height.toString())+ } dest.setAttribute(ExifInterface.TAG_ORIENTATION, orientation) if (locationEnabledMutable.value) lastLocation?.let { dest.setGpsInfo(it) } dest.saveAttributes()@@ -309,6 +346,20 @@ internal fun CameraViewModel.stampStillBytes( /** Stamps [orientation] (+GPS when [loc] is non-null) into the temp JPEG file. */ private fun stampTempFile(tmp: java.io.File, orientation: String, loc: android.location.Location?) { val exif = ExifInterface(tmp.absolutePath)+ // Guard the file metadata too: a HAL JPEG whose EXIF lacks dimension+ // tags (or carries 0) gets them from its own SOF before any Motion+ // Photo trailer is appended, so the still never records 0x0.+ val dims = com.vayunmathur.camera.domain.StillDimensionParser.jpeg(tmp.readBytes())+ if (dims?.isValid == true) {+ val existingW = exif.getAttributeInt(ExifInterface.TAG_PIXEL_X_DIMENSION, 0)+ val existingH = exif.getAttributeInt(ExifInterface.TAG_PIXEL_Y_DIMENSION, 0)+ if (existingW <= 0 || existingH <= 0) {+ exif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, dims.width.toString())+ exif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, dims.height.toString())+ exif.setAttribute(ExifInterface.TAG_PIXEL_X_DIMENSION, dims.width.toString())+ exif.setAttribute(ExifInterface.TAG_PIXEL_Y_DIMENSION, dims.height.toString())+ }+ } exif.setAttribute(ExifInterface.TAG_ORIENTATION, orientation) // GPS only when the user opted in; orientation is always stamped above. Skipping // setGpsInfo with no location keeps the bytes bit-for-bit (Ultra HDR gain map intact).
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 4859f7f6df..488a3b9371 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -454,7 +454,12 @@ internal fun CameraViewModel.assembleAndSaveMotionPhoto(request: MotionSaveReque ) out.toByteArray() }- val exifTiff = buildAvifExifTiff(stillBytes, carrier)+ val exifTiff = buildAvifExifTiff(+ stillBytes, carrier,+ com.vayunmathur.camera.domain.StillDimensions.upright(+ bitmap.width, bitmap.height, request.rotationDegrees,+ ),+ ) if (exifTiff != null) { // Combined Motion Photo + Ultra HDR (priority order): // the gain map wins over the AVIF container, and the
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.rsindex 8ac9e30b60..bb5cf6c4af 100644--- a/camera/src/main/rust/src/avif_gainmap_tests.rs+++ b/camera/src/main/rust/src/avif_gainmap_tests.rs@@ -90,6 +90,76 @@ fn ultra_hdr_encode_keeps_exif_and_gain_map() { assert_eq!((info.gain_width, info.gain_height), (48, 32)); } +/// TIFF (little-endian) carrying ImageWidth/ImageLength + PixelX/Y tags.+fn tiff_with_dimensions(width: u32, height: u32) -> Vec<u8> {+ let mut tiff = Vec::new();+ tiff.extend_from_slice(b"II\x2a\0");+ tiff.extend_from_slice(&8u32.to_le_bytes()); // first IFD at 8+ tiff.extend_from_slice(&4u16.to_le_bytes()); // 4 entries+ for (tag, value) in [(256u16, width), (257, height), (40962, width), (40963, height)] {+ tiff.extend_from_slice(&tag.to_le_bytes());+ tiff.extend_from_slice(&4u16.to_le_bytes()); // LONG+ tiff.extend_from_slice(&1u32.to_le_bytes());+ tiff.extend_from_slice(&value.to_le_bytes());+ }+ tiff.extend_from_slice(&0u32.to_le_bytes()); // no next IFD+ tiff+}++fn tiff_long(tiff: &[u8], tag: u16) -> Option<u32> {+ if tiff.len() < 8 || &tiff[0..2] != b"II" {+ return None;+ }+ let ifd = u32::from_le_bytes(tiff[4..8].try_into().ok()?) as usize;+ let count = u16::from_le_bytes(tiff[ifd..ifd + 2].try_into().ok()?) as usize;+ for i in 0..count {+ let pos = ifd + 2 + i * 12;+ if u16::from_le_bytes(tiff[pos..pos + 2].try_into().ok()?) == tag {+ return Some(u32::from_le_bytes(tiff[pos + 8..pos + 12].try_into().ok()?));+ }+ }+ None+}++#[test]+fn ultra_hdr_motion_keeps_ispe_and_exif_dimension_tags() {+ // The 0x0 report path in full: gain-map encode first, motion mux+ // second. Both the primary ispe and the Exif item's dimension tags+ // must still describe the base image afterwards.+ let rgba = gradient(48, 32);+ let tiff = tiff_with_dimensions(48, 32);+ let ultra = 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");+ let mp4: Vec<u8> = (0..256u32).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_eq!(avif_dimensions(&combined), Some((48, 32)), "primary ispe must not be zeroed");+ let parsed_tiff = avif_exif_tiff(&combined).expect("exif item survives both muxes");+ assert_eq!(parsed_tiff, tiff);+ assert_eq!(tiff_long(&parsed_tiff, 256), Some(48), "EXIF ImageWidth");+ assert_eq!(tiff_long(&parsed_tiff, 257), Some(32), "EXIF ImageLength");+ assert_eq!(tiff_long(&parsed_tiff, 40962), Some(48), "EXIF PixelXDimension");+ assert_eq!(tiff_long(&parsed_tiff, 40963), Some(32), "EXIF PixelYDimension");+ let info = avif_gain_map(&combined).expect("gain map survives");+ 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
camera/src/main/rust/src/avif_mux.rs
diff --git a/camera/src/main/rust/src/avif_mux.rs b/camera/src/main/rust/src/avif_mux.rsindex b6afa9bea1..6d66196ddf 100644--- a/camera/src/main/rust/src/avif_mux.rs+++ b/camera/src/main/rust/src/avif_mux.rs@@ -298,7 +298,13 @@ fn mux_avif_item(avif: &[u8], payload: &[u8], kind: ItemKind) -> Option<Vec<u8>> let iloc_old = children.iter().find(|b| &b.typ == b"iloc")?; let iloc_items = parse_iloc(avif, iloc_old)?; // New iloc: version 1, offset/length 4 bytes, no base offset/index.- let iloc_payload_len = 8 + (iloc_items.len() + 1) * (2 + 2 + 2 + 2 + 2 * 4);+ // Each item costs 8 bytes of fields plus 8 per extent — an item with+ // two extents (ravif splits some items that way) must be counted in+ // full, or the rebuilt meta size, and with it every shifted extent+ // offset, lands short and the file's items point into wrong bytes.+ let iloc_payload_len = 8usize+ + iloc_items.iter().map(|item| 8 + item.extents.len() * 8).sum::<usize>()+ + (8 + 8); // the new item, one extent let iloc_box_len = iloc_payload_len + 8; let mut meta_len = 4usize; // version/flags
camera/src/test/java/com/vayunmathur/camera/data/MediaStoreSaverDimensionsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/data/MediaStoreSaverDimensionsTest.kt b/camera/src/test/java/com/vayunmathur/camera/data/MediaStoreSaverDimensionsTest.ktnew file mode 100644index 0000000000..96816f7fc9--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/data/MediaStoreSaverDimensionsTest.kt@@ -0,0 +1,80 @@+package com.vayunmathur.camera.data++import android.content.ContentResolver+import android.content.ContentValues+import android.net.Uri+import android.provider.MediaStore+import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import org.junit.runner.RunWith+import org.mockito.ArgumentCaptor+import org.mockito.Mockito+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++/** A saved still must record its true dimensions in MediaStore, never 0x0. */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+class MediaStoreSaverDimensionsTest {++ private val row: Uri = Uri.parse("content://media/external/images/media/9")++ /** Minimal JPEG: SOI, SOF0 (4032x3024), SOS, EOI. */+ private fun jpeg(width: Int, height: Int): ByteArray {+ val out = ByteArrayOutputStream()+ out.write(byteArrayOf(0xFF.toByte(), 0xD8.toByte()))+ // SOF0 segment: length 17, precision 8, height, width, 3 components.+ 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()))+ out.write(byteArrayOf(0xFF.toByte(), 0xD9.toByte()))+ return out.toByteArray()+ }++ private fun capturingResolver(): Pair<ContentResolver, ArgumentCaptor<ContentValues>> {+ val captor = ArgumentCaptor.forClass(ContentValues::class.java)+ val r = Mockito.mock(ContentResolver::class.java)+ Mockito.`when`(r.insert(Mockito.any(Uri::class.java), captor.capture())).thenReturn(row)+ Mockito.`when`(r.openOutputStream(Mockito.any(Uri::class.java)))+ .thenAnswer { ByteArrayOutputStream() }+ return r to captor+ }++ @Test fun jpegBytesInsertCarriesDimensions() {+ val (r, captor) = capturingResolver()+ val bytes = jpeg(4032, 3024)+ assertNotNull(MediaStoreSaver.saveJpegBytes(r, MediaStoreSaver.imageValues("IMG_a.jpg"), bytes))+ assertEquals(4032, captor.value.getAsInteger(MediaStore.MediaColumns.WIDTH))+ assertEquals(3024, captor.value.getAsInteger(MediaStore.MediaColumns.HEIGHT))+ assertEquals(bytes.size.toLong(), captor.value.getAsLong(MediaStore.MediaColumns.SIZE))+ }++ @Test fun motionJpegInsertCarriesDimensions() {+ val (r, captor) = capturingResolver()+ val mp4 = byteArrayOf(0, 0, 0, 8, 0x66, 0x74, 0x79, 0x70)+ val bytes = com.vayunmathur.camera.domain.MotionPhotoWriter.assemble(jpeg(1920, 1080), mp4)+ assertNotNull(MediaStoreSaver.saveJpegBytes(r, MediaStoreSaver.imageValues("IMG_m.jpg"), bytes))+ assertEquals(1920, captor.value.getAsInteger(MediaStore.MediaColumns.WIDTH))+ assertEquals(1080, captor.value.getAsInteger(MediaStore.MediaColumns.HEIGHT))+ }++ @Test fun unknownDimensionsAreAbsentNeverZero() {+ val (r, captor) = capturingResolver()+ assertNotNull(MediaStoreSaver.saveJpegBytes(r, MediaStoreSaver.imageValues("IMG_x.jpg"), byteArrayOf(1, 2, 3)))+ assertEquals(null, captor.value.getAsInteger(MediaStore.MediaColumns.WIDTH))+ assertEquals(null, captor.value.getAsInteger(MediaStore.MediaColumns.HEIGHT))+ }++ @Test fun bitmapInsertCarriesDimensions() {+ val (r, captor) = capturingResolver()+ val bitmap = android.graphics.Bitmap.createBitmap(16, 12, android.graphics.Bitmap.Config.ARGB_8888)+ assertNotNull(MediaStoreSaver.saveBitmap(r, MediaStoreSaver.imageValues("IMG_b.jpg"), bitmap))+ assertEquals(16, captor.value.getAsInteger(MediaStore.MediaColumns.WIDTH))+ assertEquals(12, captor.value.getAsInteger(MediaStore.MediaColumns.HEIGHT))+ bitmap.recycle()+ }+}
camera/src/test/java/com/vayunmathur/camera/domain/StillDimensionsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/StillDimensionsTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/StillDimensionsTest.ktnew file mode 100644index 0000000000..01f7bc3738--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/StillDimensionsTest.kt@@ -0,0 +1,109 @@+package com.vayunmathur.camera.domain++import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/** Dimension derivation for every still container, incl. Motion Photo layouts. */+class StillDimensionsTest {++ 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(), 0x00, 0x08, 0x01, 0x01, 0x00, 0x00))+ out.write(byteArrayOf(0xFF.toByte(), 0xD9.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())+ }++ /** AVIF whose ipco lists a small (gain-sized) ispe first, primary ispe second. */+ 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))+ // ipma v0: one entry, item 1, one association -> ipco box 2 (the primary ispe).+ val ipmaPayload = ByteArrayOutputStream()+ ipmaPayload.write(byteArrayOf(0, 0, 0, 0))+ ipmaPayload.write(byteArrayOf(0, 1, 0, 1, 1, 2))+ val ipma = box("ipma", ipmaPayload.toByteArray())+ val iprp = box("iprp", ipco + ipma)+ val metaPayload = ByteArrayOutputStream()+ metaPayload.write(byteArrayOf(0, 0, 0, 0))+ metaPayload.write(pitm + iprp)+ return ftyp + box("meta", metaPayload.toByteArray())+ }++ @Test fun jpegSofDimensions() {+ assertEquals(StillDimensions(4032, 3024), StillDimensionParser.jpeg(jpeg(4032, 3024)))+ assertNull(StillDimensionParser.jpeg(byteArrayOf(0x01, 0x02)))+ assertNull(StillDimensionParser.jpeg(jpeg(0, 0)))+ }++ @Test fun jpegMotionPhotoKeepsDimensions() {+ val mp4 = byteArrayOf(0, 0, 0, 8, 0x66, 0x74, 0x79, 0x70)+ val motion = MotionPhotoWriter.assemble(jpeg(1920, 1080), mp4)+ assertEquals(StillDimensions(1920, 1080), StillDimensionParser.forBytes(motion))+ }++ @Test fun avifPrimaryIspeWinsOverGainIspe() {+ assertEquals(StillDimensions(64, 48), StillDimensionParser.avif(avif(64, 48)))+ }++ @Test fun avifMotionTrailerKeepsDimensions() {+ val mp4 = byteArrayOf(0, 0, 0, 8, 0x66, 0x74, 0x79, 0x70, 1, 2, 3)+ assertEquals(StillDimensions(64, 48), StillDimensionParser.forBytes(avif(64, 48) + mp4))+ }++ @Test fun tiffDimensionTags() {+ // Little-endian TIFF: IFD0 with ImageWidth=3000 (LONG), ExifIFD -> PixelY=2000.+ val tiff = ByteArrayOutputStream()+ tiff.write("II".toByteArray())+ tiff.write(byteArrayOf(0x2A, 0x00, 0x08, 0x00, 0x00, 0x00))+ // IFD0 at 8: 2 entries + next=0. Entry size 12.+ tiff.write(byteArrayOf(0x02, 0x00))+ // tag 256 (0x0100), type LONG(4), count 1, value 3000+ tiff.write(byteArrayOf(0x00, 0x01, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00))+ tiff.write(byteArrayOf((3000 and 0xFF).toByte(), ((3000 shr 8) and 0xFF).toByte(), 0x00, 0x00))+ // tag 257 (0x0101), type LONG(4), count 1, value 2000+ tiff.write(byteArrayOf(0x01, 0x01, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00))+ tiff.write(byteArrayOf((2000 and 0xFF).toByte(), ((2000 shr 8) and 0xFF).toByte(), 0x00, 0x00))+ tiff.write(byteArrayOf(0x00, 0x00, 0x00, 0x00))+ assertEquals(StillDimensions(3000, 2000), StillDimensionParser.tiff(tiff.toByteArray()))+ assertNull(StillDimensionParser.tiff(byteArrayOf(0x01)))+ }++ @Test fun guardsNeverAcceptZero() {+ assertNull(StillDimensions.firstValid(StillDimensions(0, 0), null))+ assertEquals(+ StillDimensions(10, 20),+ StillDimensions.firstValid(StillDimensions(0, 20), StillDimensions(10, 20)),+ )+ assertEquals(StillDimensions(20, 10), StillDimensions.upright(10, 20, 90))+ assertEquals(StillDimensions(10, 20), StillDimensions.upright(10, 20, 180))+ }+}