Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_graphics/src/gif.rs

5.2 KiB, 1 run

created by r1870400018:75660, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! GIF, as its first frame.
2//!
3//! An animated GIF is a sequence of frames each drawn over the last, and what a reader that does not
4//! animate shows is the first of them on the logical screen. That is what comes back here: the
5//! screen, cleared, with the first image drawn onto it at its offset, its transparent index left
6//! clear and its rows put back in order if they were stored interlaced.
7//!
8//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
9//! Anthropic Claude
10
11use crate::{
12 lzw::{
13 self,
14 BitOrder,
15 },
16 pixmap::Pixmap,
17};
18
19use oxedyne_fe2o3_core::prelude::*;
20
21fn u16le(b: &[u8], at: usize) -> Outcome<u16> {
22 match b.get(at..at + 2) {
23 Some(s) => Ok(u16::from_le_bytes([s[0], s[1]])),
24 None => Err(err!(
25 "A GIF needs two bytes at offset {}, but holds {}.", at, b.len();
26 Invalid, Input, Decode)),
27 }
28}
29
30fn byte(b: &[u8], at: usize) -> Outcome<u8> {
31 match b.get(at) {
32 Some(v) => Ok(*v),
33 None => Err(err!(
34 "A GIF ends at {} bytes where offset {} was needed.", b.len(), at;
35 Invalid, Input, Decode)),
36 }
37}
38
39/// Reads a colour table of `n` entries at `at`.
40fn table(b: &[u8], at: usize, n: usize) -> Outcome<Vec<[u8; 3]>> {
41 match b.get(at..at + 3 * n) {
42 Some(s) => Ok(s.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect()),
43 None => Err(err!(
44 "A GIF colour table of {} entries at offset {} passes the end of the file.", n, at;
45 Invalid, Input, Decode)),
46 }
47}
48
49/// Gathers a run of data sub-blocks, returning the bytes and the offset after the terminator.
50fn blocks(b: &[u8], mut at: usize) -> Outcome<(Vec<u8>, usize)> {
51 let mut out = Vec::new();
52 loop {
53 let n = match b.get(at) {
54 Some(n) => *n as usize,
55 None => return Ok((out, at)), // a file cut short keeps what it has
56 };
57 at += 1;
58 if n == 0 {
59 return Ok((out, at));
60 }
61 let end = (at + n).min(b.len());
62 out.extend_from_slice(&b[at..end]);
63 at += n;
64 }
65}
66
67/// The logical screen size a GIF declares.
68pub fn dimensions(buf: &[u8]) -> Outcome<(usize, usize)> {
69 if buf.len() < 10 || (&buf[..6] != b"GIF87a" && &buf[..6] != b"GIF89a") {
70 return Err(err!("The bytes do not begin with a GIF signature."; Invalid, Input, Decode));
71 }
72 Ok((res!(u16le(buf, 6)) as usize, res!(u16le(buf, 8)) as usize))
73}
74
75/// Decodes a GIF's first frame onto its logical screen.
76pub fn decode(buf: &[u8]) -> Outcome<Pixmap> {
77 let (sw, sh) = res!(dimensions(buf));
78 let flags = res!(byte(buf, 10));
79 let mut at = 13;
80 let global = if flags & 0x80 != 0 {
81 let n = 2usize << (flags & 7);
82 let t = res!(table(buf, at, n));
83 at += 3 * n;
84 t
85 } else {
86 Vec::new()
87 };
88 let mut transparent: Option<u8> = None;
89 loop {
90 match res!(byte(buf, at)) {
91 0x21 => {
92 let label = res!(byte(buf, at + 1));
93 let (data, next) = res!(blocks(buf, at + 2));
94 if label == 0xf9 && data.len() >= 4 && data[0] & 1 == 1 {
95 transparent = Some(data[3]);
96 }
97 at = next;
98 }
99 0x2c => break,
100 0x3b => return Err(err!("A GIF ends before its first image."; Invalid, Input, Decode)),
101 b => return Err(err!(
102 "A GIF holds block type 0x{:02x} at offset {}, which is none of image, extension \
103 or trailer.", b, at;
104 Invalid, Input, Decode)),
105 }
106 }
107 let left = res!(u16le(buf, at + 1)) as usize;
108 let top = res!(u16le(buf, at + 3)) as usize;
109 let fw = res!(u16le(buf, at + 5)) as usize;
110 let fh = res!(u16le(buf, at + 7)) as usize;
111 let iflags = res!(byte(buf, at + 9));
112 at += 10;
113 let local = if iflags & 0x80 != 0 {
114 let n = 2usize << (iflags & 7);
115 let t = res!(table(buf, at, n));
116 at += 3 * n;
117 Some(t)
118 } else {
119 None
120 };
121 let colours = match &local {
122 Some(t) => t,
123 None => &global,
124 };
125 let min = res!(byte(buf, at));
126 let (data, _) = res!(blocks(buf, at + 1));
127 let n = match fw.checked_mul(fh) {
128 Some(n) => n,
129 None => return Err(err!(
130 "A GIF frame of {} by {} overflows.", fw, fh; Invalid, Input, Decode, Overflow)),
131 };
132 let idx = res!(lzw::decode(&data, min, BitOrder::Lsb, false, n));
133 // A screen smaller than its first frame is a writer's mistake; grow it rather than crop.
134 let w = sw.max(left + fw).max(1);
135 let h = sh.max(top + fh).max(1);
136 let mut pm = res!(Pixmap::new(w, h));
137 let order = rows(fh, iflags & 0x40 != 0);
138 let out = pm.data_mut();
139 for (k, &y) in order.iter().enumerate() {
140 for x in 0..fw {
141 let i = match idx.get(k * fw + x) {
142 Some(i) => *i,
143 None => continue, // a short stream leaves the rest clear
144 };
145 if Some(i) == transparent {
146 continue;
147 }
148 let c = match colours.get(i as usize) {
149 Some(c) => *c,
150 None => [0, 0, 0],
151 };
152 let p = ((top + y) * w + left + x) * 4;
153 out[p..p + 4].copy_from_slice(&[c[0], c[1], c[2], 255]);
154 }
155 }
156 Ok(pm)
157}
158
159/// The row each stored row belongs on, which for an interlaced image is four passes: every eighth
160/// row from 0, every eighth from 4, every fourth from 2, every second from 1.
161fn rows(h: usize, interlaced: bool) -> Vec<usize> {
162 if !interlaced {
163 return (0..h).collect();
164 }
165 let mut v = Vec::with_capacity(h);
166 for &(start, step) in &[(0, 8), (4, 8), (2, 4), (1, 2)] {
167 let mut y = start;
168 while y < h {
169 v.push(y);
170 y += step;
171 }
172 }
173 v
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
181 fn test_interlaced_row_order_00() {
182 assert_eq!(rows(10, true), vec![0, 8, 4, 2, 6, 1, 3, 5, 7, 9]);
183 assert_eq!(rows(3, false), vec![0, 1, 2]);
184 }
185}