| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | use ec_core::{Error, Result}; |
| 18 | use std::collections::HashMap; |
| 19 | |
| 20 | |
| 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 22 | pub struct GifOptions { |
| 23 | |
| 24 | |
| 25 | pub loop_count: Option<u16>, |
| 26 | |
| 27 | |
| 28 | pub max_colors: u16, |
| 29 | |
| 30 | pub dither: bool, |
| 31 | } |
| 32 | |
| 33 | impl Default for GifOptions { |
| 34 | fn default() -> Self { |
| 35 | GifOptions { |
| 36 | loop_count: None, |
| 37 | max_colors: 256, |
| 38 | dither: false, |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | pub struct Encoder { |
| 47 | width: u16, |
| 48 | height: u16, |
| 49 | opts: GifOptions, |
| 50 | out: Vec<u8>, |
| 51 | |
| 52 | prev: Option<Vec<u8>>, |
| 53 | |
| 54 | last: Option<(usize, u16)>, |
| 55 | frames: usize, |
| 56 | } |
| 57 | |
| 58 | |
| 59 | const DISPOSE_KEEP: u8 = 1 << 2; |
| 60 | |
| 61 | impl Encoder { |
| 62 | |
| 63 | pub fn new(width: u16, height: u16, opts: GifOptions) -> Result<Self> { |
| 64 | if width == 0 || height == 0 { |
| 65 | return Err(Error::unsupported( |
| 66 | "GIF encode", |
| 67 | format!("{width}x{height} is not a GIF-sized image"), |
| 68 | )); |
| 69 | } |
| 70 | if !(2..=256).contains(&opts.max_colors) { |
| 71 | return Err(Error::unsupported( |
| 72 | "GIF encode", |
| 73 | format!("max_colors {} is outside 2..=256", opts.max_colors), |
| 74 | )); |
| 75 | } |
| 76 | let mut out = Vec::new(); |
| 77 | out.extend_from_slice(b"GIF89a"); |
| 78 | out.extend_from_slice(&width.to_le_bytes()); |
| 79 | out.extend_from_slice(&height.to_le_bytes()); |
| 80 | |
| 81 | out.extend_from_slice(&[0, 0, 0]); |
| 82 | if let Some(loops) = opts.loop_count { |
| 83 | out.extend_from_slice(&[0x21, 0xff, 0x0b]); |
| 84 | out.extend_from_slice(b"NETSCAPE2.0"); |
| 85 | out.extend_from_slice(&[0x03, 0x01]); |
| 86 | out.extend_from_slice(&loops.to_le_bytes()); |
| 87 | out.push(0); |
| 88 | } |
| 89 | Ok(Encoder { |
| 90 | width, |
| 91 | height, |
| 92 | opts, |
| 93 | out, |
| 94 | prev: None, |
| 95 | last: None, |
| 96 | frames: 0, |
| 97 | }) |
| 98 | } |
| 99 | |
| 100 | |
| 101 | |
| 102 | pub fn push_rgba8(&mut self, pixels: &[u8], delay_cs: u16) -> Result<()> { |
| 103 | let (w, h) = (usize::from(self.width), usize::from(self.height)); |
| 104 | if pixels.len() != w * h * 4 { |
| 105 | return Err(Error::unsupported( |
| 106 | "GIF encode", |
| 107 | format!( |
| 108 | "{} bytes of pixels for {}x{} (need {})", |
| 109 | pixels.len(), |
| 110 | self.width, |
| 111 | self.height, |
| 112 | w * h * 4 |
| 113 | ), |
| 114 | )); |
| 115 | } |
| 116 | let prev = self.prev.as_deref(); |
| 117 | |
| 118 | let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); |
| 119 | let mut any = false; |
| 120 | for y in 0..h { |
| 121 | for x in 0..w { |
| 122 | if differs(prev, pixels, y * w + x) { |
| 123 | any = true; |
| 124 | x0 = x0.min(x); |
| 125 | y0 = y0.min(y); |
| 126 | x1 = x1.max(x); |
| 127 | y1 = y1.max(y); |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | let (x0, y0, x1, y1) = if any { |
| 132 | (x0, y0, x1, y1) |
| 133 | } else { |
| 134 | |
| 135 | if let Some((at, last)) = self.last { |
| 136 | let merged = u32::from(last) + u32::from(delay_cs); |
| 137 | if merged <= u32::from(u16::MAX) { |
| 138 | let bytes = (merged as u16).to_le_bytes(); |
| 139 | self.out[at..at + 2].copy_from_slice(&bytes); |
| 140 | self.last = Some((at, merged as u16)); |
| 141 | return Ok(()); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | (0, 0, 0, 0) |
| 146 | }; |
| 147 | let (rw, rh) = (x1 - x0 + 1, y1 - y0 + 1); |
| 148 | |
| 149 | |
| 150 | let mut src: Vec<Option<[u8; 3]>> = Vec::with_capacity(rw * rh); |
| 151 | for y in y0..=y1 { |
| 152 | for x in x0..=x1 { |
| 153 | let i = y * w + x; |
| 154 | let visible = differs(prev, pixels, i) && pixels[i * 4 + 3] >= 128; |
| 155 | src.push(visible.then(|| [pixels[i * 4], pixels[i * 4 + 1], pixels[i * 4 + 2]])); |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | let transparent = src.iter().any(Option::is_none); |
| 160 | let budget = usize::from(self.opts.max_colors) - usize::from(transparent); |
| 161 | let colors: Vec<u32> = src.iter().flatten().map(|&c| pack(c)).collect(); |
| 162 | let palette = quantize(colors, budget); |
| 163 | let indices = index_of(&src, rw, &palette, self.opts.dither); |
| 164 | |
| 165 | let palette_len = palette.len(); |
| 166 | let entries = palette_len + usize::from(transparent); |
| 167 | let size = entries.max(2).next_power_of_two(); |
| 168 | let bits = size.trailing_zeros() as u8; |
| 169 | let min_code = bits.max(2); |
| 170 | let mut table = palette; |
| 171 | if transparent { |
| 172 | table.push([0, 0, 0]); |
| 173 | } |
| 174 | table.resize(size, [0, 0, 0]); |
| 175 | |
| 176 | |
| 177 | let tidx = palette_len as u8; |
| 178 | let delay = delay_cs.to_le_bytes(); |
| 179 | let packed = DISPOSE_KEEP | u8::from(transparent); |
| 180 | let at = self.out.len() + 4; |
| 181 | self.out |
| 182 | .extend_from_slice(&[0x21, 0xf9, 0x04, packed, delay[0], delay[1], tidx, 0]); |
| 183 | self.last = Some((at, delay_cs)); |
| 184 | |
| 185 | self.out.push(0x2c); |
| 186 | for v in [x0, y0, rw, rh] { |
| 187 | self.out.extend_from_slice(&(v as u16).to_le_bytes()); |
| 188 | } |
| 189 | self.out.push(0x80 | (bits - 1)); |
| 190 | for c in &table { |
| 191 | self.out.extend_from_slice(c); |
| 192 | } |
| 193 | self.out.push(min_code); |
| 194 | put_sub_blocks(&mut self.out, &lzw(&indices, min_code)); |
| 195 | |
| 196 | self.prev = Some(pixels.to_vec()); |
| 197 | self.frames += 1; |
| 198 | Ok(()) |
| 199 | } |
| 200 | |
| 201 | |
| 202 | pub fn finish(mut self) -> Result<Vec<u8>> { |
| 203 | if self.frames == 0 { |
| 204 | return Err(Error::unsupported("GIF encode", "no frames were pushed")); |
| 205 | } |
| 206 | self.out.push(0x3b); |
| 207 | Ok(self.out) |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | |
| 212 | fn differs(prev: Option<&[u8]>, pixels: &[u8], i: usize) -> bool { |
| 213 | match prev { |
| 214 | None => true, |
| 215 | Some(p) => p[i * 4..i * 4 + 4] != pixels[i * 4..i * 4 + 4], |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | fn pack(c: [u8; 3]) -> u32 { |
| 220 | (u32::from(c[0]) << 16) | (u32::from(c[1]) << 8) | u32::from(c[2]) |
| 221 | } |
| 222 | |
| 223 | fn unpack(k: u32) -> [u8; 3] { |
| 224 | [(k >> 16) as u8, (k >> 8) as u8, k as u8] |
| 225 | } |
| 226 | |
| 227 | |
| 228 | fn chan(k: u32, ch: usize) -> u32 { |
| 229 | (k >> (16 - 8 * ch)) & 0xff |
| 230 | } |
| 231 | |
| 232 | |
| 233 | |
| 234 | fn quantize(mut colors: Vec<u32>, budget: usize) -> Vec<[u8; 3]> { |
| 235 | colors.sort_unstable(); |
| 236 | let mut uniq: Vec<(u32, u32)> = Vec::new(); |
| 237 | for c in colors { |
| 238 | match uniq.last_mut() { |
| 239 | Some((k, n)) if *k == c => *n += 1, |
| 240 | _ => uniq.push((c, 1)), |
| 241 | } |
| 242 | } |
| 243 | if uniq.len() <= budget { |
| 244 | return uniq.iter().map(|&(k, _)| unpack(k)).collect(); |
| 245 | } |
| 246 | |
| 247 | let mut boxes = vec![uniq]; |
| 248 | while boxes.len() < budget { |
| 249 | |
| 250 | let mut pick: Option<(usize, usize, u32)> = None; |
| 251 | for (bi, b) in boxes.iter().enumerate() { |
| 252 | if b.len() < 2 { |
| 253 | continue; |
| 254 | } |
| 255 | for ch in 0..3 { |
| 256 | let (lo, hi) = b |
| 257 | .iter() |
| 258 | .fold((u32::MAX, 0), |(lo, hi), &(k, _)| { |
| 259 | let v = chan(k, ch); |
| 260 | (lo.min(v), hi.max(v)) |
| 261 | }); |
| 262 | let range = hi - lo; |
| 263 | match pick { |
| 264 | Some((_, _, r)) if r >= range => {} |
| 265 | _ => pick = Some((bi, ch, range)), |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | let Some((bi, ch, _)) = pick else { break }; |
| 270 | let mut b = boxes.swap_remove(bi); |
| 271 | b.sort_unstable_by_key(|&(k, _)| chan(k, ch)); |
| 272 | let total: u64 = b.iter().map(|&(_, n)| u64::from(n)).sum(); |
| 273 | let mut acc = 0u64; |
| 274 | let mut split = b.len() - 1; |
| 275 | for (i, &(_, n)) in b.iter().enumerate() { |
| 276 | acc += u64::from(n); |
| 277 | if acc * 2 >= total { |
| 278 | split = (i + 1).clamp(1, b.len() - 1); |
| 279 | break; |
| 280 | } |
| 281 | } |
| 282 | let right = b.split_off(split); |
| 283 | boxes.push(b); |
| 284 | boxes.push(right); |
| 285 | } |
| 286 | |
| 287 | boxes |
| 288 | .iter() |
| 289 | .map(|b| { |
| 290 | let total: u64 = b.iter().map(|&(_, n)| u64::from(n)).sum(); |
| 291 | std::array::from_fn(|ch| { |
| 292 | let sum: u64 = b |
| 293 | .iter() |
| 294 | .map(|&(k, n)| u64::from(chan(k, ch)) * u64::from(n)) |
| 295 | .sum(); |
| 296 | ((sum + total / 2) / total) as u8 |
| 297 | }) |
| 298 | }) |
| 299 | .collect() |
| 300 | } |
| 301 | |
| 302 | |
| 303 | |
| 304 | fn index_of(src: &[Option<[u8; 3]>], rw: usize, palette: &[[u8; 3]], dither: bool) -> Vec<u8> { |
| 305 | if dither { |
| 306 | return dither_floyd_steinberg(src, rw, palette); |
| 307 | } |
| 308 | let clear = palette.len() as u8; |
| 309 | let mut memo: HashMap<[u8; 3], u8> = HashMap::new(); |
| 310 | src.iter() |
| 311 | .map(|px| match px { |
| 312 | None => clear, |
| 313 | Some(c) => *memo |
| 314 | .entry(*c) |
| 315 | .or_insert_with(|| nearest(palette, c.map(i32::from))), |
| 316 | }) |
| 317 | .collect() |
| 318 | } |
| 319 | |
| 320 | |
| 321 | |
| 322 | fn dither_floyd_steinberg(src: &[Option<[u8; 3]>], rw: usize, palette: &[[u8; 3]]) -> Vec<u8> { |
| 323 | let rh = src.len() / rw; |
| 324 | let clear = palette.len() as u8; |
| 325 | let mut out = Vec::with_capacity(src.len()); |
| 326 | |
| 327 | let mut cur = vec![[0i32; 3]; rw + 2]; |
| 328 | let mut next = vec![[0i32; 3]; rw + 2]; |
| 329 | for y in 0..rh { |
| 330 | for x in 0..rw { |
| 331 | let Some(c) = src[y * rw + x] else { |
| 332 | out.push(clear); |
| 333 | continue; |
| 334 | }; |
| 335 | let e = cur[x + 1]; |
| 336 | let v: [i32; 3] = std::array::from_fn(|ch| (i32::from(c[ch]) + e[ch]).clamp(0, 255)); |
| 337 | let p = nearest(palette, v); |
| 338 | out.push(p); |
| 339 | let q = palette[usize::from(p)].map(i32::from); |
| 340 | let err = [v[0] - q[0], v[1] - q[1], v[2] - q[2]]; |
| 341 | for (ch, &d) in err.iter().enumerate() { |
| 342 | cur[x + 2][ch] += d * 7 / 16; |
| 343 | next[x][ch] += d * 3 / 16; |
| 344 | next[x + 1][ch] += d * 5 / 16; |
| 345 | next[x + 2][ch] += d / 16; |
| 346 | } |
| 347 | } |
| 348 | std::mem::swap(&mut cur, &mut next); |
| 349 | next.iter_mut().for_each(|e| *e = [0; 3]); |
| 350 | } |
| 351 | out |
| 352 | } |
| 353 | |
| 354 | |
| 355 | fn nearest(palette: &[[u8; 3]], rgb: [i32; 3]) -> u8 { |
| 356 | let mut best = 0usize; |
| 357 | let mut best_d = i32::MAX; |
| 358 | for (i, p) in palette.iter().enumerate() { |
| 359 | let d: i32 = rgb |
| 360 | .iter() |
| 361 | .zip(p) |
| 362 | .map(|(&a, &b)| { |
| 363 | let t = a - i32::from(b); |
| 364 | t * t |
| 365 | }) |
| 366 | .sum(); |
| 367 | if d < best_d { |
| 368 | best_d = d; |
| 369 | best = i; |
| 370 | } |
| 371 | } |
| 372 | best as u8 |
| 373 | } |
| 374 | |
| 375 | |
| 376 | #[derive(Default)] |
| 377 | struct Bits { |
| 378 | acc: u32, |
| 379 | n: u32, |
| 380 | } |
| 381 | |
| 382 | impl Bits { |
| 383 | fn put(&mut self, out: &mut Vec<u8>, code: u16, width: u32) { |
| 384 | self.acc |= u32::from(code) << self.n; |
| 385 | self.n += width; |
| 386 | while self.n >= 8 { |
| 387 | out.push(self.acc as u8); |
| 388 | self.acc >>= 8; |
| 389 | self.n -= 8; |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | fn flush(&mut self, out: &mut Vec<u8>) { |
| 394 | if self.n > 0 { |
| 395 | out.push(self.acc as u8); |
| 396 | self.acc = 0; |
| 397 | self.n = 0; |
| 398 | } |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | fn lzw(indices: &[u8], min_code: u8) -> Vec<u8> { |
| 407 | let min = u32::from(min_code); |
| 408 | let clear = 1u16 << min_code; |
| 409 | let eoi = clear + 1; |
| 410 | let mut out = Vec::new(); |
| 411 | let mut bits = Bits::default(); |
| 412 | let mut dict: HashMap<u32, u16> = HashMap::new(); |
| 413 | let mut width = min + 1; |
| 414 | let mut next = eoi + 1; |
| 415 | bits.put(&mut out, clear, width); |
| 416 | let mut prefix: Option<u16> = None; |
| 417 | for &b in indices { |
| 418 | let p = match prefix { |
| 419 | None => { |
| 420 | prefix = Some(u16::from(b)); |
| 421 | continue; |
| 422 | } |
| 423 | Some(p) => p, |
| 424 | }; |
| 425 | let key = (u32::from(p) << 8) | u32::from(b); |
| 426 | if let Some(&code) = dict.get(&key) { |
| 427 | prefix = Some(code); |
| 428 | continue; |
| 429 | } |
| 430 | bits.put(&mut out, p, width); |
| 431 | dict.insert(key, next); |
| 432 | next += 1; |
| 433 | if next == 4096 { |
| 434 | bits.put(&mut out, clear, width); |
| 435 | dict.clear(); |
| 436 | next = eoi + 1; |
| 437 | width = min + 1; |
| 438 | } else if u32::from(next) > (1 << width) { |
| 439 | width += 1; |
| 440 | } |
| 441 | prefix = Some(u16::from(b)); |
| 442 | } |
| 443 | if let Some(p) = prefix { |
| 444 | bits.put(&mut out, p, width); |
| 445 | } |
| 446 | bits.put(&mut out, eoi, width); |
| 447 | bits.flush(&mut out); |
| 448 | out |
| 449 | } |
| 450 | |
| 451 | |
| 452 | |
| 453 | fn put_sub_blocks(out: &mut Vec<u8>, data: &[u8]) { |
| 454 | for chunk in data.chunks(255) { |
| 455 | out.push(chunk.len() as u8); |
| 456 | out.extend_from_slice(chunk); |
| 457 | } |
| 458 | out.push(0); |
| 459 | } |
| 460 | |
| 461 | #[cfg(test)] |
| 462 | mod tests { |
| 463 | use super::*; |
| 464 | use crate::{gif, AnimationFrame, Limits}; |
| 465 | |
| 466 | fn encode_frames(w: u16, h: u16, opts: GifOptions, frames: &[(&[u8], u16)]) -> Vec<u8> { |
| 467 | let mut enc = Encoder::new(w, h, opts).unwrap(); |
| 468 | for (px, delay) in frames { |
| 469 | enc.push_rgba8(px, *delay).unwrap(); |
| 470 | } |
| 471 | enc.finish().unwrap() |
| 472 | } |
| 473 | |
| 474 | fn decode(data: &[u8]) -> Vec<AnimationFrame> { |
| 475 | gif::decode_animation(data, Limits::default()).unwrap() |
| 476 | } |
| 477 | |
| 478 | fn noise(seed: &mut u32) -> u8 { |
| 479 | *seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); |
| 480 | (*seed >> 24) as u8 |
| 481 | } |
| 482 | |
| 483 | |
| 484 | fn photo(w: usize, h: usize) -> Vec<u8> { |
| 485 | let mut seed = 7u32; |
| 486 | let mut px = Vec::with_capacity(w * h * 4); |
| 487 | for y in 0..h { |
| 488 | for x in 0..w { |
| 489 | let r = (x * 255 / (w - 1)) as i32 + i32::from(noise(&mut seed) % 13) - 6; |
| 490 | let g = (y * 255 / (h - 1)) as i32 + i32::from(noise(&mut seed) % 13) - 6; |
| 491 | let b = ((x + y) * 127 / (w + h - 2)) as i32 + i32::from(noise(&mut seed) % 13) - 6; |
| 492 | px.extend_from_slice(&[ |
| 493 | r.clamp(0, 255) as u8, |
| 494 | g.clamp(0, 255) as u8, |
| 495 | b.clamp(0, 255) as u8, |
| 496 | 255, |
| 497 | ]); |
| 498 | } |
| 499 | } |
| 500 | px |
| 501 | } |
| 502 | |
| 503 | fn mean_abs_error(decoded: &[u8], source: &[u8]) -> f64 { |
| 504 | let sum: u64 = decoded |
| 505 | .iter() |
| 506 | .zip(source) |
| 507 | .enumerate() |
| 508 | .filter(|(i, _)| i % 4 != 3) |
| 509 | .map(|(_, (a, b))| u64::from(a.abs_diff(*b))) |
| 510 | .sum(); |
| 511 | sum as f64 / (decoded.len() / 4 * 3) as f64 |
| 512 | } |
| 513 | |
| 514 | #[test] |
| 515 | fn a_palette_that_fits_is_reproduced_exactly() { |
| 516 | let px: Vec<u8> = (0..256) |
| 517 | .flat_map(|i: usize| { |
| 518 | let (x, y) = (i % 16, i / 16); |
| 519 | [(x * 17) as u8, (y * 17) as u8, ((x ^ y) * 5) as u8, 255] |
| 520 | }) |
| 521 | .collect(); |
| 522 | let gif = encode_frames(16, 16, GifOptions::default(), &[(&px, 4)]); |
| 523 | let frames = decode(&gif); |
| 524 | assert_eq!(frames.len(), 1); |
| 525 | assert_eq!(frames[0].image.to_rgba8(), px); |
| 526 | } |
| 527 | |
| 528 | #[test] |
| 529 | fn a_changing_sequence_decodes_frame_for_frame() { |
| 530 | let (w, h) = (32usize, 32usize); |
| 531 | let a: Vec<u8> = (0..w * h) |
| 532 | .flat_map(|i| { |
| 533 | let (x, y) = (i % w, i / w); |
| 534 | let c = [[200, 30, 30], [30, 200, 30], [30, 30, 200], [220, 220, 40]][(x / 8 + y / 8) % 4]; |
| 535 | [c[0], c[1], c[2], 255] |
| 536 | }) |
| 537 | .collect(); |
| 538 | let mut b = a.clone(); |
| 539 | for y in 10..14 { |
| 540 | for x in 10..14 { |
| 541 | b[(y * w + x) * 4..(y * w + x) * 4 + 4].copy_from_slice(&[9, 9, 9, 255]); |
| 542 | } |
| 543 | } |
| 544 | let mut d = b.clone(); |
| 545 | d[0..4].copy_from_slice(&[250, 0, 250, 255]); |
| 546 | let gif = encode_frames( |
| 547 | 32, |
| 548 | 32, |
| 549 | GifOptions::default(), |
| 550 | |
| 551 | &[(&a, 5), (&b, 7), (&b, 9), (&d, 3)], |
| 552 | ); |
| 553 | let frames = decode(&gif); |
| 554 | let delays: Vec<u32> = frames.iter().map(|f| f.delay_num).collect(); |
| 555 | assert_eq!(delays, vec![5, 16, 3]); |
| 556 | assert_eq!(frames[0].image.to_rgba8(), a); |
| 557 | assert_eq!(frames[1].image.to_rgba8(), b); |
| 558 | assert_eq!(frames[2].image.to_rgba8(), d); |
| 559 | } |
| 560 | |
| 561 | #[test] |
| 562 | fn the_loop_extension_is_written_only_when_asked() { |
| 563 | let px = [1u8, 2, 3, 255]; |
| 564 | let play_once = encode_frames(1, 1, GifOptions::default(), &[(&px, 1)]); |
| 565 | assert!(!play_once.windows(11).any(|w| w == b"NETSCAPE2.0")); |
| 566 | |
| 567 | for (loops, expect) in [(0u16, [0u8, 0]), (3, [3, 0])] { |
| 568 | let opts = GifOptions { |
| 569 | loop_count: Some(loops), |
| 570 | ..GifOptions::default() |
| 571 | }; |
| 572 | let gif = encode_frames(1, 1, opts, &[(&px, 1)]); |
| 573 | let at = gif |
| 574 | .windows(11) |
| 575 | .position(|w| w == b"NETSCAPE2.0") |
| 576 | .expect("NETSCAPE2.0 extension"); |
| 577 | let body = &gif[at + 11..]; |
| 578 | assert_eq!(&body[..2], &[0x03, 0x01]); |
| 579 | assert_eq!(&body[2..4], &expect); |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | #[test] |
| 584 | fn transparent_pixels_stay_transparent_and_unchanged_ones_keep_the_canvas() { |
| 585 | let (w, h) = (8u16, 4u16); |
| 586 | let mut f1 = Vec::new(); |
| 587 | for _y in 0..4 { |
| 588 | for x in 0..8 { |
| 589 | if x < 4 { |
| 590 | f1.extend_from_slice(&[9, 9, 9, 0]); |
| 591 | } else { |
| 592 | f1.extend_from_slice(&[200, 30 + x as u8, 30, 255]); |
| 593 | } |
| 594 | } |
| 595 | } |
| 596 | let mut f2 = f1.clone(); |
| 597 | f2[4 * 4..4 * 4 + 4].copy_from_slice(&[10, 200, 10, 255]); |
| 598 | let gif = encode_frames(w, h, GifOptions::default(), &[(&f1, 5), (&f2, 5)]); |
| 599 | let frames = decode(&gif); |
| 600 | assert_eq!(frames.len(), 2); |
| 601 | let (d1, d2) = (frames[0].image.to_rgba8(), frames[1].image.to_rgba8()); |
| 602 | for (i, px) in d1.chunks(4).enumerate() { |
| 603 | let x = i % 8; |
| 604 | if x < 4 { |
| 605 | assert_eq!(px[3], 0, "pixel {i} should be transparent"); |
| 606 | } else { |
| 607 | assert_eq!(px, &f1[i * 4..i * 4 + 4], "pixel {i}"); |
| 608 | } |
| 609 | } |
| 610 | for (i, px) in d2.chunks(4).enumerate() { |
| 611 | let x = i % 8; |
| 612 | if x < 4 { |
| 613 | assert_eq!(px[3], 0, "pixel {i} stays transparent"); |
| 614 | } else { |
| 615 | assert_eq!(px, &f2[i * 4..i * 4 + 4], "pixel {i}"); |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | #[test] |
| 621 | fn photographic_content_stays_within_a_small_error() { |
| 622 | let (w, h) = (96usize, 96usize); |
| 623 | let src = photo(w, h); |
| 624 | for dither in [false, true] { |
| 625 | let opts = GifOptions { |
| 626 | dither, |
| 627 | ..GifOptions::default() |
| 628 | }; |
| 629 | let gif = encode_frames(96, 96, opts, &[(&src, 10)]); |
| 630 | let frames = decode(&gif); |
| 631 | let err = mean_abs_error(&frames[0].image.to_rgba8(), &src); |
| 632 | assert!(err < 6.0, "dither={dither}: mean abs error {err:.2}"); |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | #[test] |
| 637 | fn a_static_frame_repeated_ten_times_costs_little_more_than_one() { |
| 638 | let (w, h) = (64usize, 64usize); |
| 639 | let px = photo(w, h); |
| 640 | let one = encode_frames(64, 64, GifOptions::default(), &[(&px, 10)]); |
| 641 | let frames: Vec<(&[u8], u16)> = (0..10).map(|_| (&px[..], 10)).collect(); |
| 642 | let ten = encode_frames(64, 64, GifOptions::default(), &frames); |
| 643 | assert!( |
| 644 | (ten.len() as f64) < 1.5 * one.len() as f64, |
| 645 | "ten frames {} bytes vs one frame {} bytes", |
| 646 | ten.len(), |
| 647 | one.len() |
| 648 | ); |
| 649 | |
| 650 | let decoded = decode(&ten); |
| 651 | assert_eq!(decoded.len(), 1); |
| 652 | assert_eq!(decoded[0].delay_num, 100); |
| 653 | } |
| 654 | |
| 655 | #[test] |
| 656 | fn bad_arguments_are_refused() { |
| 657 | assert!(Encoder::new(0, 4, GifOptions::default()).is_err()); |
| 658 | assert!(Encoder::new(4, 0, GifOptions::default()).is_err()); |
| 659 | for max_colors in [1u16, 257] { |
| 660 | let opts = GifOptions { |
| 661 | max_colors, |
| 662 | ..GifOptions::default() |
| 663 | }; |
| 664 | assert!(Encoder::new(4, 4, opts).is_err(), "max_colors {max_colors}"); |
| 665 | } |
| 666 | let mut enc = Encoder::new(2, 2, GifOptions::default()).unwrap(); |
| 667 | assert!(enc.push_rgba8(&[0; 15], 1).is_err()); |
| 668 | assert!(enc.push_rgba8(&[0; 17], 1).is_err()); |
| 669 | assert!(Encoder::new(2, 2, GifOptions::default()).unwrap().finish().is_err()); |
| 670 | } |
| 671 | |
| 672 | #[test] |
| 673 | fn ffprobe_reads_the_output_when_it_is_installed() { |
| 674 | let probe = std::process::Command::new("ffprobe").arg("-version").output(); |
| 675 | if probe.is_err() { |
| 676 | return; |
| 677 | } |
| 678 | let px: Vec<u8> = (0..8 * 4).flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255]).collect(); |
| 679 | let gif = encode_frames(8, 4, GifOptions::default(), &[(&px, 5), (&px, 5)]); |
| 680 | let path = std::env::temp_dir().join(format!("ec-gif-encode-{}.gif", std::process::id())); |
| 681 | std::fs::write(&path, &gif).unwrap(); |
| 682 | let out = std::process::Command::new("ffprobe") |
| 683 | .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) |
| 684 | .args(["stream=width,height", "-of", "csv=p=0"]) |
| 685 | .arg(&path) |
| 686 | .output(); |
| 687 | let _ = std::fs::remove_file(&path); |
| 688 | let out = out.expect("ffprobe runs"); |
| 689 | assert!(out.status.success()); |
| 690 | assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "8,4"); |
| 691 | } |
| 692 | } |