use crate::animation::{After, Frame, Kind, Laid, LoadedAnimation};
const MOST: usize = 2730;
const CODES: usize = 4096;
pub fn decode(gif: &[u8]) -> Option<(usize, Vec<u32>)> {
let mut anim = read_animation(gif, 1)?;
let (pixels, width) = anim.shown(0);
Some((width, pixels.to_vec()))
}
#[derive(Clone, Copy, Default)]
struct Control {
clear: Option<u8>,
after: u8,
shows: u64,
}
pub(crate) fn read_animation(gif: &[u8], most: usize) -> Option<LoadedAnimation> {
let head = gif.first_chunk::<13>().filter(|head| head.starts_with(b"GIF87a") || head.starts_with(b"GIF89a"))?;
let size = [u16::from_le_bytes([head[6], head[7]]) as usize, u16::from_le_bytes([head[8], head[9]]) as usize];
if size[0] * size[1] == 0 || size[0] * size[1] > gif.len().saturating_mul(MOST) {
return None;
}
let mut anim = LoadedAnimation::new(size, Kind::Gif(Vec::new(), Vec::new()), Some(1));
let mut rest = &gif[13..];
let (shared, mut control) = (list(&mut anim, &mut rest, head[10])?, Control::default());
while let Some((kind, after)) = rest.split_first().filter(|_| anim.frames.len() < most) {
rest = after;
let sound = match kind {
0x2C => frame(&mut anim, &mut rest, shared, &mut control),
0x21 => extension(&mut anim, &mut rest, &mut control),
_ => None,
};
if sound.is_none() {
break;
}
}
anim.done()
}
fn gif_buffers(kind: &mut Kind) -> (&mut Vec<u32>, &mut Vec<u8>) {
match kind {
Kind::Gif(colors, numbers) => (colors, numbers),
_ => unreachable!(),
}
}
fn list(anim: &mut LoadedAnimation, rest: &mut &[u8], flags: u8) -> Option<[usize; 2]> {
let colors = gif_buffers(&mut anim.kind).0;
let (first, count) = (colors.len(), if flags & 0x80 == 0 { 0 } else { 2 << (flags & 7) });
let (list, after) = rest.split_at_checked(count * 3)?;
colors.extend(list.as_chunks::<3>().0.iter().map(|[red, green, blue]| u32::from_be_bytes([255, *red, *green, *blue])));
*rest = after;
Some([first, colors.len()])
}
fn extension(anim: &mut LoadedAnimation, rest: &mut &[u8], control: &mut Control) -> Option<()> {
let (kind, after) = rest.split_first()?;
let mut data = Vec::new();
*rest = after;
blocks(rest, &mut data)?;
match (kind, &data[..]) {
(0xF9, [flags, low, high, clear, ..]) => {
let hundredths = u16::from_le_bytes([*low, *high]) as u64;
*control = Control { clear: (flags & 1 == 1).then_some(*clear), after: flags >> 2 & 7, shows: hundredths * 10 };
}
(0xFF, [name @ .., 1, low, high]) if name == b"NETSCAPE2.0" || name == b"ANIMEXTS1.0" => {
let again = u16::from_le_bytes([*low, *high]) as u64;
anim.plays = (again > 0).then_some(again + 1);
}
_ => {}
}
Some(())
}
fn frame(anim: &mut LoadedAnimation, rest: &mut &[u8], shared: [usize; 2], control: &mut Control) -> Option<()> {
let (head, after) = rest.split_first_chunk::<9>()?;
*rest = after;
let place = [0, 2, 4, 6].map(|at| u16::from_le_bytes([head[at], head[at + 1]]) as usize);
let (own, first) = (list(anim, rest, head[8])?, anim.packed.len());
let (bits, after) = rest.split_first()?;
*rest = after;
blocks(rest, &mut anim.packed)?;
let Control { clear, after, shows } = std::mem::take(control);
let after = match after {
2 => After::Cleared,
3 => After::PutBack,
_ => After::Stays,
};
let mut frame = Frame::new(place, [first, anim.packed.len()], shows, after, Laid::OverPng);
(frame.colors, frame.clear, frame.passes, frame.bits) = (if own[0] == own[1] { shared } else { own }, clear, head[8] & 0x40 != 0, *bits as u32);
let count = place[2] * place[3];
if count == 0 || count > (anim.packed.len() - first).saturating_mul(MOST) || !(1..=8).contains(&frame.bits) {
return None;
}
unpack(&anim.packed[first..], frame.bits, gif_buffers(&mut anim.kind).1, count)?;
anim.frames.push(frame);
Some(())
}
pub(crate) fn lay(packed: &[u8], frame: &Frame, colors: &[u32], numbers: &mut Vec<u8>, (pixels, [wide, high]): (&mut [u32], [usize; 2])) {
let [left, top, across, down] = frame.place;
let _ = unpack(packed, frame.bits, numbers, across * down);
let passes = if frame.passes { [(0, 8), (4, 8), (2, 4), (1, 2)] } else { [(0, 1), (down, 1), (down, 1), (down, 1)] };
let lines = passes.iter().flat_map(|(first, step)| (*first..down).step_by(*step));
let colors = &colors[frame.colors[0]..frame.colors[1]];
for (line, numbers) in lines.zip(numbers.chunks_exact(across)).filter(|(line, _)| top + line < high) {
let row = &mut pixels[(top + line) * wide + left.min(wide)..(top + line) * wide + (left + across).min(wide)];
let seen = row.iter_mut().zip(numbers).filter(|(_, number)| Some(**number) != frame.clear);
seen.for_each(|(pixel, number)| *pixel = colors.get(*number as usize).copied().unwrap_or(0xff00_0000));
}
}
fn blocks(rest: &mut &[u8], into: &mut Vec<u8>) -> Option<()> {
loop {
let (long, after) = rest.split_first()?;
let (block, after) = after.split_at_checked(*long as usize)?;
into.extend_from_slice(block);
*rest = after;
if *long == 0 {
return Some(());
}
}
}
fn unpack(packed: &[u8], bits: u32, numbers: &mut Vec<u8>, count: usize) -> Option<()> {
let (clear, end) = (1usize << bits, (1usize << bits) + 1);
let (mut before, mut last, mut first, mut long) = ([0u16; CODES], [0u8; CODES], [0u8; CODES], [1u16; CODES]);
for number in 0..clear {
(last[number], first[number]) = (number as u8, number as u8);
}
numbers.clear();
numbers.resize(count, 0);
let (mut size, mut next, mut prior) = (bits + 1, end + 1, None);
let (mut held, mut have, mut at, mut done) = (0u32, 0, 0, 0);
while done < count {
while have < size {
(held, have, at) = (held | (*packed.get(at)? as u32) << have, have + 8, at + 1);
}
let code = (held & ((1 << size) - 1)) as usize;
(held, have) = (held >> size, have - size);
if code == clear {
(size, next, prior) = (bits + 1, end + 1, None);
continue;
}
if code == end || code > next || (code == next && prior.is_none()) || next > CODES {
return None;
}
if let Some(prior) = prior.filter(|_| next < CODES) {
let begins = first[if code == next { prior } else { code }];
(before[next], last[next], first[next], long[next]) = (prior as u16, begins, first[prior], long[prior] + 1);
next += 1;
size += (next == 1 << size && size < 12) as u32;
}
let (run, mut link) = (long[code] as usize, code);
for slot in (done..done + run).rev() {
if let Some(number) = numbers.get_mut(slot) {
*number = last[link];
}
link = before[link] as usize;
}
(done, prior) = (done + run, Some(code));
}
Some(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::png;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::Duration;
type Tested = (&'static str, &'static [u8], &'static [u8], &'static [u64], Option<u64>);
const ANIMATIONS: [Tested; 6] = [
("still", include_bytes!("../tests/pictures/still.gif"), include_bytes!("../tests/pictures/still.frames.png"), &[40], None),
("passes", include_bytes!("../tests/pictures/passes.gif"), include_bytes!("../tests/pictures/passes.frames.png"), &[100], Some(1)),
("moving", include_bytes!("../tests/pictures/moving.gif"), include_bytes!("../tests/pictures/moving.frames.png"), &[200; 5], None),
("moving-cgif", include_bytes!("../tests/pictures/moving-cgif.gif"), include_bytes!("../tests/pictures/moving-cgif.frames.png"), &[200; 5], None),
("hand", include_bytes!("../tests/pictures/hand.gif"), include_bytes!("../tests/pictures/hand.frames.png"), &[70, 100, 300, 50], Some(3)),
("two", include_bytes!("../tests/pictures/two.gif"), include_bytes!("../tests/pictures/two.frames.png"), &[100, 100], Some(1)),
];
fn frames(anim: &mut LoadedAnimation) -> Vec<u32> {
(0..anim.frames.len()).flat_map(|frame| anim.shown(frame).0.to_vec()).collect()
}
fn seen(pixels: &[u32]) -> Vec<u32> {
pixels.iter().map(|pixel| if pixel >> 24 == 0 { 0 } else { *pixel }).collect()
}
#[test]
fn frames_come_out_as_ffmpeg_and_libnsgif_show_them() {
for (name, gif, wanted, shows, plays) in ANIMATIONS {
let mut anim = LoadedAnimation::read(gif, usize::MAX).unwrap_or_else(|| panic!("{name}.gif is read"));
let (width, wanted) = png::decode(wanted).unwrap();
assert_eq!((anim.size[0], anim.frames.len() * anim.size[1]), (width, wanted.len() / width), "{name}: its size, and how many frames it has");
assert!(seen(&frames(&mut anim)) == seen(&wanted), "{name}: its pixels");
assert_eq!((anim.frames.iter().map(|frame| frame.shows).collect::<Vec<u64>>(), anim.plays), (shows.to_vec(), plays), "{name}: its times");
assert_eq!(decode(gif).map(|(width, pixels)| (width, seen(&pixels))), Some((width, seen(&wanted[..width * anim.size[1]]))), "{name} as a picture");
}
}
#[test]
fn a_frame_is_shown_the_same_however_the_film_got_to_it() {
for (name, gif, ..) in ANIMATIONS {
let mut anim = LoadedAnimation::read(gif, usize::MAX).unwrap();
let (count, forward) = (anim.frames.len(), frames(&mut anim));
let each = forward.len() / count;
for frame in (0..count).rev().chain([0, 0, count - 1, count + 7]) {
let at = frame.min(count - 1) * each;
assert!(anim.shown(frame).0 == &forward[at..at + each], "{name}: frame {frame}");
}
}
}
#[test]
fn the_frame_that_is_due_goes_by_the_times_of_the_frames() {
let ms = Duration::from_millis;
let hand = LoadedAnimation::read(ANIMATIONS[4].1, usize::MAX).unwrap();
assert_eq!(hand.due(ms(0)), (0, Some(ms(70))));
assert_eq!([hand.due(ms(69)), hand.due(ms(70)), hand.due(ms(169))], [(0, Some(ms(1))), (1, Some(ms(100))), (1, Some(ms(1)))]);
assert_eq!([hand.due(ms(170)), hand.due(ms(470)), hand.due(ms(519))], [(2, Some(ms(300))), (3, Some(ms(50))), (3, Some(ms(1)))]);
assert_eq!([hand.due(ms(520)), hand.due(ms(520 + 75)), hand.due(ms(3 * 520 - 1))], [(0, Some(ms(70))), (1, Some(ms(95))), (3, Some(ms(1)))]);
assert_eq!([hand.due(ms(3 * 520)), hand.due(ms(1_000_000_000))], [(3, None); 2]);
let (moving, still) = (LoadedAnimation::read(ANIMATIONS[2].1, usize::MAX).unwrap(), LoadedAnimation::read(ANIMATIONS[0].1, usize::MAX).unwrap());
assert_eq!([moving.due(ms(999)), moving.due(ms(1000)), moving.due(ms(86_400_000 * 365 + 450))], [(4, Some(ms(1))), (0, Some(ms(200))), (2, Some(ms(150)))]);
assert_eq!([still.due(ms(0)), still.due(ms(5000))], [(0, None); 2]);
}
fn file(size: [u16; 2], colors: &[[u8; 3]], parts: &[Vec<u8>]) -> Vec<u8> {
let flags = if colors.is_empty() { 0 } else { 0x80 | (colors.len().trailing_zeros() as u8 - 1) };
let head = [&b"GIF89a"[..], &size[0].to_le_bytes(), &size[1].to_le_bytes(), &[flags, 0, 0]].concat();
[head, colors.concat(), parts.concat(), vec![0x3B]].concat()
}
fn frame(place: [u16; 4], flags: u8, numbers: &[u8]) -> Vec<u8> {
let codes = numbers.iter().flat_map(|number| [4, *number as u32]).chain([5]);
let (mut bits, mut have, mut packed) = (0u32, 0, Vec::new());
for code in codes {
(bits, have) = (bits | code << have, have + 3);
while have >= 8 {
packed.push(bits as u8);
(bits, have) = (bits >> 8, have - 8);
}
}
packed.push(bits as u8);
let head = place.iter().flat_map(|side| side.to_le_bytes()).collect::<Vec<u8>>();
[&[0x2C][..], &head, &[flags, 2, packed.len() as u8], &packed, &[0]].concat()
}
fn said(flags: u8, shows: u16, clear: u8) -> Vec<u8> {
[&[0x21, 0xF9, 4, flags][..], &shows.to_le_bytes(), &[clear, 0]].concat()
}
const COLORS: [[u8; 3]; 4] = [[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255]];
const BLACK: u32 = 0xff00_0000;
const RED: u32 = 0xffff_0000;
const GREEN: u32 = 0xff00_ff00;
const BLUE: u32 = 0xff00_00ff;
#[test]
fn frames_make_room_for_the_next_as_they_say() {
let parts = [
frame([0, 0, 4, 1], 0, &[1, 1, 1, 1]),
said(2 << 2, 5, 0),
frame([1, 0, 2, 1], 0, &[2, 2]),
said(3 << 2, 5, 0),
frame([3, 0, 1, 1], 0, &[3]),
said(1, 5, 0),
frame([0, 0, 2, 1], 0, &[2, 0]),
];
let mut anim = LoadedAnimation::read(&file([4, 1], &COLORS, &parts), usize::MAX).unwrap();
assert_eq!(frames(&mut anim), [[RED, RED, RED, RED], [RED, GREEN, GREEN, RED], [RED, 0, 0, BLUE], [GREEN, 0, 0, RED]].concat());
let own = frame([3, 0, 4, 1], 0x80, &[0, 1, 1, 1]);
let own = [&own[..10], &[9, 9, 9, 8, 8, 8], &own[10..]].concat();
let mut anim = LoadedAnimation::read(&file([4, 1], &COLORS, &[frame([0, 0, 4, 1], 0, &[3, 3, 3, 3]), own]), usize::MAX).unwrap();
assert_eq!(frames(&mut anim), [[BLUE; 4], [BLUE, BLUE, BLUE, 0xff09_0909]].concat());
let mut anim = LoadedAnimation::read(&file([2, 1], &COLORS[..2], &[frame([0, 0, 2, 1], 0, &[1, 3])]), 1).unwrap();
assert_eq!(anim.shown(0).0, [RED, BLACK]);
assert_eq!(decode(&file([2, 1], &[], &[frame([0, 0, 2, 1], 0, &[1, 3])])), Some((2, vec![BLACK; 2])));
}
#[test]
fn what_is_no_gif_or_cannot_be_what_it_says_gives_nothing() {
let good = file([2, 1], &COLORS, &[frame([0, 0, 2, 1], 0, &[1, 2])]);
assert_eq!(decode(&good), Some((2, vec![RED, GREEN])));
let changed = |at: usize, to: u8| decode(&[&good[..at], &[to], &good[at + 1..]].concat());
assert_eq!([decode(b"not a picture"), decode(&[]), decode(&good[..12]), decode(include_bytes!("../tests/pictures/plain.png")), changed(4, b'8')], [None, None, None, None, None]);
let frame_at = good.iter().position(|byte| *byte == 0x2C).unwrap();
assert!([changed(6, 0), changed(8, 0), changed(frame_at + 5, 0), changed(frame_at + 5, 3), changed(frame_at + 10, 9), changed(frame_at + 10, 0)].iter().all(Option::is_none));
assert_eq!(decode(&[&good[..6], &[255; 4], &good[10..]].concat()), None);
let two = file([2, 1], &COLORS, &[frame([0, 0, 2, 1], 0, &[1, 2]), frame([0, 0, 2, 1], 0, &[3, 3])]);
let frames_read = |file: &[u8]| LoadedAnimation::read(file, usize::MAX).map(|anim| anim.frames.len());
assert_eq!([frames_read(&two), frames_read(&two[..two.len() - 3]), frames_read(&two[..two.len() - 1])], [Some(2), Some(1), Some(2)]);
assert_eq!(LoadedAnimation::read(&two, 1).map(|anim| anim.frames.len()), Some(1));
}
#[test]
fn a_damaged_file_gives_nothing_or_some_film() {
let sound = |gif: &[u8]| {
let Some(mut anim) = LoadedAnimation::read(gif, usize::MAX) else { return true };
let screen = anim.size[0] * anim.size[1];
(0..anim.frames.len()).rev().all(|frame| anim.shown(frame).0.len() == screen) && decode(gif).is_some()
};
for (name, gif, ..) in ANIMATIONS {
assert!((0..gif.len()).all(|cut| sound(&gif[..cut])), "{name}, cut short");
for at in 0..gif.len() {
let damaged = |to: u8| [&gif[..at], &[to], &gif[at + 1..]].concat();
assert!([gif[at] ^ (1 << (at % 8)), 0, 255].into_iter().all(|to| sound(&damaged(to))), "{name}, byte {at}");
}
}
let still = ANIMATIONS[0].1;
assert!((0..still.len() - 1).all(|cut| decode(&still[..cut]).is_none()));
}
#[test]
#[ignore = "needs ffmpeg, vips and giflib's tools, and writes the files the other tests read"]
fn the_films_are_made_afresh() {
let pictures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests").join("pictures");
let work = std::env::temp_dir().join(format!("taut-animations-{}", std::process::id()));
std::fs::create_dir_all(&work).unwrap();
for step in 0..5usize {
let pixel = |at: usize| {
let (x, y) = (at % 24, at / 24);
match () {
_ if x + y < 5 => 0,
_ if (4 * step + 2..4 * step + 8).contains(&x) && (5..11).contains(&y) => 0xfff5_9e0b,
_ => [0xff1e_3a8a, 0xff0f_766e, 0xff7c_2d12, 0xfff1_f5f9][y / 4],
}
};
std::fs::write(work.join(format!("f{step}.png")), png::encode_rgba(24, &(0..24 * 16).map(pixel).collect::<Vec<u32>>()).unwrap()).unwrap();
}
let run = |program: &str, arguments: &[&str], input: Option<&PathBuf>, output: Option<&PathBuf>| {
let mut command = Command::new(program);
command.args(arguments).current_dir(&work).stdin(input.map_or(Stdio::null(), |file| std::fs::File::open(file).unwrap().into()));
command.stdout(output.map_or(Stdio::null(), |file| std::fs::File::create(file).unwrap().into()));
assert!(command.status().is_ok_and(|status| status.success()), "{program} {arguments:?}");
};
let at = |name: &str| pictures.join(name);
let text = |name: &str| at(name).to_str().unwrap().to_string();
let colours = "split[a][b];[a]palettegen=reserve_transparent=1[p];[b][p]paletteuse";
run("ffmpeg", &["-y", "-loglevel", "error", "-i", "f0.png", "-filter_complex", colours, &text("still.gif")], None, None);
run("giftool", &["-i", "1"], Some(&at("still.gif")), Some(&at("passes.gif")));
run("ffmpeg", &["-y", "-loglevel", "error", "-framerate", "5", "-i", "f%d.png", "-filter_complex", colours, "-loop", "0", &text("moving.gif")], None, None);
run("vips", &["copy", &format!("{}[n=-1]", text("moving.gif")), &text("moving-cgif.gif")], None, None);
run("gifbuild", &[], Some(&at("hand.txt")), Some(&at("hand.gif")));
run("gifbuild", &[], Some(&at("two.txt")), Some(&at("two.gif")));
for (name, ..) in ANIMATIONS {
let (gif, frames) = (text(&format!("{name}.gif")), text(&format!("{name}.frames.png")));
run("vips", &["copy", &format!("{gif}[n=-1]"), &frames], None, None);
let nsgif = png::decode(&std::fs::read(&frames).unwrap()).unwrap();
let under = format!("tile=1x{}", nsgif.1.len() / decode(&std::fs::read(&gif).unwrap()).unwrap().1.len());
run("ffmpeg", &["-y", "-loglevel", "error", "-i", &gif, "-vf", &under, "-frames:v", "1", "-pix_fmt", "rgba", "ffmpeg.png"], None, None);
let ffmpeg = png::decode(&std::fs::read(work.join("ffmpeg.png")).unwrap()).unwrap();
assert!(name == "two" || (ffmpeg.0 == nsgif.0 && seen(&ffmpeg.1) == seen(&nsgif.1)), "{name}: ffmpeg and libnsgif show the same");
}
std::fs::remove_dir_all(work).unwrap();
}
}