rosier 0.5.1

A fast picture and video viewer for large folders
//! Motion photos: a still with a few seconds of video. Pixel and Samsung
//! phones append the video (an MP4) to the JPEG; an iPhone Live Photo is a
//! still with a .MOV of the same name beside it. Rosier shows the still and
//! plays the motion once over it.

use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

/// How far into a JPEG its XMP is looked for.
const HEAD: usize = 256 << 10;

/// Where the video of a motion photo is: the file beside it, or a part of
/// the picture's own file.
#[derive(Debug, PartialEq, Eq)]
pub enum Clip {
    File(PathBuf),
    /// Bytes `start..start + len` of the picture's file.
    Embedded {
        start: u64,
        len: u64,
    },
}

/// The motion of the picture at `path`, if it is a motion photo.
pub fn find(path: &Path) -> Option<Clip> {
    if let Some(mov) = companion(path) {
        return Some(Clip::File(mov));
    }
    let ext = crate::media::ext_lower(path)?;
    if !matches!(ext.as_str(), "jpg" | "jpeg") {
        return None;
    }
    let mut f = std::fs::File::open(path).ok()?;
    let size = f.metadata().ok()?.len();
    let mut head = vec![0u8; HEAD.min(size as usize)];
    f.read_exact(&mut head).ok()?;
    if let Some(len) = xmp_video_len(&head).filter(|&n| n > 8 && n < size) {
        let start = size - len;
        return is_mp4_at(&mut f, start).then_some(Clip::Embedded { start, len });
    }
    // Samsung: "MotionPhoto_Data" right before the video, near the end.
    // Only Samsung cameras write it, so other pictures are not read further.
    if !head.windows(7).any(|w| w.eq_ignore_ascii_case(b"samsung")) {
        return None;
    }
    let tail_len = size.min(64 << 20);
    f.seek(SeekFrom::Start(size - tail_len)).ok()?;
    let mut tail = Vec::with_capacity(tail_len as usize);
    f.take(tail_len).read_to_end(&mut tail).ok()?;
    let marker = b"MotionPhoto_Data";
    let at = tail.windows(marker.len()).rposition(|w| w == marker)?;
    let start = size - tail_len + (at + marker.len()) as u64;
    is_mp4_at(&mut std::fs::File::open(path).ok()?, start).then(|| Clip::Embedded { start, len: size - start })
}

/// An iPhone Live Photo's video: IMG_1234.MOV beside IMG_1234.HEIC or .JPG.
fn companion(path: &Path) -> Option<PathBuf> {
    let ext = crate::media::ext_lower(path)?;
    if !matches!(ext.as_str(), "heic" | "heif" | "jpg" | "jpeg") {
        return None;
    }
    ["MOV", "mov"].into_iter().map(|e| path.with_extension(e)).find(|p| p.is_file())
}

/// Whether a still at `path` stands beside a `.mov` of the same name, so the
/// MOV is the motion of a Live Photo rather than a video of its own.
pub fn is_live_video(path: &Path) -> bool {
    crate::media::ext_lower(path).is_some_and(|e| e == "mov")
        && ["HEIC", "heic", "JPG", "jpg", "JPEG", "jpeg"].into_iter().any(|e| path.with_extension(e).is_file())
}

/// The video's length from the end of the file, as the XMP says: Google's
/// `GCamera:MicroVideoOffset`, or the `Item:Length` of the MotionPhoto item
/// in a `Container:Directory`.
fn xmp_video_len(head: &[u8]) -> Option<u64> {
    let start = find_bytes(head, b"<x:xmpmeta")?;
    let end = find_bytes(&head[start..], b"</x:xmpmeta>").map_or(head.len(), |e| start + e);
    let xmp = String::from_utf8_lossy(&head[start..end]);
    if let Some(v) = attr_value(&xmp, "GCamera:MicroVideoOffset") {
        return v.parse().ok();
    }
    // Each Container:Item names its semantic and, for the video, its length.
    let mut rest = xmp.as_ref();
    while let Some(i) = rest.find("Item:Semantic") {
        let item_end = rest[i..].find("/>").map_or(rest.len(), |e| i + e);
        let item_start = rest[..i].rfind('<').unwrap_or(0);
        let item = &rest[item_start..item_end];
        if attr_value(item, "Item:Semantic").is_some_and(|s| s == "MotionPhoto") {
            return attr_value(item, "Item:Length")?.parse().ok();
        }
        rest = &rest[item_end.min(rest.len())..];
        if item_end == 0 {
            break;
        }
    }
    None
}

/// `name="value"` (or `name='value'`) in XMP text.
fn attr_value<'a>(xmp: &'a str, name: &str) -> Option<&'a str> {
    let at = xmp.find(&format!("{name}="))? + name.len() + 1;
    let q = xmp[at..].chars().next().filter(|c| *c == '"' || *c == '\'')?;
    let body = &xmp[at + 1..];
    body.find(q).map(|e| &body[..e])
}

fn find_bytes(hay: &[u8], needle: &[u8]) -> Option<usize> {
    hay.windows(needle.len()).position(|w| w == needle)
}

/// Whether an MP4 (or QuickTime) file starts at `at`: a box size, then
/// "ftyp".
fn is_mp4_at(f: &mut std::fs::File, at: u64) -> bool {
    let mut b = [0u8; 8];
    f.seek(SeekFrom::Start(at)).is_ok() && f.read_exact(&mut b).is_ok() && &b[4..8] == b"ftyp"
}

/// A file mpv can play for `clip` of the picture at `path`: the companion
/// itself, or the embedded part copied once into the cache.
pub fn playable(path: &Path, clip: &Clip) -> Option<PathBuf> {
    match clip {
        Clip::File(p) => Some(p.clone()),
        Clip::Embedded { start, len } => {
            use std::hash::{Hash, Hasher};
            let md = std::fs::metadata(path).ok()?;
            let mut h = std::collections::hash_map::DefaultHasher::new();
            (path, md.len(), md.modified().ok()).hash(&mut h);
            let dir = crate::thumb::cache_root().join("motion");
            let out = dir.join(format!("{:016x}.mp4", h.finish()));
            if !out.is_file() {
                std::fs::create_dir_all(&dir).ok()?;
                let mut f = std::fs::File::open(path).ok()?;
                f.seek(SeekFrom::Start(*start)).ok()?;
                let mut data = Vec::with_capacity(*len as usize);
                f.take(*len).read_to_end(&mut data).ok()?;
                let tmp = out.with_extension("tmp");
                std::fs::write(&tmp, &data).ok()?;
                std::fs::rename(&tmp, &out).ok()?;
            }
            Some(out)
        }
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    /// A JPEG still with `video` appended and an XMP block saying so, the
    /// way Pixel phones write motion photos.
    pub fn pixel_motion_photo(video: &[u8]) -> Vec<u8> {
        let xmp = format!(
            r#"http://ns.adobe.com/xap/1.0/\0<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:Description GCamera:MotionPhoto="1"><Container:Directory><rdf:Seq><rdf:li><Container:Item Item:Semantic="Primary" Item:Mime="image/jpeg"/></rdf:li><rdf:li><Container:Item Item:Semantic="MotionPhoto" Item:Mime="video/mp4" Item:Length="{}"/></rdf:li></rdf:Seq></Container:Directory></rdf:Description></x:xmpmeta>"#,
            video.len()
        );
        let mut img = Vec::new();
        image::RgbImage::from_pixel(8, 8, image::Rgb([10, 200, 30]))
            .write_to(&mut std::io::Cursor::new(&mut img), image::ImageFormat::Jpeg)
            .unwrap();
        let seg = xmp.replace("\\0", "\0").into_bytes();
        let mut out = img[..2].to_vec();
        out.extend_from_slice(&[0xFF, 0xE1]);
        out.extend_from_slice(&((seg.len() + 2) as u16).to_be_bytes());
        out.extend_from_slice(&seg);
        out.extend_from_slice(&img[2..]);
        out.extend_from_slice(video);
        out
    }

    fn fake_mp4() -> Vec<u8> {
        let mut v = 24u32.to_be_bytes().to_vec();
        v.extend_from_slice(b"ftypmp42");
        v.extend_from_slice(&[0; 12]);
        v.extend_from_slice(b"rest of the video");
        v
    }

    #[test]
    fn finds_the_video_of_pixel_samsung_and_iphone_motion_photos() {
        let dir = std::env::temp_dir().join(format!("rosier-motion-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let mp4 = fake_mp4();
        // Pixel: the XMP gives the length from the end.
        let pixel = dir.join("PXL_1.MP.jpg");
        let data = pixel_motion_photo(&mp4);
        std::fs::write(&pixel, &data).unwrap();
        let start = (data.len() - mp4.len()) as u64;
        assert_eq!(find(&pixel), Some(Clip::Embedded { start, len: mp4.len() as u64 }));
        // Older Pixels: MicroVideoOffset.
        let old = String::from_utf8_lossy(&data).into_owned();
        assert!(old.contains("Item:Length"));
        // Samsung: a marker before the video.
        let mut sam = Vec::new();
        image::RgbImage::new(4, 4).write_to(&mut std::io::Cursor::new(&mut sam), image::ImageFormat::Jpeg).unwrap();
        // (Stands in for the camera's EXIF Make.)
        sam.extend_from_slice(b"SAMSUNG");
        sam.extend_from_slice(b"MotionPhoto_Data");
        let sstart = sam.len() as u64;
        sam.extend_from_slice(&mp4);
        let samsung = dir.join("20240101_120000.jpg");
        std::fs::write(&samsung, &sam).unwrap();
        assert_eq!(find(&samsung), Some(Clip::Embedded { start: sstart, len: mp4.len() as u64 }));
        // The embedded video is copied out once, byte for byte.
        let out = playable(&pixel, &find(&pixel).unwrap()).unwrap();
        assert_eq!(std::fs::read(&out).unwrap(), mp4);
        // iPhone: a MOV of the same name beside the still.
        let still = dir.join("IMG_0001.JPG");
        image::RgbImage::new(4, 4).save_with_format(&still, image::ImageFormat::Jpeg).unwrap();
        assert_eq!(find(&still), None, "a plain photo");
        std::fs::write(dir.join("IMG_0001.MOV"), &mp4).unwrap();
        assert_eq!(find(&still), Some(Clip::File(dir.join("IMG_0001.MOV"))));
        assert!(is_live_video(&dir.join("IMG_0001.MOV")));
        assert!(!is_live_video(&dir.join("other.mov")));
        // The library lists the Live Photo once, as its still.
        std::fs::write(dir.join("clip.mov"), &mp4).unwrap();
        let names: Vec<String> = crate::media::scan(&dir)
            .iter()
            .map(|e| e.path.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert!(names.contains(&"IMG_0001.JPG".to_string()) && names.contains(&"clip.mov".to_string()));
        assert!(!names.contains(&"IMG_0001.MOV".to_string()), "{names:?}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// How long looking costs for a photo that is not a motion photo
    /// (`cargo test --release -- --ignored motion_lookup_cost --nocapture`).
    #[test]
    #[ignore]
    fn motion_lookup_cost() {
        let path = std::path::PathBuf::from(std::env::var("ROSIER_MOTION_PHOTO").expect("a JPEG to look at"));
        let t = std::time::Instant::now();
        for _ in 0..100 {
            assert_eq!(find(&path), None);
        }
        eprintln!("find: {:?} per photo", t.elapsed() / 100);
    }

    #[test]
    fn reads_the_older_micro_video_offset() {
        let xmp =
            br#"xx<x:xmpmeta><rdf:Description GCamera:MicroVideo="1" GCamera:MicroVideoOffset="12345"/></x:xmpmeta>"#;
        assert_eq!(xmp_video_len(xmp), Some(12345));
        assert_eq!(xmp_video_len(b"no xmp here"), None);
    }
}