use std::io::Cursor;
use std::time::Duration;
use anyhow::Result;
use image::AnimationDecoder as _;
use crate::thumb::fit;
use crate::turbo::Bgra;
const BUDGET_BYTES: usize = 192 << 20;
const MAX_FRAMES: usize = 1000;
const MIN_LONG: u32 = 128;
pub struct Animation {
pub frames: Vec<(Bgra, Duration)>,
pub full: (u32, u32),
}
pub fn decode(data: &[u8], max_long: u32) -> Result<Option<Animation>> {
decode_within(data, max_long, BUDGET_BYTES)
}
fn decode_within(data: &[u8], max_long: u32, budget: usize) -> Result<Option<Animation>> {
let cursor = Cursor::new(data);
let frames = 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),
};
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 mut b = Bgra { width: full.0, height: full.1, pixels: buf.into_raw() };
for px in b.pixels.as_chunks_mut::<4>().0 {
px.swap(0, 2);
}
long = long.min(full.0.max(full.1));
let b = fit(b, long)?;
bytes += b.pixels.len();
out.push((b, delay));
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 }))
}
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::*;
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 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)));
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() {
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");
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);
}
}