[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,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<u32>,
|
||||
}
|
||||
|
||||
/// 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<Probe> {
|
||||
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<DynamicImage> {
|
||||
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<DynamicImage> {
|
||||
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<Format> {
|
||||
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<impl ImageDecoder + '_> {
|
||||
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<T>(format: Format, f: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
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<u32> {
|
||||
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<u32> {
|
||||
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<u32> {
|
||||
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<usize> {
|
||||
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<u32> {
|
||||
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)
|
||||
}
|
||||
@@ -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<Vec<u8>> {
|
||||
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<u8>) -> 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) }
|
||||
}
|
||||
@@ -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<T> = std::result::Result<T, RasterError>;
|
||||
|
||||
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)) }
|
||||
}
|
||||
@@ -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<Format> {
|
||||
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<Format> {
|
||||
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<image::ImageFormat> {
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -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<Brand> {
|
||||
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<Info> {
|
||||
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<Vec<usize>> {
|
||||
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<u16> {
|
||||
Some(u16::from_be_bytes(d.get(at..at.checked_add(2)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn be32(d: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn be64(d: &[u8], at: usize) -> Option<u64> {
|
||||
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<u8> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<DynamicImage> {
|
||||
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<DynamicImage> {
|
||||
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<u32> {
|
||||
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)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8>,
|
||||
pub format: Format,
|
||||
/// JPEG quality used; `None` for lossless formats.
|
||||
pub quality: Option<u8>,
|
||||
/// 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<Compressed> {
|
||||
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<u8>| -> Result<Vec<u8>> {
|
||||
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<u8>, quality: Option<u8>, 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<DynamicImage> = 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 })
|
||||
}
|
||||
@@ -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, <https://apps.microsoft.com/detail/9PMMSR1CGPWG>): the WIC decoder for the
|
||||
//! HEIF container. Without it, WIC finds no decoder (`WINCODEC_ERR_COMPONENTNOTFOUND`, 0x88982F50).
|
||||
//! - "HEVC Video Extensions" ($0.99, <https://apps.microsoft.com/detail/9NMZLZ57R3T7>): 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<Self, windows::core::Error> {
|
||||
// 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<IWICImagingFactory> {
|
||||
// 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<DynamicImage> {
|
||||
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<DynamicImage> {
|
||||
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<u16> {
|
||||
// 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<String> {
|
||||
let input = MFT_REGISTER_TYPE_INFO { guidMajorType: MFMediaType_Video, guidSubtype: subtype };
|
||||
let mut list: *mut Option<IMFActivate> = 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user