| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use ec_image::transform::{Layout, apply_orientation}; |
| 8 | use image::{DynamicImage, ExtendedColorType, ImageDecoder, ImageEncoder}; |
| 9 | use std::io::{Cursor, Read}; |
| 10 | |
| 11 | |
| 12 | fn pattern(w: u32, h: u32) -> Vec<u8> { |
| 13 | let mut v = Vec::with_capacity((w * h * 3) as usize); |
| 14 | for y in 0..h { |
| 15 | for x in 0..w { |
| 16 | v.extend_from_slice(&[ |
| 17 | (x * 35) as u8, |
| 18 | (y * 50) as u8, |
| 19 | ((x * 7 + y * 13) % 256) as u8, |
| 20 | ]); |
| 21 | } |
| 22 | } |
| 23 | v |
| 24 | } |
| 25 | |
| 26 | |
| 27 | fn tiff(o: u16, big_endian: bool) -> Vec<u8> { |
| 28 | let mut t = Vec::new(); |
| 29 | let u16b = |v: u16| { |
| 30 | if big_endian { |
| 31 | v.to_be_bytes() |
| 32 | } else { |
| 33 | v.to_le_bytes() |
| 34 | } |
| 35 | }; |
| 36 | let u32b = |v: u32| { |
| 37 | if big_endian { |
| 38 | v.to_be_bytes() |
| 39 | } else { |
| 40 | v.to_le_bytes() |
| 41 | } |
| 42 | }; |
| 43 | t.extend_from_slice(if big_endian { b"MM" } else { b"II" }); |
| 44 | t.extend_from_slice(&u16b(42)); |
| 45 | t.extend_from_slice(&u32b(8)); |
| 46 | t.extend_from_slice(&u16b(1)); |
| 47 | t.extend_from_slice(&u16b(0x0112)); |
| 48 | t.extend_from_slice(&u16b(3)); |
| 49 | t.extend_from_slice(&u32b(1)); |
| 50 | t.extend_from_slice(&u16b(o)); |
| 51 | t.extend_from_slice(&u16b(0)); |
| 52 | t.extend_from_slice(&u32b(0)); |
| 53 | t |
| 54 | } |
| 55 | |
| 56 | fn jpeg(w: u32, h: u32, px: &[u8]) -> Vec<u8> { |
| 57 | let mut out = Vec::new(); |
| 58 | image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95) |
| 59 | .write_image(px, w, h, ExtendedColorType::Rgb8) |
| 60 | .unwrap(); |
| 61 | out |
| 62 | } |
| 63 | |
| 64 | fn png(w: u32, h: u32, px: &[u8], color: ExtendedColorType) -> Vec<u8> { |
| 65 | let mut out = Vec::new(); |
| 66 | image::codecs::png::PngEncoder::new(&mut out) |
| 67 | .write_image(px, w, h, color) |
| 68 | .unwrap(); |
| 69 | out |
| 70 | } |
| 71 | |
| 72 | fn webp_lossless(w: u32, h: u32, px: &[u8]) -> Vec<u8> { |
| 73 | let mut out = Vec::new(); |
| 74 | image::codecs::webp::WebPEncoder::new_lossless(&mut out) |
| 75 | .write_image(px, w, h, ExtendedColorType::Rgb8) |
| 76 | .unwrap(); |
| 77 | out |
| 78 | } |
| 79 | |
| 80 | |
| 81 | fn jpeg_with_exif(plain: &[u8], o: u16, be: bool) -> Vec<u8> { |
| 82 | let mut seg = b"Exif\0\0".to_vec(); |
| 83 | seg.extend(tiff(o, be)); |
| 84 | let mut out = plain[..2].to_vec(); |
| 85 | out.extend_from_slice(&[0xff, 0xe1]); |
| 86 | out.extend_from_slice(&((seg.len() + 2) as u16).to_be_bytes()); |
| 87 | out.extend(seg); |
| 88 | out.extend_from_slice(&plain[2..]); |
| 89 | out |
| 90 | } |
| 91 | |
| 92 | |
| 93 | fn png_with_exif(plain: &[u8], o: u16, be: bool) -> Vec<u8> { |
| 94 | let idat = plain.windows(4).position(|w| w == b"IDAT").unwrap() - 4; |
| 95 | let body = tiff(o, be); |
| 96 | let mut chunk = (body.len() as u32).to_be_bytes().to_vec(); |
| 97 | let mut typed = b"eXIf".to_vec(); |
| 98 | typed.extend(&body); |
| 99 | chunk.extend(&typed); |
| 100 | chunk.extend(crc32(&typed).to_be_bytes()); |
| 101 | let mut out = plain[..idat].to_vec(); |
| 102 | out.extend(chunk); |
| 103 | out.extend_from_slice(&plain[idat..]); |
| 104 | out |
| 105 | } |
| 106 | |
| 107 | fn crc32(data: &[u8]) -> u32 { |
| 108 | let mut c = 0xffff_ffffu32; |
| 109 | for &b in data { |
| 110 | c ^= u32::from(b); |
| 111 | for _ in 0..8 { |
| 112 | c = if c & 1 != 0 { |
| 113 | 0xedb8_8320 ^ (c >> 1) |
| 114 | } else { |
| 115 | c >> 1 |
| 116 | }; |
| 117 | } |
| 118 | } |
| 119 | !c |
| 120 | } |
| 121 | |
| 122 | |
| 123 | fn webp_with_exif(plain: &[u8], o: u16, be: bool, w: u32, h: u32) -> Vec<u8> { |
| 124 | let image_chunk = &plain[12..]; |
| 125 | let exif = tiff(o, be); |
| 126 | let mut vp8x = vec![0x08, 0, 0, 0]; |
| 127 | vp8x.extend_from_slice(&(w - 1).to_le_bytes()[..3]); |
| 128 | vp8x.extend_from_slice(&(h - 1).to_le_bytes()[..3]); |
| 129 | let mut body = b"WEBP".to_vec(); |
| 130 | body.extend_from_slice(b"VP8X"); |
| 131 | body.extend_from_slice(&10u32.to_le_bytes()); |
| 132 | body.extend(&vp8x); |
| 133 | body.extend_from_slice(image_chunk); |
| 134 | body.extend_from_slice(b"EXIF"); |
| 135 | body.extend_from_slice(&(exif.len() as u32).to_le_bytes()); |
| 136 | body.extend(&exif); |
| 137 | if exif.len() % 2 == 1 { |
| 138 | body.push(0); |
| 139 | } |
| 140 | let mut out = b"RIFF".to_vec(); |
| 141 | out.extend_from_slice(&(body.len() as u32).to_le_bytes()); |
| 142 | out.extend(body); |
| 143 | out |
| 144 | } |
| 145 | |
| 146 | |
| 147 | fn image_view(bytes: &[u8]) -> (u8, Vec<u8>, u32, u32) { |
| 148 | let reader = image::ImageReader::new(Cursor::new(bytes)) |
| 149 | .with_guessed_format() |
| 150 | .unwrap(); |
| 151 | let mut decoder = reader.into_decoder().unwrap(); |
| 152 | let orientation = decoder.orientation().unwrap().to_exif(); |
| 153 | let mut img = DynamicImage::from_decoder(decoder).unwrap(); |
| 154 | img.apply_orientation(image::metadata::Orientation::from_exif(orientation).unwrap()); |
| 155 | let (w, h) = (img.width(), img.height()); |
| 156 | (orientation, img.to_rgb8().into_raw(), w, h) |
| 157 | } |
| 158 | |
| 159 | const W: u32 = 7; |
| 160 | const H: u32 = 5; |
| 161 | |
| 162 | fn bytes_close(a: &[u8], b: &[u8], tolerance: u8) -> usize { |
| 163 | assert_eq!(a.len(), b.len()); |
| 164 | a.iter() |
| 165 | .zip(b) |
| 166 | .filter(|(x, y)| x.abs_diff(**y) > tolerance) |
| 167 | .count() |
| 168 | } |
| 169 | |
| 170 | #[test] |
| 171 | fn every_orientation_is_probed_and_applied_like_image_for_jpeg_png_and_webp() { |
| 172 | let px = pattern(W, H); |
| 173 | let plain_jpeg = jpeg(W, H, &px); |
| 174 | let plain_png = png(W, H, &px, ExtendedColorType::Rgb8); |
| 175 | let plain_webp = webp_lossless(W, H, &px); |
| 176 | for o in 1..=8u16 { |
| 177 | for be in [false, true] { |
| 178 | let cases = [ |
| 179 | ("jpeg", jpeg_with_exif(&plain_jpeg, o, be), 3u8), |
| 180 | ("png", png_with_exif(&plain_png, o, be), 0), |
| 181 | ("webp", webp_with_exif(&plain_webp, o, be, W, H), 0), |
| 182 | ]; |
| 183 | for (what, bytes, tol) in cases { |
| 184 | let info = ec_image::info(&bytes).unwrap(); |
| 185 | assert_eq!( |
| 186 | info.orientation, o as u8, |
| 187 | "{what} info, orientation {o} be={be}" |
| 188 | ); |
| 189 | let probed = ec_image::probe(&bytes).unwrap(); |
| 190 | assert_eq!(probed, info, "{what} probe matches info"); |
| 191 | let (theirs_o, theirs_px, tw, th) = image_view(&bytes); |
| 192 | assert_eq!(theirs_o, o as u8, "image reads the same {what} orientation"); |
| 193 | let decoded = ec_image::decode(&bytes).unwrap(); |
| 194 | assert_eq!( |
| 195 | decoded.meta.orientation, |
| 196 | Some(o as u8), |
| 197 | "{what} decode meta" |
| 198 | ); |
| 199 | let ours = decoded.to_rgb8(); |
| 200 | let (uw, uh, upright) = |
| 201 | apply_orientation(Layout::Rgb8, W, H, &ours, o as u8).unwrap(); |
| 202 | assert_eq!((uw, uh), (tw, th), "{what} upright size {o}"); |
| 203 | let wrong = bytes_close(&upright, &theirs_px, tol); |
| 204 | assert_eq!( |
| 205 | wrong, 0, |
| 206 | "{what} upright pixels differ from image at orientation {o}" |
| 207 | ); |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[test] |
| 214 | fn transforms_match_image_on_random_rgba_for_all_orientations() { |
| 215 | let (w, h) = (9u32, 4u32); |
| 216 | let mut s = 0x1234_5678u32; |
| 217 | let px: Vec<u8> = (0..(w * h * 4)) |
| 218 | .map(|_| { |
| 219 | s = s.wrapping_mul(1_103_515_245).wrapping_add(12_345); |
| 220 | (s >> 16) as u8 |
| 221 | }) |
| 222 | .collect(); |
| 223 | for o in 1..=8u8 { |
| 224 | let (uw, uh, got) = apply_orientation(Layout::Rgba8, w, h, &px, o).unwrap(); |
| 225 | let mut img = image::RgbaImage::from_raw(w, h, px.clone()).unwrap(); |
| 226 | let mut dynimg = DynamicImage::ImageRgba8(img.clone()); |
| 227 | dynimg.apply_orientation(image::metadata::Orientation::from_exif(o).unwrap()); |
| 228 | img = dynimg.to_rgba8(); |
| 229 | assert_eq!((uw, uh), (img.width(), img.height()), "size at {o}"); |
| 230 | assert_eq!(got, img.into_raw(), "rgba transform at orientation {o}"); |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn gif_and_bmp_report_orientation_one() { |
| 236 | let px = pattern(W, H); |
| 237 | let rgba: Vec<u8> = px.chunks(3).flat_map(|p| [p[0], p[1], p[2], 255]).collect(); |
| 238 | let mut gif = Vec::new(); |
| 239 | image::codecs::gif::GifEncoder::new(&mut gif) |
| 240 | .encode_frame(image::Frame::new( |
| 241 | image::RgbaImage::from_raw(W, H, rgba).unwrap(), |
| 242 | )) |
| 243 | .unwrap(); |
| 244 | assert_eq!(ec_image::info(&gif).unwrap().orientation, 1); |
| 245 | let mut bmp = Vec::new(); |
| 246 | image::codecs::bmp::BmpEncoder::new(&mut bmp) |
| 247 | .write_image(&px, W, H, ExtendedColorType::Rgb8) |
| 248 | .unwrap(); |
| 249 | assert_eq!(ec_image::info(&bmp).unwrap().orientation, 1); |
| 250 | } |
| 251 | |
| 252 | #[test] |
| 253 | fn probe_reads_the_header_and_never_the_pixels() { |
| 254 | |
| 255 | let px = pattern(W, H); |
| 256 | let mut bytes = png(W, H, &px, ExtendedColorType::Rgb8); |
| 257 | let idat = bytes.windows(4).position(|w| w == b"IDAT").unwrap(); |
| 258 | let body_at = idat + 4; |
| 259 | let len = u32::from_be_bytes(bytes[idat - 4..idat].try_into().unwrap()) as usize; |
| 260 | for b in &mut bytes[body_at..body_at + len] { |
| 261 | *b = 0xa5; |
| 262 | } |
| 263 | let info = ec_image::probe(&bytes).unwrap(); |
| 264 | assert_eq!( |
| 265 | (info.width, info.height, info.format), |
| 266 | (W, H, ec_image::ImageFormat::Png) |
| 267 | ); |
| 268 | |
| 269 | assert!(ec_image::decode(&bytes).is_err()); |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn a_prefix_of_a_large_jpeg_probes_to_the_same_answer() { |
| 274 | let (w, h) = (640u32, 480u32); |
| 275 | let px: Vec<u8> = pattern(w, h); |
| 276 | let bytes = jpeg_with_exif(&jpeg(w, h, &px), 6, false); |
| 277 | let whole = ec_image::info(&bytes).unwrap(); |
| 278 | |
| 279 | let prefix = ec_image::probe(&bytes[..bytes.len() / 2]).unwrap(); |
| 280 | assert_eq!(prefix, whole); |
| 281 | |
| 282 | assert!(ec_image::probe(&bytes[..10]).is_err()); |
| 283 | } |
| 284 | |
| 285 | |
| 286 | struct Endless<'a> { |
| 287 | header: &'a [u8], |
| 288 | at: usize, |
| 289 | pulled: usize, |
| 290 | } |
| 291 | |
| 292 | impl Read for Endless<'_> { |
| 293 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { |
| 294 | let mut n = 0; |
| 295 | while n < buf.len() { |
| 296 | let b = if self.at < self.header.len() { |
| 297 | self.header[self.at] |
| 298 | } else { |
| 299 | 0 |
| 300 | }; |
| 301 | buf[n] = b; |
| 302 | self.at += 1; |
| 303 | n += 1; |
| 304 | } |
| 305 | self.pulled += n; |
| 306 | Ok(n) |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | #[test] |
| 311 | fn probe_reader_stops_at_the_window() { |
| 312 | let px = pattern(W, H); |
| 313 | let bytes = png_with_exif(&png(W, H, &px, ExtendedColorType::Rgb8), 8, false); |
| 314 | let mut endless = Endless { |
| 315 | header: &bytes, |
| 316 | at: 0, |
| 317 | pulled: 0, |
| 318 | }; |
| 319 | let info = ec_image::probe_reader(&mut endless).unwrap(); |
| 320 | assert_eq!((info.width, info.height, info.orientation), (W, H, 8)); |
| 321 | assert_eq!( |
| 322 | endless.pulled, |
| 323 | ec_image::PROBE_LIMIT, |
| 324 | "exactly one window is read" |
| 325 | ); |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn a_huge_declared_size_is_reported_without_allocating_it() { |
| 330 | |
| 331 | let px = pattern(W, H); |
| 332 | let mut bytes = png(W, H, &px, ExtendedColorType::Rgb8); |
| 333 | bytes[16..20].copy_from_slice(&0x7fff_ffffu32.to_be_bytes()); |
| 334 | bytes[20..24].copy_from_slice(&0x7fff_ffffu32.to_be_bytes()); |
| 335 | let ihdr_crc = crc32(&bytes[12..29]); |
| 336 | bytes[29..33].copy_from_slice(&ihdr_crc.to_be_bytes()); |
| 337 | let info = ec_image::probe(&bytes[..33]).unwrap(); |
| 338 | assert_eq!((info.width, info.height), (0x7fff_ffff, 0x7fff_ffff)); |
| 339 | } |
| 340 | |
| 341 | #[test] |
| 342 | fn png_encoder_round_trips_bit_exact_and_matches_image_decode() { |
| 343 | let (w, h) = (97u32, 61u32); |
| 344 | let rgb = pattern(w, h); |
| 345 | let out = ec_image::png_encode::encode_rgb8(w, h, &rgb).unwrap(); |
| 346 | assert_eq!(ec_image::decode(&out).unwrap().to_rgb8(), rgb); |
| 347 | assert_eq!( |
| 348 | image::load_from_memory(&out).unwrap().to_rgb8().into_raw(), |
| 349 | rgb |
| 350 | ); |
| 351 | |
| 352 | let rgba: Vec<u8> = rgb |
| 353 | .chunks(3) |
| 354 | .enumerate() |
| 355 | .flat_map(|(i, p)| [p[0], p[1], p[2], (i * 37 % 256) as u8]) |
| 356 | .collect(); |
| 357 | let out = ec_image::png_encode::encode_rgba8(w, h, &rgba).unwrap(); |
| 358 | assert_eq!(ec_image::decode(&out).unwrap().to_rgba8(), rgba); |
| 359 | assert_eq!( |
| 360 | image::load_from_memory(&out).unwrap().to_rgba8().into_raw(), |
| 361 | rgba |
| 362 | ); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn png_encoder_size_against_image_on_the_still_fixture() { |
| 367 | let path = |
| 368 | std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills/source.png"); |
| 369 | let Ok(bytes) = std::fs::read(&path) else { |
| 370 | eprintln!("skipped: {} not generated", path.display()); |
| 371 | return; |
| 372 | }; |
| 373 | let src = image::load_from_memory(&bytes).unwrap().to_rgb8(); |
| 374 | let (w, h) = src.dimensions(); |
| 375 | let ours = ec_image::png_encode::encode_rgb8(w, h, src.as_raw()).unwrap(); |
| 376 | let mut theirs = Vec::new(); |
| 377 | image::codecs::png::PngEncoder::new(&mut theirs) |
| 378 | .write_image(src.as_raw(), w, h, ExtendedColorType::Rgb8) |
| 379 | .unwrap(); |
| 380 | eprintln!( |
| 381 | "png encode {w}x{h} rgb8: ec-image {} bytes, image {} bytes ({:.2}x)", |
| 382 | ours.len(), |
| 383 | theirs.len(), |
| 384 | ours.len() as f64 / theirs.len() as f64 |
| 385 | ); |
| 386 | assert_eq!( |
| 387 | ec_image::decode(&ours).unwrap().to_rgb8(), |
| 388 | src.as_raw().as_slice() |
| 389 | ); |
| 390 | } |
| 391 | |
| 392 | #[test] |
| 393 | fn probing_arbitrary_mutations_never_panics() { |
| 394 | let px = pattern(W, H); |
| 395 | let seeds = [ |
| 396 | jpeg_with_exif(&jpeg(W, H, &px), 6, false), |
| 397 | png_with_exif(&png(W, H, &px, ExtendedColorType::Rgb8), 6, false), |
| 398 | webp_with_exif(&webp_lossless(W, H, &px), 6, true, W, H), |
| 399 | ]; |
| 400 | let mut s = 99u32; |
| 401 | for seed in &seeds { |
| 402 | for i in 0..seed.len().min(256) { |
| 403 | for v in [0u8, 0xff, 0x7f] { |
| 404 | let mut m = seed.clone(); |
| 405 | m[i] = v; |
| 406 | let _ = ec_image::probe(&m); |
| 407 | let _ = ec_image::info(&m); |
| 408 | } |
| 409 | } |
| 410 | for _ in 0..2000 { |
| 411 | s = s.wrapping_mul(1_103_515_245).wrapping_add(12_345); |
| 412 | let mut m = seed.clone(); |
| 413 | let at = (s >> 8) as usize % m.len(); |
| 414 | m[at] = (s >> 16) as u8; |
| 415 | m.truncate(((s >> 4) as usize % m.len()).max(1)); |
| 416 | let _ = ec_image::probe(&m); |
| 417 | } |
| 418 | } |
| 419 | } |