image-codecs: read JPEG XL through craft-jxl behind a jxl feature (#2135)

* image-codecs: read JPEG XL through craft-jxl behind a jxl feature

Format::Jxl reads when the non-default `jxl` feature is on (decode only, so the
encoder's jixel dependency is not built); without it JPEG XL is still detected and
opening one is an Unsupported error that says the build lacks it. Orientation is
applied by the decoder, so the Exif and XMP orientation become 1. ICC, Exif and XMP
come through; associated alpha is divided out; float files open as F32.

* image-codecs: skip JPEG XL in the one-pixel round trip

The encoder refuses images narrower than two pixels; with the jxl feature JPEG XL is a
read-and-write format, so the generic round trip reached it.
This commit is contained in:
Diego Chagas
2026-11-18 15:26:57 -05:00
committed by GitHub
parent f57bbca24f
commit 7ff0f967db
9 changed files with 147 additions and 7 deletions
Generated
+1
View File
@@ -2299,6 +2299,7 @@ dependencies = [
"craft-dds",
"craft-heif",
"craft-jpeg",
"craft-jxl",
"craft-media-testkit",
"craft-metadata",
"craft-tiff",
+1 -1
View File
@@ -126,7 +126,7 @@ craft-jpeg = { path = "crates/jpeg" }
craft-control-protocol = { path = "crates/control-protocol" }
craft-jsonrpc = { path = "crates/jsonrpc" }
craft-mcp = { path = "crates/mcp" }
craft-jxl = { path = "crates/jxl" }
craft-jxl = { path = "crates/jxl", default-features = false }
craft-kiwi = { path = "crates/kiwi" }
craft-keymap = { path = "crates/keymap" }
craft-assuan = { path = "crates/assuan" }
+4
View File
@@ -19,6 +19,9 @@ sgi = []
sunraster = []
avif = ["image/avif", "dep:ravif", "dep:rav1e", "dep:avif-serialize"]
heif = ["dep:craft-heif"]
# JPEG XL decode via craft-jxl (jxl-oxide, pure Rust). Without it JPEG XL files are still detected
# and opening one is a clear unsupported error; export needs no feature.
jxl = ["dep:craft-jxl"]
# AVIF decode: craft-video's clean-room pure-Rust AV1 decoder. Native targets only (on wasm32 a
# decoder panic aborts instead of becoming an error), so wasm32 builds leave AVIF unreadable.
avif-decode = ["dep:craft-video", "craft-video/av1-decode"]
@@ -43,6 +46,7 @@ craft-metadata = { workspace = true }
craft-tiff = { workspace = true }
zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] }
craft-heif = { workspace = true, optional = true }
craft-jxl = { workspace = true, optional = true, features = ["decode"] }
ravif = { version = "0.13", default-features = false, optional = true }
rav1e = { version = "0.8", default-features = false, optional = true }
avif-serialize = { version = "0.8", optional = true }
+75
View File
@@ -150,6 +150,81 @@ pub(crate) fn encode(image: &Image, plan: Plan) -> Result<Vec<u8>, CodecError> {
.unwrap_or_else(|_| Err(CodecError::encode(F, "the JPEG XL encoder failed")))
}
/// The reason given when this build has no JPEG XL decoder.
#[cfg(not(feature = "jxl"))]
pub(crate) const NOT_IN_BUILD: &str = "JPEG XL support isn't included in this build";
#[cfg(not(feature = "jxl"))]
pub(crate) fn decode(_bytes: &[u8], _limits: &crate::options::Limits) -> Result<Image, CodecError> {
Err(CodecError::unsupported(F, NOT_IN_BUILD))
}
#[cfg(feature = "jxl")]
fn decode_err(e: craft_jxl::Error) -> CodecError {
use craft_jxl::Error as E;
match e {
E::Malformed(what) | E::Encode(what) => CodecError::malformed(F, what),
E::LimitExceeded(what) => CodecError::LimitExceeded(what),
E::PixelLimitExceeded { width, height, max_pixels } => {
CodecError::LimitExceeded(format!("{width}×{height} pixels exceed max_pixels {max_pixels}"))
}
E::InvalidImage(what) => CodecError::InvalidImage(what),
E::Unsupported(what) => CodecError::unsupported(F, what),
}
}
/// Decodes the first frame. The codestream's orientation is already applied to the pixels, so the
/// Exif and XMP orientation are rewritten to 1 (the same promise as HEIF without `keep_orientation`).
#[cfg(feature = "jxl")]
pub(crate) fn decode(bytes: &[u8], limits: &crate::options::Limits) -> Result<Image, CodecError> {
let options = craft_jxl::DecodeLimits { max_pixels: limits.max_pixels, max_tracked_bytes: Some(limits.max_alloc), max_input_bytes: usize::MAX };
let decoded = craft_jxl::decode(bytes, options).map_err(decode_err)?;
let layout = match decoded.layout {
craft_jxl::Layout::Gray => ChannelLayout::Gray,
craft_jxl::Layout::GrayAlpha => ChannelLayout::GrayA,
craft_jxl::Layout::Rgb => ChannelLayout::Rgb,
craft_jxl::Layout::Rgba => ChannelLayout::Rgba,
};
let sample = match (decoded.float_samples, decoded.bit_depth) {
(true, _) => SampleType::F32,
(false, 0..=8) => SampleType::U8,
(false, _) => SampleType::U16,
};
limits.check(decoded.width, decoded.height, layout, sample)?;
let mut pixels = decoded.pixels;
if decoded.pixels_premultiplied {
unpremultiply(&mut pixels, layout);
}
let mut image = Image::from_normalized(decoded.width, decoded.height, layout, sample, &pixels)?;
image.icc = Some(decoded.rendered_icc).filter(|icc| !icc.is_empty()).or(decoded.metadata.icc);
if image.icc.is_none() {
image.cicp = decoded.rendered_cicp.map(|[primaries, transfer, matrix, range]| crate::cicp::Cicp {
primaries: u16::from(primaries),
transfer: u16::from(transfer),
matrix: u16::from(matrix),
full_range: range != 0,
});
}
image.meta.exif = decoded.metadata.exif.map(|e| crate::orientation::upright_exif(&e).into_owned());
// An XMP packet is UTF-8 text; bytes that are not are dropped rather than guessed at.
image.meta.xmp = decoded.metadata.xmp.and_then(|x| String::from_utf8(x).ok()).map(|x| crate::orientation::upright_xmp(&x).into_owned());
Ok(image)
}
/// Divides colour by alpha where alpha is not zero (JPEG XL can keep colour associated with alpha).
#[cfg(feature = "jxl")]
fn unpremultiply(pixels: &mut [f32], layout: ChannelLayout) {
if !layout.has_alpha() {
return;
}
for px in pixels.chunks_exact_mut(layout.channels()) {
let Some((alpha, colour)) = px.split_last_mut().map(|(a, c)| (*a, c)) else { continue };
if alpha > 0.0 {
colour.iter_mut().for_each(|c| *c /= alpha);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
+7 -2
View File
@@ -101,7 +101,12 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[
`avif-decode` feature, native targets only (on wasm32 a decoder panic would abort). A build \
with only one of them reads or writes AVIF, not both.",
),
(Format::Jxl, "Lossless JPEG XL export uses the pure-Rust zune-jpegxl encoder; JPEG XL reading is tracked separately and is not yet available."),
(
Format::Jxl,
"Lossless JPEG XL export uses the pure-Rust zune-jpegxl encoder in every build; JPEG XL decode \
(craft-jxl on jxl-oxide, pure Rust) is behind the non-default `jxl` feature, which official \
builds enable. Without the feature JPEG XL is written but not read.",
),
(
Format::Heif,
"HEIC decode uses heic-rs (pure Rust, in the optional craft-heif crate behind the \
@@ -330,7 +335,7 @@ pub fn caps(format: Format) -> FormatCaps {
// `text`: the DPX header fields only (see `fidelity_warnings_with`).
Format::Dpx => FormatCaps { depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb, L::Rgba], text: true, ..base },
// GrayA is widened to RGBA at the same depth; the 16-bit alpha header is corrected.
Format::Jxl => FormatCaps { read: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb, L::Rgba], ..base },
Format::Jxl => FormatCaps { read: cfg!(feature = "jxl"), depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb, L::Rgba], ..base },
Format::Cineon => FormatCaps { depths: &[S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base },
Format::Dicom => FormatCaps { read: true, write: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base },
Format::Iff => FormatCaps { depths: &[S::U8], layouts: &[L::Rgb, L::Rgba], alpha: true, ..base },
+1 -1
View File
@@ -140,7 +140,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res
Format::OpenExr => exr::decode(bytes, l),
Format::Heif => heif::decode(bytes, l, opts.keep_orientation),
Format::Jp2 => jp2::decode(bytes, l),
Format::Jxl => Err(CodecError::unsupported(format, "JPEG XL reading is not yet available; export is supported")),
Format::Jxl => jxl::decode(bytes, l),
#[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))]
Format::Avif => codecs::avif_decode::decode(bytes, l, opts.keep_orientation),
#[cfg(not(all(feature = "avif-decode", not(target_arch = "wasm32"))))]
@@ -318,6 +318,10 @@ fn webp_lossy_request_is_a_lossy_file() {
#[test]
fn one_pixel_images_roundtrip() {
for f in rw_formats() {
// The JPEG XL encoder refuses images narrower than two pixels (jxl_export.rs pins the error).
if f == Format::Jxl {
continue;
}
let img = synth(1, 1, ChannelLayout::Rgb, SampleType::U8, 1, 0.0);
let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap();
assert_eq!(back.dimensions(), (1, 1), "{f:?}");
+44
View File
@@ -0,0 +1,44 @@
//! JPEG XL decode through craft-jxl: lossless round trips, metadata, and hostile containers.
#![cfg(feature = "jxl")]
use craft_image_codecs::{ChannelLayout, CodecError, DecodeOptions, EncodeOptions, Format, Image, Limits, SampleType, decode, decode_with, encode};
fn rgba_8bit() -> Image {
let data = vec![0, 255, 17, 127, 20, 40, 80, 255, 255, 0, 2, 0, 10, 20, 30, 64, 0, 0, 0, 1, 90, 80, 70, 128];
Image::from_u8(3, 2, ChannelLayout::Rgba, data).unwrap()
}
#[test]
fn an_eight_bit_export_decodes_back_to_the_same_pixels() {
let input = rgba_8bit();
let bytes = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap();
let out = decode(&bytes).unwrap();
assert_eq!((out.width(), out.height(), out.layout(), out.sample_type()), (3, 2, ChannelLayout::Rgba, SampleType::U8));
assert_eq!(out.data(), input.data());
}
#[test]
fn a_sixteen_bit_gray_export_decodes_back_to_the_same_samples() {
let samples: Vec<u16> = (0..12).map(|i| i * 5461).collect();
let input = Image::from_u16(4, 3, ChannelLayout::Gray, &samples).unwrap();
let bytes = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap();
let out = decode(&bytes).unwrap();
assert_eq!((out.layout(), out.sample_type()), (ChannelLayout::Gray, SampleType::U16));
assert_eq!(out.data(), input.data());
}
#[test]
fn the_pixel_limit_is_an_error_not_an_allocation() {
let bytes = encode(&rgba_8bit(), Format::Jxl, &EncodeOptions::default()).unwrap();
let opts = DecodeOptions { limits: Limits { max_pixels: 4, ..Limits::default() }, ..DecodeOptions::default() };
let err = decode_with(&bytes, &opts);
assert!(matches!(err, Err(CodecError::LimitExceeded(_))), "{err:?}");
}
#[test]
fn every_prefix_of_a_file_is_an_error_or_an_image_never_a_panic() {
let bytes = encode(&rgba_8bit(), Format::Jxl, &EncodeOptions::default()).unwrap();
for end in 0..bytes.len() {
let _ = decode(&bytes[..end]);
}
}
+10 -3
View File
@@ -5,9 +5,10 @@ use craft_image_codecs::{
};
#[test]
fn jpeg_xl_is_export_only_and_detects_both_signatures() {
fn jpeg_xl_is_export_only_without_the_jxl_feature_and_detects_both_signatures() {
let c = caps(Format::Jxl);
assert!(c.write && !c.read);
assert!(c.write);
assert_eq!(c.read, cfg!(feature = "jxl"));
assert_eq!(c.depths, &[SampleType::U8, SampleType::U16]);
assert_eq!(c.layouts, &[ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba]);
assert!(c.alpha && !c.icc && !c.exif && !c.xmp && !c.dpi && !c.lossy);
@@ -17,7 +18,13 @@ fn jpeg_xl_is_export_only_and_detects_both_signatures() {
assert_eq!(detect(b"\0\0\0\x0cJXL \r\n\x87\n"), Some(Format::Jxl));
assert!(ASYMMETRIC_EXCEPTIONS.iter().any(|(format, reason)| *format == Format::Jxl && !reason.is_empty()));
let err = decode(&[0xff, 0x0a]);
assert!(matches!(err, Err(CodecError::Unsupported { format: Format::Jxl, .. })), "{err:?}");
#[cfg(not(feature = "jxl"))]
assert!(
matches!(&err, Err(CodecError::Unsupported { format: Format::Jxl, reason }) if reason.contains("isn't included in this build")),
"{err:?}"
);
#[cfg(feature = "jxl")]
assert!(matches!(err, Err(CodecError::Malformed { format: Format::Jxl, .. })), "{err:?}");
}
#[test]