diff --git a/Cargo.lock b/Cargo.lock index fde4ac01b8..19f41c5e57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4307,6 +4307,8 @@ dependencies = [ "tiff", "zune-core 0.5.3", "zune-jpeg 0.5.15", + "zune-jpegxl", + "jxl-oxide", ] [[package]] diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index a55dcf1213..e5c2413f0c 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -31,6 +31,8 @@ image-webp = "0.2" zune-jpeg = "0.5" zune-core = "0.5" jpeg-encoder = "0.6" +# Pure-Rust modular JPEG XL lossless encoder, pinned in Cargo.lock already (raw test fixtures). +zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } photocraft-heif = { path = "../heif", optional = true } # Orientation is applied a band of rows per task on native; wasm stays single-threaded. @@ -42,5 +44,9 @@ proptest.workspace = true # Oracle decoders for cross-checking in tests only. image = { workspace = true, features = ["png", "jpeg", "tiff"] } +# Independent decoder oracle for verifying lossless output; not linked into the app. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +jxl-oxide = { version = "=0.12.6", default-features = false, features = ["rayon"] } + [lints] workspace = true diff --git a/crates/codecs/src/codecs/jxl.rs b/crates/codecs/src/codecs/jxl.rs new file mode 100644 index 0000000000..169a1f30ef --- /dev/null +++ b/crates/codecs/src/codecs/jxl.rs @@ -0,0 +1,50 @@ +//! Pure-Rust lossless JPEG XL (Modular) writer. +//! +//! Currently writes a bare JPEG XL codestream. The encoder accepts 8- or 16-bit +//! gray, gray+alpha, RGB and RGBA samples, but does not write ICC/EXIF/XMP boxes. +//! The flat export pipeline converts tagged RGB documents to sRGB first. + +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use zune_core::{bit_depth::BitDepth, colorspace::ColorSpace, options::EncoderOptions as ZuneOptions}; +use zune_jpegxl::JxlSimpleEncoder; + +use crate::error::CodecError; +use crate::fidelity::Plan; +use crate::format::Format; +use crate::image::{ChannelLayout, Image, SampleType}; + +const F: Format = Format::Jxl; + +pub(crate) fn encode(image: &Image, plan: Plan) -> Result, CodecError> { + let image = image.converted(plan.layout, plan.sample); + let space = match image.layout() { + ChannelLayout::Gray => ColorSpace::Luma, + ChannelLayout::GrayA => ColorSpace::LumaA, + ChannelLayout::Rgb => ColorSpace::RGB, + ChannelLayout::Rgba => ColorSpace::RGBA, + _ => return Err(CodecError::unsupported(F, "JPEG XL export supports grayscale and RGB, with optional alpha")), + }; + let depth = match image.sample_type() { + SampleType::U8 => BitDepth::Eight, + SampleType::U16 => BitDepth::Sixteen, + _ => return Err(CodecError::unsupported(F, "JPEG XL lossless export supports 8 or 16-bit integer pixels")), + }; + let (width, height) = image.dimensions(); + let samples = (width as usize) + .checked_mul(height as usize) + .and_then(|n| n.checked_mul(image.layout().channels())) + .and_then(|n| n.checked_mul(image.sample_type().bytes())) + .ok_or_else(|| CodecError::encode(F, "image dimensions overflow the buffer size"))?; + if image.data().len() != samples { + return Err(CodecError::InvalidImage("incorrect JPEG XL pixel buffer length".into())); + } + // A panic in an external image encoder must not terminate the host application. + catch_unwind(AssertUnwindSafe(|| { + let options = ZuneOptions::new(width as usize, height as usize, space, depth); + let mut output = Vec::new(); + JxlSimpleEncoder::new(image.data(), options).encode(&mut output).map_err(|e| CodecError::encode(F, e.to_string()))?; + Ok(output) + })) + .unwrap_or_else(|_| Err(CodecError::encode(F, "the JPEG XL encoder failed"))) +} diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs/mod.rs index 3a6352ed82..ab0dabecd8 100644 --- a/crates/codecs/src/codecs/mod.rs +++ b/crates/codecs/src/codecs/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod exr; pub(crate) mod exr_cryptomatte; pub(crate) mod heif; pub(crate) mod jpeg; +pub(crate) mod jxl; pub(crate) mod png; pub(crate) mod pnm; pub(crate) mod tiff; diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs index c40e3ef167..ff367bf3e4 100644 --- a/crates/codecs/src/format.rs +++ b/crates/codecs/src/format.rs @@ -23,6 +23,8 @@ pub enum Format { Avif, /// HEIF/HEIC (HEVC-coded): read-only; see [`ASYMMETRIC_EXCEPTIONS`]. Heif, + /// Lossless JPEG XL: encode-only until the separate JPEG XL decoder lands. + Jxl, } /// What a format can hold **and** what this crate reads/writes for it. @@ -59,6 +61,11 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ "AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \ until a pure-Rust AV1 decoder is viable. Only enabled with the non-default `avif` feature.", ), + ( + Format::Jxl, + "Lossless JPEG XL encoding uses the pure-Rust zune-jpegxl encoder. Opening JXL files is + tracked separately; read support is not available in this build.", + ), ( Format::Heif, "HEIC decode uses heic-rs (pure Rust, in the optional photocraft-heif crate behind the \ @@ -76,7 +83,7 @@ const ALL_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::C impl Format { /// Every format known to the crate (enabled or not). - pub const ALL: [Format; 14] = [ + pub const ALL: [Format; 15] = [ Format::Png, Format::Jpeg, Format::Tiff, @@ -91,6 +98,7 @@ impl Format { Format::Hdr, Format::Avif, Format::Heif, + Format::Jxl, ]; pub fn caps(self) -> FormatCaps { @@ -119,6 +127,7 @@ impl Format { Format::Hdr => "Radiance HDR", Format::Avif => "AVIF", Format::Heif => "HEIF", + Format::Jxl => "JPEG XL", } } @@ -140,6 +149,7 @@ impl Format { Format::Hdr => &["hdr"], Format::Avif => &["avif"], Format::Heif => &["heic", "heif", "hif"], + Format::Jxl => &["jxl"], } } @@ -159,6 +169,7 @@ impl Format { Format::Hdr => "image/vnd.radiance", Format::Avif => "image/avif", Format::Heif => "image/heif", + Format::Jxl => "image/jxl", } } @@ -205,6 +216,9 @@ pub fn caps(format: Format) -> FormatCaps { Format::OpenExr => FormatCaps { depths: &[S::F16, S::F32], layouts: RGB_GRAY, ..base }, Format::Hdr => FormatCaps { depths: &[S::F32], layouts: &[L::Rgb], alpha: false, lossy: true, ..base }, Format::Avif => FormatCaps { read: false, write: cfg!(feature = "avif"), lossy: true, ..base }, + // The modular encoder is lossless for integer gray/RGB(A). Its bare codestream + // has no ICC/EXIF/XMP container boxes: callers must convert to sRGB. + Format::Jxl => FormatCaps { read: false, depths: &[S::U8, S::U16], layouts: RGB_GRAY, ..base }, Format::Heif => { FormatCaps { read: cfg!(feature = "heif"), write: false, depths: &[S::U8, S::U16], icc: true, exif: true, xmp: true, lossy: true, ..base } } @@ -221,6 +235,10 @@ pub fn detect(bytes: &[u8]) -> Option { if b.starts_with(&[0xFF, 0xD8, 0xFF]) { return Some(Format::Jpeg); } + // JPEG XL bare codestream and ISO/IEC 18181-2 container signature box. + if b.starts_with(&[0xFF, 0x0A]) || b.starts_with(b"\0\0\0\x0cJXL \r\n\x87\n") { + return Some(Format::Jxl); + } if b.starts_with(b"II*\0") || b.starts_with(b"MM\0*") || b.starts_with(b"II+\0") || b.starts_with(b"MM\0+") { return Some(Format::Tiff); } diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index cc8d0558b2..0e5a4f0554 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -38,7 +38,7 @@ pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp}; pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution}; pub use half::f16; -use crate::codecs::{exr, heif, jpeg, png, pnm, tiff, via_image, webp}; +use crate::codecs::{exr, heif, jpeg, jxl, png, pnm, tiff, via_image, webp}; /// Detect the format and decode with default [`Limits`]. pub fn decode(bytes: &[u8]) -> Result { @@ -71,6 +71,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Pnm => pnm::decode(bytes, l), Format::OpenExr => exr::decode(bytes, l), Format::Heif => heif::decode(bytes, l, opts.keep_orientation), + Format::Jxl => Err(CodecError::unsupported(format, "JPEG XL reading is not yet available; export is supported")), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::decode(format, bytes, l), }?; // Without a resolution of the format's own (PNG pHYs, TIFF tags, JPEG's metadata), the @@ -205,6 +206,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result pnm::encode(image, plan, opts), Format::OpenExr => exr::encode(image, plan, opts), Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")), + Format::Jxl => jxl::encode(image, plan), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::encode(format, image, plan, opts), } }