PhotoCraft: An open-source, photo editor written by scratch in pure Rust
DNG: JPEG XL compression 52546 (DNG 1.7, Samsung Expert RAW) (#2047)
ravelund510636f461b2
diff --git a/Cargo.lock b/Cargo.lockindex 11b88c8ae..ada883dfb 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -164,6 +164,21 @@ dependencies = ["equator",]+[[package]]+name = "alloc-no-stdlib"+version = "2.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"++[[package]]+name = "alloc-stdlib"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"+dependencies = [+ "alloc-no-stdlib",+]+[[package]]name = "allocator-api2"version = "0.2.21"@@ -670,6 +685,16 @@ dependencies = ["piper",]+[[package]]+name = "brotli-decompressor"+version = "5.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+]+[[package]]name = "built"version = "0.8.1"@@ -2737,6 +2762,184 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "jxl-bitstream"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"+dependencies = [+ "tracing",+]++[[package]]+name = "jxl-coding"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"+dependencies = [+ "jxl-bitstream",+ "tracing",+]++[[package]]+name = "jxl-color"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"+dependencies = [+ "jxl-bitstream",+ "jxl-coding",+ "jxl-grid",+ "jxl-image",+ "jxl-oxide-common",+ "jxl-threadpool",+ "tracing",+]++[[package]]+name = "jxl-frame"+version = "0.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"+dependencies = [+ "jxl-bitstream",+ "jxl-coding",+ "jxl-grid",+ "jxl-image",+ "jxl-modular",+ "jxl-oxide-common",+ "jxl-threadpool",+ "jxl-vardct",+ "tracing",+]++[[package]]+name = "jxl-grid"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"+dependencies = [+ "tracing",+]++[[package]]+name = "jxl-image"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"+dependencies = [+ "jxl-bitstream",+ "jxl-grid",+ "jxl-oxide-common",+ "tracing",+]++[[package]]+name = "jxl-jbr"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"+dependencies = [+ "brotli-decompressor",+ "jxl-bitstream",+ "jxl-frame",+ "jxl-grid",+ "jxl-image",+ "jxl-modular",+ "jxl-oxide-common",+ "jxl-threadpool",+ "jxl-vardct",+ "tracing",+]++[[package]]+name = "jxl-modular"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"+dependencies = [+ "jxl-bitstream",+ "jxl-coding",+ "jxl-grid",+ "jxl-oxide-common",+ "jxl-threadpool",+ "tracing",+]++[[package]]+name = "jxl-oxide"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"+dependencies = [+ "brotli-decompressor",+ "jxl-bitstream",+ "jxl-color",+ "jxl-frame",+ "jxl-grid",+ "jxl-image",+ "jxl-jbr",+ "jxl-oxide-common",+ "jxl-render",+ "jxl-threadpool",+ "tracing",+]++[[package]]+name = "jxl-oxide-common"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"+dependencies = [+ "jxl-bitstream",+]++[[package]]+name = "jxl-render"+version = "0.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"+dependencies = [+ "bytemuck",+ "jxl-bitstream",+ "jxl-coding",+ "jxl-color",+ "jxl-frame",+ "jxl-grid",+ "jxl-image",+ "jxl-modular",+ "jxl-oxide-common",+ "jxl-threadpool",+ "jxl-vardct",+ "tracing",+]++[[package]]+name = "jxl-threadpool"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"+dependencies = [+ "rayon",+ "rayon-core",+ "tracing",+]++[[package]]+name = "jxl-vardct"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"+dependencies = [+ "jxl-bitstream",+ "jxl-coding",+ "jxl-grid",+ "jxl-modular",+ "jxl-oxide-common",+ "jxl-threadpool",+ "tracing",+]+[[package]]name = "keyboard-types"version = "0.8.3"@@ -4298,9 +4501,12 @@ name = "photocraft-raw"version = "0.5.0"dependencies = ["flate2",+ "jxl-oxide","photocraft-raw","png 0.18.1","rayon",+ "zune-core 0.5.3",+ "zune-jpegxl",][[package]]@@ -7488,6 +7694,15 @@ dependencies = ["zune-core 0.5.3",]+[[package]]+name = "zune-jpegxl"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"+dependencies = [+ "zune-core 0.5.3",+]+[[package]]name = "zvariant"version = "5.15.0"diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.tomlindex 608594c5b..eff61537f 100644--- a/crates/raw/Cargo.toml+++ b/crates/raw/Cargo.toml@@ -17,15 +17,22 @@ corpus = [][dependencies]# Adobe DNG compression 8: zlib (RFC 1950) with the TIFF predictor (pure-Rust backend).flate2 = { workspace = true }+# JPEG XL-compressed DNG (DNG 1.7, e.g. Samsung Expert RAW). Pure Rust, MIT OR Apache-2.0. Pinned+# exactly: it parses untrusted files; moving the pin is a reviewed change (re-run the raw fuzz target).+jxl-oxide = { version = "=0.12.6", default-features = false }# Parallel bands on native; wasm builds stay single-threaded.[target.'cfg(not(target_arch = "wasm32"))'.dependencies]rayon = { workspace = true }+jxl-oxide = { version = "=0.12.6", default-features = false, features = ["rayon"] }[dev-dependencies]photocraft-raw = { path = ".", features = ["testgen"] }# Writes sRGB PNG previews in the `rawinfo` example.png = "0.18"+# Lossless JPEG XL encoder for the JPEG XL DNG tests (tests only).+zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] }+zune-core = "0.5"[lints]workspace = truediff --git a/crates/raw/README.md b/crates/raw/README.mdindex dc9f6669d..c2afe3a38 100644--- a/crates/raw/README.md+++ b/crates/raw/README.md@@ -1,7 +1,8 @@# photocraft-rawA clean-room, pure-Rust camera raw decoder and developer. The crate is standalone (no workspace-dependencies), has no `unsafe`, does no I/O (`&[u8]` in), builds for `wasm32-unknown-unknown`+dependencies; its decoding dependencies are `flate2` for Deflate DNG and `jxl-oxide`, a pure-Rust+JPEG XL decoder, for DNG 1.7), has no `unsafe`, does no I/O (`&[u8]` in), builds for `wasm32-unknown-unknown`(sequential there, rayon-parallel on native) and never panics on hostile input: every offset isbounds-checked and sizes are checked against `Limits` before allocating.@@ -57,8 +58,8 @@ camera colour tables were copied.| Format | Status ||---|---|-| DNG | Uncompressed (8–16 bit, packed or not) and lossless JPEG; strips and tiles; CFA (Bayer) and LinearRaw; LinearizationTable, BlackLevel (+ repeat, DeltaH/V), WhiteLevel, ActiveArea, DefaultCrop, ColorMatrix1/2, CameraCalibration, ForwardMatrix, AnalogBalance, AsShotNeutral / AsShotWhiteXY, BaselineExposure, Orientation, OpcodeList2 GainMap (lens shading) |-| DNG (lossy JPEG, JPEG XL, floating point; opcodes other than GainMap) | Unsupported / not applied (reported) |+| DNG | Uncompressed (8–16 bit, packed or not), Deflate (compression 8, predictors 1 and 2), lossless JPEG and JPEG XL (DNG 1.7, e.g. Samsung Expert RAW; decoded by `jxl-oxide`); strips and tiles; CFA (Bayer) and LinearRaw; LinearizationTable, BlackLevel (+ repeat, DeltaH/V), WhiteLevel, ActiveArea, DefaultCrop, ColorMatrix1/2, CameraCalibration, ForwardMatrix, AnalogBalance, AsShotNeutral / AsShotWhiteXY, BaselineExposure, Orientation, OpcodeList2 GainMap (lens shading) |+| DNG (lossy JPEG, floating point; opcodes other than GainMap; ProfileGainTableMap) | Unsupported / not applied (reported) || CR2 | Lossless JPEG with slices, borders and as-shot white balance from the maker note, black measured on the masked border. CR2 has no CFA tag and the row phase varies by model, so it is measured from the data (the green diagonal), with a Canon model-ID table as the fallback (see `src/cr2.rs`) || CR2 sRAW / mRAW | Unsupported || NEF / NRW, ARW, PEF and other TIFF/EP raws | Uncompressed and lossless-JPEG (incl. Sony lossless ARW) CFA data |diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rsindex 0f2344ce3..0cf3bb75d 100644--- a/crates/raw/src/dng.rs+++ b/crates/raw/src/dng.rs@@ -206,6 +206,12 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {}}+ // DNG 1.6 ProfileGainTableMap: the local tone mapping that phones (Samsung Expert RAW) rely on+ // for their default look. Without it the rendering is darker in the shadows.+ if ifd0.has(tag::PROFILE_GAIN_TABLE_MAP) || raw.has(tag::PROFILE_GAIN_TABLE_MAP) {+ warnings.push("DNG ProfileGainTableMap (local tone mapping) is not applied".to_string());+ }+let max = ((1u32 << plane.bits) - 1) as f32;let linearization = raw.get(tag::LINEARIZATION_TABLE).map(|e| t.uints(e)).filter(|v| !v.is_empty() && v.len() <= 65536);let linearization: Option<Vec<u16>> = linearization.map(|v| v.into_iter().map(|x| x.min(65535) as u16).collect());diff --git a/crates/raw/src/jxl.rs b/crates/raw/src/jxl.rsnew file mode 100644index 000000000..3522ed5db--- /dev/null+++ b/crates/raw/src/jxl.rs@@ -0,0 +1,59 @@+//! JPEG XL-compressed DNG tiles and strips (Adobe DNG Specification 1.7, Compression 52546).+//!+//! Each strip or tile holds one JPEG XL codestream (bare or in the ISO/IEC 18181-2 container)+//! whose image is the segment's samples: one channel for CFA data, three for LinearRaw. Samsung+//! Expert RAW writes LinearRaw this way. Decoding is done by `jxl-oxide`, a pure-Rust decoder;+//! like heic-rs in `photocraft-heif`, every call into it runs under `catch_unwind` so a decoder+//! panic on a malformed file becomes [`RawError::Malformed`].++use jxl_oxide::{AllocTracker, JxlImage};++use crate::Limits;+use crate::error::{RawError, Result};++/// Decodes one segment into `w * h * samples` interleaved samples at `bits` per sample (the+/// TIFF BitsPerSample, which DNG requires the codestream's bit depth to match).+pub(crate) fn decode(src: &[u8], w: usize, h: usize, samples: usize, bits: u32, limits: &Limits) -> Result<Vec<u16>> {+ limits.check(w as u64, h as u64, samples as u64 * 2)?;+ // jxl-oxide decodes into f32/i32 planes: allow a few times the output size, and never more+ // than the caller's per-buffer limit.+ let budget = (w as u64).saturating_mul(h as u64).saturating_mul(samples as u64).saturating_mul(16).min(limits.max_alloc);+ let budget = usize::try_from(budget).unwrap_or(usize::MAX);+ guarded(|| {+ let image =+ JxlImage::builder().alloc_tracker(AllocTracker::with_limit(budget)).read(src).map_err(|e| RawError::malformed(format!("JPEG XL raw data: {e}")))?;+ let (jw, jh) = (image.width() as usize, image.height() as usize);+ if (jw, jh) != (w, h) {+ return Err(RawError::malformed(format!("JPEG XL raw tile is {jw}x{jh}, expected {w}x{h}")));+ }+ let render = image.render_frame(0).map_err(|e| RawError::malformed(format!("JPEG XL raw data: {e}")))?;+ let mut stream = render.stream_no_alpha();+ let channels = stream.channels() as usize;+ if channels != samples {+ return Err(RawError::unsupported(format!("JPEG XL raw tile with {channels} channels for {samples} samples per pixel")));+ }+ // Orientation is applied by the stream; DNG tiles are stored upright, so anything else+ // would not fit the tile grid.+ if (stream.width() as usize, stream.height() as usize) != (w, h) {+ return Err(RawError::unsupported("rotated JPEG XL raw tile"));+ }+ let n = w.checked_mul(h).and_then(|p| p.checked_mul(samples)).ok_or_else(|| RawError::malformed("JPEG XL raw tile is too large"))?;+ let mut out = vec![0u16; n];+ if stream.write_to_buffer(&mut out) != n {+ return Err(RawError::malformed("JPEG XL raw data is truncated"));+ }+ // 16-bit samples come back as stored; other depths are scaled to 0..=65535, so scale+ // them back to the TIFF's range (exact for lossless data: 65535 / (2^bits - 1) >= 1).+ if bits < 16 {+ let max = f64::from((1u32 << bits) - 1);+ for v in &mut out {+ *v = (f64::from(*v) * max / 65535.0).round() as u16;+ }+ }+ Ok(out)+ })+}++fn guarded<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(RawError::malformed("the JPEG XL decoder failed on this file")))+}diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rsindex f69a67c25..deffcc9f2 100644--- a/crates/raw/src/lib.rs+++ b/crates/raw/src/lib.rs@@ -23,8 +23,8 @@//! Bodies whose full profile is not measured yet can still carry a measured//! image area (the D800E, the ILCE-7).//!-//! Decoded today: DNG (uncompressed and lossless-JPEG, strips and tiles, CFA-//! and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or+//! Decoded today: DNG (uncompressed, lossless-JPEG and JPEG XL, strips and+//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or//! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed),//! Nikon compressed NEF (lossless and lossy), Sony compressed ARW (cRAW),//! Panasonic RW2 (RawFormat 5), uncompressed Olympus ORF and uncompressed@@ -45,6 +45,7 @@ mod demosaic;mod develop;mod dng;mod error;+mod jxl;mod ljpeg;mod nefc;mod opcodes;diff --git a/crates/raw/src/sensor.rs b/crates/raw/src/sensor.rsindex 9eae9c5b0..309512b53 100644--- a/crates/raw/src/sensor.rs+++ b/crates/raw/src/sensor.rs@@ -3,7 +3,7 @@use crate::color::ColorInfo;use crate::error::{RawError, Result};use crate::tiff::{Ifd, Tiff, tag};-use crate::{Limits, RawFormat, ljpeg, par};+use crate::{Limits, RawFormat, jxl, ljpeg, par};/// A rectangle in sensor-data pixels.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -189,7 +189,10 @@ pub(crate) enum JpegLayout {Quads,}-/// Reads the (uncompressed or lossless-JPEG) image of a raw IFD.+/// DNG 1.7 JPEG XL compression.+const JPEG_XL: u32 = 52546;++/// Reads the (uncompressed, lossless-JPEG or JPEG XL) image of a raw IFD.pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayout) -> Result<Plane> {let width = t.tag_uint(ifd, tag::IMAGE_WIDTH).ok_or_else(|| RawError::malformed("raw image has no width"))? as usize;let height = t.tag_uint(ifd, tag::IMAGE_LENGTH).ok_or_else(|| RawError::malformed("raw image has no height"))? as usize;@@ -209,9 +212,8 @@ pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayoureturn Err(RawError::unsupported("planar raw data"));}match compression {- 1 | 7 | 8 => {}+ 1 | 7 | 8 | JPEG_XL => {}34892 => return Err(RawError::unsupported("lossy-compressed DNG")),- 52546 => return Err(RawError::unsupported("JPEG XL-compressed DNG")),34713 => return Err(RawError::unsupported("Nikon compressed NEF")),32767 => return Err(RawError::unsupported("Sony compressed ARW")),65535 => return Err(RawError::unsupported("Pentax compressed PEF")),@@ -246,6 +248,13 @@ pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayoup => Err(RawError::malformed(format!("unknown predictor {p}"))),}}+ // A JPEG XL segment codes only the rows inside the image (strips) or the whole tile.+ JPEG_XL => {+ let coded_rows = if t.tag_uint(ifd, tag::TILE_WIDTH).is_some() { s.h } else { rows };+ let mut v = jxl::decode(src, s.w, coded_rows, samples, bits, limits)?;+ v.resize(s.w * s.h * samples, 0);+ Ok(v)+ }_ => {let need = s.w * rows * samples;let max = s.w.saturating_mul(s.h).saturating_mul(samples).saturating_mul(4);diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rsindex e3611d8ed..a372ee641 100644--- a/crates/raw/src/testgen.rs+++ b/crates/raw/src/testgen.rs@@ -375,6 +375,12 @@ pub enum DngStorage {Lj92Tiles { width: usize, height: usize },/// Lossless-JPEG strips of this many rows, 1 component.Lj92Strips { rows: usize },+ /// JPEG XL strips of this many rows (Compression 52546): one codestream per strip, taken from+ /// [`DngSpec::jxl_segments`] (the tests encode them; this crate has no JPEG XL encoder).+ JxlStrips { rows: usize },+ /// JPEG XL tiles of this size, one codestream per tile in row-major order from+ /// [`DngSpec::jxl_segments`].+ JxlTiles { width: usize, height: usize },}/// A synthetic DNG.@@ -411,6 +417,10 @@ pub struct DngSpec {pub baseline_exposure: Option<f64>,/// Raw OpcodeList2 bytes (see [`gain_map_opcode_list`]).pub opcode_list2: Option<Vec<u8>>,+ /// Encoded segments for [`DngStorage::JxlStrips`] / [`DngStorage::JxlTiles`].+ pub jxl_segments: Vec<Vec<u8>>,+ /// Raw ProfileGainTableMap bytes, written to IFD0 (contents are not interpreted).+ pub profile_gain_table_map: Option<Vec<u8>>,pub orientation: u16,pub make: String,pub model: String,@@ -444,6 +454,8 @@ impl DngSpec {baseline_exposure: None,orientation: 1,opcode_list2: None,+ jxl_segments: Vec::new(),+ profile_gain_table_map: None,make: "Photocraft".into(),model: "Synthetic".into(),}@@ -596,6 +608,23 @@ impl DngSpec {raw.push((324, Val::Blobs(offs)));raw.push((325, Val::Long(lens)));}+ DngStorage::JxlStrips { rows } => {+ let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect();+ let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect();+ raw.push((259, Val::Short(vec![52546])));+ raw.push((278, Val::Long(vec![rows as u32])));+ raw.push((273, Val::Blobs(offs)));+ raw.push((279, Val::Long(lens)));+ }+ DngStorage::JxlTiles { width: tw, height: th } => {+ let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect();+ let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect();+ raw.push((259, Val::Short(vec![52546])));+ raw.push((322, Val::Long(vec![tw as u32])));+ raw.push((323, Val::Long(vec![th as u32])));+ raw.push((324, Val::Blobs(offs)));+ raw.push((325, Val::Long(lens)));+ }}if let Some(a) = self.active_area {raw.push((50829, Val::Long(a.to_vec())));@@ -657,6 +686,9 @@ impl DngSpec {if let Some(b) = self.baseline_exposure {ifd0.push((50730, Val::SRational(vec![srat(b)])));}+ if let Some(m) = &self.profile_gain_table_map {+ ifd0.push((52525, Val::Undefined(m.clone())));+ }let i0 = t.ifd(ifd0);t.chain = vec![i0];t.build()diff --git a/crates/raw/src/tiff.rs b/crates/raw/src/tiff.rsindex e5cb396c6..17b9b8af7 100644--- a/crates/raw/src/tiff.rs+++ b/crates/raw/src/tiff.rs@@ -66,6 +66,7 @@ pub(crate) mod tag {pub const OPCODE_LIST_2: u16 = 51009;pub const OPCODE_LIST_3: u16 = 51022;pub const BASELINE_EXPOSURE_OFFSET: u16 = 51109;+ pub const PROFILE_GAIN_TABLE_MAP: u16 = 52525;// CR2 private tag in the raw IFD: slice count, slice width, last slice width.pub const CR2_SLICE: u16 = 50752;}diff --git a/crates/raw/tests/dng.rs b/crates/raw/tests/dng.rsindex 9bd2886ac..f0ce247f5 100644--- a/crates/raw/tests/dng.rs+++ b/crates/raw/tests/dng.rs@@ -450,3 +450,113 @@ fn deflate_8_bit_predictor_and_packed_12_bit() {bytes[at..at + old.len()].copy_from_slice(&new);assert_eq!(sensor(&bytes).data, data12, "12-bit packed");}++// ---------------------------------------------------------------- JPEG XL (DNG 1.7)++/// Losslessly encodes `w × h` samples (1 = grey, 3 = RGB) at 8 or 16 bits as a JPEG XL codestream.+fn jxl(samples: &[u16], w: usize, h: usize, channels: usize, bits: u16) -> Vec<u8> {+ use zune_core::{bit_depth::BitDepth, colorspace::ColorSpace, options::EncoderOptions};+ let (depth, bytes): (BitDepth, Vec<u8>) = match bits {+ 8 => (BitDepth::Eight, samples.iter().map(|&v| v as u8).collect()),+ _ => (BitDepth::Sixteen, samples.iter().flat_map(|v| v.to_ne_bytes()).collect()),+ };+ let space = if channels == 1 { ColorSpace::Luma } else { ColorSpace::RGB };+ let mut out = Vec::new();+ zune_jpegxl::JxlSimpleEncoder::new(&bytes, EncoderOptions::new(w, h, space, depth)).encode(&mut out).unwrap();+ out+}++/// `data` (`w × h × spp`) cut into `tw × th` tiles, edge tiles padded by repeating the last row / column.+fn tiles(data: &[u16], w: usize, h: usize, spp: usize, tw: usize, th: usize) -> Vec<Vec<u16>> {+ let mut out = Vec::new();+ for ty in (0..h).step_by(th) {+ for tx in (0..w).step_by(tw) {+ let mut t = Vec::with_capacity(tw * th * spp);+ for y in 0..th {+ for x in 0..tw {+ let at = ((ty + y).min(h - 1) * w + (tx + x).min(w - 1)) * spp;+ t.extend_from_slice(&data[at..at + spp]);+ }+ }+ out.push(t);+ }+ }+ out+}++#[test]+fn jpeg_xl_layouts_decode_exactly() {+ let (w, h) = (37, 23); // odd sizes: a short last strip and partial edge tiles+ for (name, spp, bits, tiled) in [+ ("LinearRaw 16-bit strips", 3, 16, false),+ ("LinearRaw 16-bit tiles", 3, 16, true),+ ("CFA 16-bit strips", 1, 16, false),+ ("CFA 16-bit tiles", 1, 16, true),+ ("LinearRaw 8-bit strips", 3, 8, false),+ ("CFA 8-bit tiles", 1, 8, true),+ ] {+ let data = noise(w * h * spp, bits);+ let mut spec = DngSpec::cfa(w, h, data.clone());+ spec.samples = spp;+ spec.bits = bits;+ spec.white = (1u32 << bits) - 1;+ if tiled {+ let (tw, th) = (16, 16);+ spec.storage = DngStorage::JxlTiles { width: tw, height: th };+ spec.jxl_segments = tiles(&data, w, h, spp, tw, th).iter().map(|t| jxl(t, tw, th, spp, bits)).collect();+ } else {+ let rows = 10;+ spec.storage = DngStorage::JxlStrips { rows };+ spec.jxl_segments =+ (0..h).step_by(rows).map(|y| (y, (y + rows).min(h) - y)).map(|(y, r)| jxl(&data[y * w * spp..(y + r) * w * spp], w, r, spp, bits)).collect();+ }+ let s = sensor(&spec.build());+ assert_eq!((s.width, s.height, s.samples), (w, h, spp), "{name}");+ assert_eq!(s.data, data, "{name}");+ }+}++#[test]+fn jpeg_xl_linear_raw_develops() {+ // A Samsung Expert RAW-like file: one 16-bit LinearRaw JPEG XL strip with a baseline exposure.+ let (w, h) = (24, 16);+ let data: Vec<u16> = scene(w, h).iter().flat_map(|p| p.map(|v| (v * 20000.0) as u16)).collect();+ let mut spec = DngSpec::cfa(w, h, data.clone());+ spec.samples = 3;+ spec.storage = DngStorage::JxlStrips { rows: h };+ spec.jxl_segments = vec![jxl(&data, w, h, 3, 16)];+ spec.baseline_exposure = Some(1.0);+ let b = spec.build();+ let d = develop(&b, &DevelopOptions::default()).unwrap();+ assert_eq!((d.width as usize, d.height as usize, d.rgb.len()), (w, h, w * h * 3));+ // Same pixels stored uncompressed develop identically.+ spec.storage = DngStorage::Strips { rows: h };+ assert_eq!(develop(&spec.build(), &DevelopOptions::default()).unwrap().rgb, d.rgb);+}++#[test]+fn jpeg_xl_mismatches_are_errors() {+ let (w, h) = (16, 8);+ let data = noise(w * h * 3, 16);+ let mut spec = DngSpec::cfa(w, h, data.clone());+ spec.samples = 3;+ spec.storage = DngStorage::JxlStrips { rows: h };+ // Codestream smaller than the strip.+ spec.jxl_segments = vec![jxl(&data[..w * 4 * 3], w, 4, 3, 16)];+ assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_))));+ // Grey codestream for RGB samples.+ spec.jxl_segments = vec![jxl(&data[..w * h], w, h, 1, 16)];+ assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Unsupported(_))));+ // Not a codestream at all.+ spec.jxl_segments = vec![vec![0xff, 0x0a, 1, 2, 3, 4, 5]];+ assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_))));+}++#[test]+fn profile_gain_table_map_is_reported() {+ let gain_table = |s: &Sensor| s.warnings.iter().any(|w| w.contains("ProfileGainTableMap"));+ let mut spec = DngSpec::cfa(8, 8, vec![500; 64]);+ assert!(!gain_table(&sensor(&spec.build())));+ spec.profile_gain_table_map = Some(vec![0; 64]);+ assert!(gain_table(&sensor(&spec.build())));+}diff --git a/crates/raw/tests/hostile.rs b/crates/raw/tests/hostile.rsindex 44bb3acdc..d932181d0 100644--- a/crates/raw/tests/hostile.rs+++ b/crates/raw/tests/hostile.rs@@ -4,6 +4,15 @@use photocraft_raw::testgen::{Cr2Spec, DngSpec, DngStorage, RafPacking, RafSpec, XTRANS, mosaic, mosaic_cfa, orf, rw2, scene, sony_craw, tiff_ep};use photocraft_raw::*;+/// Losslessly encodes 16-bit RGB as a JPEG XL codestream.+fn jxl_rgb16(rgb: &[u16], w: usize, h: usize) -> Vec<u8> {+ use zune_core::{bit_depth::BitDepth, colorspace::ColorSpace, options::EncoderOptions};+ let bytes: Vec<u8> = rgb.iter().flat_map(|v| v.to_ne_bytes()).collect();+ let mut out = Vec::new();+ zune_jpegxl::JxlSimpleEncoder::new(&bytes, EncoderOptions::new(w, h, ColorSpace::RGB, BitDepth::Sixteen)).encode(&mut out).unwrap();+ out+}+fn samples() -> Vec<Vec<u8>> {let (w, h) = (24, 12);let cfa = mosaic(&scene(w, h), w, [0, 1, 1, 2], 64, 4000);@@ -22,6 +31,14 @@ fn samples() -> Vec<Vec<u8>> {d.storage = DngStorage::Strips { rows: 5 };d.big_endian = true;out.push(d.build());+ // LinearRaw in one JPEG XL strip (DNG 1.7, as Samsung Expert RAW writes it).+ let rgb: Vec<u16> = scene(w, h).iter().flat_map(|p| p.map(|v| (v * 30000.0) as u16)).collect();+ let mut j = DngSpec::cfa(w, h, rgb.clone());+ j.samples = 3;+ j.storage = DngStorage::JxlStrips { rows: h };+ j.jxl_segments = vec![jxl_rgb16(&rgb, w, h)];+ j.profile_gain_table_map = Some(vec![0; 32]);+ out.push(j.build());let mut data = vec![600u16; 40 * 10];for (i, v) in data.iter_mut().enumerate() {*v = 600 + (i as u16 * 7) % 3000;