From a05083e2f02ff88f0729f3ef61ee2e6eaef24d04 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:37:40 +0000 Subject: [PATCH] Expose original AVIF sample depth during decode --- crates/image-codecs/src/codecs/avif_decode.rs | 8 ++++++-- crates/image-codecs/src/lib.rs | 8 ++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/image-codecs/src/codecs/avif_decode.rs b/crates/image-codecs/src/codecs/avif_decode.rs index 302433661..4dd15fd7d 100644 --- a/crates/image-codecs/src/codecs/avif_decode.rs +++ b/crates/image-codecs/src/codecs/avif_decode.rs @@ -822,6 +822,10 @@ fn read_metadata(c: &Container) -> (Option>, Option) { /// Decodes the primary image. `keep_orientation` leaves the container's `clap`, `irot` and /// `imir` unapplied (the stored pixels), as for HEIF. pub(crate) fn decode(bytes: &[u8], limits: &Limits, keep_orientation: bool) -> Result { + decode_with_depth(bytes, limits, keep_orientation).map(|(image, _)| image) +} + +pub(crate) fn decode_with_depth(bytes: &[u8], limits: &Limits, keep_orientation: bool) -> Result<(Image, u8)> { let c = parse(bytes)?; let id = c.primary; let (w, h) = item_size(&c, id)?; @@ -860,9 +864,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits, keep_orientation: bool) -> R // PQ or HLG: linear light in 32-bit float, as for HEIF. if cicp.is_hdr() { limits.check(w, h, layout, SampleType::F32)?; - return crate::cicp::linearize(img, cicp); + return crate::cicp::linearize(img, cicp).map(|image| (image, bits)); } - Ok(img) + Ok((img, bits)) } #[cfg(test)] diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index a4480b2b8..86c4290b8 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -115,6 +115,14 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res finish_format(format, bytes, img, opts) } +/// Decode AVIF pixels and report their original AV1 bit depth (8, 10 or 12). +/// The returned image may use a wider sample type, particularly for linear HDR. +#[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))] +pub fn decode_avif_with_depth(bytes: &[u8], opts: &DecodeOptions) -> Result<(Image, u8), CodecError> { + let (image, depth) = codecs::avif_decode::decode_with_depth(bytes, &opts.limits, opts.keep_orientation)?; + Ok((finish_format(Format::Avif, bytes, image, opts)?, depth)) +} + /// What [`decode_as_with`] does with a PNG decoded in steps by [`PngDecodeRows`] (`img` is its /// output): the resolution from the metadata, the upright orientation and the final limit check, /// so the result equals [`decode_as_with`]'s on the same file.