[raster] Toolbox: probe/decode with caps, convert, crop, rotate, resize, presets, compress to size, HEIC via WIC

This commit is contained in:
2026-11-16 13:30:42 +01:00
parent ede068f7c9
commit ce1e8785d9
16 changed files with 2394 additions and 1 deletions
+347
View File
@@ -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);
}
}