Modern Apps git

← Modern-Apps.git

camera: correctly tag spherical photos

Commit
a471937384effacec650b31192f8090155eec858
Author
Vayun Mathur <[email protected]>
When
2026-07-10 21:33 UTC (4 months ago)
Parents
87a0dbb

Diff

camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex 8343e709b1..aa0f6fb7bf 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -1112,9 +1112,9 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     private fun finishPanoramaSweep() {         panoramaEngine.stopSweep()         viewModelScope.launch {-            panoramaEngine.stitch()?.let {-                panoramaEngine.saveToMediaStore(it)-                it.recycle()+            panoramaEngine.stitch()?.let { (bitmap, info) ->+                panoramaEngine.saveToMediaStore(bitmap, info)+                bitmap.recycle()             }             panoramaEngine.reset()         }
camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.kt b/camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.ktindex 62b1cea357..09aeecb956 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.kt@@ -39,6 +39,19 @@ object MediaStoreSaver {         return uri     } +    /** Write pre-encoded JPEG [bytes] (e.g. with injected XMP) to the image store. */+    fun saveJpegBytes(+        resolver: ContentResolver,+        values: ContentValues,+        bytes: ByteArray,+    ): Uri? {+        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return null+        resolver.openOutputStream(uri)?.use { os ->+            os.write(bytes)+        }+        return uri+    }+     fun saveVideoFile(resolver: ContentResolver, values: ContentValues, file: File): Uri? {         val uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values) ?: return null         resolver.openOutputStream(uri)?.use { os ->
camera/src/main/java/com/vayunmathur/camera/util/PanoXmp.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PanoXmp.kt b/camera/src/main/java/com/vayunmathur/camera/util/PanoXmp.ktnew file mode 100644index 0000000000..759336f42b--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/util/PanoXmp.kt@@ -0,0 +1,65 @@+package com.vayunmathur.camera.util++import java.io.ByteArrayOutputStream++/**+ * Builds and injects a standard GPano XMP packet so stitched panoramas/spheres+ * are recognised as 360/panoramic by compliant viewers (Google Photos, VR+ * viewers, etc.). Uses only the JPEG APP1 segment — no extra dependency.+ */+object PanoXmp {++    private const val XMP_NAMESPACE = "http://ns.adobe.com/xap/1.0/\u0000"++    /** Emit a standard XMP packet carrying the GPano fields for [info]. */+    fun buildGPanoXmp(info: PanoInfo): String = buildString {+        append("<?xpacket begin=\"\uFEFF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>")+        append("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">")+        append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">")+        append("<rdf:Description rdf:about=\"\" ")+        append("xmlns:GPano=\"http://ns.google.com/photos/1.0/panorama/\" ")+        append("GPano:UsePanoramaViewer=\"True\" ")+        append("GPano:ProjectionType=\"${info.projectionType}\" ")+        append("GPano:FullPanoWidthPixels=\"${info.fullWidth}\" ")+        append("GPano:FullPanoHeightPixels=\"${info.fullHeight}\" ")+        append("GPano:CroppedAreaImageWidthPixels=\"${info.croppedWidth}\" ")+        append("GPano:CroppedAreaImageHeightPixels=\"${info.croppedHeight}\" ")+        append("GPano:CroppedAreaLeftPixels=\"${info.croppedLeft}\" ")+        append("GPano:CroppedAreaTopPixels=\"${info.croppedTop}\"/>")+        append("</rdf:RDF>")+        append("</x:xmpmeta>")+        append("<?xpacket end=\"w\"?>")+    }++    /**+     * Insert an APP1 (0xFFE1) XMP segment right after the SOI marker (0xFFD8).+     * Payload = namespace signature + XMP bytes; length is a 2-byte big-endian+     * value covering the length field + payload (must fit in 65533 bytes, which+     * these few GPano fields always do).+     */+    fun injectXmp(jpeg: ByteArray, xmp: String): ByteArray {+        // Not a JPEG (no SOI) — return unchanged rather than corrupting it.+        if (jpeg.size < 2 || jpeg[0] != 0xFF.toByte() || jpeg[1] != 0xD8.toByte()) return jpeg++        val nsBytes = XMP_NAMESPACE.toByteArray(Charsets.UTF_8)+        val xmpBytes = xmp.toByteArray(Charsets.UTF_8)+        val payloadLen = nsBytes.size + xmpBytes.size+        val segmentLen = payloadLen + 2 // includes the 2-byte length field itself+        if (segmentLen > 0xFFFF) return jpeg++        val out = ByteArrayOutputStream(jpeg.size + segmentLen + 2)+        // SOI+        out.write(0xFF)+        out.write(0xD8)+        // APP1 marker + length + payload+        out.write(0xFF)+        out.write(0xE1)+        out.write((segmentLen shr 8) and 0xFF)+        out.write(segmentLen and 0xFF)+        out.write(nsBytes)+        out.write(xmpBytes)+        // Rest of the original JPEG after the SOI.+        out.write(jpeg, 2, jpeg.size - 2)+        return out.toByteArray()+    }+}
camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.ktindex f51161e218..4214c0551a 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt@@ -37,6 +37,21 @@ data class GuideDot(     val state: GuideDotState ) +/**+ * Geometry of a stitched panorama, describing how the cropped output bitmap maps+ * onto the full equirectangular sphere. Written out as GPano XMP so compliant+ * viewers render the image as 360/panoramic.+ */+data class PanoInfo(+    val projectionType: String,+    val fullWidth: Int,+    val fullHeight: Int,+    val croppedWidth: Int,+    val croppedHeight: Int,+    val croppedLeft: Int,+    val croppedTop: Int,+)+ class PanoramaEngine(private val context: Context) : SensorEventListener {      private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager@@ -236,7 +251,7 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {         }     } -    suspend fun stitch(): Bitmap? {+    suspend fun stitch(): Pair<Bitmap, PanoInfo>? {         if (frames.size < 2) return null         _isStitching.value = true         return withContext(Dispatchers.IO) {@@ -323,7 +338,7 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {         return Pair(medianDx, medianDy)     } -    private fun stitchManual(): Bitmap? {+    private fun stitchManual(): Pair<Bitmap, PanoInfo>? {         return try {             val mats = frames.map { bmp ->                 val mat = Mat()@@ -458,13 +473,29 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {             val bitmap = Bitmap.createBitmap(cropped.cols(), cropped.rows(), Bitmap.Config.ARGB_8888)             Utils.matToBitmap(cropped, bitmap)             cropped.release()-            bitmap++            // A cylindrical strip of width W covers a horizontal FOV of W/f radians,+            // so the equivalent full equirectangular sphere is 2π·f wide. Center the+            // covered strip inside that full sphere. GPano only defines+            // "equirectangular"; viewers handle the limited cropped area.+            val fullWidth = Math.round(2.0 * Math.PI * f).toInt()+            val fullHeight = fullWidth / 2+            val info = PanoInfo(+                projectionType = "equirectangular",+                fullWidth = fullWidth,+                fullHeight = fullHeight,+                croppedWidth = bitmap.width,+                croppedHeight = bitmap.height,+                croppedLeft = ((fullWidth - bitmap.width) / 2).coerceAtLeast(0),+                croppedTop = ((fullHeight - bitmap.height) / 2).coerceAtLeast(0),+            )+            Pair(bitmap, info)         } catch (_: Exception) {             null         }     } -    private fun stitchSphere(): Bitmap? {+    private fun stitchSphere(): Pair<Bitmap, PanoInfo>? {         if (frames.isEmpty() || frameOrientations.size != frames.size) return null          val frameW = frames[0].width@@ -574,15 +605,36 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {         if (right > left && bottom > top) {             val cropped = Bitmap.createBitmap(full, left, top, right - left + 1, bottom - top + 1)             full.recycle()-            return cropped+            val info = PanoInfo(+                projectionType = "equirectangular",+                fullWidth = eqW,+                fullHeight = eqH,+                croppedWidth = right - left + 1,+                croppedHeight = bottom - top + 1,+                croppedLeft = left,+                croppedTop = top,+            )+            return Pair(cropped, info)         }-        return full+        val info = PanoInfo(+            projectionType = "equirectangular",+            fullWidth = eqW,+            fullHeight = eqH,+            croppedWidth = eqW,+            croppedHeight = eqH,+            croppedLeft = 0,+            croppedTop = 0,+        )+        return Pair(full, info)     } -    fun saveToMediaStore(bitmap: Bitmap) {+    fun saveToMediaStore(bitmap: Bitmap, info: PanoInfo) {         val prefix = if (sphereMode) "SPHERE" else "PANO"         val contentValues = MediaStoreSaver.imageValues("${prefix}_${MediaStoreSaver.timestamp()}.jpg")-        MediaStoreSaver.saveBitmap(context.contentResolver, contentValues, bitmap)+        val baos = java.io.ByteArrayOutputStream()+        bitmap.compress(Bitmap.CompressFormat.JPEG, 95, baos)+        val tagged = PanoXmp.injectXmp(baos.toByteArray(), PanoXmp.buildGPanoXmp(info))+        MediaStoreSaver.saveJpegBytes(context.contentResolver, contentValues, tagged)     }      fun reset() {