diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml new file mode 100644 index 0000000..2c5e78d --- /dev/null +++ b/crates/raster/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "pictor-raster" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +thiserror.workspace = true +serde.workspace = true +image.workspace = true + +[target.'cfg(windows)'.dependencies] +windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_Com", "Win32_Graphics_Imaging", "Win32_UI_Shell_PropertiesSystem", "Win32_System_Variant", "Win32_System_Com_StructuredStorage", "Win32_Media_MediaFoundation"] } + +[dev-dependencies] +proptest.workspace = true diff --git a/crates/raster/src/decode.rs b/crates/raster/src/decode.rs new file mode 100644 index 0000000..f71abc2 --- /dev/null +++ b/crates/raster/src/decode.rs @@ -0,0 +1,236 @@ +use std::io::Cursor; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use image::metadata::Orientation; +use image::{DynamicImage, ImageDecoder, ImageError, ImageReader}; +use serde::{Deserialize, Serialize}; + +use crate::error::{RasterError, Result}; +use crate::{Format, Limits, isobmff}; + +/// What the headers say, read without decoding pixels. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Probe { + pub format: Format, + /// Stored size, before the EXIF orientation is applied (`decode` applies it, so a portrait photo + /// tagged with orientation 6 probes as landscape and decodes as portrait). + pub width: u32, + pub height: u32, + pub has_alpha: bool, + /// Number of frames or icon entries when the header tells it cheaply; `None` when unknown. + pub frames: Option, +} + +/// Read the header only. Refuses empty, oversized and unknown input, but reports a pixel bomb's size +/// rather than refusing it (that is `decode`'s job), so the Toolbox can say how large it is. +pub fn probe(bytes: &[u8], limits: &Limits) -> Result { + let format = check_input(bytes, limits)?; + if format.is_heif_family() { + let info = isobmff::info(bytes) + .ok_or_else(|| RasterError::Corrupt { format, detail: "no readable ispe property".into() })?; + return Ok(Probe { format, width: info.width, height: info.height, has_alpha: info.has_alpha, frames: None }); + } + guarded(format, || { + let decoder = open(bytes, format, header_limits(limits))?; + let (width, height) = decoder.dimensions(); + let has_alpha = decoder.color_type().has_alpha(); + Ok(Probe { format, width, height, has_alpha, frames: count_frames(format, bytes) }) + }) +} + +/// Decode to pixels with every cap applied, then apply the EXIF orientation. +/// +/// Order: input size, format sniff, header-only pixel count (refused above `max_pixels` before any pixel +/// buffer exists), decoder with `image`'s own limits (dimensions and `max_alloc`), output-buffer size check, +/// decode, orientation. HEIC/AVIF go to the Windows codec (see `wic`), elsewhere they are refused. +pub fn decode(bytes: &[u8], limits: &Limits) -> Result { + let format = check_input(bytes, limits)?; + if format.is_heif_family() { + return decode_heif(bytes, format, limits); + } + guarded(format, || { + let (width, height) = open(bytes, format, header_limits(limits))?.dimensions(); + check_pixels(width, height, limits)?; + + let mut caps = header_limits(limits); + caps.max_image_width = Some(width); + caps.max_image_height = Some(height); + let mut decoder = open(bytes, format, caps)?; + let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); + let copies = match orientation { + Orientation::Rotate90 + | Orientation::Rotate270 + | Orientation::Rotate90FlipH + | Orientation::Rotate270FlipH => 2, + _ => 1, + }; + let needed = decoder.total_bytes().saturating_mul(copies); + if needed > limits.max_alloc { + return Err(RasterError::TooMuchMemory { limit: limits.max_alloc }); + } + let mut img = DynamicImage::from_decoder(decoder).map_err(|e| map_image_error(format, e, limits))?; + img.apply_orientation(orientation); + Ok(img) + }) +} + +fn decode_heif(bytes: &[u8], format: Format, limits: &Limits) -> Result { + if let Some(info) = isobmff::info(bytes) { + check_pixels(info.width, info.height, limits)?; + } + #[cfg(windows)] + { + crate::wic::decode(bytes, format, limits) + } + #[cfg(not(windows))] + { + let _ = limits; + Err(match format { + Format::Avif => RasterError::AvifCodecMissing, + _ => RasterError::HeifCodecMissing { needs_heif: true }, + }) + } +} + +pub(crate) fn check_input(bytes: &[u8], limits: &Limits) -> Result { + if bytes.is_empty() { + return Err(RasterError::Empty); + } + let len = bytes.len() as u64; + if len > limits.max_input_bytes { + return Err(RasterError::InputTooLarge { bytes: len, limit: limits.max_input_bytes }); + } + Format::sniff(bytes).ok_or(RasterError::UnknownFormat) +} + +pub(crate) fn check_pixels(width: u32, height: u32, limits: &Limits) -> Result<()> { + let pixels = u64::from(width) * u64::from(height); + if pixels > limits.max_pixels { + return Err(RasterError::TooManyPixels { width: width.into(), height: height.into() }); + } + if pixels == 0 { + return Err(RasterError::InvalidSize); + } + Ok(()) +} + +fn header_limits(limits: &Limits) -> image::Limits { + let mut l = image::Limits::default(); + l.max_alloc = Some(limits.max_alloc); + l +} + +fn open(bytes: &[u8], format: Format, caps: image::Limits) -> Result { + let image_format = format.to_image().ok_or(RasterError::UnknownFormat)?; + let mut reader = ImageReader::with_format(Cursor::new(bytes), image_format); + let max_alloc = caps.max_alloc.unwrap_or(u64::MAX); + reader.limits(caps); + reader.into_decoder().map_err(|e| map_image_error_alloc(format, e, max_alloc)) +} + +/// Third-party decoders are not ours to prove panic-free; a panic on hostile bytes becomes `Corrupt`. +pub(crate) fn guarded(format: Format, f: impl FnOnce() -> Result) -> Result { + catch_unwind(AssertUnwindSafe(f)) + .unwrap_or_else(|_| Err(RasterError::Corrupt { format, detail: "the decoder panicked".into() })) +} + +fn map_image_error(format: Format, e: ImageError, limits: &Limits) -> RasterError { + map_image_error_alloc(format, e, limits.max_alloc) +} + +fn map_image_error_alloc(format: Format, e: ImageError, max_alloc: u64) -> RasterError { + match e { + ImageError::Limits(_) => RasterError::TooMuchMemory { limit: max_alloc }, + ImageError::Unsupported(u) => RasterError::UnsupportedFeature { format, detail: u.to_string() }, + other => RasterError::Corrupt { format, detail: other.to_string() }, + } +} + +/// Frame counts that the container states cheaply; never decodes image data. +fn count_frames(format: Format, bytes: &[u8]) -> Option { + match format { + Format::Png => Some(png_frames(bytes).unwrap_or(1)), + Format::Gif => gif_frames(bytes), + Format::Ico => Some(u32::from(u16::from_le_bytes([*bytes.get(4)?, *bytes.get(5)?]))), + Format::WebP => webp_frames(bytes), + Format::Jpeg | Format::Bmp => Some(1), + Format::Tiff | Format::Heif | Format::Avif => None, + } +} + +/// APNG `acTL.num_frames`, if present before the first IDAT. +fn png_frames(bytes: &[u8]) -> Option { + let mut pos = 8usize; + for _ in 0..10_000 { + let len = u32::from_be_bytes(bytes.get(pos..pos + 4)?.try_into().ok()?) as usize; + let kind = bytes.get(pos + 4..pos + 8)?; + if kind == b"acTL" { + return Some(u32::from_be_bytes(bytes.get(pos + 8..pos + 12)?.try_into().ok()?)); + } + if kind == b"IDAT" { + return None; + } + pos = pos.checked_add(12)?.checked_add(len)?; + } + None +} + +/// Walk GIF blocks, skipping LZW data by its sub-block lengths, counting image descriptors. +fn gif_frames(bytes: &[u8]) -> Option { + let flags = *bytes.get(10)?; + let mut pos = 13usize; + if flags & 0x80 != 0 { + pos += 3 << ((flags & 7) + 1); + } + let skip_sub_blocks = |mut p: usize| -> Option { + loop { + let n = usize::from(*bytes.get(p)?); + p += 1; + if n == 0 { + return Some(p); + } + p += n; + } + }; + let mut frames = 0u32; + while frames < 1_000_000 { + match bytes.get(pos) { + Some(0x2C) => { + let local = *bytes.get(pos + 9)?; + pos += 10; + if local & 0x80 != 0 { + pos += 3 << ((local & 7) + 1); + } + pos = skip_sub_blocks(pos + 1)?; // LZW minimum code size, then data + frames += 1; + } + Some(0x21) => pos = skip_sub_blocks(pos + 2)?, + Some(0x3B) => return Some(frames), + _ => return (frames > 0).then_some(frames), + } + } + Some(frames) +} + +/// 1 for a still WebP, the number of ANMF chunks for an animated one. +fn webp_frames(bytes: &[u8]) -> Option { + if bytes.get(12..16)? != b"VP8X" { + return Some(1); + } + let animated = bytes.get(20)? & 0x02 != 0; + if !animated { + return Some(1); + } + let mut pos = 12usize; + let mut frames = 0u32; + for _ in 0..1_000_000 { + let Some(kind) = bytes.get(pos..pos + 4) else { break }; + let Some(len) = bytes.get(pos + 4..pos + 8) else { break }; + let len = u32::from_le_bytes(len.try_into().ok()?) as usize; + if kind == b"ANMF" { + frames += 1; + } + pos = pos.checked_add(8)?.checked_add(len)?.checked_add(len & 1)?; + } + Some(frames) +} diff --git a/crates/raster/src/encode.rs b/crates/raster/src/encode.rs new file mode 100644 index 0000000..eeeb182 --- /dev/null +++ b/crates/raster/src/encode.rs @@ -0,0 +1,169 @@ +use std::borrow::Cow; +use std::io::Cursor; + +use image::codecs::bmp::BmpEncoder; +use image::codecs::gif::GifEncoder; +use image::codecs::ico::{IcoEncoder, IcoFrame}; +use image::codecs::jpeg::JpegEncoder; +use image::codecs::png::PngEncoder; +use image::codecs::tiff::TiffEncoder; +use image::codecs::webp::WebPEncoder; +use image::imageops::FilterType; +use image::{DynamicImage, ExtendedColorType, GenericImageView, ImageError, Rgb, RgbImage, RgbaImage}; +use serde::{Deserialize, Serialize}; + +use crate::Format; +use crate::error::{RasterError, Result}; + +/// Encoder settings. Only JPEG is lossy: the WebP encoder in `image` 0.25 writes **lossless** WebP only. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct EncodeOptions { + /// 1..=100 (clamped). + pub jpeg_quality: u8, + /// JPEG has no alpha: transparent pixels are composited onto this colour. + pub jpeg_background: [u8; 3], +} + +impl Default for EncodeOptions { + fn default() -> Self { + Self { jpeg_quality: 88, jpeg_background: [255, 255, 255] } + } +} + +/// The ICO sizes written besides the largest one (each only when smaller than it). +const ICO_SMALL_SIZES: [u32; 3] = [48, 32, 16]; + +/// Encode `img` as `format`. +/// +/// - JPEG: alpha is flattened onto `jpeg_background` (white by default); grey stays grey. +/// - WebP: lossless (the only mode `image` 0.25 can write). +/// - GIF: a single frame, palette by NeuQuant. +/// - ICO: fitted into 256 × 256 (never enlarged), centred on a transparent square, plus 48/32/16 px entries, +/// each stored as PNG. +/// - HEIC/AVIF: [`RasterError::CannotWrite`]. +pub fn encode(img: &DynamicImage, format: Format, options: &EncodeOptions) -> Result> { + if !format.can_encode() { + return Err(RasterError::CannotWrite { format }); + } + let (w, h) = img.dimensions(); + if w == 0 || h == 0 { + return Err(RasterError::InvalidSize); + } + let mut out = Vec::new(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> std::result::Result<(), ImageError> { + match format { + Format::Png => for_png_tiff(img, false).write_with_encoder(PngEncoder::new(&mut out)), + Format::Tiff => { + let mut cursor = Cursor::new(&mut out); + for_png_tiff(img, true).write_with_encoder(TiffEncoder::new(&mut cursor)) + } + Format::Jpeg => { + let flat = flatten(img, options.jpeg_background); + let quality = options.jpeg_quality.clamp(1, 100); + flat.write_with_encoder(JpegEncoder::new_with_quality(&mut out, quality)) + } + Format::WebP => to_8bit(img).write_with_encoder(WebPEncoder::new_lossless(&mut out)), + Format::Bmp => to_8bit(img).write_with_encoder(BmpEncoder::new(&mut out)), + Format::Gif => { + let rgba = img.to_rgba8(); + let mut encoder = GifEncoder::new_with_speed(&mut out, 10); + encoder.encode(rgba.as_raw(), w, h, ExtendedColorType::Rgba8) + } + Format::Ico => encode_ico(img, &mut out), + Format::Heif | Format::Avif => unreachable!("checked above"), + } + })); + match result { + Ok(Ok(())) => Ok(out), + Ok(Err(e)) => Err(RasterError::Encode { format, detail: e.to_string() }), + Err(_) => Err(RasterError::Encode { format, detail: "the encoder panicked".into() }), + } +} + +/// 8/16-bit grey or colour as is; everything else to 8-bit. TIFF has no grey+alpha in `image`'s encoder. +fn for_png_tiff(img: &DynamicImage, tiff: bool) -> Cow<'_, DynamicImage> { + match img { + DynamicImage::ImageLuma8(_) + | DynamicImage::ImageRgb8(_) + | DynamicImage::ImageRgba8(_) + | DynamicImage::ImageLuma16(_) + | DynamicImage::ImageRgb16(_) + | DynamicImage::ImageRgba16(_) => Cow::Borrowed(img), + DynamicImage::ImageLumaA8(_) | DynamicImage::ImageLumaA16(_) if !tiff => Cow::Borrowed(img), + DynamicImage::ImageLumaA16(_) => Cow::Owned(DynamicImage::ImageRgba16(img.to_rgba16())), + _ => to_8bit(img), + } +} + +fn to_8bit(img: &DynamicImage) -> Cow<'_, DynamicImage> { + match img { + DynamicImage::ImageLuma8(_) + | DynamicImage::ImageLumaA8(_) + | DynamicImage::ImageRgb8(_) + | DynamicImage::ImageRgba8(_) => Cow::Borrowed(img), + DynamicImage::ImageLuma16(_) => Cow::Owned(DynamicImage::ImageLuma8(img.to_luma8())), + DynamicImage::ImageLumaA16(_) => Cow::Owned(DynamicImage::ImageLumaA8(img.to_luma_alpha8())), + _ if img.color().has_alpha() => Cow::Owned(DynamicImage::ImageRgba8(img.to_rgba8())), + _ => Cow::Owned(DynamicImage::ImageRgb8(img.to_rgb8())), + } +} + +/// Opaque 8-bit image for JPEG: alpha composited onto `bg`. +fn flatten(img: &DynamicImage, bg: [u8; 3]) -> DynamicImage { + if !img.color().has_alpha() { + return match img { + DynamicImage::ImageLuma8(_) => img.clone(), + DynamicImage::ImageLuma16(_) => DynamicImage::ImageLuma8(img.to_luma8()), + _ => DynamicImage::ImageRgb8(img.to_rgb8()), + }; + } + let rgba = img.to_rgba8(); + let out = RgbImage::from_fn(rgba.width(), rgba.height(), |x, y| { + let [r, g, b, a] = rgba.get_pixel(x, y).0; + let a = u32::from(a); + let mix = |c: u8, bg: u8| ((u32::from(c) * a + u32::from(bg) * (255 - a) + 127) / 255) as u8; + Rgb([mix(r, bg[0]), mix(g, bg[1]), mix(b, bg[2])]) + }); + DynamicImage::ImageRgb8(out) +} + +fn encode_ico(img: &DynamicImage, out: &mut Vec) -> std::result::Result<(), ImageError> { + let (w, h) = img.dimensions(); + let long = w.max(h); + let side = long.min(256); + let fitted = if long > 256 { + let (nw, nh) = fit_within(w, h, 256); + img.resize_exact(nw, nh, FilterType::Lanczos3).to_rgba8() + } else { + img.to_rgba8() + }; + let mut square = RgbaImage::new(side, side); + let (dx, dy) = ((side - fitted.width()) / 2, (side - fitted.height()) / 2); + image::imageops::replace(&mut square, &fitted, i64::from(dx), i64::from(dy)); + + let mut sizes = vec![side]; + sizes.extend(ICO_SMALL_SIZES.iter().copied().filter(|&s| s < side)); + let mut frames = Vec::with_capacity(sizes.len()); + for s in sizes { + let frame = if s == side { + IcoFrame::as_png(square.as_raw(), s, s, ExtendedColorType::Rgba8)? + } else { + let small = image::imageops::resize(&square, s, s, FilterType::Lanczos3); + IcoFrame::as_png(small.as_raw(), s, s, ExtendedColorType::Rgba8)? + }; + frames.push(frame); + } + IcoEncoder::new(out).encode_images(&frames) +} + +/// The largest size with the same aspect ratio whose long edge is `long_edge` (each side at least 1). +pub(crate) fn fit_within(w: u32, h: u32, long_edge: u32) -> (u32, u32) { + let long = w.max(h); + if long <= long_edge { + return (w, h); + } + let scale = f64::from(long_edge) / f64::from(long); + let side = |v: u32| ((f64::from(v) * scale).round() as u32).clamp(1, long_edge); + if w >= h { (long_edge, side(h)) } else { (side(w), long_edge) } +} diff --git a/crates/raster/src/error.rs b/crates/raster/src/error.rs new file mode 100644 index 0000000..de6ae2a --- /dev/null +++ b/crates/raster/src/error.rs @@ -0,0 +1,85 @@ +use crate::Format; + +/// Every failure of this crate. `Display` is a plain-English sentence the Toolbox shows as is; +/// technical detail, when there is any, is kept in a field for the log. +#[derive(Debug, thiserror::Error)] +pub enum RasterError { + #[error("The file is empty.")] + Empty, + + #[error("This file is too large ({}; the limit is {}).", mb(*bytes), mb(*limit))] + InputTooLarge { bytes: u64, limit: u64 }, + + #[error("This file is not an image Pictor can open (PNG, JPG, WebP, BMP, GIF, TIFF, ICO or HEIC).")] + UnknownFormat, + + #[error("This image is too large ({width} × {height} pixels).")] + TooManyPixels { width: u64, height: u64 }, + + #[error("This image would need more memory than the {} allowed.", mb(*limit))] + TooMuchMemory { limit: u64 }, + + #[error("This {} file is damaged or incomplete.", format.name())] + Corrupt { format: Format, detail: String }, + + #[error("This {} file uses a feature Pictor cannot read.", format.name())] + UnsupportedFeature { format: Format, detail: String }, + + #[error("Pictor cannot save {} images. Choose PNG or JPG instead.", format.name())] + CannotWrite { format: Format }, + + #[error("This image could not be saved as {}.", format.name())] + Encode { format: Format, detail: String }, + + /// The HEIF/HEIC container codec or the HEVC decoder is not installed. Windows needs two Microsoft Store + /// extensions for iPhone photos: "HEIF Image Extensions" (free, https://apps.microsoft.com/detail/9PMMSR1CGPWG, + /// the container) and "HEVC Video Extensions" ($0.99, https://apps.microsoft.com/detail/9NMZLZ57R3T7, the + /// image data itself). `needs_heif` is true when the container codec is missing too. + #[error("{}", heif_message(*needs_heif))] + HeifCodecMissing { needs_heif: bool }, + + /// AVIF goes through the same HEIF container codec plus Microsoft's AV1 decoder. + #[error( + "This AVIF image needs Microsoft's \"AV1 Video Extension\" and \"HEIF Image Extensions\" from the \ + Microsoft Store. Install them, then try again." + )] + AvifCodecMissing, + + /// The Windows codec failed for another reason. + #[error("Windows could not open this photo (error {code:#010X}).")] + Os { code: u32, detail: String }, + + #[error("The crop area is outside the image.")] + InvalidCrop, + + #[error("The requested size is not valid.")] + InvalidSize, + + #[error("The image cannot be made smaller than {} even at the lowest quality and size.", size(*smallest_bytes))] + CannotReachTarget { smallest_bytes: u64 }, + + #[error("The target size must be larger than zero.")] + InvalidTarget, +} + +pub type Result = std::result::Result; + +fn heif_message(needs_heif: bool) -> &'static str { + if needs_heif { + "This photo needs two Microsoft codecs that Windows does not have yet. Install \ + \"HEIF Image Extensions\" (https://apps.microsoft.com/detail/9PMMSR1CGPWG) and \"HEVC Video Extensions\" \ + (https://apps.microsoft.com/detail/9NMZLZ57R3T7) from the Microsoft Store, then try again." + } else { + "This photo needs Microsoft's HEVC codec, which Windows does not have yet. Install \"HEVC Video \ + Extensions\" from the Microsoft Store (https://apps.microsoft.com/detail/9NMZLZ57R3T7), then try again." + } +} + +fn mb(bytes: u64) -> String { + let mib = bytes as f64 / (1024.0 * 1024.0); + if mib >= 10.0 { format!("{mib:.0} MB") } else { format!("{mib:.1} MB") } +} + +fn size(bytes: u64) -> String { + if bytes >= 1024 * 1024 { mb(bytes) } else { format!("{} kB", bytes.div_ceil(1024)) } +} diff --git a/crates/raster/src/format.rs b/crates/raster/src/format.rs new file mode 100644 index 0000000..0550ffe --- /dev/null +++ b/crates/raster/src/format.rs @@ -0,0 +1,151 @@ +use serde::{Deserialize, Serialize}; + +use crate::isobmff; + +/// The image formats the Toolbox knows. `Heif` and `Avif` share the ISO-BMFF/HEIF container and are read +/// only through the Windows codec; neither can be written. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Format { + Png, + Jpeg, + WebP, + Bmp, + Gif, + Tiff, + Ico, + /// HEIF/HEIC (brands heic, heix, hevc, heim, heis, hevm, hevs, mif1, msf1). + Heif, + /// AVIF (brands avif, avis): HEIF container with AV1 data. + Avif, +} + +impl Format { + /// Every format, in the order the Toolbox lists them. + pub const ALL: [Format; 9] = [ + Format::Png, + Format::Jpeg, + Format::WebP, + Format::Bmp, + Format::Gif, + Format::Tiff, + Format::Ico, + Format::Heif, + Format::Avif, + ]; + + /// Identify a format by its magic bytes only (never by the file name). + pub fn sniff(bytes: &[u8]) -> Option { + let starts = |sig: &[u8]| bytes.starts_with(sig); + if starts(b"\x89PNG\r\n\x1a\n") { + Some(Format::Png) + } else if starts(&[0xFF, 0xD8, 0xFF]) { + Some(Format::Jpeg) + } else if bytes.len() >= 12 && starts(b"RIFF") && &bytes[8..12] == b"WEBP" { + Some(Format::WebP) + } else if starts(b"GIF87a") || starts(b"GIF89a") { + Some(Format::Gif) + } else if starts(b"II*\0") || starts(b"MM\0*") || starts(b"II+\0") || starts(b"MM\0+") { + Some(Format::Tiff) + } else if bytes.len() >= 14 && starts(b"BM") { + Some(Format::Bmp) + } else if bytes.len() >= 6 && starts(&[0, 0, 1, 0]) && (bytes[4] != 0 || bytes[5] != 0) { + Some(Format::Ico) + } else { + match isobmff::brand(bytes)? { + isobmff::Brand::Heif => Some(Format::Heif), + isobmff::Brand::Avif => Some(Format::Avif), + } + } + } + + /// The usual file extension, without the dot. + pub fn extension(self) -> &'static str { + match self { + Format::Png => "png", + Format::Jpeg => "jpg", + Format::WebP => "webp", + Format::Bmp => "bmp", + Format::Gif => "gif", + Format::Tiff => "tif", + Format::Ico => "ico", + Format::Heif => "heic", + Format::Avif => "avif", + } + } + + /// The name shown to people. + pub fn name(self) -> &'static str { + match self { + Format::Png => "PNG", + Format::Jpeg => "JPG", + Format::WebP => "WebP", + Format::Bmp => "BMP", + Format::Gif => "GIF", + Format::Tiff => "TIFF", + Format::Ico => "ICO", + Format::Heif => "HEIC", + Format::Avif => "AVIF", + } + } + + pub fn mime_type(self) -> &'static str { + match self { + Format::Png => "image/png", + Format::Jpeg => "image/jpeg", + Format::WebP => "image/webp", + Format::Bmp => "image/bmp", + Format::Gif => "image/gif", + Format::Tiff => "image/tiff", + Format::Ico => "image/x-icon", + Format::Heif => "image/heic", + Format::Avif => "image/avif", + } + } + + /// Look a format up by an extension or a file name: `"jpg"`, `".JPEG"`, `"photo.heic"`. + pub fn from_name(name: &str) -> Option { + let ext = name.rsplit('.').next().unwrap_or(name).trim().to_ascii_lowercase(); + Some(match ext.as_str() { + "png" => Format::Png, + "jpg" | "jpeg" | "jpe" | "jfif" => Format::Jpeg, + "webp" => Format::WebP, + "bmp" | "dib" => Format::Bmp, + "gif" => Format::Gif, + "tif" | "tiff" => Format::Tiff, + "ico" => Format::Ico, + "heic" | "heif" | "heics" | "heifs" | "hif" => Format::Heif, + "avif" => Format::Avif, + _ => return None, + }) + } + + /// HEIF container (HEIC or AVIF): decoded by the OS codec. + pub fn is_heif_family(self) -> bool { + matches!(self, Format::Heif | Format::Avif) + } + + /// Whether `encode` can write this format. + pub fn can_encode(self) -> bool { + !self.is_heif_family() + } + + pub(crate) fn to_image(self) -> Option { + Some(match self { + Format::Png => image::ImageFormat::Png, + Format::Jpeg => image::ImageFormat::Jpeg, + Format::WebP => image::ImageFormat::WebP, + Format::Bmp => image::ImageFormat::Bmp, + Format::Gif => image::ImageFormat::Gif, + Format::Tiff => image::ImageFormat::Tiff, + Format::Ico => image::ImageFormat::Ico, + Format::Heif | Format::Avif => return None, + }) + } +} + +impl std::fmt::Display for Format { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.name()) + } +} diff --git a/crates/raster/src/isobmff.rs b/crates/raster/src/isobmff.rs new file mode 100644 index 0000000..d9d6444 --- /dev/null +++ b/crates/raster/src/isobmff.rs @@ -0,0 +1,208 @@ +//! Just enough ISO-BMFF (ISO/IEC 14496-12 / 23008-12) to sniff a HEIF brand and read the primary item's size +//! from its `ispe` property, so a HEIC bomb is refused before the OS codec sees it. Every read is bounds-checked; +//! the walk is iterative and visits a fixed set of box levels. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Brand { + Heif, + Avif, +} + +/// Brands that name HEVC-coded HEIF. +const HEVC_BRANDS: [&[u8; 4]; 8] = [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"hevm", b"hevs"]; +/// Codec-neutral HEIF structural brands (image and sequence). +const GENERIC_BRANDS: [&[u8; 4]; 2] = [b"mif1", b"msf1"]; +const AVIF_BRANDS: [&[u8; 4]; 2] = [b"avif", b"avis"]; + +/// The brand family named in a leading `ftyp` box. AVIF files also list `mif1`, so an AV1 brand wins over the +/// generic ones; when both an AV1 and an HEVC brand are listed, the major brand decides. +pub(crate) fn brand(bytes: &[u8]) -> Option { + let (kind, body, _) = next_box(bytes, 0)?; + if &kind != b"ftyp" || body.len() < 8 { + return None; + } + let major = &body[0..4]; + let brands = || std::iter::once(major).chain(body[8..].as_chunks::<4>().0.iter().map(|c| &c[..])); + let any = |set: &[&[u8; 4]]| brands().any(|b| set.iter().any(|s| &s[..] == b)); + let avif = any(&AVIF_BRANDS); + let hevc = any(&HEVC_BRANDS); + match (avif, hevc) { + (true, true) if AVIF_BRANDS.iter().any(|s| &s[..] == major) => Some(Brand::Avif), + (true, false) => Some(Brand::Avif), + (_, true) => Some(Brand::Heif), + (false, false) if any(&GENERIC_BRANDS) => Some(Brand::Heif), + _ => None, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Info { + pub width: u32, + pub height: u32, + pub has_alpha: bool, +} + +/// Size of the primary item (falls back to the largest `ispe` when the item associations are unreadable). +pub(crate) fn info(bytes: &[u8]) -> Option { + let meta = find_child(bytes, b"meta")?; + let meta = meta.get(4..)?; // full box + let primary = find_child(meta, b"pitm").and_then(|p| { + let version = *p.first()?; + if version == 0 { be16(p, 4).map(u32::from) } else { be32(p, 4) } + }); + let iprp = find_child(meta, b"iprp")?; + let ipco = find_child(iprp, b"ipco")?; + + let mut props: Vec<([u8; 4], &[u8])> = Vec::new(); + let mut pos = 0; + while let Some((kind, body, next)) = next_box(ipco, pos) { + if props.len() >= 4096 { + break; + } + props.push((kind, body)); + pos = next; + } + let ispe_of = |body: &[u8]| -> Option<(u32, u32)> { Some((be32(body, 4)?, be32(body, 8)?)) }; + let has_alpha = props.iter().any(|(kind, body)| { + &kind[..] == b"auxC" && { + let urn = body.get(4..).unwrap_or(&[]); + let urn = &urn[..urn.iter().position(|&b| b == 0).unwrap_or(urn.len())]; + urn.ends_with(b"auxiliary:alpha") || urn == b"urn:mpeg:hevc:2015:auxid:1" + } + }); + + let from_primary = primary.and_then(|item| { + let ipma = find_child(iprp, b"ipma")?; + primary_props(ipma, item)? + .into_iter() + .filter_map(|index| props.get(index.checked_sub(1)?)) + .find(|(kind, _)| &kind[..] == b"ispe") + .and_then(|(_, body)| ispe_of(body)) + }); + let (width, height) = from_primary.or_else(|| { + props + .iter() + .filter(|(kind, _)| &kind[..] == b"ispe") + .filter_map(|(_, body)| ispe_of(body)) + .max_by_key(|(w, h)| u64::from(*w) * u64::from(*h)) + })?; + Some(Info { width, height, has_alpha }) +} + +/// Property indices (1-based into `ipco`) associated with `item` in an `ipma` box. +fn primary_props(ipma: &[u8], item: u32) -> Option> { + let version = *ipma.first()?; + let flags = be32(ipma, 0)? & 0x00FF_FFFF; + let count = be32(ipma, 4)?; + let mut pos = 8usize; + for _ in 0..count.min(1 << 20) { + let id = if version < 1 { + let v = u32::from(be16(ipma, pos)?); + pos += 2; + v + } else { + let v = be32(ipma, pos)?; + pos += 4; + v + }; + let n = usize::from(*ipma.get(pos)?); + pos += 1; + let mut indices = Vec::with_capacity(n); + for _ in 0..n { + if flags & 1 != 0 { + indices.push(usize::from(be16(ipma, pos)? & 0x7FFF)); + pos += 2; + } else { + indices.push(usize::from(*ipma.get(pos)? & 0x7F)); + pos += 1; + } + } + if id == item { + return Some(indices); + } + } + None +} + +fn find_child<'a>(data: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> { + let mut pos = 0; + let mut guard = 0; + while let Some((kind, body, next)) = next_box(data, pos) { + if &kind == want { + return Some(body); + } + guard += 1; + if guard > 4096 { + return None; + } + pos = next; + } + None +} + +/// The box starting at `pos`: (type, body, offset of the next box). +fn next_box(data: &[u8], pos: usize) -> Option<([u8; 4], &[u8], usize)> { + let size32 = be32(data, pos)?; + let kind: [u8; 4] = data.get(pos + 4..pos + 8)?.try_into().ok()?; + let (header, size) = match size32 { + 0 => (8usize, data.len().checked_sub(pos)?), + 1 => (16, usize::try_from(be64(data, pos + 8)?).ok()?), + n => (8, usize::try_from(n).ok()?), + }; + if size < header { + return None; + } + let end = pos.checked_add(size)?; + let body = data.get(pos + header..end)?; + Some((kind, body, end)) +} + +fn be16(d: &[u8], at: usize) -> Option { + Some(u16::from_be_bytes(d.get(at..at.checked_add(2)?)?.try_into().ok()?)) +} + +fn be32(d: &[u8], at: usize) -> Option { + Some(u32::from_be_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?)) +} + +fn be64(d: &[u8], at: usize) -> Option { + Some(u64::from_be_bytes(d.get(at..at.checked_add(8)?)?.try_into().ok()?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ftyp(major: &[u8; 4], compat: &[&[u8; 4]]) -> Vec { + let mut body = major.to_vec(); + body.extend_from_slice(&[0; 4]); + for c in compat { + body.extend_from_slice(&c[..]); + } + let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec(); + out.extend_from_slice(b"ftyp"); + out.extend_from_slice(&body); + out + } + + #[test] + fn brands() { + assert_eq!(brand(&ftyp(b"heic", &[b"mif1", b"heic"])), Some(Brand::Heif)); + assert_eq!(brand(&ftyp(b"mif1", &[b"heic"])), Some(Brand::Heif)); + assert_eq!(brand(&ftyp(b"msf1", &[])), Some(Brand::Heif)); + assert_eq!(brand(&ftyp(b"avif", &[b"mif1", b"miaf"])), Some(Brand::Avif)); + assert_eq!(brand(&ftyp(b"mif1", &[b"avif"])), Some(Brand::Avif)); + assert_eq!(brand(&ftyp(b"isom", &[b"mp41"])), None, "an MP4 is not an image"); + assert_eq!(brand(b"\0\0\0\x08ftyp"), None); + assert_eq!(brand(b"\xff\xff\xff\xffftypheic"), None); + } + + #[test] + fn hostile_box_sizes() { + // size 1 with a giant 64-bit size, size smaller than the header, truncated header. + assert!(next_box(b"\0\0\0\x01meta\xff\xff\xff\xff\xff\xff\xff\xff", 0).is_none()); + assert!(next_box(b"\0\0\0\x04meta", 0).is_none()); + assert!(next_box(b"\0\0\0", 0).is_none()); + assert!(info(b"\0\0\0\x0cmeta\0\0\0\0").is_none()); + } +} diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs new file mode 100644 index 0000000..fbc52fb --- /dev/null +++ b/crates/raster/src/lib.rs @@ -0,0 +1,76 @@ +//! pictor-raster: the image side of Pictor's Toolbox. +//! +//! Decode with caps ([`probe`], [`decode`]), encode ([`encode`]), [`crop`], [`rotate`], [`resize`], batch +//! presets ([`apply_preset`]) and "compress to under N MB" ([`compress_to`]). Formats: PNG, JPG, WebP, BMP, +//! GIF, TIFF and ICO both ways through the `image` crate; HEIC/HEIF (and AVIF) in only, through the Windows +//! Imaging Component and the codecs Microsoft ships in the Store (see [`heif_support`]). No HEVC code is bundled. +//! +//! Every input is treated as hostile: sizes are read from headers and checked against [`Limits`] before any +//! pixel buffer exists, third-party decoder panics are caught, and every error is a [`RasterError`] whose +//! `Display` is a plain-English sentence. + +mod decode; +mod encode; +mod error; +mod format; +mod isobmff; +mod ops; +mod preset; +#[cfg(windows)] +mod wic; + +pub use decode::{Probe, decode, probe}; +pub use encode::{EncodeOptions, encode}; +pub use error::{RasterError, Result}; +pub use format::Format; +pub use image::DynamicImage; +pub use ops::{Fit, Rect, Rotation, crop, resize, rotate}; +pub use preset::{Compressed, Preset, apply_preset, compress_to, has_transparency}; + +use serde::{Deserialize, Serialize}; + +/// Caps applied to every decode. The worker process adds its own memory and time caps on top. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Limits { + /// Largest width × height accepted (default 128 million: a 16000 × 8000 panorama). + pub max_pixels: u64, + /// Largest input file in bytes (default 512 MiB). + pub max_input_bytes: u64, + /// Largest decoded buffer, and the budget handed to the decoders (default 1 GiB). + pub max_alloc: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_pixels: 128_000_000, max_input_bytes: 512 * 1024 * 1024, max_alloc: 1024 * 1024 * 1024 } + } +} + +/// Whether this machine can decode HEIC photos. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum HeifSupport { + /// The HEIF container codec and an HEVC decoder are installed. + Ready, + /// "HEIF Image Extensions" is installed, "HEVC Video Extensions" is not. + NeedsHevc, + /// An HEVC decoder exists but "HEIF Image Extensions" is missing. + NeedsHeif, + /// Neither is installed. + NeedsHeifAndHevc, + /// Not Windows: HEIC is never decoded here. + Unavailable, +} + +/// Probe the OS codecs without a file: the WIC HEIF decoder is instantiated by its container GUID, and +/// Media Foundation is asked (`MFTEnumEx`) for a decoder that takes HEVC video. Never fails. +pub fn heif_support() -> HeifSupport { + #[cfg(windows)] + { + wic::heif_support() + } + #[cfg(not(windows))] + { + HeifSupport::Unavailable + } +} diff --git a/crates/raster/src/ops.rs b/crates/raster/src/ops.rs new file mode 100644 index 0000000..e28a77a --- /dev/null +++ b/crates/raster/src/ops.rs @@ -0,0 +1,106 @@ +use image::imageops::FilterType; +use image::{DynamicImage, GenericImageView}; +use serde::{Deserialize, Serialize}; + +use crate::Limits; +use crate::encode::fit_within; +use crate::error::{RasterError, Result}; + +/// A crop rectangle in pixels, origin at the top left. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub width: u32, + pub height: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Rotation { + /// 90° clockwise. + Cw90, + /// 90° counter-clockwise. + Ccw90, + R180, + /// Mirror left-right. + FlipH, + /// Mirror top-bottom. + FlipV, +} + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub enum Fit { + /// Shrink so the longer side is at most this many pixels; never enlarges. + LongEdge(u32), + /// Exactly this size (aspect ratio not kept; may enlarge, within `Limits`). + Exact(u32, u32), + /// Scale both sides by this percentage (100 = unchanged); each side is at least 1 pixel. + Percent(f32), +} + +/// Cut out `rect`; it must lie fully inside the image and be at least 1 × 1. +pub fn crop(img: &DynamicImage, rect: Rect) -> Result { + let (w, h) = img.dimensions(); + let right = rect.x.checked_add(rect.width).ok_or(RasterError::InvalidCrop)?; + let bottom = rect.y.checked_add(rect.height).ok_or(RasterError::InvalidCrop)?; + if rect.width == 0 || rect.height == 0 || right > w || bottom > h { + return Err(RasterError::InvalidCrop); + } + Ok(img.crop_imm(rect.x, rect.y, rect.width, rect.height)) +} + +pub fn rotate(img: &DynamicImage, rotation: Rotation) -> DynamicImage { + match rotation { + Rotation::Cw90 => img.rotate90(), + Rotation::Ccw90 => img.rotate270(), + Rotation::R180 => img.rotate180(), + Rotation::FlipH => img.fliph(), + Rotation::FlipV => img.flipv(), + } +} + +/// Resize with Lanczos3 when shrinking and Catmull-Rom when enlarging. The result is checked against +/// `limits.max_pixels` and `limits.max_alloc` before any buffer is made. +pub fn resize(img: &DynamicImage, fit: Fit, limits: &Limits) -> Result { + let (w, h) = img.dimensions(); + let (nw, nh) = target_size(w, h, fit)?; + if (nw, nh) == (w, h) { + return Ok(img.clone()); + } + let pixels = u64::from(nw) * u64::from(nh); + if pixels > limits.max_pixels { + return Err(RasterError::TooManyPixels { width: nw.into(), height: nh.into() }); + } + // Output buffer plus `image`'s f32 intermediate (one pass, 4 channels). + let bpp = u64::from(img.color().bytes_per_pixel()); + let needed = + pixels.saturating_mul(bpp).saturating_add(u64::from(nw).saturating_mul(u64::from(h)).saturating_mul(16)); + if needed > limits.max_alloc { + return Err(RasterError::TooMuchMemory { limit: limits.max_alloc }); + } + Ok(resize_exact(img, nw, nh)) +} + +pub(crate) fn resize_exact(img: &DynamicImage, nw: u32, nh: u32) -> DynamicImage { + let (w, h) = img.dimensions(); + let filter = if nw <= w && nh <= h { FilterType::Lanczos3 } else { FilterType::CatmullRom }; + img.resize_exact(nw, nh, filter) +} + +fn target_size(w: u32, h: u32, fit: Fit) -> Result<(u32, u32)> { + match fit { + Fit::LongEdge(0) | Fit::Exact(0, _) | Fit::Exact(_, 0) => Err(RasterError::InvalidSize), + Fit::LongEdge(n) => Ok(fit_within(w, h, n)), + Fit::Exact(nw, nh) => Ok((nw, nh)), + Fit::Percent(p) => { + if !p.is_finite() || p <= 0.0 { + return Err(RasterError::InvalidSize); + } + let side = |v: u32| -> Result { + let s = (f64::from(v) * f64::from(p) / 100.0).round().max(1.0); + if s > f64::from(u32::MAX) { Err(RasterError::InvalidSize) } else { Ok(s as u32) } + }; + Ok((side(w)?, side(h)?)) + } + } +} diff --git a/crates/raster/src/preset.rs b/crates/raster/src/preset.rs new file mode 100644 index 0000000..a2131af --- /dev/null +++ b/crates/raster/src/preset.rs @@ -0,0 +1,168 @@ +use image::{DynamicImage, GenericImageView}; +use serde::{Deserialize, Serialize}; + +use crate::encode::{EncodeOptions, encode, fit_within}; +use crate::error::{RasterError, Result}; +use crate::ops::resize_exact; +use crate::{Format, Limits}; + +/// Batch-resize presets of the Toolbox. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Preset { + /// Long edge 1600 px, JPEG quality 80. + Email, + /// Long edge 2048 px, JPEG quality 85; an image with real transparency is written as PNG instead. + Web, + /// No resize, the source format (HEIC/AVIF, which cannot be written, become JPEG at the default quality). + Original, +} + +/// Apply a preset; returns the encoded bytes and the format they are in. Never enlarges. +pub fn apply_preset(img: &DynamicImage, src_format: Format, preset: Preset) -> Result<(Vec, Format)> { + let shrink = |long: u32| { + let (w, h) = img.dimensions(); + let (nw, nh) = fit_within(w, h, long); + if (nw, nh) == (w, h) { + std::borrow::Cow::Borrowed(img) + } else { + std::borrow::Cow::Owned(resize_exact(img, nw, nh)) + } + }; + let jpeg = |q: u8| EncodeOptions { jpeg_quality: q, ..EncodeOptions::default() }; + match preset { + Preset::Email => Ok((encode(&shrink(1600), Format::Jpeg, &jpeg(80))?, Format::Jpeg)), + Preset::Web => { + let small = shrink(2048); + if has_transparency(&small) { + Ok((encode(&small, Format::Png, &EncodeOptions::default())?, Format::Png)) + } else { + Ok((encode(&small, Format::Jpeg, &jpeg(85))?, Format::Jpeg)) + } + } + Preset::Original => { + let format = if src_format.can_encode() { src_format } else { Format::Jpeg }; + Ok((encode(img, format, &EncodeOptions::default())?, format)) + } + } +} + +/// An alpha channel with at least one pixel that is not fully opaque. +pub fn has_transparency(img: &DynamicImage) -> bool { + match img { + DynamicImage::ImageRgba8(b) => b.pixels().any(|p| p.0[3] < 255), + DynamicImage::ImageLumaA8(b) => b.pixels().any(|p| p.0[1] < 255), + DynamicImage::ImageRgba16(b) => b.pixels().any(|p| p.0[3] < u16::MAX), + DynamicImage::ImageLumaA16(b) => b.pixels().any(|p| p.0[1] < u16::MAX), + other if other.color().has_alpha() => other.to_rgba8().pixels().any(|p| p.0[3] < 255), + _ => false, + } +} + +/// Result of [`compress_to`]. +#[derive(Debug, Clone, PartialEq)] +pub struct Compressed { + pub bytes: Vec, + pub format: Format, + /// JPEG quality used; `None` for lossless formats. + pub quality: Option, + /// Output long edge divided by the input long edge (1.0 = full size). + pub scale: f32, + pub width: u32, + pub height: u32, +} + +const JPEG_MIN_Q: u8 = 40; +const JPEG_MAX_Q: u8 = 92; +const JPEG_SCALED_Q: u8 = 75; +const SCALE_STEP: f64 = 0.85; +const MIN_LONG_EDGE: u32 = 320; + +/// Make the encoded image fit in `target_bytes`. +/// +/// JPEG: the highest quality in 40..=92 that fits at full size (binary search). If even quality 40 is too +/// large, the image is shrunk in 0.85 steps at quality 75 until it fits; the last step that keeps the long edge +/// at 320 px or more is also tried at quality 40. PNG, WebP (lossless) and the other lossless formats: the +/// 0.85 shrink steps only. Below 320 px: [`RasterError::CannotReachTarget`] with the smallest size seen. +pub fn compress_to(img: &DynamicImage, format: Format, target_bytes: u64, limits: &Limits) -> Result { + if !format.can_encode() { + return Err(RasterError::CannotWrite { format }); + } + if target_bytes == 0 { + return Err(RasterError::InvalidTarget); + } + let (w, h) = img.dimensions(); + crate::decode::check_pixels(w, h, limits)?; + let jpeg = format == Format::Jpeg; + let run = |im: &DynamicImage, q: Option| -> Result> { + let options = EncodeOptions { jpeg_quality: q.unwrap_or(88), ..EncodeOptions::default() }; + encode(im, format, &options) + }; + let fits = |b: &[u8]| b.len() as u64 <= target_bytes; + let done = |bytes: Vec, quality: Option, nw: u32, nh: u32| Compressed { + bytes, + format, + quality, + scale: nw.max(nh) as f32 / w.max(h) as f32, + width: nw, + height: nh, + }; + let mut smallest = u64::MAX; + + if jpeg { + let at_max = run(img, Some(JPEG_MAX_Q))?; + if fits(&at_max) { + return Ok(done(at_max, Some(JPEG_MAX_Q), w, h)); + } + let at_min = run(img, Some(JPEG_MIN_Q))?; + smallest = smallest.min(at_min.len() as u64); + if fits(&at_min) { + // Invariant: `lo` fits, `hi` does not. + let (mut lo, mut hi, mut best) = (JPEG_MIN_Q, JPEG_MAX_Q, at_min); + while hi - lo > 1 { + let mid = lo + (hi - lo) / 2; + let b = run(img, Some(mid))?; + if fits(&b) { + lo = mid; + best = b; + } else { + hi = mid; + } + } + return Ok(done(best, Some(lo), w, h)); + } + } else { + let full = run(img, None)?; + smallest = smallest.min(full.len() as u64); + if fits(&full) { + return Ok(done(full, None, w, h)); + } + } + + let quality = jpeg.then_some(JPEG_SCALED_Q); + let long = w.max(h); + let mut scale = 1.0f64; + let mut last: Option = None; + loop { + scale *= SCALE_STEP; + let new_long = (f64::from(long) * scale).round() as u32; + if new_long < MIN_LONG_EDGE { + break; + } + let (nw, nh) = fit_within(w, h, new_long); + let small = resize_exact(img, nw, nh); + let b = run(&small, quality)?; + smallest = smallest.min(b.len() as u64); + if fits(&b) { + return Ok(done(b, quality, nw, nh)); + } + last = Some(small); + } + if jpeg && let Some(small) = last { + let b = run(&small, Some(JPEG_MIN_Q))?; + smallest = smallest.min(b.len() as u64); + if fits(&b) { + return Ok(done(b, Some(JPEG_MIN_Q), small.width(), small.height())); + } + } + Err(RasterError::CannotReachTarget { smallest_bytes: smallest }) +} diff --git a/crates/raster/src/wic.rs b/crates/raster/src/wic.rs new file mode 100644 index 0000000..402de0c --- /dev/null +++ b/crates/raster/src/wic.rs @@ -0,0 +1,347 @@ +//! HEIC/HEIF (and AVIF) decoding through the Windows Imaging Component. +//! +//! Windows has no HEIF support out of the box. Two Microsoft Store packages provide it: +//! - "HEIF Image Extensions" (free, ): the WIC decoder for the +//! HEIF container. Without it, WIC finds no decoder (`WINCODEC_ERR_COMPONENTNOTFOUND`, 0x88982F50). +//! - "HEVC Video Extensions" ($0.99, ): the Media Foundation +//! HEVC decoder the container codec calls for the pixels. Without it the container opens, the frame size is +//! readable, and the failure appears only when pixels are requested. +//! +//! AVIF uses the same container codec plus the "AV1 Video Extension". Pictor bundles none of these codecs. +//! +//! Every call initialises COM on the calling thread (apartment-threaded; an existing multithreaded apartment +//! is tolerated) and releases every COM object before uninitialising. + +use image::metadata::Orientation; +use image::{DynamicImage, RgbaImage}; +use windows::Win32::Foundation::RPC_E_CHANGED_MODE; +use windows::Win32::Graphics::Imaging::{ + CLSID_WICImagingFactory, GUID_ContainerFormatHeif, GUID_WICPixelFormat32bppRGBA, IWICBitmapFrameDecode, + IWICImagingFactory, WICBitmapDitherTypeNone, WICBitmapPaletteTypeCustom, WICDecodeMetadataCacheOnDemand, +}; +use windows::Win32::Media::MediaFoundation::{ + IMFActivate, MFMediaType_Video, MFT_CATEGORY_VIDEO_DECODER, MFT_ENUM_FLAG, MFT_ENUM_FLAG_ASYNCMFT, + MFT_ENUM_FLAG_HARDWARE, MFT_ENUM_FLAG_LOCALMFT, MFT_ENUM_FLAG_SORTANDFILTER, MFT_ENUM_FLAG_SYNCMFT, + MFT_FRIENDLY_NAME_Attribute, MFT_REGISTER_TYPE_INFO, MFTEnumEx, MFVideoFormat_AV1, MFVideoFormat_HEVC, +}; +use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear}; +use windows::Win32::System::Com::{ + CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, +}; +use windows::Win32::System::Variant::{VT_I2, VT_I4, VT_UI2, VT_UI4}; +use windows::core::{GUID, PWSTR, w}; + +use crate::error::{RasterError, Result}; +use crate::{Format, HeifSupport, Limits}; + +/// No decoder matched the stream (the HEIF container codec is not installed, or the bytes are not HEIF). +const WINCODEC_ERR_COMPONENTNOTFOUND: u32 = 0x8898_2F50; +/// The codec is registered but could not start (e.g. a half-installed Store package). +const WINCODEC_ERR_COMPONENTINITIALIZEFAILURE: u32 = 0x8898_200B; +/// HRESULTs that mean "these bytes are broken" rather than "a codec is missing". +const CORRUPT_CODES: [u32; 6] = [ + 0x8898_2F61, // WINCODEC_ERR_BADHEADER + 0x8898_2F60, // WINCODEC_ERR_BADIMAGE + 0x8898_2F62, // WINCODEC_ERR_BADMETADATAHEADER + 0x8898_2F8A, // WINCODEC_ERR_STREAMREAD + 0x8898_2F8E, // WINCODEC_ERR_STREAMNOTAVAILABLE + 0x8898_2F8F, // WINCODEC_ERR_UNEXPECTEDSIZE +]; + +/// Balances a successful `CoInitializeEx`. Declared before any COM object so it drops last. +struct Com { + uninit: bool, +} + +impl Com { + fn init() -> std::result::Result { + // SAFETY: plain FFI call with no pointers. + let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; + if hr == RPC_E_CHANGED_MODE { + // The thread already lives in a multithreaded apartment; WIC works there too. + Ok(Self { uninit: false }) + } else if hr.is_ok() { + // S_OK or S_FALSE (already initialised): both must be balanced. + Ok(Self { uninit: true }) + } else { + Err(hr.into()) + } + } +} + +impl Drop for Com { + fn drop(&mut self) { + if self.uninit { + // SAFETY: balances the successful CoInitializeEx above on this thread. + unsafe { CoUninitialize() }; + } + } +} + +fn factory() -> windows::core::Result { + // SAFETY: creating an in-process COM object; COM is initialised by the caller. + unsafe { CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER) } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Stage { + /// Matching a decoder to the stream: only the container codec is involved. + Open, + /// Frame access and pixel copy: the HEVC/AV1 decoder is involved. + Pixels, +} + +pub(crate) fn decode(bytes: &[u8], format: Format, limits: &Limits) -> Result { + let _com = Com::init().map_err(|e| os_error(&e))?; + decode_with_com(bytes, format, limits) +} + +fn decode_with_com(bytes: &[u8], format: Format, limits: &Limits) -> Result { + if u32::try_from(bytes.len()).is_err() { + return Err(RasterError::InputTooLarge { bytes: bytes.len() as u64, limit: u64::from(u32::MAX) }); + } + let factory = factory().map_err(|e| os_error(&e))?; + // SAFETY: the stream reads `bytes` in place; `bytes` outlives the stream, the decoder and every frame, + // which are all dropped at the end of this function. + let decoder = unsafe { + let stream = factory.CreateStream().map_err(|e| os_error(&e))?; + stream.InitializeFromMemory(bytes).map_err(|e| os_error(&e))?; + factory.CreateDecoderFromStream(&stream, std::ptr::null(), WICDecodeMetadataCacheOnDemand) + } + .map_err(|e| classify(&e, format, Stage::Open))?; + + // SAFETY: COM calls on live interfaces; out-pointers point at locals. + let frame = unsafe { decoder.GetFrame(0) }.map_err(|e| classify(&e, format, Stage::Pixels))?; + let (mut width, mut height) = (0u32, 0u32); + unsafe { frame.GetSize(&mut width, &mut height) }.map_err(|e| classify(&e, format, Stage::Pixels))?; + crate::decode::check_pixels(width, height, limits)?; + + let orientation = read_orientation(&frame); + let stride = width.checked_mul(4).ok_or(RasterError::TooMuchMemory { limit: limits.max_alloc })?; + let total = u64::from(stride) * u64::from(height); + let copies = if orientation.is_some_and(|o| o >= 5) { 2 } else { 1 }; + if total.saturating_mul(copies) > limits.max_alloc || total > u64::from(u32::MAX) { + return Err(RasterError::TooMuchMemory { limit: limits.max_alloc }); + } + let total = usize::try_from(total).map_err(|_| RasterError::TooMuchMemory { limit: limits.max_alloc })?; + + let converter = unsafe { factory.CreateFormatConverter() }.map_err(|e| os_error(&e))?; + unsafe { + converter.Initialize( + &frame, + &GUID_WICPixelFormat32bppRGBA, + WICBitmapDitherTypeNone, + None, + 0.0, + WICBitmapPaletteTypeCustom, + ) + } + .map_err(|e| classify(&e, format, Stage::Pixels))?; + + let mut pixels = Vec::new(); + pixels.try_reserve_exact(total).map_err(|_| RasterError::TooMuchMemory { limit: limits.max_alloc })?; + pixels.resize(total, 0); + // SAFETY: `pixels` holds exactly stride × height bytes. + unsafe { converter.CopyPixels(std::ptr::null(), stride, &mut pixels) } + .map_err(|e| classify(&e, format, Stage::Pixels))?; + + let rgba = RgbaImage::from_raw(width, height, pixels) + .ok_or_else(|| RasterError::Corrupt { format, detail: "pixel buffer size mismatch".into() })?; + let mut img = DynamicImage::ImageRgba8(rgba); + if let Some(o) = orientation.and_then(|o| Orientation::from_exif(o as u8)) { + img.apply_orientation(o); + } + Ok(img) +} + +/// EXIF-style orientation (1..=8) from the frame's metadata: the photo policy name first, then the HEIF +/// property (WICHeifOrientation), then the raw EXIF tag 274. Absent or unreadable: `None`. +fn read_orientation(frame: &IWICBitmapFrameDecode) -> Option { + // SAFETY: COM calls on a live frame; every PROPVARIANT is cleared after reading. + unsafe { + let reader = frame.GetMetadataQueryReader().ok()?; + for query in [w!("System.Photo.Orientation"), w!("/heifProps/{ushort=1}"), w!("/ifd/{ushort=274}")] { + let mut value = PROPVARIANT::default(); + if reader.GetMetadataByName(query, &mut value).is_err() { + continue; + } + let inner = &value.Anonymous.Anonymous; + let v = match inner.vt { + VT_UI2 => Some(inner.Anonymous.uiVal), + VT_I2 => u16::try_from(inner.Anonymous.iVal).ok(), + VT_UI4 => u16::try_from(inner.Anonymous.ulVal).ok(), + VT_I4 => u16::try_from(inner.Anonymous.lVal).ok(), + _ => None, + }; + let _ = PropVariantClear(&mut value); + if let Some(v) = v.filter(|v| (1..=8).contains(v)) { + return Some(v); + } + } + None + } +} + +fn os_error(e: &windows::core::Error) -> RasterError { + RasterError::Os { code: e.code().0 as u32, detail: e.message() } +} + +/// Map a WIC failure. A missing codec shows up as `COMPONENTNOTFOUND` / `COMPONENTINITIALIZEFAILURE` when +/// opening; a missing HEVC decoder shows up later, when pixels are requested, with an HRESULT that is not +/// specific to it (on Windows 10 22H2 with only the HEIF extension, `GetFrame` fails with +/// `WINCODEC_ERR_UNSUPPORTEDOPERATION`, 0x88982F81), so a pixel-stage failure is checked against the decoders +/// Media Foundation lists. The probes are only run when needed: instantiating the Store codec costs ~0.3 s. +fn classify(e: &windows::core::Error, format: Format, stage: Stage) -> RasterError { + let code = e.code().0 as u32; + let codec_present = || match format { + Format::Avif => has_video_decoder(MFVideoFormat_AV1), + _ => has_video_decoder(MFVideoFormat_HEVC), + }; + let missing = |needs_heif: bool| match format { + Format::Avif => RasterError::AvifCodecMissing, + _ => RasterError::HeifCodecMissing { needs_heif }, + }; + let not_found = code == WINCODEC_ERR_COMPONENTNOTFOUND || code == WINCODEC_ERR_COMPONENTINITIALIZEFAILURE; + match stage { + Stage::Open if not_found => { + if !heif_container_present() { + missing(true) + } else if format == Format::Avif && !codec_present() { + RasterError::AvifCodecMissing + } else { + RasterError::Corrupt { format, detail: format!("no WIC decoder accepts the stream ({code:#010X})") } + } + } + // The container decoder opened the stream, so only the video decoder can be missing. + Stage::Pixels if not_found || !codec_present() => missing(false), + _ if CORRUPT_CODES.contains(&code) => RasterError::Corrupt { format, detail: format!("{code:#010X}") }, + _ => RasterError::Os { code, detail: e.message() }, + } +} + +pub(crate) fn heif_support() -> HeifSupport { + let _com = Com::init().ok(); + match (heif_container_present(), has_video_decoder(MFVideoFormat_HEVC)) { + (true, true) => HeifSupport::Ready, + (true, false) => HeifSupport::NeedsHevc, + (false, true) => HeifSupport::NeedsHeif, + (false, false) => HeifSupport::NeedsHeifAndHevc, + } +} + +/// The WIC HEIF container decoder can be instantiated by its GUID (needs no file). +fn heif_container_present() -> bool { + let Ok(factory) = factory() else { return false }; + // SAFETY: COM call with a pointer to a constant GUID. + unsafe { factory.CreateDecoder(&GUID_ContainerFormatHeif, std::ptr::null()) }.is_ok() +} + +fn enum_flags() -> MFT_ENUM_FLAG { + MFT_ENUM_FLAG( + MFT_ENUM_FLAG_SYNCMFT.0 + | MFT_ENUM_FLAG_ASYNCMFT.0 + | MFT_ENUM_FLAG_HARDWARE.0 + | MFT_ENUM_FLAG_LOCALMFT.0 + | MFT_ENUM_FLAG_SORTANDFILTER.0, + ) +} + +/// Friendly names of the Media Foundation decoders that accept `subtype` video. +pub(crate) fn video_decoders(subtype: GUID) -> Vec { + let input = MFT_REGISTER_TYPE_INFO { guidMajorType: MFMediaType_Video, guidSubtype: subtype }; + let mut list: *mut Option = std::ptr::null_mut(); + let mut count = 0u32; + let mut names = Vec::new(); + // SAFETY: MFTEnumEx hands back a CoTaskMemAlloc'd array of `count` owned interface pointers; each is + // moved out (released on drop) and the array freed. + unsafe { + if MFTEnumEx(MFT_CATEGORY_VIDEO_DECODER, enum_flags(), Some(&input), None, &mut list, &mut count).is_err() { + return names; + } + if list.is_null() { + return names; + } + for i in 0..count as usize { + let activate = std::ptr::read(list.add(i)); + let name = activate.as_ref().and_then(|a| { + let mut s = PWSTR::null(); + let mut len = 0u32; + a.GetAllocatedString(&MFT_FRIENDLY_NAME_Attribute, &mut s, &mut len).ok()?; + let out = s.to_string().ok(); + CoTaskMemFree(Some(s.0 as *const _)); + out + }); + names.push(name.unwrap_or_else(|| "(unnamed)".into())); + } + CoTaskMemFree(Some(list as *const _)); + } + names +} + +fn has_video_decoder(subtype: GUID) -> bool { + !video_decoders(subtype).is_empty() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn list_codecs() { + let _com = Com::init().ok(); + eprintln!("\nHEIF container decoder: {}", heif_container_present()); + eprintln!("HEVC decoders: {:?}", video_decoders(MFVideoFormat_HEVC)); + eprintln!("AV1 decoders: {:?}", video_decoders(MFVideoFormat_AV1)); + } + + #[path = "../../../tests/common/mod.rs"] + mod common; + + /// Logs the raw HRESULT of each stage for the hand-built HEIC (what a missing HEVC codec produces). + #[test] + fn raw_hresults_of_minimal_heic() { + let bytes = common::minimal_heic(64, 64); + let _com = Com::init().unwrap(); + let factory = factory().unwrap(); + unsafe { + let stream = factory.CreateStream().unwrap(); + stream.InitializeFromMemory(&bytes).unwrap(); + let decoder = + match factory.CreateDecoderFromStream(&stream, std::ptr::null(), WICDecodeMetadataCacheOnDemand) { + Ok(d) => d, + Err(e) => return eprintln!("CreateDecoderFromStream: {:#010X} {}", e.code().0, e.message()), + }; + eprintln!("container: {:?}", decoder.GetContainerFormat()); + let frame = match decoder.GetFrame(0) { + Ok(f) => f, + Err(e) => return eprintln!("GetFrame: {:#010X} {}", e.code().0, e.message()), + }; + let (mut w, mut h) = (0, 0); + eprintln!("GetSize: {:?} {w}x{h}", frame.GetSize(&mut w, &mut h)); + let converter = factory.CreateFormatConverter().unwrap(); + let r = converter.Initialize( + &frame, + &GUID_WICPixelFormat32bppRGBA, + WICBitmapDitherTypeNone, + None, + 0.0, + WICBitmapPaletteTypeCustom, + ); + eprintln!( + "converter.Initialize: {:?}", + r.as_ref().map_err(|e| format!("{:#010X} {}", e.code().0, e.message())) + ); + let mut buf = vec![0u8; (w * h * 4) as usize]; + let r = converter.CopyPixels(std::ptr::null(), w * 4, &mut buf); + eprintln!("CopyPixels: {:?}", r.map_err(|e| format!("{:#010X} {}", e.code().0, e.message()))); + } + } + + #[test] + fn com_init_twice_is_balanced() { + let a = Com::init().unwrap(); + let b = Com::init().unwrap(); + drop(b); + drop(a); + } +} diff --git a/crates/raster/tests/common/mod.rs b/crates/raster/tests/common/mod.rs new file mode 100644 index 0000000..37f7e7f --- /dev/null +++ b/crates/raster/tests/common/mod.rs @@ -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, 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 { + 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 { + 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 { + 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, width: u16, height: u16) -> Vec { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 = { + 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 +} diff --git a/crates/raster/tests/heif.rs b/crates/raster/tests/heif.rs new file mode 100644 index 0000000..de426db --- /dev/null +++ b/crates/raster/tests/heif.rs @@ -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)); + } +} diff --git a/crates/raster/tests/hostile.rs b/crates/raster/tests/hostile.rs new file mode 100644 index 0000000..b9f19ad --- /dev/null +++ b/crates/raster/tests/hostile.rs @@ -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 = (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 = 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)> { + 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 { + 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 = (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()); +} diff --git a/crates/raster/tests/roundtrip.rs b/crates/raster/tests/roundtrip.rs new file mode 100644 index 0000000..6e2df71 --- /dev/null +++ b/crates/raster/tests/roundtrip.rs @@ -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)); +} diff --git a/crates/raster/tests/transform.rs b/crates/raster/tests/transform.rs new file mode 100644 index 0000000..d0bc8c2 --- /dev/null +++ b/crates/raster/tests/transform.rs @@ -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); +} diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index de4ca9d..b96f932 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -37,7 +37,7 @@ script exit 1, and the feature that needs it waits (the brief: "it never gets a | sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | | getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF | | flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) | -| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | +| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), MFTEnumEx (is an HEVC decoder installed?), Job Objects | | rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | | proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests |