[raster] Toolbox: probe/decode with caps, convert, crop, rotate, resize, presets, compress to size, HEIC via WIC
This commit is contained in:
@@ -0,0 +1,311 @@
|
||||
//! Fixtures built in code: nothing binary is checked in.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use image::{DynamicImage, ImageBuffer, Rgb, RgbImage, Rgba, RgbaImage};
|
||||
|
||||
/// Deterministic xorshift64* generator, so every run mutates the same bytes.
|
||||
pub struct XorShift(u64);
|
||||
|
||||
impl XorShift {
|
||||
pub fn new(seed: u64) -> Self {
|
||||
Self(seed.max(1))
|
||||
}
|
||||
|
||||
pub fn next_u64(&mut self) -> u64 {
|
||||
let mut x = self.0;
|
||||
x ^= x >> 12;
|
||||
x ^= x << 25;
|
||||
x ^= x >> 27;
|
||||
self.0 = x;
|
||||
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
|
||||
pub fn below(&mut self, n: usize) -> usize {
|
||||
if n == 0 { 0 } else { (self.next_u64() % n as u64) as usize }
|
||||
}
|
||||
|
||||
pub fn byte(&mut self) -> u8 {
|
||||
(self.next_u64() >> 56) as u8
|
||||
}
|
||||
}
|
||||
|
||||
/// A small RGB image with a gradient and a few hard edges.
|
||||
pub fn sample_rgb(width: u32, height: u32) -> DynamicImage {
|
||||
let img: RgbImage = ImageBuffer::from_fn(width, height, |x, y| {
|
||||
let r = (x * 255 / width.max(1)) as u8;
|
||||
let g = (y * 255 / height.max(1)) as u8;
|
||||
let b = if (x / 8 + y / 8) % 2 == 0 { 40 } else { 210 };
|
||||
Rgb([r, g, b])
|
||||
});
|
||||
DynamicImage::ImageRgb8(img)
|
||||
}
|
||||
|
||||
/// A small RGBA image whose alpha varies, including fully transparent pixels.
|
||||
pub fn sample_rgba(width: u32, height: u32) -> DynamicImage {
|
||||
let img: RgbaImage = ImageBuffer::from_fn(width, height, |x, y| {
|
||||
let r = (x * 255 / width.max(1)) as u8;
|
||||
let g = (y * 255 / height.max(1)) as u8;
|
||||
let a = if x < width / 4 { 0 } else { ((x + y) * 7 % 256) as u8 };
|
||||
Rgba([r, g, 128, a])
|
||||
});
|
||||
DynamicImage::ImageRgba8(img)
|
||||
}
|
||||
|
||||
/// A noisy photo-like image: a smooth gradient plus per-pixel noise (hard to compress).
|
||||
pub fn noisy_rgb(width: u32, height: u32, seed: u64) -> DynamicImage {
|
||||
let mut rng = XorShift::new(seed);
|
||||
let mut img = RgbImage::new(width, height);
|
||||
for (x, y, px) in img.enumerate_pixels_mut() {
|
||||
let n = rng.next_u64();
|
||||
let base_r = (x * 200 / width) as i32;
|
||||
let base_g = (y * 200 / height) as i32;
|
||||
let noise = |shift: u32| ((n >> shift) & 0x3F) as i32 - 32;
|
||||
px.0 = [
|
||||
(base_r + noise(0)).clamp(0, 255) as u8,
|
||||
(base_g + noise(8)).clamp(0, 255) as u8,
|
||||
(120 + noise(16)).clamp(0, 255) as u8,
|
||||
];
|
||||
}
|
||||
DynamicImage::ImageRgb8(img)
|
||||
}
|
||||
|
||||
pub fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc = 0xFFFF_FFFFu32;
|
||||
for &b in data {
|
||||
crc ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
let mask = (crc & 1).wrapping_neg();
|
||||
crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
pub fn png_chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
let mut body = Vec::with_capacity(4 + data.len());
|
||||
body.extend_from_slice(kind);
|
||||
body.extend_from_slice(data);
|
||||
out.extend_from_slice(&body);
|
||||
out.extend_from_slice(&crc32(&body).to_be_bytes());
|
||||
}
|
||||
|
||||
/// A hand-built PNG with an arbitrary IHDR size (8-bit RGB) and a tiny stored-zlib IDAT.
|
||||
pub fn png_with_size(width: u32, height: u32) -> Vec<u8> {
|
||||
let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
let mut ihdr = Vec::new();
|
||||
ihdr.extend_from_slice(&width.to_be_bytes());
|
||||
ihdr.extend_from_slice(&height.to_be_bytes());
|
||||
ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
|
||||
png_chunk(&mut out, b"IHDR", &ihdr);
|
||||
// zlib header + one empty stored final block + adler32 of nothing.
|
||||
let idat = [0x78, 0x01, 0x01, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01];
|
||||
png_chunk(&mut out, b"IDAT", &idat);
|
||||
png_chunk(&mut out, b"IEND", &[]);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn encode_with_image(img: &DynamicImage, fmt: image::ImageFormat) -> Vec<u8> {
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
img.write_to(&mut out, fmt).expect("fixture encodes");
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
pub fn jpeg_fixture(width: u32, height: u32) -> Vec<u8> {
|
||||
encode_with_image(&sample_rgb(width, height), image::ImageFormat::Jpeg)
|
||||
}
|
||||
|
||||
/// Replace the dimensions in the first SOF0/SOF2 segment of a JPEG.
|
||||
pub fn patch_jpeg_sof(mut jpeg: Vec<u8>, width: u16, height: u16) -> Vec<u8> {
|
||||
let mut i = 2;
|
||||
while i + 9 < jpeg.len() {
|
||||
if jpeg[i] != 0xFF {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let marker = jpeg[i + 1];
|
||||
let len = u16::from_be_bytes([jpeg[i + 2], jpeg[i + 3]]) as usize;
|
||||
if matches!(marker, 0xC0..=0xC2) {
|
||||
jpeg[i + 5..i + 7].copy_from_slice(&height.to_be_bytes());
|
||||
jpeg[i + 7..i + 9].copy_from_slice(&width.to_be_bytes());
|
||||
return jpeg;
|
||||
}
|
||||
i += 2 + len;
|
||||
}
|
||||
panic!("no SOF in fixture");
|
||||
}
|
||||
|
||||
/// Insert a minimal EXIF APP1 segment (one IFD0 entry: Orientation) right after SOI.
|
||||
pub fn jpeg_with_orientation(jpeg: &[u8], orientation: u16) -> Vec<u8> {
|
||||
let mut tiff = Vec::new();
|
||||
tiff.extend_from_slice(b"II*\0");
|
||||
tiff.extend_from_slice(&8u32.to_le_bytes());
|
||||
tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry
|
||||
tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation
|
||||
tiff.extend_from_slice(&3u16.to_le_bytes()); // SHORT
|
||||
tiff.extend_from_slice(&1u32.to_le_bytes()); // count
|
||||
tiff.extend_from_slice(&orientation.to_le_bytes());
|
||||
tiff.extend_from_slice(&[0, 0]); // padding of the 4-byte value field
|
||||
tiff.extend_from_slice(&0u32.to_le_bytes()); // no next IFD
|
||||
let mut payload = b"Exif\0\0".to_vec();
|
||||
payload.extend_from_slice(&tiff);
|
||||
let mut out = jpeg[..2].to_vec();
|
||||
out.extend_from_slice(&[0xFF, 0xE1]);
|
||||
out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
|
||||
out.extend_from_slice(&payload);
|
||||
out.extend_from_slice(&jpeg[2..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// GIF89a whose logical screen and image descriptor claim `w × h`, with a tiny LZW stream.
|
||||
pub fn gif_with_size(width: u16, height: u16) -> Vec<u8> {
|
||||
let mut out = b"GIF89a".to_vec();
|
||||
out.extend_from_slice(&width.to_le_bytes());
|
||||
out.extend_from_slice(&height.to_le_bytes());
|
||||
out.extend_from_slice(&[0x80, 0, 0]); // global colour table of 2 entries
|
||||
out.extend_from_slice(&[0, 0, 0, 255, 255, 255]);
|
||||
out.push(0x2C);
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(&width.to_le_bytes());
|
||||
out.extend_from_slice(&height.to_le_bytes());
|
||||
out.push(0);
|
||||
out.push(2); // LZW minimum code size
|
||||
out.extend_from_slice(&[2, 0x44, 0x01, 0]); // clear, a pixel, end
|
||||
out.push(0x3B);
|
||||
out
|
||||
}
|
||||
|
||||
/// Little-endian baseline TIFF whose IFD claims `w × h` (8-bit grey, one strip of 1 byte).
|
||||
pub fn tiff_with_size(width: u32, height: u32) -> Vec<u8> {
|
||||
let entries: [(u16, u16, u32, u32); 8] = [
|
||||
(256, 4, 1, width), // ImageWidth LONG
|
||||
(257, 4, 1, height), // ImageLength LONG
|
||||
(258, 3, 1, 8), // BitsPerSample
|
||||
(259, 3, 1, 1), // Compression none
|
||||
(262, 3, 1, 1), // BlackIsZero
|
||||
(273, 4, 1, 0), // StripOffsets (patched below)
|
||||
(278, 4, 1, height), // RowsPerStrip
|
||||
(279, 4, 1, 1), // StripByteCounts
|
||||
];
|
||||
let mut out = b"II*\0".to_vec();
|
||||
out.extend_from_slice(&8u32.to_le_bytes());
|
||||
out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
|
||||
let data_offset = 8 + 2 + entries.len() as u32 * 12 + 4;
|
||||
for (tag, kind, count, value) in entries {
|
||||
out.extend_from_slice(&tag.to_le_bytes());
|
||||
out.extend_from_slice(&kind.to_le_bytes());
|
||||
out.extend_from_slice(&count.to_le_bytes());
|
||||
let v = if tag == 273 { data_offset } else { value };
|
||||
if kind == 3 {
|
||||
out.extend_from_slice(&(v as u16).to_le_bytes());
|
||||
out.extend_from_slice(&[0, 0]);
|
||||
} else {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(&0u32.to_le_bytes());
|
||||
out.push(0x80);
|
||||
out
|
||||
}
|
||||
|
||||
/// ICO header claiming three entries that point outside the file with silly sizes.
|
||||
pub fn bogus_ico() -> Vec<u8> {
|
||||
let mut out = vec![0, 0, 1, 0, 3, 0];
|
||||
for i in 0..3u32 {
|
||||
out.extend_from_slice(&[0, 0, 0, 0, 1, 0, 32, 0]);
|
||||
out.extend_from_slice(&(0xFFFF_FFF0u32 - i).to_le_bytes()); // size
|
||||
out.extend_from_slice(&(0x7FFF_0000u32 + i).to_le_bytes()); // offset
|
||||
}
|
||||
out.extend_from_slice(&[0xAB; 20]);
|
||||
out
|
||||
}
|
||||
|
||||
fn bmff_box(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec();
|
||||
out.extend_from_slice(kind);
|
||||
out.extend_from_slice(body);
|
||||
out
|
||||
}
|
||||
|
||||
fn full_box(kind: &[u8; 4], version: u8, body: &[u8]) -> Vec<u8> {
|
||||
let mut b = vec![version, 0, 0, 0];
|
||||
b.extend_from_slice(body);
|
||||
bmff_box(kind, &b)
|
||||
}
|
||||
|
||||
/// A syntactically valid HEIF container (ftyp, meta with hdlr/pitm/iinf/iloc/iprp, mdat) holding one
|
||||
/// `hvc1` item whose HEVC payload is a dummy NAL unit. Written by hand from ISO/IEC 23008-12; the image data
|
||||
/// itself does not decode, so on a machine with the codecs this still yields a typed error.
|
||||
pub fn minimal_heic(width: u32, height: u32) -> Vec<u8> {
|
||||
let mut ftyp = b"heic".to_vec();
|
||||
ftyp.extend_from_slice(&0u32.to_be_bytes());
|
||||
ftyp.extend_from_slice(b"mif1heic");
|
||||
let ftyp = bmff_box(b"ftyp", &ftyp);
|
||||
|
||||
let mut hdlr = vec![0; 4];
|
||||
hdlr.extend_from_slice(b"pict");
|
||||
hdlr.extend_from_slice(&[0; 12]);
|
||||
hdlr.push(0);
|
||||
let hdlr = full_box(b"hdlr", 0, &hdlr);
|
||||
let pitm = full_box(b"pitm", 0, &1u16.to_be_bytes());
|
||||
let mut infe = Vec::new();
|
||||
infe.extend_from_slice(&1u16.to_be_bytes());
|
||||
infe.extend_from_slice(&0u16.to_be_bytes());
|
||||
infe.extend_from_slice(b"hvc1");
|
||||
infe.push(0);
|
||||
let infe = full_box(b"infe", 2, &infe);
|
||||
let mut iinf = 1u16.to_be_bytes().to_vec();
|
||||
iinf.extend_from_slice(&infe);
|
||||
let iinf = full_box(b"iinf", 0, &iinf);
|
||||
|
||||
// hvcC: version 1, Main profile, level 3.0, 4:2:0, 8 bit, 4-byte NAL lengths, no parameter-set arrays.
|
||||
let hvcc = bmff_box(
|
||||
b"hvcC",
|
||||
&[1, 0x01, 0x60, 0, 0, 0, 0x90, 0, 0, 0, 0, 0, 90, 0xF0, 0x00, 0xFC, 0xFD, 0xF8, 0xF8, 0, 0, 0x0F, 0],
|
||||
);
|
||||
let mut ispe = width.to_be_bytes().to_vec();
|
||||
ispe.extend_from_slice(&height.to_be_bytes());
|
||||
let ispe = full_box(b"ispe", 0, &ispe);
|
||||
let mut ipco = hvcc;
|
||||
ipco.extend_from_slice(&ispe);
|
||||
let ipco = bmff_box(b"ipco", &ipco);
|
||||
let mut ipma = 1u32.to_be_bytes().to_vec();
|
||||
ipma.extend_from_slice(&1u16.to_be_bytes());
|
||||
ipma.extend_from_slice(&[2, 0x81, 0x02]);
|
||||
let ipma = full_box(b"ipma", 0, &ipma);
|
||||
let mut iprp = ipco;
|
||||
iprp.extend_from_slice(&ipma);
|
||||
let iprp = bmff_box(b"iprp", &iprp);
|
||||
|
||||
let payload: Vec<u8> = {
|
||||
let nal = [0x26, 0x01, 0xAF, 0x13, 0x9C, 0x50, 0x00, 0x00];
|
||||
let mut p = (nal.len() as u32).to_be_bytes().to_vec();
|
||||
p.extend_from_slice(&nal);
|
||||
p
|
||||
};
|
||||
|
||||
// iloc is built twice: once to learn the meta size, once with the real mdat offset.
|
||||
let build = |offset: u32| {
|
||||
let mut iloc = vec![0x44, 0x00];
|
||||
iloc.extend_from_slice(&1u16.to_be_bytes());
|
||||
iloc.extend_from_slice(&1u16.to_be_bytes());
|
||||
iloc.extend_from_slice(&0u16.to_be_bytes());
|
||||
iloc.extend_from_slice(&1u16.to_be_bytes());
|
||||
iloc.extend_from_slice(&offset.to_be_bytes());
|
||||
iloc.extend_from_slice(&(payload.len() as u32).to_be_bytes());
|
||||
let iloc = full_box(b"iloc", 0, &iloc);
|
||||
let mut meta = Vec::new();
|
||||
for part in [&hdlr, &pitm, &iinf, &iloc, &iprp] {
|
||||
meta.extend_from_slice(part);
|
||||
}
|
||||
full_box(b"meta", 0, &meta)
|
||||
};
|
||||
let meta_len = build(0).len();
|
||||
let offset = (ftyp.len() + meta_len + 8) as u32;
|
||||
let meta = build(offset);
|
||||
let mut out = ftyp;
|
||||
out.extend_from_slice(&meta);
|
||||
out.extend_from_slice(&bmff_box(b"mdat", &payload));
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! HEIC/HEIF goes through the OS codec. These tests only demand clean, typed outcomes.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use common::minimal_heic;
|
||||
use pictor_raster::{HeifSupport, Limits, RasterError, decode, heif_support};
|
||||
|
||||
#[test]
|
||||
fn heif_support_returns() {
|
||||
let start = Instant::now();
|
||||
let s = heif_support();
|
||||
eprintln!("heif_support() = {s:?} in {:?}", start.elapsed());
|
||||
#[cfg(not(windows))]
|
||||
assert_eq!(s, HeifSupport::Unavailable);
|
||||
#[cfg(windows)]
|
||||
assert_ne!(s, HeifSupport::Unavailable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_heic_gives_a_typed_error() {
|
||||
let bytes = minimal_heic(64, 64);
|
||||
let start = Instant::now();
|
||||
let result = decode(&bytes, &Limits::default());
|
||||
let took = start.elapsed();
|
||||
eprintln!("decode(minimal heic) = {:?} in {took:?}", result.as_ref().map(|i| (i.width(), i.height())));
|
||||
assert!(took < Duration::from_secs(20), "took {took:?}");
|
||||
let err = result.expect_err("the payload is not real HEVC");
|
||||
match &err {
|
||||
RasterError::HeifCodecMissing { .. } => {
|
||||
assert!(err.to_string().contains("9NMZLZ57R3T7"), "{err}");
|
||||
}
|
||||
RasterError::Corrupt { .. } | RasterError::Os { .. } => {
|
||||
// A machine with every codec installed rejects the dummy HEVC payload instead.
|
||||
assert_eq!(heif_support(), HeifSupport::Ready, "{err:?}");
|
||||
}
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heic_bomb_is_refused_before_the_os_codec() {
|
||||
let bytes = minimal_heic(100_000, 100_000);
|
||||
let err = decode(&bytes, &Limits::default()).unwrap_err();
|
||||
assert!(matches!(err, RasterError::TooManyPixels { width: 100_000, height: 100_000 }), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_heic_does_not_hang_or_panic() {
|
||||
let bytes = minimal_heic(64, 64);
|
||||
for cut in [12, 24, 40, bytes.len() / 2, bytes.len() - 3] {
|
||||
let start = Instant::now();
|
||||
let r = decode(&bytes[..cut], &Limits::default());
|
||||
assert!(r.is_err());
|
||||
assert!(start.elapsed() < Duration::from_secs(20));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Hostile inputs: bombs, truncation, garbage and mutation. Nothing may panic or allocate from a header.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use common::*;
|
||||
use pictor_raster::{Format, Limits, RasterError, decode, probe};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_bomb_is_refused_by_the_pixel_cap_quickly() {
|
||||
let bomb = png_with_size(100_000, 100_000);
|
||||
assert!(bomb.len() < 100);
|
||||
let start = Instant::now();
|
||||
let err = decode(&bomb, &limits()).unwrap_err();
|
||||
assert!(start.elapsed() < Duration::from_secs(1), "took {:?}", start.elapsed());
|
||||
match &err {
|
||||
RasterError::TooManyPixels { width, height } => assert_eq!((*width, *height), (100_000, 100_000)),
|
||||
other => panic!("expected TooManyPixels, got {other:?}"),
|
||||
}
|
||||
assert_eq!(err.to_string(), "This image is too large (100000 × 100000 pixels).");
|
||||
let p = probe(&bomb, &limits()).unwrap();
|
||||
assert_eq!((p.width, p.height, p.format), (100_000, 100_000, Format::Png));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_with_huge_sof_is_refused() {
|
||||
let bomb = patch_jpeg_sof(jpeg_fixture(32, 32), 65_000, 65_000);
|
||||
let start = Instant::now();
|
||||
let err = decode(&bomb, &limits()).unwrap_err();
|
||||
assert!(start.elapsed() < Duration::from_secs(1));
|
||||
assert!(matches!(err, RasterError::TooManyPixels { width: 65_000, height: 65_000 }), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_bomb_by_header_is_refused() {
|
||||
let bomb = gif_with_size(65_535, 65_535);
|
||||
let start = Instant::now();
|
||||
let err = decode(&bomb, &limits()).unwrap_err();
|
||||
assert!(start.elapsed() < Duration::from_secs(1));
|
||||
assert!(matches!(err, RasterError::TooManyPixels { .. } | RasterError::Corrupt { .. }), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiff_bomb_by_header_is_refused() {
|
||||
let bomb = tiff_with_size(1_000_000, 1_000_000);
|
||||
let start = Instant::now();
|
||||
let err = decode(&bomb, &limits()).unwrap_err();
|
||||
assert!(start.elapsed() < Duration::from_secs(1));
|
||||
assert!(matches!(err, RasterError::TooManyPixels { width: 1_000_000, height: 1_000_000 }), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiny_cap_refuses_an_ordinary_image() {
|
||||
let png = encode_with_image(&sample_rgb(64, 64), image::ImageFormat::Png);
|
||||
let small = Limits { max_pixels: 1000, ..Limits::default() };
|
||||
assert!(matches!(decode(&png, &small), Err(RasterError::TooManyPixels { .. })));
|
||||
let tiny_input = Limits { max_input_bytes: 10, ..Limits::default() };
|
||||
assert!(matches!(decode(&png, &tiny_input), Err(RasterError::InputTooLarge { .. })));
|
||||
let tiny_alloc = Limits { max_alloc: 1000, ..Limits::default() };
|
||||
assert!(matches!(decode(&png, &tiny_alloc), Err(RasterError::TooMuchMemory { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_png_errors() {
|
||||
let png = encode_with_image(&sample_rgb(200, 150), image::ImageFormat::Png);
|
||||
let cut = &png[..png.len() * 6 / 10];
|
||||
let err = decode(cut, &limits()).unwrap_err();
|
||||
assert!(matches!(err, RasterError::Corrupt { format: Format::Png, .. }), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_jpeg_does_not_panic() {
|
||||
let jpeg = jpeg_fixture(200, 150);
|
||||
let cut = &jpeg[..jpeg.len() * 6 / 10];
|
||||
// zune-jpeg may fill the missing part; both outcomes are acceptable as long as nothing panics.
|
||||
match decode(cut, &limits()) {
|
||||
Ok(img) => assert_eq!((img.width(), img.height()), (200, 150)),
|
||||
Err(e) => assert!(matches!(e, RasterError::Corrupt { format: Format::Jpeg, .. }), "{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_random_inputs_are_typed_errors() {
|
||||
assert!(matches!(decode(&[], &limits()), Err(RasterError::Empty)));
|
||||
assert!(matches!(probe(&[], &limits()), Err(RasterError::Empty)));
|
||||
let mut rng = XorShift::new(7);
|
||||
for len in [1usize, 3, 16, 100, 4096] {
|
||||
let junk: Vec<u8> = (0..len).map(|_| rng.byte()).collect();
|
||||
let err = decode(&junk, &limits()).unwrap_err();
|
||||
assert!(matches!(err, RasterError::UnknownFormat | RasterError::Corrupt { .. }), "{err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bogus_ico_directory_is_a_typed_error() {
|
||||
let ico = bogus_ico();
|
||||
assert_eq!(Format::sniff(&ico), Some(Format::Ico));
|
||||
let err = decode(&ico, &limits()).unwrap_err();
|
||||
assert!(matches!(err, RasterError::Corrupt { .. } | RasterError::TooManyPixels { .. }), "{err:?}");
|
||||
let _ = probe(&ico, &limits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_error_message_is_plain_english() {
|
||||
let samples: Vec<RasterError> = vec![
|
||||
decode(&[], &limits()).unwrap_err(),
|
||||
decode(b"hello world, not an image", &limits()).unwrap_err(),
|
||||
decode(&png_with_size(100_000, 100_000), &limits()).unwrap_err(),
|
||||
decode(&bogus_ico(), &limits()).unwrap_err(),
|
||||
];
|
||||
for e in samples {
|
||||
let msg = e.to_string();
|
||||
assert!(msg.ends_with('.'), "{msg}");
|
||||
assert!(!msg.contains("Error") && !msg.contains("{"), "{msg}");
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_fixtures() -> Vec<(&'static str, Vec<u8>)> {
|
||||
let rgb = sample_rgb(24, 16);
|
||||
let rgba = sample_rgba(24, 16);
|
||||
vec![
|
||||
("png", encode_with_image(&rgba, image::ImageFormat::Png)),
|
||||
("jpeg", encode_with_image(&rgb, image::ImageFormat::Jpeg)),
|
||||
("jpeg-exif", jpeg_with_orientation(&encode_with_image(&rgb, image::ImageFormat::Jpeg), 6)),
|
||||
("gif", encode_with_image(&rgba, image::ImageFormat::Gif)),
|
||||
("bmp", encode_with_image(&rgb, image::ImageFormat::Bmp)),
|
||||
("tiff", encode_with_image(&rgba, image::ImageFormat::Tiff)),
|
||||
("webp", encode_with_image(&rgba, image::ImageFormat::WebP)),
|
||||
("ico", encode_with_image(&rgba, image::ImageFormat::Ico)),
|
||||
("heic", minimal_heic(64, 64)),
|
||||
]
|
||||
}
|
||||
|
||||
fn mutate(rng: &mut XorShift, src: &[u8]) -> Vec<u8> {
|
||||
let mut m = src.to_vec();
|
||||
match rng.below(5) {
|
||||
0 => {
|
||||
for _ in 0..1 + rng.below(8) {
|
||||
let i = rng.below(m.len());
|
||||
m[i] = rng.byte();
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
let i = rng.below(m.len());
|
||||
m[i] ^= 1 << rng.below(8);
|
||||
}
|
||||
2 => m.truncate(rng.below(m.len())),
|
||||
3 => {
|
||||
let i = rng.below(m.len());
|
||||
let extra: Vec<u8> = (0..1 + rng.below(16)).map(|_| rng.byte()).collect();
|
||||
m.splice(i..i, extra);
|
||||
}
|
||||
_ => {
|
||||
// Header fields are where the interesting bugs live: hammer the first 64 bytes with 0xFF / 0x00.
|
||||
let i = rng.below(m.len().min(64));
|
||||
m[i] = if rng.below(2) == 0 { 0xFF } else { 0x00 };
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutation_loop_never_panics() {
|
||||
let limits = Limits { max_pixels: 4_000_000, max_input_bytes: 1 << 20, max_alloc: 64 << 20 };
|
||||
let mut rng = XorShift::new(0x5EED_1234_ABCD);
|
||||
let start = Instant::now();
|
||||
for (name, fixture) in valid_fixtures() {
|
||||
if name != "heic" {
|
||||
assert!(decode(&fixture, &limits).is_ok(), "fixture {name} must decode");
|
||||
}
|
||||
// Each HEIC attempt activates the Store codec (~0.3 s), so it gets fewer rounds.
|
||||
let rounds = if name == "heic" { 20 } else { 300 };
|
||||
let t = Instant::now();
|
||||
for round in 0..rounds {
|
||||
let m = mutate(&mut rng, &fixture);
|
||||
let caught = std::panic::catch_unwind(|| {
|
||||
let _ = probe(&m, &limits);
|
||||
let _ = decode(&m, &limits);
|
||||
});
|
||||
assert!(caught.is_ok(), "panic on {name} mutation {round}");
|
||||
}
|
||||
eprintln!("{name}: {rounds} mutations in {:?}", t.elapsed());
|
||||
}
|
||||
eprintln!("mutation loop took {:?}", start.elapsed());
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Every writable format encodes and decodes back.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use image::{DynamicImage, GenericImageView};
|
||||
use pictor_raster::{EncodeOptions, Format, Limits, RasterError, decode, encode, probe};
|
||||
|
||||
fn round(img: &DynamicImage, format: Format) -> DynamicImage {
|
||||
let bytes = encode(img, format, &EncodeOptions::default()).unwrap_or_else(|e| panic!("{format:?}: {e}"));
|
||||
assert_eq!(Format::sniff(&bytes), Some(format), "sniff of encoded {format:?}");
|
||||
let p = probe(&bytes, &Limits::default()).unwrap();
|
||||
assert_eq!(p.format, format);
|
||||
decode(&bytes, &Limits::default()).unwrap_or_else(|e| panic!("{format:?}: {e}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lossless_formats_are_pixel_identical() {
|
||||
let rgba = sample_rgba(37, 23);
|
||||
for format in [Format::Png, Format::Tiff, Format::WebP, Format::Bmp] {
|
||||
let back = round(&rgba, format);
|
||||
assert_eq!(back.dimensions(), (37, 23), "{format:?}");
|
||||
assert_eq!(back.to_rgba8().as_raw(), rgba.to_rgba8().as_raw(), "{format:?} pixels");
|
||||
}
|
||||
let rgb = sample_rgb(37, 23);
|
||||
for format in [Format::Png, Format::Tiff, Format::WebP, Format::Bmp] {
|
||||
let back = round(&rgb, format);
|
||||
assert_eq!(back.to_rgb8().as_raw(), rgb.to_rgb8().as_raw(), "{format:?} rgb pixels");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_is_within_tolerance() {
|
||||
let rgb = sample_rgb(64, 48);
|
||||
let back = round(&rgb, Format::Jpeg);
|
||||
assert_eq!(back.dimensions(), (64, 48));
|
||||
let (a, b) = (rgb.to_rgb8(), back.to_rgb8());
|
||||
let total: u64 = a.as_raw().iter().zip(b.as_raw()).map(|(x, y)| u64::from(x.abs_diff(*y))).sum();
|
||||
let mean = total as f64 / a.as_raw().len() as f64;
|
||||
assert!(mean < 6.0, "mean abs error {mean}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_flattens_alpha_onto_white() {
|
||||
let rgba = sample_rgba(32, 32); // the left quarter is fully transparent
|
||||
let back = round(&rgba, Format::Jpeg).to_rgb8();
|
||||
let px = back.get_pixel(2, 16).0;
|
||||
assert!(px.iter().all(|&c| c > 235), "transparent area should be white, got {px:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_keeps_dimensions() {
|
||||
let back = round(&sample_rgba(40, 30), Format::Gif);
|
||||
assert_eq!(back.dimensions(), (40, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ico_fits_256_and_pads_to_square() {
|
||||
let back = round(&sample_rgba(48, 48), Format::Ico);
|
||||
assert_eq!(back.dimensions(), (48, 48));
|
||||
|
||||
let big = sample_rgb(600, 300);
|
||||
let back = round(&big, Format::Ico);
|
||||
assert_eq!(back.dimensions(), (256, 256));
|
||||
let rgba = back.to_rgba8();
|
||||
assert_eq!(rgba.get_pixel(128, 2).0[3], 0, "padding is transparent");
|
||||
assert_eq!(rgba.get_pixel(128, 128).0[3], 255, "content is opaque");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heif_output_is_a_typed_error() {
|
||||
let err = encode(&sample_rgb(8, 8), Format::Heif, &EncodeOptions::default()).unwrap_err();
|
||||
assert!(matches!(err, RasterError::CannotWrite { format: Format::Heif }), "{err:?}");
|
||||
assert!(err.to_string().contains("HEIC"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_bit_images_encode_everywhere() {
|
||||
let img = DynamicImage::ImageRgba16(sample_rgba(20, 10).to_rgba16());
|
||||
for format in [Format::Png, Format::Jpeg, Format::WebP, Format::Bmp, Format::Gif, Format::Tiff, Format::Ico] {
|
||||
let back = round(&img, format);
|
||||
assert!(back.width() > 0, "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sniff_and_names() {
|
||||
assert_eq!(Format::from_name("jpg"), Some(Format::Jpeg));
|
||||
assert_eq!(Format::from_name(".JPEG"), Some(Format::Jpeg));
|
||||
assert_eq!(Format::from_name("photo.HEIC"), Some(Format::Heif));
|
||||
assert_eq!(Format::from_name("tif"), Some(Format::Tiff));
|
||||
assert_eq!(Format::from_name("avif"), Some(Format::Avif));
|
||||
assert_eq!(Format::from_name("exe"), None);
|
||||
assert_eq!(Format::Jpeg.extension(), "jpg");
|
||||
assert_eq!(Format::Heif.extension(), "heic");
|
||||
assert_eq!(Format::sniff(&minimal_heic(10, 10)), Some(Format::Heif));
|
||||
let mut avif = minimal_heic(10, 10);
|
||||
avif[8..12].copy_from_slice(b"avif");
|
||||
avif[16..24].copy_from_slice(b"mif1avif");
|
||||
assert_eq!(Format::sniff(&avif), Some(Format::Avif));
|
||||
assert!(Format::Avif.is_heif_family());
|
||||
assert_eq!(Format::sniff(b"GIF89a"), Some(Format::Gif));
|
||||
assert_eq!(Format::sniff(b"BM"), None, "too short to be a BMP");
|
||||
assert_eq!(Format::sniff(&[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_reports_alpha_and_frames() {
|
||||
let png = encode(&sample_rgba(10, 12), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let p = probe(&png, &Limits::default()).unwrap();
|
||||
assert_eq!((p.width, p.height, p.has_alpha, p.frames), (10, 12, true, Some(1)));
|
||||
let jpg = encode(&sample_rgb(10, 12), Format::Jpeg, &EncodeOptions::default()).unwrap();
|
||||
assert!(!probe(&jpg, &Limits::default()).unwrap().has_alpha);
|
||||
let gif = encode(&sample_rgb(10, 12), Format::Gif, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(probe(&gif, &Limits::default()).unwrap().frames, Some(1));
|
||||
let heic = probe(&minimal_heic(4032, 3024), &Limits::default()).unwrap();
|
||||
assert_eq!((heic.format, heic.width, heic.height), (Format::Heif, 4032, 3024));
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Orientation, crop, rotate, resize, presets, compress-to-size.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use image::GenericImageView;
|
||||
use pictor_raster::{
|
||||
Fit, Format, Limits, Preset, RasterError, Rect, Rotation, apply_preset, compress_to, crop, decode, probe, resize,
|
||||
rotate,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn exif_orientation_6_rotates_on_decode() {
|
||||
// Left half red, right half blue, 40 × 20.
|
||||
let mut img = image::RgbImage::new(40, 20);
|
||||
for (x, _, px) in img.enumerate_pixels_mut() {
|
||||
px.0 = if x < 20 { [255, 0, 0] } else { [0, 0, 255] };
|
||||
}
|
||||
let jpeg = encode_with_image(&image::DynamicImage::ImageRgb8(img), image::ImageFormat::Jpeg);
|
||||
let tagged = jpeg_with_orientation(&jpeg, 6);
|
||||
let out = decode(&tagged, &Limits::default()).unwrap();
|
||||
assert_eq!(out.dimensions(), (20, 40), "width and height swap");
|
||||
// Orientation 6 means "rotate 90° clockwise to display": the left (red) half ends up on top.
|
||||
let top = out.get_pixel(10, 5).0;
|
||||
let bottom = out.get_pixel(10, 35).0;
|
||||
assert!(top[0] > 200 && top[2] < 60, "top {top:?}");
|
||||
assert!(bottom[2] > 200 && bottom[0] < 60, "bottom {bottom:?}");
|
||||
// probe reports the stored size, before orientation.
|
||||
let p = probe(&tagged, &Limits::default()).unwrap();
|
||||
assert_eq!((p.width, p.height), (40, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_checks_bounds() {
|
||||
let img = sample_rgb(100, 50);
|
||||
let c = crop(&img, Rect { x: 10, y: 5, width: 30, height: 20 }).unwrap();
|
||||
assert_eq!(c.dimensions(), (30, 20));
|
||||
assert_eq!(c.get_pixel(0, 0), img.get_pixel(10, 5));
|
||||
for bad in [
|
||||
Rect { x: 90, y: 0, width: 20, height: 10 },
|
||||
Rect { x: 0, y: 0, width: 0, height: 10 },
|
||||
Rect { x: u32::MAX, y: 0, width: 2, height: 2 },
|
||||
] {
|
||||
assert!(matches!(crop(&img, bad), Err(RasterError::InvalidCrop)), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotations() {
|
||||
let img = sample_rgb(30, 10);
|
||||
assert_eq!(rotate(&img, Rotation::Cw90).dimensions(), (10, 30));
|
||||
assert_eq!(rotate(&img, Rotation::Ccw90).dimensions(), (10, 30));
|
||||
assert_eq!(rotate(&img, Rotation::R180).dimensions(), (30, 10));
|
||||
assert_eq!(rotate(&img, Rotation::FlipH).get_pixel(0, 0), img.get_pixel(29, 0));
|
||||
assert_eq!(rotate(&img, Rotation::FlipV).get_pixel(0, 0), img.get_pixel(0, 9));
|
||||
assert_eq!(rotate(&img, Rotation::Cw90).get_pixel(9, 0), img.get_pixel(0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_fits() {
|
||||
let l = Limits::default();
|
||||
let img = sample_rgb(400, 200);
|
||||
assert_eq!(resize(&img, Fit::LongEdge(100), &l).unwrap().dimensions(), (100, 50));
|
||||
assert_eq!(resize(&img, Fit::LongEdge(1000), &l).unwrap().dimensions(), (400, 200), "never upscales");
|
||||
assert_eq!(resize(&img, Fit::Exact(50, 70), &l).unwrap().dimensions(), (50, 70));
|
||||
assert_eq!(resize(&img, Fit::Percent(50.0), &l).unwrap().dimensions(), (200, 100));
|
||||
assert_eq!(resize(&img, Fit::Percent(0.01), &l).unwrap().dimensions(), (1, 1));
|
||||
for bad in [Fit::Percent(f32::NAN), Fit::Percent(-5.0), Fit::Percent(f32::INFINITY), Fit::Exact(0, 5)] {
|
||||
assert!(matches!(resize(&img, bad, &l), Err(RasterError::InvalidSize)), "{bad:?}");
|
||||
}
|
||||
let err = resize(&img, Fit::Exact(100_000, 100_000), &l).unwrap_err();
|
||||
assert!(matches!(err, RasterError::TooManyPixels { .. }), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn email_preset_long_edge_1600_jpeg() {
|
||||
let big = sample_rgb(3200, 2000);
|
||||
let (bytes, format) = apply_preset(&big, Format::Png, Preset::Email).unwrap();
|
||||
assert_eq!(format, Format::Jpeg);
|
||||
let p = probe(&bytes, &Limits::default()).unwrap();
|
||||
assert_eq!((p.width, p.height), (1600, 1000));
|
||||
|
||||
let small = sample_rgb(800, 600);
|
||||
let (bytes, _) = apply_preset(&small, Format::Jpeg, Preset::Email).unwrap();
|
||||
let p = probe(&bytes, &Limits::default()).unwrap();
|
||||
assert_eq!((p.width, p.height), (800, 600), "never upscales");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_preset_keeps_alpha_as_png() {
|
||||
let rgba = sample_rgba(3000, 1000);
|
||||
let (bytes, format) = apply_preset(&rgba, Format::Png, Preset::Web).unwrap();
|
||||
assert_eq!(format, Format::Png);
|
||||
let p = probe(&bytes, &Limits::default()).unwrap();
|
||||
assert_eq!((p.width, p.height), (2048, 683));
|
||||
|
||||
let (_, format) = apply_preset(&sample_rgb(300, 200), Format::Png, Preset::Web).unwrap();
|
||||
assert_eq!(format, Format::Jpeg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn original_preset_keeps_size_and_format() {
|
||||
let img = sample_rgb(321, 123);
|
||||
let (bytes, format) = apply_preset(&img, Format::Bmp, Preset::Original).unwrap();
|
||||
assert_eq!(format, Format::Bmp);
|
||||
assert_eq!(decode(&bytes, &Limits::default()).unwrap().dimensions(), (321, 123));
|
||||
let (_, format) = apply_preset(&img, Format::Heif, Preset::Original).unwrap();
|
||||
assert_eq!(format, Format::Jpeg, "HEIC cannot be written, so Original falls back to JPEG");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compress_noisy_photo_under_500_kb() {
|
||||
let img = noisy_rgb(3000, 2000, 42);
|
||||
let target = 500_000;
|
||||
let c = compress_to(&img, Format::Jpeg, target, &Limits::default()).unwrap();
|
||||
eprintln!("compressed: {} bytes, q {:?}, scale {}, {}×{}", c.bytes.len(), c.quality, c.scale, c.width, c.height);
|
||||
assert!(c.bytes.len() as u64 <= target);
|
||||
let back = decode(&c.bytes, &Limits::default()).unwrap();
|
||||
assert_eq!(back.dimensions(), (c.width, c.height));
|
||||
assert!(c.width >= 320);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compress_easy_target_keeps_full_size() {
|
||||
let img = sample_rgb(800, 600);
|
||||
let c = compress_to(&img, Format::Jpeg, 2_000_000, &Limits::default()).unwrap();
|
||||
assert_eq!((c.width, c.height, c.scale), (800, 600, 1.0));
|
||||
assert_eq!(c.quality, Some(92));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compress_impossible_target_reports_smallest() {
|
||||
let img = noisy_rgb(1200, 800, 9);
|
||||
match compress_to(&img, Format::Jpeg, 1_000, &Limits::default()) {
|
||||
Err(RasterError::CannotReachTarget { smallest_bytes }) => assert!(smallest_bytes > 1_000),
|
||||
other => panic!("expected CannotReachTarget, got {:?}", other.map(|c| c.bytes.len())),
|
||||
}
|
||||
match compress_to(&img, Format::Png, 1_000, &Limits::default()) {
|
||||
Err(RasterError::CannotReachTarget { smallest_bytes }) => assert!(smallest_bytes > 1_000),
|
||||
other => panic!("expected CannotReachTarget, got {:?}", other.map(|c| c.bytes.len())),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compress_png_scales_down() {
|
||||
let img = noisy_rgb(1000, 800, 3);
|
||||
let c = compress_to(&img, Format::Png, 600_000, &Limits::default()).unwrap();
|
||||
assert!(c.bytes.len() <= 600_000);
|
||||
assert!(c.scale < 1.0);
|
||||
assert_eq!(c.quality, None);
|
||||
assert_eq!(c.format, Format::Png);
|
||||
}
|
||||
Reference in New Issue
Block a user