rosier 0.5.2

A fast picture and video viewer for large folders
//! Animated GIF and WebP: every frame, fitted to the viewer, with how long
//! each one shows. gpui plays a picture with several frames by itself.

use std::io::Cursor;
use std::time::Duration;

use anyhow::Result;
use image::AnimationDecoder as _;

use crate::thumb::fit;
use crate::turbo::Bgra;

/// Memory for one animation's decoded frames. Past it, the frames are
/// decoded smaller instead of being dropped.
const BUDGET_BYTES: usize = 192 << 20;
/// Frames beyond this are not played.
const MAX_FRAMES: usize = 1000;
/// Smallest long side an animation is shrunk to while fitting the budget.
const MIN_LONG: u32 = 128;

/// The frames of an animated GIF or WebP, and its full size.
pub struct Animation {
    pub frames: Vec<(Bgra, Duration)>,
    pub full: (u32, u32),
}

/// Decodes every frame of `data` if it is an animated GIF or WebP, fitted
/// so the longer side is at most `max_long`. None for other formats and for
/// a GIF or WebP with a single frame.
pub fn decode(data: &[u8], max_long: u32) -> Result<Option<Animation>> {
    decode_within(data, max_long, BUDGET_BYTES)
}

/// The first frame of `data`, fitted like `decode`, and the full size, if
/// it is an animated GIF or WebP: what the viewer shows while the rest is
/// decoded. Reads one frame past it to tell an animation from a still.
pub fn first(data: &[u8], max_long: u32) -> Result<Option<(Bgra, (u32, u32))>> {
    let Some(mut frames) = frames_of(data)? else { return Ok(None) };
    let Some(frame) = frames.next() else { return Ok(None) };
    let buf = frame?.into_buffer();
    if frames.next().is_none() {
        return Ok(None);
    }
    let full = buf.dimensions();
    let b = Bgra::from_rgba(full.0, full.1, buf.into_raw());
    Ok(Some((fit(b, max_long.min(full.0.max(full.1)))?, full)))
}

/// The frames of an animated GIF or WebP; None for other formats and for a
/// still WebP.
fn frames_of(data: &[u8]) -> Result<Option<image::Frames<'_>>> {
    let cursor = Cursor::new(data);
    Ok(Some(match image::guess_format(data) {
        Ok(image::ImageFormat::Gif) => image::codecs::gif::GifDecoder::new(cursor)?.into_frames(),
        Ok(image::ImageFormat::WebP) => {
            let d = image::codecs::webp::WebPDecoder::new(cursor)?;
            if !d.has_animation() {
                return Ok(None);
            }
            d.into_frames()
        }
        _ => return Ok(None),
    }))
}

fn decode_within(data: &[u8], max_long: u32, budget: usize) -> Result<Option<Animation>> {
    let Some(frames) = frames_of(data)? else { return Ok(None) };
    let mut out: Vec<(Bgra, Duration)> = Vec::new();
    let (mut long, mut bytes, mut full) = (max_long, 0, (0, 0));
    for frame in frames.take(MAX_FRAMES) {
        let frame = frame?;
        let delay = shown_for(frame.delay());
        let buf = frame.into_buffer();
        full = buf.dimensions();
        let b = Bgra::from_rgba(full.0, full.1, buf.into_raw());
        long = long.min(full.0.max(full.1));
        let b = fit(b, long)?;
        bytes += b.pixels.len();
        out.push((b, delay));
        // Over budget: halve every frame so far and decode the rest at
        // that size.
        while bytes > budget && long > MIN_LONG {
            long = (long / 2).max(MIN_LONG);
            out = out.into_iter().map(|(b, d)| Ok((fit(b, long)?, d))).collect::<Result<_>>()?;
            bytes = out.iter().map(|(b, _)| b.pixels.len()).sum();
        }
        if bytes > budget {
            out.pop();
            break;
        }
    }
    Ok((out.len() > 1).then_some(Animation { frames: out, full }))
}

/// How long a frame shows. Like browsers, delays under 20 ms (often 0 in
/// old GIFs) play at 100 ms.
fn shown_for(delay: image::Delay) -> Duration {
    let (num, den) = delay.numer_denom_ms();
    let ms = num as f64 / den.max(1) as f64;
    if ms < 20.0 { Duration::from_millis(100) } else { Duration::from_secs_f64(ms / 1000.0) }
}

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

    /// A GIF of `n` frames of `w`x`h`, each `delay_cs` hundredths of a second.
    pub fn gif(n: u8, w: u16, h: u16, delay_cs: u16) -> Vec<u8> {
        use image::codecs::gif::{GifEncoder, Repeat};
        let mut out = Vec::new();
        {
            let mut enc = GifEncoder::new(&mut out);
            enc.set_repeat(Repeat::Infinite).unwrap();
            for k in 0..n {
                let buf = image::RgbaImage::from_pixel(
                    w as u32,
                    h as u32,
                    image::Rgba([k.wrapping_mul(40), 0, 255 - k.wrapping_mul(40), 255]),
                );
                let delay = image::Delay::from_numer_denom_ms(delay_cs as u32 * 10, 1);
                enc.encode_frame(image::Frame::from_parts(buf, 0, 0, delay)).unwrap();
            }
        }
        out
    }

    #[test]
    fn the_first_frame_comes_alone_and_stills_are_not_animations() {
        let (b, full) = first(&gif(3, 40, 20, 5), 1000).unwrap().unwrap();
        assert_eq!(full, (40, 20));
        assert_eq!((b.width, b.height), (40, 20));
        assert_eq!(&b.pixels[..4], &[255, 0, 0, 255], "the first frame");
        let (small, _) = first(&gif(2, 400, 200, 5), 100).unwrap().unwrap();
        assert_eq!((small.width, small.height), (100, 50));
        assert!(first(&gif(1, 40, 20, 5), 1000).unwrap().is_none(), "one frame is a still");
        assert!(first(b"not a picture", 1000).unwrap().is_none());
    }

    #[test]
    fn decodes_every_frame_with_its_delay() {
        let a = decode(&gif(3, 40, 20, 5), 1000).unwrap().unwrap();
        assert_eq!(a.full, (40, 20));
        assert_eq!(a.frames.len(), 3);
        assert!(a.frames.iter().all(|(_, d)| *d == Duration::from_millis(50)));
        // Red in the first frame (BGRA: blue byte first), blue in the last.
        assert_eq!(&a.frames[0].0.pixels[..4], &[255, 0, 0, 255]);
        assert_eq!(a.frames[2].0.pixels[2], 80);
    }

    #[test]
    fn fits_frames_and_plays_zero_delays_at_100_ms() {
        let a = decode(&gif(2, 400, 200, 0), 100).unwrap().unwrap();
        assert_eq!((a.frames[0].0.width, a.frames[0].0.height), (100, 50));
        assert_eq!(a.full, (400, 200), "the full size is the file's");
        assert_eq!(a.frames[1].1, Duration::from_millis(100));
    }

    #[test]
    fn stills_and_other_formats_are_not_animations() {
        assert!(decode(&gif(1, 8, 8, 5), 100).unwrap().is_none());
        let mut png = Vec::new();
        image::RgbaImage::new(4, 4).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
        assert!(decode(&png, 100).unwrap().is_none());
        assert!(decode(b"GIF89a broken", 100).is_err());
    }

    #[test]
    fn a_big_animation_is_shrunk_to_fit_the_budget() {
        // 20 frames of 400x400 are 12.8 MB; the budget here is 4 MB.
        let a = decode_within(&gif(20, 400, 400, 5), 4000, 4 << 20).unwrap().unwrap();
        let bytes: usize = a.frames.iter().map(|(b, _)| b.pixels.len()).sum();
        assert_eq!(a.frames.len(), 20);
        assert!(bytes <= 4 << 20, "{bytes}");
        assert_eq!(a.frames[0].0.width, 200, "halved once, no further");
        assert!(a.frames.iter().all(|(b, _)| b.width == 200), "every frame the same size");
        // Even the smallest size cannot hold them all: the rest is cut.
        let a = decode_within(&gif(20, 400, 400, 5), 4000, 300_000).unwrap().unwrap();
        let bytes: usize = a.frames.iter().map(|(b, _)| b.pixels.len()).sum();
        assert!(a.frames.len() < 20 && a.frames[0].0.width == MIN_LONG && bytes <= 300_000);
    }
}