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