Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][photos] Add Rust media inspector for motion photo parsing

Neeraj Gupta40aadb46be1c
diff --git a/mobile/apps/photos/rust/Cargo.lock b/mobile/apps/photos/rust/Cargo.lock
index 76ba7a98b1..6ac7e63afc 100644
--- a/mobile/apps/photos/rust/Cargo.lock
+++ b/mobile/apps/photos/rust/Cargo.lock
@@ -304,10 +304,18 @@ dependencies = [
"crypto-common",
]
+[[package]]
+name = "ente_media_inspector"
+version = "0.1.0"
+dependencies = [
+ "quick-xml",
+]
+
[[package]]
name = "ente_photos_rust"
version = "0.0.1"
dependencies = [
+ "ente_media_inspector",
"flutter_rust_bridge",
"usearch",
]
@@ -668,6 +676,15 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "quick-xml"
+version = "0.37.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "quote"
version = "1.0.42"
diff --git a/mobile/apps/photos/rust/Cargo.toml b/mobile/apps/photos/rust/Cargo.toml
index 96ce348658..763e852159 100644
--- a/mobile/apps/photos/rust/Cargo.toml
+++ b/mobile/apps/photos/rust/Cargo.toml
@@ -9,6 +9,7 @@ crate-type = ["cdylib", "staticlib"]
[dependencies]
flutter_rust_bridge = "=2.11.1"
usearch = "2.21.3"
+ente_media_inspector = { path = "../../../../rust/photos" }
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] }
diff --git a/mobile/apps/photos/rust/src/api/mod.rs b/mobile/apps/photos/rust/src/api/mod.rs
index 0f2ad1bb99..2d5dea2cd1 100644
--- a/mobile/apps/photos/rust/src/api/mod.rs
+++ b/mobile/apps/photos/rust/src/api/mod.rs
@@ -1,2 +1,3 @@
pub mod init;
+pub mod motion_photo_api;
pub mod usearch_api;
diff --git a/mobile/apps/photos/rust/src/api/motion_photo_api.rs b/mobile/apps/photos/rust/src/api/motion_photo_api.rs
new file mode 100644
index 0000000000..2cfc9467ff
--- /dev/null
+++ b/mobile/apps/photos/rust/src/api/motion_photo_api.rs
@@ -0,0 +1,69 @@
+use std::collections::HashMap;
+
+use ente_media_inspector::{
+ VideoIndex as CoreVideoIndex, extract_motion_video_file_from_path, extract_xmp_from_path,
+ get_motion_video_index_from_path,
+};
+
+#[derive(Clone, Debug)]
+pub struct VideoIndex {
+ pub start: i64,
+ pub end: i64,
+}
+
+impl TryFrom<CoreVideoIndex> for VideoIndex {
+ type Error = String;
+
+ fn try_from(value: CoreVideoIndex) -> Result<Self, Self::Error> {
+ let start = i64::try_from(value.start)
+ .map_err(|_| "video index start does not fit i64".to_string())?;
+ let end =
+ i64::try_from(value.end).map_err(|_| "video index end does not fit i64".to_string())?;
+ Ok(Self { start, end })
+ }
+}
+
+impl TryFrom<VideoIndex> for CoreVideoIndex {
+ type Error = String;
+
+ fn try_from(value: VideoIndex) -> Result<Self, Self::Error> {
+ if value.start < 0 || value.end < 0 {
+ return Err("video index cannot be negative".to_string());
+ }
+ let start = usize::try_from(value.start)
+ .map_err(|_| "video index start does not fit usize".to_string())?;
+ let end = usize::try_from(value.end)
+ .map_err(|_| "video index end does not fit usize".to_string())?;
+ Ok(Self { start, end })
+ }
+}
+
+pub fn get_motion_video_index(file_path: String) -> Result<Option<VideoIndex>, String> {
+ let result = get_motion_video_index_from_path(file_path)
+ .map_err(|err| format!("failed to get motion video index: {err}"))?;
+
+ result.map(TryInto::try_into).transpose()
+}
+
+pub fn extract_motion_video_file(
+ file_path: String,
+ destination_directory: String,
+ file_name: Option<String>,
+ index: Option<VideoIndex>,
+) -> Result<Option<String>, String> {
+ let file_name = file_name.unwrap_or_else(|| "motionphoto.mp4".to_string());
+ let core_index = index.map(TryInto::try_into).transpose()?;
+ let output = extract_motion_video_file_from_path(
+ file_path,
+ destination_directory,
+ &file_name,
+ core_index,
+ )
+ .map_err(|err| format!("failed to extract motion video file: {err}"))?;
+
+ Ok(output.map(|path| path.to_string_lossy().to_string()))
+}
+
+pub fn extract_xmp(file_path: String) -> Result<HashMap<String, String>, String> {
+ extract_xmp_from_path(file_path).map_err(|err| format!("failed to extract xmp: {err}"))
+}
diff --git a/rust/photos/Cargo.lock b/rust/photos/Cargo.lock
new file mode 100644
index 0000000000..5e67f7ff13
--- /dev/null
+++ b/rust/photos/Cargo.lock
@@ -0,0 +1,452 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anyhow"
+version = "1.0.101"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea"
+
+[[package]]
+name = "bitflags"
+version = "2.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "ente_media_inspector"
+version = "0.1.0"
+dependencies = [
+ "quick-xml",
+ "tempfile",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "getrandom"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "wasip2",
+ "wasip3",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
+[[package]]
+name = "indexmap"
+version = "2.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.16.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
+
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
+[[package]]
+name = "libc"
+version = "0.2.181"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "459427e2af2b9c839b132acb702a1c654d95e10f8c326bfc2ad11310e458b1c5"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "memchr"
+version = "2.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+
+[[package]]
+name = "once_cell"
+version = "1.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.37.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "rustix"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.114"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1"
+dependencies = [
+ "fastrand",
+ "getrandom",
+ "once_cell",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+[[package]]
+name = "wasip2"
+version = "1.0.2+wasi-0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4de98dfa5d5b7fef4ee834d0073d560c9ca7b6c46a71d058c48db7960f8cfaf7"
diff --git a/rust/photos/Cargo.toml b/rust/photos/Cargo.toml
new file mode 100644
index 0000000000..77c9276e44
--- /dev/null
+++ b/rust/photos/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "ente_media_inspector"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+quick-xml = "0.37"
+
+[dev-dependencies]
+tempfile = "3.12"
diff --git a/rust/photos/src/lib.rs b/rust/photos/src/lib.rs
new file mode 100644
index 0000000000..1e7135c0bb
--- /dev/null
+++ b/rust/photos/src/lib.rs
@@ -0,0 +1,346 @@
+use std::collections::HashMap;
+use std::fmt::{Display, Formatter};
+use std::fs;
+use std::path::{Path, PathBuf};
+
+const XMP_MARKER_BEGIN: &[u8] = b"<x:xmpmeta";
+const XMP_MARKER_END: &[u8] = b"</x:xmpmeta>";
+const ITEM_LENGTH_OFFSET_KEY: &str = "Item:Length";
+const GCAMERA_MOTION_PHOTO: &str = "GCamera:MotionPhoto";
+const ITEM_MIME_TYPE: &str = "Item:Mime";
+const FILE_OFFSET_KEYS: [&str; 2] = [ITEM_LENGTH_OFFSET_KEY, "GCamera:MicroVideoOffset"];
+const MP4_HEADER_PATTERN: [u8; 16] = [
+ 0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, 0x32, 0x00, 0x00, 0x00, 0x00,
+];
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct VideoIndex {
+ pub start: usize,
+ pub end: usize,
+}
+
+#[derive(Debug)]
+pub enum MotionPhotoError {
+ Io(std::io::Error),
+ Xml(String),
+ InvalidIndex,
+ VideoNotFound,
+}
+
+impl Display for MotionPhotoError {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Io(err) => write!(f, "io error: {err}"),
+ Self::Xml(err) => write!(f, "xmp parse error: {err}"),
+ Self::InvalidIndex => write!(f, "invalid video index"),
+ Self::VideoNotFound => write!(f, "unable to find video index"),
+ }
+ }
+}
+
+impl std::error::Error for MotionPhotoError {}
+
+impl From<std::io::Error> for MotionPhotoError {
+ fn from(value: std::io::Error) -> Self {
+ Self::Io(value)
+ }
+}
+
+pub fn get_motion_video_index_from_path<P: AsRef<Path>>(
+ file_path: P,
+) -> Result<Option<VideoIndex>, MotionPhotoError> {
+ let bytes = fs::read(file_path)?;
+ Ok(get_motion_video_index(&bytes))
+}
+
+fn get_motion_video_index(bytes: &[u8]) -> Option<VideoIndex> {
+ if let Some(start) = find_subslice(bytes, &MP4_HEADER_PATTERN) {
+ return Some(VideoIndex {
+ start,
+ end: bytes.len(),
+ });
+ }
+
+ extract_video_index_from_xmp(bytes)
+}
+
+pub fn extract_motion_video_from_path<P: AsRef<Path>>(
+ file_path: P,
+ index: Option<VideoIndex>,
+) -> Result<Option<Vec<u8>>, MotionPhotoError> {
+ let bytes = fs::read(file_path)?;
+ extract_motion_video(&bytes, index).map(Some)
+}
+
+fn extract_motion_video(
+ bytes: &[u8],
+ index: Option<VideoIndex>,
+) -> Result<Vec<u8>, MotionPhotoError> {
+ let video_index = index.or_else(|| get_motion_video_index(bytes));
+ let video_index = match video_index {
+ Some(value) => value,
+ None => return Err(MotionPhotoError::VideoNotFound),
+ };
+
+ if video_index.start >= video_index.end || video_index.end > bytes.len() {
+ return Err(MotionPhotoError::InvalidIndex);
+ }
+
+ Ok(bytes[video_index.start..video_index.end].to_vec())
+}
+
+pub fn extract_motion_video_file_from_path<P: AsRef<Path>, Q: AsRef<Path>>(
+ file_path: P,
+ destination_directory: Q,
+ file_name: &str,
+ index: Option<VideoIndex>,
+) -> Result<Option<PathBuf>, MotionPhotoError> {
+ let video = match extract_motion_video_from_path(file_path, index)? {
+ Some(data) => data,
+ None => return Ok(None),
+ };
+ fs::create_dir_all(destination_directory.as_ref())?;
+ let output = destination_directory.as_ref().join(file_name);
+ fs::write(&output, video)?;
+ Ok(Some(output))
+}
+
+pub fn extract_xmp_from_path<P: AsRef<Path>>(
+ file_path: P,
+) -> Result<HashMap<String, String>, MotionPhotoError> {
+ let bytes = fs::read(file_path)?;
+ extract_xmp(&bytes)
+}
+
+fn extract_xmp(source: &[u8]) -> Result<HashMap<String, String>, MotionPhotoError> {
+ let (begin, end) = extract_xmp_bounds(source)
+ .ok_or_else(|| MotionPhotoError::Xml("xmp markers not found".to_string()))?;
+ let xml_bytes = &source[begin..end];
+ parse_xmp_attributes(xml_bytes)
+}
+
+fn extract_video_index_from_xmp(bytes: &[u8]) -> Option<VideoIndex> {
+ let xmp_data = extract_xmp(bytes).ok()?;
+ let size = bytes.len();
+
+ for offset_key in FILE_OFFSET_KEYS {
+ let Some(raw_offset) = xmp_data.get(offset_key) else {
+ continue;
+ };
+ let Ok(offset_from_end) = raw_offset.parse::<usize>() else {
+ continue;
+ };
+
+ if offset_key == ITEM_LENGTH_OFFSET_KEY
+ && offset_from_end + offset_from_end < size
+ && !has_motion_photo_tags(&xmp_data)
+ {
+ continue;
+ }
+
+ if offset_from_end == 0 || offset_from_end > size {
+ continue;
+ }
+
+ return Some(VideoIndex {
+ start: size - offset_from_end,
+ end: size,
+ });
+ }
+
+ None
+}
+
+fn has_motion_photo_tags(xmp_data: &HashMap<String, String>) -> bool {
+ if xmp_data.contains_key(GCAMERA_MOTION_PHOTO) {
+ return true;
+ }
+
+ xmp_data
+ .get(ITEM_MIME_TYPE)
+ .map(|value| value.starts_with("video"))
+ .unwrap_or(false)
+}
+
+fn extract_xmp_bounds(source: &[u8]) -> Option<(usize, usize)> {
+ let offset_begin = find_subslice(source, XMP_MARKER_BEGIN)?;
+ let offset_end_start = find_subslice(&source[offset_begin..], XMP_MARKER_END)? + offset_begin;
+ let offset_end = offset_end_start + XMP_MARKER_END.len();
+ Some((offset_begin, offset_end))
+}
+
+fn parse_xmp_attributes(xml_bytes: &[u8]) -> Result<HashMap<String, String>, MotionPhotoError> {
+ use quick_xml::Reader;
+ use quick_xml::events::Event;
+
+ let xml_buffer = String::from_utf8_lossy(xml_bytes);
+ let mut reader = Reader::from_str(&xml_buffer);
+ let mut result = HashMap::<String, String>::new();
+ let mut scratch = Vec::<u8>::new();
+
+ loop {
+ match reader.read_event_into(&mut scratch) {
+ Ok(Event::Start(element)) | Ok(Event::Empty(element)) => {
+ for attribute in element.attributes() {
+ let attribute = attribute.map_err(|err| {
+ MotionPhotoError::Xml(format!("invalid attribute: {err}"))
+ })?;
+ let key = std::str::from_utf8(attribute.key.as_ref())
+ .map_err(|err| MotionPhotoError::Xml(format!("invalid key bytes: {err}")))?
+ .trim()
+ .to_string();
+ if key.starts_with("xmlns:") || key.starts_with("xml:") {
+ continue;
+ }
+
+ let value = attribute
+ .decode_and_unescape_value(reader.decoder())
+ .map_err(|err| MotionPhotoError::Xml(format!("invalid value: {err}")))?
+ .to_string();
+ result.insert(key, value);
+ }
+ }
+ Ok(Event::Eof) => break,
+ Ok(_) => {}
+ Err(err) => return Err(MotionPhotoError::Xml(format!("xml parse failed: {err}"))),
+ }
+ scratch.clear();
+ }
+
+ Ok(result)
+}
+
+fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ if needle.is_empty() {
+ return Some(0);
+ }
+ haystack
+ .windows(needle.len())
+ .position(|window| window == needle)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::tempdir;
+
+ fn xmp_with_offset(offset: usize, extra_attributes: &str) -> String {
+ format!(
+ r#"<x:xmpmeta><rdf:RDF><rdf:Description xmlns:x="adobe:ns:meta/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" Item:Length="{offset}" {extra_attributes} /></rdf:RDF></x:xmpmeta>"#
+ )
+ }
+
+ fn append_video_payload(mut bytes: Vec<u8>, payload_len: usize) -> Vec<u8> {
+ bytes.extend(std::iter::repeat_n(0xAB, payload_len));
+ bytes
+ }
+
+ fn bytes_with_xmp_and_video(offset: usize, extra_attributes: &str) -> Vec<u8> {
+ let mut bytes = b"jpeg-prefix-data".to_vec();
+ bytes.extend_from_slice(xmp_with_offset(offset, extra_attributes).as_bytes());
+ append_video_payload(bytes, offset)
+ }
+
+ #[test]
+ fn finds_mp4_header_in_jpeg_like_file() {
+ let mut bytes = b"jpeg-prefix".to_vec();
+ bytes.extend_from_slice(&MP4_HEADER_PATTERN);
+ bytes.extend_from_slice(&[1, 2, 3, 4]);
+
+ let index = get_motion_video_index(&bytes).expect("video index should exist");
+ assert_eq!(index.start, "jpeg-prefix".len());
+ assert_eq!(index.end, bytes.len());
+ }
+
+ #[test]
+ fn finds_xmp_offset_for_jpeg_like_file() {
+ let bytes = bytes_with_xmp_and_video(24, "GCamera:MotionPhoto=\"1\"");
+ let index = get_motion_video_index(&bytes).expect("video index should exist");
+ assert_eq!(index.start, bytes.len() - 24);
+ assert_eq!(index.end, bytes.len());
+ }
+
+ #[test]
+ fn finds_xmp_offset_for_heic_like_file() {
+ let mut bytes = b"heic-prefix-data".to_vec();
+ bytes.extend_from_slice(xmp_with_offset(32, "Item:Mime=\"video/mp4\"").as_bytes());
+ bytes = append_video_payload(bytes, 32);
+
+ let index = get_motion_video_index(&bytes).expect("video index should exist");
+ assert_eq!(index.start, bytes.len() - 32);
+ assert_eq!(index.end, bytes.len());
+ }
+
+ #[test]
+ fn returns_none_for_non_motion_file() {
+ let bytes = b"plain-still-image-data-without-motion-video-or-xmp".to_vec();
+ assert_eq!(get_motion_video_index(&bytes), None);
+ }
+
+ #[test]
+ fn skips_invalid_item_length_without_motion_tags() {
+ let mut bytes = b"prefix-data".to_vec();
+ bytes.extend_from_slice(xmp_with_offset(8, "").as_bytes());
+ bytes.extend_from_slice(b"small-tail");
+ assert_eq!(get_motion_video_index(&bytes), None);
+ }
+
+ #[test]
+ fn extracts_video_bytes_for_valid_index() {
+ let bytes = bytes_with_xmp_and_video(20, "GCamera:MotionPhoto=\"1\"");
+ let video = extract_motion_video(&bytes, None).expect("video bytes should extract");
+ assert_eq!(video.len(), 20);
+ assert!(video.iter().all(|byte| *byte == 0xAB));
+ }
+
+ #[test]
+ fn extracts_xmp_attributes() {
+ let bytes = bytes_with_xmp_and_video(
+ 16,
+ "GPano:ProjectionType=\"equirectangular\" GCamera:MotionPhoto=\"1\"",
+ );
+ let xmp = extract_xmp(&bytes).expect("xmp must parse");
+ assert_eq!(
+ xmp.get("GPano:ProjectionType"),
+ Some(&"equirectangular".to_string())
+ );
+ assert_eq!(xmp.get("GCamera:MotionPhoto"), Some(&"1".to_string()));
+ }
+
+ #[test]
+ fn path_apis_work_for_various_file_types() {
+ let temp = tempdir().expect("temp dir");
+ let jpeg_motion = temp.path().join("motion.jpg");
+ let heic_motion = temp.path().join("motion.heic");
+ let non_motion = temp.path().join("normal.jpg");
+
+ fs::write(
+ &jpeg_motion,
+ bytes_with_xmp_and_video(40, "GCamera:MotionPhoto=\"1\""),
+ )
+ .expect("write jpeg motion");
+
+ fs::write(
+ &heic_motion,
+ bytes_with_xmp_and_video(28, "Item:Mime=\"video/mp4\""),
+ )
+ .expect("write heic motion");
+
+ fs::write(&non_motion, b"non-motion-image").expect("write still");
+
+ assert!(
+ get_motion_video_index_from_path(&jpeg_motion)
+ .expect("jpeg read")
+ .is_some()
+ );
+ assert!(
+ get_motion_video_index_from_path(&heic_motion)
+ .expect("heic read")
+ .is_some()
+ );
+ assert_eq!(
+ get_motion_video_index_from_path(&non_motion).expect("still read"),
+ None
+ );
+ }
+}
diff --git a/rust/photos/tests/motion_photos_assets_test.rs b/rust/photos/tests/motion_photos_assets_test.rs
new file mode 100644
index 0000000000..ced1ca0db3
--- /dev/null
+++ b/rust/photos/tests/motion_photos_assets_test.rs
@@ -0,0 +1,87 @@
+use ente_media_inspector::{extract_motion_video_from_path, get_motion_video_index_from_path};
+use std::path::{Path, PathBuf};
+
+fn fixture_dir() -> Option<PathBuf> {
+ // Optional override for CI or custom local layouts.
+ if let Some(path) = std::env::var_os("ENTE_TEST_FIXTURES_DIR") {
+ return Some(PathBuf::from(path).join("media/motion-photos/v1/files"));
+ }
+
+ // CARGO_MANIFEST_DIR points to `<repo>/rust/photos`.
+ // We resolve `<repo>/..../test-fixtures/media/motion-photos/v1/files`,
+ // where `test-fixtures` is expected to be a sibling of the main repo root.
+ let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
+ let repo_root = manifest_dir.parent()?.parent()?; // rust/photos -> rust -> <repo root>
+ let parent_of_repo = repo_root.parent()?;
+ Some(
+ parent_of_repo
+ .join("test-fixtures")
+ .join("media/motion-photos/v1/files"),
+ )
+}
+
+fn fixture(name: &str) -> Option<PathBuf> {
+ let mut path = fixture_dir()?;
+ path.push(name);
+ if path.exists() { Some(path) } else { None }
+}
+
+#[test]
+fn validates_known_motion_photo_indices_when_fixtures_present() {
+ let Some(motion_jpg) = fixture("motionphoto.jpg") else {
+ eprintln!("Skipping: external fixture motionphoto.jpg not present");
+ return;
+ };
+ let Some(motion_heic) = fixture("motionphoto.heic") else {
+ eprintln!("Skipping: external fixture motionphoto.heic not present");
+ return;
+ };
+ let Some(pixel6) = fixture("pixel_6_small_video.jpg") else {
+ eprintln!("Skipping: external fixture pixel_6_small_video.jpg not present");
+ return;
+ };
+ let Some(pixel8) = fixture("pixel_8.jpg") else {
+ eprintln!("Skipping: external fixture pixel_8.jpg not present");
+ return;
+ };
+ let Some(normal) = fixture("normalphoto.jpg") else {
+ eprintln!("Skipping: external fixture normalphoto.jpg not present");
+ return;
+ };
+
+ let motion_jpg_index = get_motion_video_index_from_path(&motion_jpg)
+ .expect("read motionphoto.jpg")
+ .expect("motionphoto.jpg should have index");
+ assert_eq!(motion_jpg_index.start, 3_366_251);
+ assert_eq!(motion_jpg_index.end, 8_013_982);
+
+ let motion_heic_index = get_motion_video_index_from_path(&motion_heic)
+ .expect("read motionphoto.heic")
+ .expect("motionphoto.heic should have index");
+ assert_eq!(motion_heic_index.start, 1_455_411);
+ assert_eq!(motion_heic_index.end, 3_649_069);
+
+ let pixel6_index = get_motion_video_index_from_path(&pixel6)
+ .expect("read pixel_6_small_video.jpg")
+ .expect("pixel_6_small_video.jpg should have index");
+ assert!(pixel6_index.start > 0);
+
+ assert_eq!(
+ get_motion_video_index_from_path(&pixel8).expect("read pixel_8.jpg"),
+ None
+ );
+ assert_eq!(
+ get_motion_video_index_from_path(&normal).expect("read normalphoto.jpg"),
+ None
+ );
+
+ let motion_jpg_video = extract_motion_video_from_path(&motion_jpg, None)
+ .expect("extract motionphoto.jpg video")
+ .expect("video present");
+ assert!(motion_jpg_video.len() > 1_000_000);
+
+ let motion_heic_video = extract_motion_video_from_path(&motion_heic, None)
+ .expect("extract motionphoto.heic video")
+ .expect("video present");
+ assert!(motion_heic_video.len() > 1_000_000);
+}