use std::io::Cursor;
use std::num::NonZeroU64;
use std::path::Path;
use std::time::Duration;
use crabshell_ui::{Fit, ImageFilters};
use gif::DisposalMethod;
use tiny_skia::Pixmap;
use crate::icons::{premultiplied, read_capped};
use crate::images::{MAX_BYTES, MAX_PIXELS, Picture, check, filtered, finish};
const MAX_DECODED_PIXELS: u64 = 64 * 1024 * 1024;
const MAX_KEPT_PIXELS: u64 = 8 * 1024 * 1024;
pub(crate) struct Frames {
pub(crate) frames: Vec<Frame>,
pub(crate) repeats: Option<u32>,
}
impl Frames {
pub(crate) fn still(pixmap: Pixmap) -> Frames {
Frames {
frames: vec![Frame {
pixmap,
delay: Duration::ZERO,
}],
repeats: Some(0),
}
}
}
pub(crate) struct Frame {
pub(crate) pixmap: Pixmap,
pub(crate) delay: Duration,
}
pub(crate) fn frames(
path: &Path,
size: (u32, u32),
fit: Fit,
filters: &ImageFilters,
scale: f32,
room: usize,
) -> Result<Frames, String> {
let limits = Limits {
work: MAX_DECODED_PIXELS,
kept: MAX_KEPT_PIXELS.min(room as u64 / 4),
};
frames_within(path, size, fit, filters, scale, limits)
}
#[derive(Clone, Copy)]
pub(crate) struct Limits {
pub(crate) work: u64,
pub(crate) kept: u64,
}
pub(crate) fn frames_within(
path: &Path,
size: (u32, u32),
fit: Fit,
filters: &ImageFilters,
scale: f32,
limits: Limits,
) -> Result<Frames, String> {
let is_gif = path
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("gif"));
if !is_gif || filters.blur > 0.0 {
return filtered(path, size, fit, filters, scale).map(Frames::still);
}
if size.0 == 0 || size.1 == 0 {
return Err(String::from("an image with no pixels"));
}
let data = read_capped(path, MAX_BYTES)?;
let mut gif = Gif::open(&data)?;
let canvas_pixels = u64::from(gif.width) * u64::from(gif.height);
let drawn = u64::from(size.0) * u64::from(size.1);
let mut frames = Vec::new();
let mut broken = false;
loop {
let (canvas, delay) = match gif.next_frame() {
Ok(Some(frame)) => frame,
Ok(None) => break,
Err(error) if frames.is_empty() => return Err(error),
Err(error) => {
tracing::warn!(image = %path.display(), %error, "a GIF stops at a broken frame");
broken = true;
break;
}
};
let count = frames.len() as u64 + 1;
let past = if count.saturating_mul(canvas_pixels) > limits.work {
Some(("decoding", limits.work))
} else if count.saturating_mul(drawn) > limits.kept {
Some(("keeping", limits.kept))
} else {
None
};
if let Some((what, limit)) = past.filter(|_| count > 1) {
tracing::warn!(
image = %path.display(),
"{what} a GIF's frames at this size is past {limit} pixels, so it shows its first"
);
frames.truncate(1);
break;
}
let pixmap = finish(&Picture::Pixels(canvas), size, fit, filters, scale)?;
frames.push(Frame { pixmap, delay });
}
let repeats = match gif.decoder.repeat() {
_ if broken || frames.len() < 2 => Some(0),
gif::Repeat::Infinite => None,
gif::Repeat::Finite(count) => Some(u32::from(count)),
};
Ok(Frames { frames, repeats })
}
pub(crate) struct Gif<'a> {
decoder: gif::Decoder<Cursor<&'a [u8]>>,
width: u32,
height: u32,
canvas: Vec<u8>,
}
impl<'a> Gif<'a> {
pub(crate) fn open(data: &'a [u8]) -> Result<Gif<'a>, String> {
let mut options = gif::DecodeOptions::new();
options.set_color_output(gif::ColorOutput::RGBA);
options.check_frame_consistency(true);
if let Some(limit) = NonZeroU64::new(MAX_PIXELS * 4) {
options.set_memory_limit(gif::MemoryLimit::Bytes(limit));
}
let decoder = options
.read_info(Cursor::new(data))
.map_err(|error| error.to_string())?;
let (width, height) = (u32::from(decoder.width()), u32::from(decoder.height()));
check(width, height)?;
Ok(Gif {
decoder,
width,
height,
canvas: vec![0; width as usize * height as usize * 4],
})
}
pub(crate) fn next_frame(&mut self) -> Result<Option<(Pixmap, Duration)>, String> {
let Some(frame) = self
.decoder
.read_next_frame()
.map_err(|error| error.to_string())?
else {
return Ok(None);
};
if frame.width == 0 || frame.height == 0 {
return Err(String::from("a GIF frame with no pixels"));
}
let (left, top) = (u32::from(frame.left), u32::from(frame.top));
if left + u32::from(frame.width) > self.width || top + u32::from(frame.height) > self.height {
return Err(String::from("a GIF frame past its canvas"));
}
let columns = usize::from(frame.width);
let previous = (frame.dispose == DisposalMethod::Previous).then(|| self.canvas.clone());
let mut rows = Vec::new();
for (row, line) in frame.buffer.chunks_exact(columns * 4).enumerate() {
let y = top + row as u32;
let start = (y as usize * self.width as usize + left as usize) * 4;
rows.push(start);
let target = &mut self.canvas[start..start + columns * 4];
for (pixel, source) in target
.as_chunks_mut::<4>()
.0
.iter_mut()
.zip(line.as_chunks::<4>().0)
{
if source[3] != 0 {
*pixel = *source;
}
}
}
let delay = match frame.delay {
0 | 1 => Duration::from_millis(100),
delay => Duration::from_millis(u64::from(delay) * 10),
};
let dispose = frame.dispose;
let shown = premultiplied(self.canvas.clone(), self.width, self.height)?;
match dispose {
DisposalMethod::Background => {
for start in rows {
self.canvas[start..start + columns * 4].fill(0);
}
}
DisposalMethod::Previous => {
if let Some(previous) = previous {
self.canvas = previous;
}
}
DisposalMethod::Any | DisposalMethod::Keep => {}
}
Ok(Some((shown, delay)))
}
}