photos: motion photo playback (#708)
- Commit
6552a96980d8b335d72768e2c19a221a069366cf- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-13 18:39 UTC (2 months ago)
- Parents
f744580
Diff
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.ktnew file mode 100644index 0000000000..bb63b8af52--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/MotionPhotoXmp.kt@@ -0,0 +1,32 @@+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.+ *+ * Samsung (SEF) motion photos use a different container and are out of scope.+ */+object MotionPhotoXmp {++ fun parseMicroVideoOffset(xmp: String?): Long? {+ if (xmp.isNullOrEmpty()) return null+ if (!attr(xmp, "MicroVideo").equals("1", ignoreCase = true)) return null+ return attr(xmp, "MicroVideoOffset")?.trim()?.toLongOrNull()?.takeIf { it > 0 }+ }++ // MicroVideo fields appear either as attributes+ // (GCamera:MicroVideoOffset="123") or as child elements+ // (<GCamera:MicroVideoOffset>123</...>); handle both, namespace-agnostic.+ // Same shape as the GPano lookup in PanoXmpParser.+ private fun attr(xmp: String, name: String): String? {+ Regex("""[:\s]$name\s*=\s*["']([^"']*)["']""").find(xmp)?.let { return it.groupValues[1] }+ Regex("""<[^>]*:$name>\s*([^<]*)\s*</""").find(xmp)?.let { return it.groupValues[1].trim() }+ return null+ }+}
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.ktnew file mode 100644index 0000000000..bb0a1218bb--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/platform/MotionPhotoVideo.kt@@ -0,0 +1,106 @@+package com.vayunmathur.photos.platform++import android.content.Context+import android.net.Uri+import android.provider.MediaStore+import androidx.core.net.toUri+import androidx.exifinterface.media.ExifInterface+import com.vayunmathur.photos.domain.MotionPhotoXmp+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.io.File+import java.io.InputStream++/**+ * Extracts the embedded MicroVideo clip from a Google 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.+ */+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.+ */+ 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+ }.getOrDefault(false)+ }++ suspend fun motionVideoFile(context: Context, photoUri: String, photoId: Long): File? =+ withContext(Dispatchers.IO) {+ 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++ // 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)) {+ tmp.delete()+ return@runCatching null+ }+ out+ }.getOrNull()+ }++ private fun contentLength(context: Context, uri: Uri): Long {+ context.contentResolver.query(+ uri, arrayOf(MediaStore.MediaColumns.SIZE), null, null, null+ )?.use { c -> if (c.moveToFirst()) return c.getLong(0) }+ return context.contentResolver.openAssetFileDescriptor(uri, "r")?.use { it.length } ?: -1L+ }++ /**+ * Skips exactly [n] bytes. [InputStream.skip] may skip fewer than asked+ * (or zero at EOF), so loop; a single-byte read distinguishes a lazy+ * stream from a truncated one.+ */+ private fun skipFully(stream: InputStream, n: Long): Boolean {+ var remaining = n+ while (remaining > 0) {+ val skipped = stream.skip(remaining)+ if (skipped > 0) {+ remaining -= skipped+ } else if (stream.read() == -1) {+ return false+ } else {+ remaining--+ }+ }+ return true+ }+}
photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.ktindex cc7692beab..b40125adbd 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt@@ -2,6 +2,7 @@ package com.vayunmathur.photos.ui import android.content.Context import android.content.Intent+import android.net.Uri import android.provider.MediaStore import androidx.compose.foundation.background import androidx.compose.foundation.gestures.awaitEachGesture@@ -9,7 +10,9 @@ import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.calculatePan import androidx.compose.foundation.gestures.calculateZoom import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding@@ -23,7 +26,9 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow@@ -49,18 +54,22 @@ import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.ui.FadeVisibility import com.vayunmathur.library.ui.FilledTonalButton import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.util.sharedContainer import com.vayunmathur.photos.R import com.vayunmathur.photos.data.OcrLayout import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.domain.OcrBoxStore+import com.vayunmathur.photos.platform.MotionPhotoVideo import com.vayunmathur.photos.util.PhotoFaceBoxes import com.vayunmathur.photos.util.PhotoMapViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import java.io.File import kotlin.math.absoluteValue // Helper class to store zoom information@@ -178,6 +187,23 @@ fun PhotoDetailView( val isSphere = photo.panoData?.isSphere == true var showImmersive by remember(photo.id) { mutableStateOf(false) } + // Motion photos (still JPEG with an embedded MicroVideo clip) play like+ // panoramas view: a toggle button replaces the still with the shared+ // VideoPlayer. Detection opens the original bytes' XMP off the main+ // thread and reads as not-motion on any failure; the grid is untouched+ // (per-tile EXIF IO would jank scrolling), so the check lives here in the+ // viewer only. The GIF path below is untouched: mimeType wins there.+ val messenger = rememberMessenger()+ val motionFailedMessage = stringResource(R.string.motion_photo_failed)+ val canBeMotion = photo.videoData == null && !photo.isGif+ val isMotionPhoto by produceState(initialValue = false, photo.id, canBeMotion) {+ value = if (canBeMotion) MotionPhotoVideo.isMotionPhoto(context, photo.uri) else false+ }+ var motionPlaying by remember(photo.id) { mutableStateOf(false) }+ var motionFile by remember(photo.id) { mutableStateOf<File?>(null) }+ var motionExtracting by remember(photo.id) { mutableStateOf(false) }+ val scope = rememberCoroutineScope()+ Box( modifier = Modifier.fillMaxSize()@@ -201,7 +227,7 @@ fun PhotoDetailView( translationX = zoom.offset.x translationY = zoom.offset.y }- if (photo.videoData == null) {+ if (photo.videoData == null && !(motionPlaying && motionFile != null)) { val imageModifier = Modifier.fillMaxSize() .onGloballyPositioned { layoutCoordinates ->@@ -242,6 +268,19 @@ fun PhotoDetailView( contentScale = ContentScale.Fit ) }+ } else if (motionPlaying && motionFile != null) {+ // Motion-photo playback. The seek bar is the frame inspector:+ // scrubbing pauses polling and seeks on release, like videos.+ // Autoplay is gated on the settled page, mirroring plain videos.+ VideoPlayer(+ modifier =+ Modifier.fillMaxSize()+ .onGloballyPositioned { size = it.size }+ .then(zoomModifier),+ uri = Uri.fromFile(motionFile!!),+ isMetadataVisible = isMetadataVisible,+ isSettledPage = isSettled && motionPlaying+ ) } else { VideoPlayer( modifier =@@ -299,19 +338,56 @@ fun PhotoDetailView( pageOffset = pageOffset, peopleCount = peopleCount, isSphere = isSphere,+ isMotionPhoto = isMotionPhoto, onSetWallpaper = onSetWallpaper, onEditPhoto = onEditPhoto, onDelete = onDelete, ) } - if (isPanorama) {+ if (isPanorama || isMotionPhoto) { FadeVisibility( visible = isMetadataVisible, modifier = Modifier.align(Alignment.TopEnd).padding(16.dp) ) {- FilledTonalButton(onClick = { showImmersive = true }) {- Text(stringResource(if (isSphere) R.string.view_360 else R.string.view_panorama))+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ if (isPanorama) {+ FilledTonalButton(onClick = { showImmersive = true }) {+ Text(stringResource(if (isSphere) R.string.view_360 else R.string.view_panorama))+ }+ }+ if (isMotionPhoto) {+ FilledTonalButton(+ onClick = {+ if (motionPlaying) {+ motionPlaying = false+ } else if (motionFile != null) {+ motionPlaying = true+ } else if (!motionExtracting) {+ motionExtracting = true+ scope.launch {+ val file = MotionPhotoVideo.motionVideoFile(context, photo.uri, photo.id)+ motionExtracting = false+ if (file != null) {+ motionFile = file+ motionPlaying = true+ } else {+ // Extraction failure: stay on the still and report it.+ messenger.show(motionFailedMessage)+ }+ }+ }+ },+ enabled = !motionExtracting+ ) {+ Text(+ stringResource(+ if (motionPlaying) R.string.stop_motion_photo+ else R.string.play_motion_photo+ )+ )+ }+ } } } }
photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.ktindex ce02731b7d..73b053897b 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt@@ -45,6 +45,7 @@ internal fun PhotoMetadataCard( pageOffset: Float, peopleCount: Int = 0, isSphere: Boolean = false,+ isMotionPhoto: Boolean = false, onSetWallpaper: (Photo) -> Unit = {}, onEditPhoto: () -> Unit, onDelete: (Photo) -> Unit = {},@@ -100,6 +101,11 @@ internal fun PhotoMetadataCard( if (photo.panoData != null) { Text(text = if (isSphere) "360°" else stringResource(R.string.panorama), color = Color.LightGray) }+ // Motion badge lives in the viewer metadata only: the grid shows no+ // motion marking, since detecting it needs per-file EXIF reads.+ if (isMotionPhoto) {+ Text(text = stringResource(R.string.motion_badge), color = Color.LightGray)+ } if (peopleCount > 0) { Text( text = pluralStringResource(R.plurals.people_in_photo, peopleCount, peopleCount),