From e4dd081dd4d2173db33b06483ab35f67ce8939fb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 00:43:54 -0500 Subject: [PATCH] Use craft-gainmap from craft-libs for gain map metadata and arithmetic Use craft-gainmap from craft-libs for gain map metadata and arithmetic * Use craft-heif from craft-libs; remove crates/heif lightcraft-heif moved to craft-libs unchanged as craft-heif (storytold/craft-libs#784), so PhotoCraft can share it. The layer table, the heif CI step and the change triggers drop the local crate; a workspace file change (which a craft-heif rev bump is) still runs the heif step. * Pin craft-heif to the merge of storytold/craft-libs#794 * docs: the HEIF rows point at craft-heif, not the removed crates/heif * Use craft-gainmap from craft-libs for gain map metadata and arithmetic crates/codecs/src/gainmap.rs keeps the JPEG layout (encode_jpeg, read_jpeg, is_gain_map_jpeg) and re-exports GainMapMeta, GainImage, GainMapOptions, ISO_URN, compute and apply from craft-gainmap, which is this file's metadata and arithmetic moved to craft-libs (storytold/craft-libs#904). The tests of the moved code went with it. * craft-heif's Options has a chroma field at this rev: keep the libheif upsampling LightCraft had * raw: count the chunks a TIFF declares from its offsets table craft-tiff builds at most one chunk descriptor per byte of file (craft-libs#827), so a grid of tiles sharing one payload lists fewer chunks than the image declares. Compare the offsets table, which is the source of truth, so such a file reaches the byte-accounting check and is refused for the data it actually holds. --- Cargo.lock | 34 +- Cargo.toml | 7 +- apps/lightcraft-cli/Cargo.toml | 2 +- apps/lightcraft-web/Cargo.toml | 2 +- apps/lightcraft/Cargo.toml | 2 +- crates/codecs/Cargo.toml | 9 +- crates/codecs/README.md | 2 +- crates/codecs/src/gainmap.rs | 642 +---------------------------- crates/codecs/src/heif.rs | 18 +- crates/codecs/tests/it/heif.rs | 4 +- crates/engine/Cargo.toml | 2 +- crates/engine/src/tests/import.rs | 4 +- crates/heif/Cargo.toml | 26 -- crates/heif/README.md | 47 --- crates/heif/src/census.rs | 122 ------ crates/heif/src/lib.rs | 605 --------------------------- crates/heif/src/orient.rs | 178 -------- crates/heif/src/testdata.rs | 569 ------------------------- crates/heif/src/tests_synthetic.rs | 214 ---------- crates/heif/src/vui.rs | 567 ------------------------- crates/heif/src/ycc.rs | 352 ---------------- crates/meta/Cargo.toml | 2 +- crates/meta/src/heif.rs | 8 +- crates/raw/src/tiffraw.rs | 7 +- docs/file-format-parity.md | 4 +- docs/parity-checklist.md | 2 +- xtask/src/ci.rs | 5 +- xtask/src/ci_quick.rs | 4 +- xtask/src/layers.rs | 1 - 29 files changed, 75 insertions(+), 3366 deletions(-) delete mode 100644 crates/heif/Cargo.toml delete mode 100644 crates/heif/README.md delete mode 100644 crates/heif/src/census.rs delete mode 100644 crates/heif/src/lib.rs delete mode 100644 crates/heif/src/orient.rs delete mode 100644 crates/heif/src/testdata.rs delete mode 100644 crates/heif/src/tests_synthetic.rs delete mode 100644 crates/heif/src/vui.rs delete mode 100644 crates/heif/src/ycc.rs diff --git a/Cargo.lock b/Cargo.lock index 91917ef5b1..a715ac36cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1199,6 +1199,23 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +[[package]] +name = "craft-gainmap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-heif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" +dependencies = [ + "heic-rs", + "rayon", +] + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1225,7 +1242,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3b3104981bb3093904a12e44d6a3b41c6c4c39c8#3b3104981bb3093904a12e44d6a3b41c6c4c39c8" +source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" dependencies = [ "serde", "thiserror 2.0.21", @@ -3668,6 +3685,8 @@ version = "0.21.1" dependencies = [ "avif-serialize", "bytemuck", + "craft-gainmap", + "craft-heif", "dhat", "image", "image-webp", @@ -3677,7 +3696,6 @@ dependencies = [ "jxl-oxide", "lightcraft-color", "lightcraft-geom", - "lightcraft-heif", "lightcraft-raster", "lightcraft-testkit", "moxcms 0.9.1", @@ -3754,6 +3772,7 @@ dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "craft-heif", "craft-tiff", "crc32fast", "fs4", @@ -3771,7 +3790,6 @@ dependencies = [ "lightcraft-geocode", "lightcraft-geom", "lightcraft-gpu", - "lightcraft-heif", "lightcraft-lensdb", "lightcraft-merge", "lightcraft-meta", @@ -3863,14 +3881,6 @@ dependencies = [ "wgpu", ] -[[package]] -name = "lightcraft-heif" -version = "0.21.1" -dependencies = [ - "heic-rs", - "rayon", -] - [[package]] name = "lightcraft-inpaint" version = "0.21.1" @@ -3919,9 +3929,9 @@ name = "lightcraft-meta" version = "0.21.1" dependencies = [ "chrono", + "craft-heif", "craft-tiff", "lightcraft-geom", - "lightcraft-heif", "proptest", "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 6f52ff48b6..f7dd56589e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,8 @@ craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +# HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). +craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } lightcraft-denoise = { path = "crates/denoise", default-features = false } @@ -27,7 +29,7 @@ lightcraft-wincolor = { path = "crates/wincolor" } lightcraft-color = { path = "crates/color" } lightcraft-raster = { path = "crates/raster" } # TIFF/IFD: the shared reader and writer (moved from crates/tiff; craft-libs#783). -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "3b3104981bb3093904a12e44d6a3b41c6c4c39c8" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" } lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } lightcraft-meta = { path = "crates/meta" } @@ -45,7 +47,8 @@ lightcraft-engine = { path = "crates/engine" } lightcraft-ui-egui = { path = "crates/ui-egui" } lightcraft-mcp = { path = "crates/mcp" } lightcraft-fetch = { path = "crates/fetch" } -lightcraft-heif = { path = "crates/heif" } +# HEIC/HEIF: the shared decoder (moved from crates/heif; craft-libs#784). +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" } lightcraft-segment = { path = "crates/segment" } lightcraft-geocode = { path = "crates/geocode" } lightcraft-slideshow = { path = "crates/slideshow" } diff --git a/apps/lightcraft-cli/Cargo.toml b/apps/lightcraft-cli/Cargo.toml index e55d458b32..380bace5f2 100644 --- a/apps/lightcraft-cli/Cargo.toml +++ b/apps/lightcraft-cli/Cargo.toml @@ -37,6 +37,6 @@ rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"] # (open it in DHAT's viewer: allocation sites by bytes at the peak). Slows allocation-heavy work. dhat-heap = ["dep:dhat"] -# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose +# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose # it (HEVC patents); build with `--features heif` to include it. heif = ["lightcraft-codecs/heif"] diff --git a/apps/lightcraft-web/Cargo.toml b/apps/lightcraft-web/Cargo.toml index 62fb546991..8946efb048 100644 --- a/apps/lightcraft-web/Cargo.toml +++ b/apps/lightcraft-web/Cargo.toml @@ -77,7 +77,7 @@ web-sys = { workspace = true, features = [ ] } [features] -# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose +# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose # it (HEVC patents); build with `--features heif` to include it. On wasm32 panics abort, so # heic-rs's `catch_unwind` guard does not apply there. heif = ["lightcraft-codecs/heif"] diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index cf8aaf2e06..18024a32f6 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -13,7 +13,7 @@ workspace = true default = ["denoise"] denoise = ["lightcraft-engine/denoise"] rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"] -# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose +# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose # it (HEVC patents); build with `--features heif` to include it. heif = ["lightcraft-codecs/heif"] diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 589d285fae..019009d7c1 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -12,7 +12,8 @@ workspace = true lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } -lightcraft-heif = { workspace = true, optional = true } +craft-gainmap = { workspace = true } +craft-heif = { workspace = true, optional = true } serde = { workspace = true } bytemuck = { workspace = true } thiserror = { workspace = true } @@ -40,10 +41,10 @@ default = ["parallel", "jxl", "avif"] parallel = ["dep:rayon", "lightcraft-raster/parallel", "jpeg-decoder/rayon"] ## JPEG XL decode (jxl-oxide) and, on native targets, encode (jixel); both pure Rust. jxl = ["dep:jxl-oxide", "dep:jixel"] -# HEIC/HEIF decode via the optional lightcraft-heif crate (heic-rs, pure Rust). Off by default so +# HEIC/HEIF decode via the optional craft-heif crate (heic-rs, pure Rust). Off by default so # distributors choose it at build time (HEVC patents are a distributor's call, same policy as # PhotoCraft); `cargo xtask ci` clippies and tests it (`--features heif`), releases don't ship it yet. -heif = ["dep:lightcraft-heif"] +heif = ["dep:craft-heif"] ## AVIF encoding via ravif/rav1e (pure Rust, BSD). Native targets only; a no-op on wasm32. avif = ["dep:ravif", "dep:rav1e", "dep:avif-serialize"] @@ -54,7 +55,7 @@ lightcraft-testkit = { workspace = true } jxl-oxide = { workspace = true } proptest = { workspace = true } # Lossless synthetic HEIC files for the `heif` feature's tests. -lightcraft-heif = { workspace = true, features = ["testdata"] } +craft-heif = { workspace = true, features = ["testdata"] } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] dhat = { workspace = true } diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 7df71c9a11..51b07eb66d 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -54,7 +54,7 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d | PSD / PSB | merged composite: 8/16/32-bit gray, RGB, CMYK, indexed, duotone (as gray); raw/RLE | — | ICC (1039), EXIF (1058), XMP (1060); ZIP-compressed composite, Lab and 1-bit unsupported | | JPEG XL | yes (jxl-oxide, feature `jxl`, default on) | yes (jixel, `encode_jxl`, feature `jxl`, native only): lossy VarDCT / lossless Modular, 8/16-bit, effort (fast / normal), progressive; HDR as 16-bit Rec. 2020 PQ | decode: enum colour → rendered straight to linear Rec.2020 (XYB via linear sRGB primaries); ICC → our ICC path; orientation applied by the decoder (reported as 1). Encode: lossy files declare an enum encoding (sRGB, Display P3, Rec. 2020 BT.709 curve, Rec. 2020 PQ), lossless ones embed the ICC profile; EXIF / XMP in `Exif` / `xml ` boxes | | AVIF | **no** | yes (ravif/rav1e, native only, feature `avif`) | 8/10-bit sRGB, EXIF; no ICC in the muxer. HDR: `encode_avif_hdr` writes 10-bit BT.2020 PQ (SDR white at 203 cd/m², CICP `nclx` + `clli`) or HLG (`hlg_signal`, SDR white at 0.75) | -| HEIC/HEIF | yes with feature `heif` (lightcraft-heif: heic-rs + libheif-matching colour; 4:2:0/mono, 8–10-bit, grids, irot/imir/clap, ICC/nclx/VUI, EXIF/XMP, thumbnail item) | — | 4:2:2/4:4:4 (Canon/Sony HIF) unsupported | +| HEIC/HEIF | yes with feature `heif` (craft-heif: heic-rs + libheif-matching colour; 4:2:0/mono, 8–10-bit, grids, irot/imir/clap, ICC/nclx/VUI, EXIF/XMP, thumbnail item) | — | 4:2:2/4:4:4 (Canon/Sony HIF) unsupported | | Gain map JPEG (HDR) | gain map found and decoded (`gainmap::read_jpeg`): ISO 21496-1 metadata, else Adobe `hdrgm` XMP | yes (`gainmap::encode_jpeg`) | CIPA DC-007 MPF index (gain map typed `0x050000`), ISO 21496-1 APP2 on both images, `hdrgm` + Container XMP for Android/Chrome, Apple `HDRGainMap`/`HDRToneMap` XMP; gain maps are never used as thumbnails | ## Colour diff --git a/crates/codecs/src/gainmap.rs b/crates/codecs/src/gainmap.rs index 9280314067..4a6f485818 100644 --- a/crates/codecs/src/gainmap.rs +++ b/crates/codecs/src/gainmap.rs @@ -1,547 +1,21 @@ -//! Gain map HDR images (ISO 21496-1): an SDR base image plus a gain map that a decoder uses to -//! rebuild the HDR rendition, so the file looks right everywhere and lights up on HDR displays. +//! Gain map JPEGs (ISO 21496-1): an SDR base image plus a gain map that a decoder uses to rebuild +//! the HDR rendition, so the file looks right everywhere and lights up on HDR displays. +//! +//! The metadata formats and the arithmetic ([`compute`], [`apply`], [`GainMapMeta`]) are +//! `craft-gainmap`'s, re-exported here. This module lays the two images out in a JPEG: //! -//! - [`compute`] measures a gain map from an SDR and an HDR rendition of the same picture (linear -//! light, same primaries). Measure it against the base *as written* (decoded from its 8-bit -//! codes), so quantisation in the base is handed back by the gain map. -//! - [`apply`] rebuilds the HDR rendition from a base and its gain map. //! - [`encode_jpeg`] writes a gain map JPEG: the base with an MPF index (CIPA DC-007), the ISO //! 21496-1 marker and Adobe/Google container XMP, followed by the gain map JPEG carrying the ISO //! 21496-1 metadata, the Adobe `hdrgm` XMP (Android, Chrome) and Apple's description of the same //! map (what survives an iMessage send). //! - [`read_jpeg`] finds and decodes the gain map of a gain map JPEG (ours, cameras, Lightroom), //! from its ISO 21496-1 metadata or, failing that, its `hdrgm` XMP. -//! -//! All gains are log2. A decoder recovers `log2(hdr + offset_hdr) − log2(sdr + offset_sdr)` as -//! `min + (max − min) · (code / 255)^(1 / gamma)`, scaled by a weight in 0..1 that depends on how -//! much headroom the display has between `base_headroom` and `alternate_headroom`. + +pub use craft_gainmap::{GainImage, GainMapMeta, GainMapOptions, ISO_URN, apply, compute}; use crate::encode::{EncodeImage, EncodeMeta, Samples, jpeg_app_segments, xmp_segment}; use crate::{ChromaSubsampling, Error, Format, Result, jpeg, jpeg_par}; -/// The ISO 21496-1 namespace that opens its APP2 payloads (NUL terminated). -pub const ISO_URN: &[u8] = b"urn:iso:std:iso:ts:21496:-1\0"; - -/// Fixed denominator for the metadata's rationals: one value per setting, byte-identical output. -const DENOMINATOR: u32 = 1_000_000; - -/// Gain map parameters (ISO 21496-1 / Adobe `hdrgm`). Per-channel arrays repeat the first value -/// when the map is single-channel. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct GainMapMeta { - /// Three gain channels (R, G, B) instead of one luminance gain. - pub multichannel: bool, - /// The gain applies in the base image's colour space. - pub use_base_colour_space: bool, - /// log2 headroom at which the base is shown as is (0: an SDR base). - pub base_headroom: f32, - /// log2 headroom at which the gain map applies in full. - pub alternate_headroom: f32, - pub min: [f32; 3], - pub max: [f32; 3], - pub gamma: [f32; 3], - pub base_offset: [f32; 3], - pub alternate_offset: [f32; 3], -} - -impl Default for GainMapMeta { - fn default() -> Self { - GainMapMeta { - multichannel: false, - use_base_colour_space: true, - base_headroom: 0.0, - alternate_headroom: 1.0, - min: [0.0; 3], - max: [1.0; 3], - gamma: [1.0; 3], - base_offset: [1.0 / 64.0; 3], - alternate_offset: [1.0 / 64.0; 3], - } - } -} - -impl GainMapMeta { - fn channels(&self) -> usize { - if self.multichannel { 3 } else { 1 } - } - - /// Usable by [`apply`]: finite, positive gammas, max ≥ min, headrooms in order. - pub fn is_valid(&self) -> bool { - let fin = |a: &[f32; 3]| a.iter().all(|v| v.is_finite()); - fin(&self.min) - && fin(&self.max) - && fin(&self.gamma) - && fin(&self.base_offset) - && fin(&self.alternate_offset) - && self.gamma.iter().all(|g| *g > 0.0) - && self.min.iter().zip(&self.max).all(|(a, b)| b >= a) - && self.base_headroom.is_finite() - && self.alternate_headroom.is_finite() - && self.alternate_headroom > self.base_headroom - } - - /// The ISO 21496-1 APP2 payload of the gain map image, URN included. - pub fn to_iso(&self) -> Vec { - let mut p = ISO_URN.to_vec(); - p.extend_from_slice(&0u16.to_be_bytes()); // minimum_version: readers gate on this - p.extend_from_slice(&0u16.to_be_bytes()); // writer_version - let mut flags = 0u8; - if self.multichannel { - flags |= FLAG_MULTICHANNEL; - } - if self.use_base_colour_space { - flags |= FLAG_BASE_COLOUR_SPACE; - } - p.push(flags); - let unsigned = |p: &mut Vec, v: f32| { - let n = (v as f64 * DENOMINATOR as f64).round().clamp(0.0, u32::MAX as f64) as u32; - p.extend_from_slice(&n.to_be_bytes()); - p.extend_from_slice(&DENOMINATOR.to_be_bytes()); - }; - let signed = |p: &mut Vec, v: f32| { - let n = (v as f64 * DENOMINATOR as f64).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32; - p.extend_from_slice(&n.to_be_bytes()); - p.extend_from_slice(&DENOMINATOR.to_be_bytes()); - }; - unsigned(&mut p, self.base_headroom.max(0.0)); - unsigned(&mut p, self.alternate_headroom.max(0.0)); - for c in 0..self.channels() { - signed(&mut p, self.min[c]); - signed(&mut p, self.max[c]); - unsigned(&mut p, self.gamma[c]); - signed(&mut p, self.base_offset[c]); - signed(&mut p, self.alternate_offset[c]); - } - p - } - - /// Parse an ISO 21496-1 payload (the bytes after [`ISO_URN`]). `None` for the versions-only - /// marker a primary image carries, unknown versions, a base that is the HDR rendition, or - /// values no decoder could use. - pub fn from_iso(p: &[u8]) -> Option { - let mut r = Reader { b: p, at: 0 }; - let min_version = r.u16()?; - let _writer_version = r.u16()?; - if min_version != 0 { - return None; - } - let flags = r.u8()?; - if flags & FLAG_BACKWARD != 0 { - return None; - } - let multichannel = flags & FLAG_MULTICHANNEL != 0; - let common = flags & FLAG_COMMON_DENOMINATOR != 0; - let common_d = if common { r.u32()? } else { 0 }; - let unsigned = |r: &mut Reader| -> Option { - let n = r.u32()?; - let d = if common { common_d } else { r.u32()? }; - (d != 0).then(|| (n as f64 / d as f64) as f32) - }; - let signed = |r: &mut Reader| -> Option { - let n = r.u32()? as i32; - let d = if common { common_d } else { r.u32()? }; - (d != 0).then(|| (n as f64 / d as f64) as f32) - }; - let mut m = GainMapMeta { - multichannel, - use_base_colour_space: flags & FLAG_BASE_COLOUR_SPACE != 0, - base_headroom: unsigned(&mut r)?, - alternate_headroom: unsigned(&mut r)?, - ..GainMapMeta::default() - }; - for c in 0..m.channels() { - m.min[c] = signed(&mut r)?; - m.max[c] = signed(&mut r)?; - m.gamma[c] = unsigned(&mut r)?; - m.base_offset[c] = signed(&mut r)?; - m.alternate_offset[c] = signed(&mut r)?; - } - if !multichannel { - m.fill_from_first(); - } - m.is_valid().then_some(m) - } - - fn fill_from_first(&mut self) { - for a in [&mut self.min, &mut self.max, &mut self.gamma, &mut self.base_offset, &mut self.alternate_offset] { - a[1] = a[0]; - a[2] = a[0]; - } - } - - /// The gain parameters from Adobe `hdrgm` XMP (the gain map image's packet), for files - /// without ISO 21496-1 metadata (the first Ultra HDR files). Attributes or `rdf:Seq` lists. - pub fn from_hdrgm_xmp(xmp: &str) -> Option { - if !xmp.contains("hdrgm:") { - return None; - } - let base_rendition_hdr = xmp_values(xmp, "BaseRenditionIsHDR").is_some_and(|v| v.first().is_some_and(|s| s.eq_ignore_ascii_case("true"))); - if base_rendition_hdr { - return None; - } - let get = |name: &str, default: f32| -> Option<([f32; 3], bool)> { - let Some(v) = xmp_values(xmp, name) else { return Some(([default; 3], false)) }; - let f: Vec = v.iter().map(|s| s.trim().parse::().ok()).collect::>()?; - match f.as_slice() { - [a] => Some(([*a; 3], false)), - [a, b, c] => Some(([*a, *b, *c], true)), - _ => None, - } - }; - let (max, m1) = get("GainMapMax", f32::NAN)?; - if max.iter().any(|v| v.is_nan()) { - return None; // the one required parameter - } - let (min, m2) = get("GainMapMin", 0.0)?; - let (gamma, m3) = get("Gamma", 1.0)?; - let (base_offset, m4) = get("OffsetSDR", 1.0 / 64.0)?; - let (alternate_offset, m5) = get("OffsetHDR", 1.0 / 64.0)?; - let (cap_min, _) = get("HDRCapacityMin", 0.0)?; - let max_gain = max.iter().copied().fold(f32::MIN, f32::max); - let (cap_max, _) = get("HDRCapacityMax", max_gain)?; - let m = GainMapMeta { - multichannel: m1 || m2 || m3 || m4 || m5, - use_base_colour_space: true, - base_headroom: cap_min[0].max(0.0), - alternate_headroom: cap_max[0], - min, - max, - gamma, - base_offset, - alternate_offset, - }; - m.is_valid().then_some(m) - } - - /// The gain map image's XMP: the Adobe `hdrgm` parameters (read by Android and Chrome, which - /// ignore the ISO payload) and Apple's description of the same map (what iMessage keeps). - pub fn to_gain_map_xmp(&self) -> String { - let names = ["GainMapMin", "GainMapMax", "Gamma", "OffsetSDR", "OffsetHDR"]; - let values = [&self.min, &self.max, &self.gamma, &self.base_offset, &self.alternate_offset]; - let uniform = |v: &[f32; 3]| !self.multichannel || (v[0] == v[1] && v[1] == v[2]); - let mut s = String::from(XMP_OPEN); - s.push_str(r#"'); - // per-channel values are an rdf:Seq of three, not a comma list: readers parse each item - for (n, v) in names.iter().zip(values) { - if !uniform(v) { - s.push_str(&format!("")); - for x in v { - s.push_str(&format!("{}", num(*x))); - } - s.push_str(&format!("")); - } - } - s.push_str(""); - s.push_str(&self.apple_description()); - s.push_str(XMP_CLOSE); - s - } - - /// Apple's own description of the map (`apdi`, `HDRGainMap`, `HDRToneMap` namespaces). - fn apple_description(&self) -> String { - // 'L008' (8-bit luminance) or '444f'; the stored map must really have that many channels - let format = if self.multichannel { 0x3434_3466u32 } else { 0x4C30_3038 }; - let mut s = String::from( - r#""#, - ); - s.push_str("urn:com:apple:photo:2020:aux:hdrgainmap"); - s.push_str(&format!("{format}{format}")); - s.push_str("131072"); - // linear, not log2: the headroom multiplier itself - s.push_str(&format!("{}", num(self.alternate_headroom.exp2()))); - s.push_str(&format!("{}", num(self.alternate_headroom))); - s.push_str(""); - for c in 0..self.channels() { - s.push_str(&format!( - r#"{}{}{}{}{}"#, - num(self.min[c]), - num(self.max[c]), - num(self.gamma[c]), - num(self.base_offset[c]), - num(self.alternate_offset[c]) - )); - } - s.push_str(""); - s.push_str(&format!("{}", num(self.base_headroom))); - s.push_str("True1"); - s.push_str(""); - s - } -} - -const FLAG_MULTICHANNEL: u8 = 0x80; -const FLAG_BASE_COLOUR_SPACE: u8 = 0x40; -const FLAG_COMMON_DENOMINATOR: u8 = 0x08; -const FLAG_BACKWARD: u8 = 0x04; - -const XMP_OPEN: &str = ""; -const XMP_CLOSE: &str = ""; - -/// A short decimal (up to 6 significant digits, no exponent for ordinary values). -fn num(v: f32) -> String { - if !v.is_finite() { - return "0".into(); - } - let s = format!("{:.6}", v); - let s = s.trim_end_matches('0').trim_end_matches('.'); - if s == "-0" || s.is_empty() { "0".into() } else { s.to_string() } -} - -/// The values of `hdrgm:`: an attribute (`name="v"`) or an element holding an `rdf:Seq`. -fn xmp_values(xmp: &str, name: &str) -> Option> { - let attr = format!("hdrgm:{name}="); - if let Some(i) = xmp.find(&attr) { - let rest = xmp.get(i + attr.len()..)?; - let q = rest.chars().next()?; - if q == '"' || q == '\'' { - let body = rest.get(1..)?; - let end = body.find(q)?; - return Some(vec![body.get(..end)?.to_string()]); - } - } - let open = format!(""); - let close = format!(""); - let i = xmp.find(&open)?; - let body = xmp.get(i + open.len()..)?; - let body = body.get(..body.find(&close)?)?; - let mut out = Vec::new(); - let mut rest = body; - while let Some(a) = rest.find("") { - let after = rest.get(a + 8..)?; - let b = after.find("")?; - out.push(after.get(..b)?.to_string()); - rest = after.get(b..)?; - if out.len() > 3 { - return None; - } - } - if out.is_empty() { - // a plain element value - out.push(body.trim().to_string()); - } - Some(out) -} - -struct Reader<'a> { - b: &'a [u8], - at: usize, -} - -impl Reader<'_> { - fn take(&mut self) -> Option<[u8; N]> { - let s = self.b.get(self.at..self.at.checked_add(N)?)?; - self.at += N; - s.try_into().ok() - } - fn u8(&mut self) -> Option { - self.take::<1>().map(|a| a[0]) - } - fn u16(&mut self) -> Option { - self.take().map(u16::from_be_bytes) - } - fn u32(&mut self) -> Option { - self.take().map(u32::from_be_bytes) - } -} - -/// A gain map image: `channels` (1 or 3) interleaved 8-bit codes. -#[derive(Clone, Debug, PartialEq)] -pub struct GainImage { - pub width: usize, - pub height: usize, - pub channels: usize, - pub data: Vec, -} - -impl GainImage { - /// Bilinear code of channel `c` at gain map coordinates (`x`, `y`) (pixel centres at +0.5). - fn sample(&self, x: f32, y: f32, c: usize) -> f32 { - let (w, h) = (self.width, self.height); - let fx = (x - 0.5).clamp(0.0, (w - 1) as f32); - let fy = (y - 0.5).clamp(0.0, (h - 1) as f32); - let (x0, y0) = (fx as usize, fy as usize); - let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); - let (tx, ty) = (fx - x0 as f32, fy - y0 as f32); - let at = |x: usize, y: usize| self.data.get((y * w + x) * self.channels + c).copied().unwrap_or(0) as f32; - let a = at(x0, y0) + (at(x1, y0) - at(x0, y0)) * tx; - let b = at(x0, y1) + (at(x1, y1) - at(x0, y1)) * tx; - a + (b - a) * ty - } -} - -/// How [`compute`] builds the map. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct GainMapOptions { - /// Downscale factor of the map (1, 2 or 4). - pub scale: usize, - /// Three gains (R, G, B) instead of one luminance gain. Apple's readers want a single - /// channel, so this is off by default. - pub multichannel: bool, - pub gamma: f32, - /// Offsets added to SDR and HDR before the ratio (keep blacks finite and noise quiet). - pub offset: f32, -} - -impl Default for GainMapOptions { - fn default() -> Self { - GainMapOptions { scale: 2, multichannel: false, gamma: 1.0, offset: 1.0 / 64.0 } - } -} - -/// Measure the gain map that turns `sdr` into `hdr` (both `width × height` linear RGB in the same -/// primaries; `luma` = that space's luminance weights). -pub fn compute( - sdr: &[[f32; 3]], - hdr: &[[f32; 3]], - width: usize, - height: usize, - luma: [f32; 3], - o: &GainMapOptions, -) -> Result<(GainImage, GainMapMeta)> { - let n = width.checked_mul(height).ok_or_else(|| Error::Encode("gain map: image too large".into()))?; - if n == 0 || sdr.len() < n || hdr.len() < n { - return Err(Error::Encode("gain map: SDR and HDR renditions must match the image size".into())); - } - if !(matches!(o.scale, 1 | 2 | 4) && o.gamma > 0.0 && o.gamma.is_finite() && o.offset > 0.0 && o.offset.is_finite()) { - return Err(Error::Encode("gain map: scale must be 1, 2 or 4, gamma and offset positive".into())); - } - let s = o.scale; - let (gw, gh) = (width.div_ceil(s), height.div_ceil(s)); - let ch = if o.multichannel { 3 } else { 1 }; - let y = |p: &[f32; 3]| luma[0] * p[0] + luma[1] * p[1] + luma[2] * p[2]; - let ratio = |a: f32, b: f32| ((b.max(0.0) + o.offset) / (a.max(0.0) + o.offset)).log2(); - // block means of the log gains - let mut gains = vec![0f32; gw * gh * ch]; - let mut lo = [f32::MAX; 3]; - let mut hi = [f32::MIN; 3]; - for gy in 0..gh { - for gx in 0..gw { - let mut acc = [0f32; 3]; - let mut count = 0f32; - for yy in gy * s..((gy + 1) * s).min(height) { - for xx in gx * s..((gx + 1) * s).min(width) { - let i = yy * width + xx; - let (Some(a), Some(b)) = (sdr.get(i), hdr.get(i)) else { continue }; - if o.multichannel { - for c in 0..3 { - acc[c] += ratio(a[c], b[c]); - } - } else { - acc[0] += ratio(y(a), y(b)); - } - count += 1.0; - } - } - for c in 0..ch { - let g = if count > 0.0 { acc[c] / count } else { 0.0 }; - let g = if g.is_finite() { g } else { 0.0 }; - gains[(gy * gw + gx) * ch + c] = g; - lo[c] = lo[c].min(g); - hi[c] = hi[c].max(g); - } - } - } - let mut m = GainMapMeta { - multichannel: o.multichannel, - gamma: [o.gamma; 3], - base_offset: [o.offset; 3], - alternate_offset: [o.offset; 3], - ..GainMapMeta::default() - }; - for c in 0..ch { - // the range always includes 0 (no change) so an SDR-only area encodes exactly - m.min[c] = lo[c].min(0.0); - m.max[c] = hi[c].max(m.min[c] + 1e-4); - } - if !o.multichannel { - m.fill_from_first(); - } - m.base_headroom = 0.0; - m.alternate_headroom = m.max.iter().copied().fold(0.0f32, f32::max).max(1e-3); - let data = gains - .iter() - .enumerate() - .map(|(i, g)| { - let c = i % ch; - let norm = ((g - m.min[c]) / (m.max[c] - m.min[c])).clamp(0.0, 1.0); - (norm.powf(o.gamma) * 255.0).round() as u8 - }) - .collect(); - Ok((GainImage { width: gw, height: gh, channels: ch, data }, m)) -} - -/// Rebuild the HDR rendition in place: `base` (`width × height` linear RGB) is replaced by the -/// rendition at `weight` (0 = the base, 1 = the full alternate rendition; a display with headroom -/// `H` uses `(H − base_headroom) / (alternate_headroom − base_headroom)`, clamped). -pub fn apply(base: &mut [[f32; 3]], width: usize, height: usize, gain: &GainImage, m: &GainMapMeta, weight: f32) -> Result<()> { - let n = width.checked_mul(height).ok_or_else(|| Error::Encode("gain map: image too large".into()))?; - if base.len() < n - || gain.width == 0 - || gain.height == 0 - || !matches!(gain.channels, 1 | 3) - || gain.data.len() < gain.width * gain.height * gain.channels - { - return Err(Error::Encode("gain map: base and gain map sizes don't match".into())); - } - if !m.is_valid() { - return Err(Error::Encode("gain map: unusable metadata".into())); - } - let weight = if weight.is_finite() { weight.clamp(0.0, 1.0) } else { 1.0 }; - let (sx, sy) = (gain.width as f32 / width as f32, gain.height as f32 / height as f32); - let inv_gamma = m.gamma.map(|g| 1.0 / g); - for (i, p) in base.iter_mut().enumerate().take(n) { - let (x, y) = ((i % width) as f32 + 0.5, (i / width) as f32 + 0.5); - let (gx, gy) = (x * sx, y * sy); - let mut g = [0f32; 3]; - for (c, gc) in g.iter_mut().enumerate() { - let src = if gain.channels == 3 { c } else { 0 }; - let norm = (gain.sample(gx, gy, src) / 255.0).clamp(0.0, 1.0).powf(inv_gamma[c]); - *gc = m.min[c] + (m.max[c] - m.min[c]) * norm; - } - for c in 0..3 { - let v = (p[c] + m.base_offset[c]) * (g[c] * weight).exp2() - m.alternate_offset[c]; - p[c] = v.max(0.0); - } - } - Ok(()) -} - -/// The primary image's container XMP: `hdrgm:Version` (marks the file as a gain map image for -/// Adobe/Google readers) and the Container directory naming the gain map and its length. -fn primary_description(gain_len: usize) -> String { - format!( - concat!( - r#""#, - r#""#, - r#""#, - r#""#, - r#""# - ), - gain_len - ) -} - -/// `xmp` with `description` added as another `rdf:Description` (a fresh packet when there is -/// none, or when it has no `rdf:RDF` to add to). -fn merge_xmp(xmp: Option<&str>, description: &str) -> String { - if let Some(x) = xmp - && let Some(i) = x.rfind("") - && let (Some(a), Some(b)) = (x.get(..i), x.get(i..)) - { - return format!("{a}{description}{b}"); - } - format!("{XMP_OPEN}{description}{XMP_CLOSE}") -} - /// Offsets within the MPF payload (from "MPF\0"): the endian field, then the index IFD (3 tags). const MPF_ENTRIES_FROM_ENDIAN: usize = 8 + 2 + 3 * 12 + 4; @@ -598,11 +72,9 @@ pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, qualit let gain_segs = vec![(0xE1, xmp_segment(&m.to_gain_map_xmp())?), (0xE2, m.to_iso())]; let gain_jpeg = jpeg_par::encode(&gain.data, gain.width, gain.height, gain.channels, quality, ChromaSubsampling::S444, &gain_segs); - let xmp = merge_xmp(meta.xmp, &primary_description(gain_jpeg.len())); + let xmp = craft_gainmap::primary_xmp(meta.xmp, gain_jpeg.len()); let mut segs = jpeg_app_segments(&EncodeMeta { xmp: Some(&xmp), ..*meta })?; - let mut iso_marker = ISO_URN.to_vec(); - iso_marker.extend_from_slice(&[0, 0, 0, 0]); // versions only: "this image has a gain map" - segs.push((0xE2, iso_marker)); + segs.push((0xE2, craft_gainmap::primary_iso_marker())); segs.push((0xE2, mpf_placeholder())); let mut primary = jpeg_par::encode(data, w, h, base.channels as usize, quality, sub, &segs); @@ -672,77 +144,6 @@ pub fn is_gain_map_jpeg(bytes: &[u8]) -> bool { mod tests { use super::*; - fn meta3() -> GainMapMeta { - GainMapMeta { - multichannel: true, - use_base_colour_space: true, - base_headroom: 0.0, - alternate_headroom: 2.5, - min: [-0.25, -0.5, 0.0], - max: [2.5, 2.25, 2.0], - gamma: [1.0, 1.25, 0.75], - base_offset: [0.015625; 3], - alternate_offset: [0.015625, 0.03125, 0.015625], - } - } - - #[test] - fn iso_metadata_round_trips() { - for m in [GainMapMeta { alternate_headroom: 3.0, max: [3.0; 3], ..GainMapMeta::default() }, meta3()] { - let p = m.to_iso(); - assert!(p.starts_with(ISO_URN)); - let back = GainMapMeta::from_iso(&p[ISO_URN.len()..]).unwrap(); - for (a, b) in [(back.min, m.min), (back.max, m.max), (back.gamma, m.gamma), (back.alternate_offset, m.alternate_offset)] { - for c in 0..3 { - assert!((a[c] - b[c]).abs() < 1e-6, "{a:?} {b:?}"); - } - } - assert_eq!(back.multichannel, m.multichannel); - assert!((back.alternate_headroom - m.alternate_headroom).abs() < 1e-6); - } - } - - #[test] - fn iso_common_denominator_and_rejections() { - // common-denominator form, single channel: d = 4, headrooms 0 and 2, min 0, max 2, gamma 1, offsets 0 - let mut p = vec![0, 0, 0, 0, FLAG_COMMON_DENOMINATOR]; - for v in [4u32, 0, 8, 0, 8, 4, 0, 0] { - p.extend_from_slice(&v.to_be_bytes()); - } - let m = GainMapMeta::from_iso(&p).unwrap(); - assert_eq!((m.alternate_headroom, m.max[2], m.gamma[1]), (2.0, 2.0, 1.0)); - // versions only (a primary image's marker), unknown version, truncated, backward - assert!(GainMapMeta::from_iso(&[0, 0, 0, 0]).is_none()); - assert!(GainMapMeta::from_iso(&[0, 1, 0, 0, 0]).is_none()); - assert!(GainMapMeta::from_iso(&p[..p.len() - 1]).is_none()); - let mut back = p.clone(); - back[4] |= FLAG_BACKWARD; - assert!(GainMapMeta::from_iso(&back).is_none()); - // a zero denominator is rejected, not divided by - let mut z = p.clone(); - z[5..9].copy_from_slice(&0u32.to_be_bytes()); - assert!(GainMapMeta::from_iso(&z).is_none()); - } - - #[test] - fn hdrgm_xmp_round_trips_including_per_channel_sequences() { - for m in [GainMapMeta { alternate_headroom: 2.0, max: [2.0; 3], ..GainMapMeta::default() }, meta3()] { - let x = m.to_gain_map_xmp(); - assert!(x.contains("apdi:AuxiliaryImageType")); - if m.multichannel { - assert!(x.contains("2.5"), "{x}"); - } - let back = GainMapMeta::from_hdrgm_xmp(&x).unwrap(); - assert_eq!(back.multichannel, m.multichannel); - for c in 0..3 { - assert!((back.max[c] - m.max[c]).abs() < 1e-5 && (back.gamma[c] - m.gamma[c]).abs() < 1e-5); - } - assert!((back.alternate_headroom - m.alternate_headroom).abs() < 1e-5); - } - assert!(GainMapMeta::from_hdrgm_xmp("").is_none(), "no GainMapMax"); - assert!(GainMapMeta::from_hdrgm_xmp("hdrgm:GainMapMax=\"nope\"").is_none()); - } - fn renditions(w: usize, h: usize) -> (Vec<[f32; 3]>, Vec<[f32; 3]>) { // a ramp: SDR rolls off at 1, HDR keeps going to 6 let hdr: Vec<[f32; 3]> = (0..w * h) @@ -765,31 +166,6 @@ mod tests { (sdr, hdr) } - #[test] - fn compute_then_apply_recovers_the_hdr_rendition() { - let (w, h) = (64, 8); - let (sdr, hdr) = renditions(w, h); - for multichannel in [false, true] { - let o = GainMapOptions { scale: 1, multichannel, ..GainMapOptions::default() }; - let (g, m) = compute(&sdr, &hdr, w, h, [0.2126, 0.7152, 0.0722], &o).unwrap(); - assert!(m.is_valid() && m.alternate_headroom > 1.0); - let mut out = sdr.clone(); - apply(&mut out, w, h, &g, &m, 1.0).unwrap(); - for (a, b) in out.iter().zip(&hdr) { - for c in 0..3 { - // 8-bit codes over the gain range: within ~2 % in linear light - assert!((a[c] - b[c]).abs() <= 0.03 * b[c] + 0.01, "{multichannel}: {a:?} vs {b:?}"); - } - } - // weight 0 is the base - let mut base = sdr.clone(); - apply(&mut base, w, h, &g, &m, 0.0).unwrap(); - for (a, b) in base.iter().zip(&sdr) { - assert!((a[0] - b[0]).abs() < 1e-5); - } - } - } - #[test] fn a_gain_map_wider_than_a_jpeg_allows_is_refused() { let base = [0u8; 3]; diff --git a/crates/codecs/src/heif.rs b/crates/codecs/src/heif.rs index 702a0d27d2..2d4d5a7a1d 100644 --- a/crates/codecs/src/heif.rs +++ b/crates/codecs/src/heif.rs @@ -1,6 +1,6 @@ //! HEIF / HEIC (the iPhone and Mac photo format), read-only. //! -//! Decoding lives in the optional `lightcraft-heif` crate (heic-rs, a pure-Rust HEVC +//! Decoding lives in the optional `craft-heif` crate (heic-rs, a pure-Rust HEVC //! still-picture decoder, plus a libheif-matching colour conversion), enabled by this crate's //! `heif` feature — off by default because HEVC is patent-encumbered and whether a build carries //! an HEVC decoder is the distributor's call (the same policy as the sibling PhotoCraft). Without @@ -35,10 +35,10 @@ pub(crate) fn header(_bytes: &[u8]) -> Result<(u32, u32, u16)> { } #[cfg(feature = "heif")] -fn err(e: lightcraft_heif::Error) -> Error { +fn err(e: craft_heif::Error) -> Error { match e { - lightcraft_heif::Error::Unsupported(why) => Error::Unsupported(F, why), - lightcraft_heif::Error::Limit(m) | lightcraft_heif::Error::Malformed(m) => Error::Malformed(F, m), + craft_heif::Error::Unsupported(why) => Error::Unsupported(F, why), + craft_heif::Error::Limit(m) | craft_heif::Error::Malformed(m) => Error::Malformed(F, m), } } @@ -46,24 +46,24 @@ fn err(e: lightcraft_heif::Error) -> Error { /// alone: no picture is decoded. #[cfg(feature = "heif")] pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { - let info = lightcraft_heif::probe(bytes).map_err(err)?; + let info = craft_heif::probe(bytes).map_err(err)?; Ok((info.width, info.height, 1)) } #[cfg(feature = "heif")] pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { // The container alone: the declared size is checked before any pixel is decoded. - let info = lightcraft_heif::probe(bytes).map_err(err)?; + let info = craft_heif::probe(bytes).map_err(err)?; if (info.width as u64).saturating_mul(info.height as u64) > opts.max_pixels { return Err(Error::TooLarge(info.width as u64, info.height as u64)); } - let options = lightcraft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true }; + let options = craft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true, ..craft_heif::Options::default() }; // A small decode (a thumbnail or a cataloguing probe) uses the file's own thumbnail image when // it is at least as large as asked: iPhones store one of 320 × 240, and decoding it is a // hundredth of the work of the 12 MP photo. let thumb = match opts.max_size { Some((mw, mh)) if mw > 0 && mh > 0 && mw.max(mh) < info.width.max(info.height) => { - lightcraft_heif::decode_thumbnail(bytes, mw.max(mh), &options).ok().flatten().filter(|t| { + craft_heif::decode_thumbnail(bytes, mw.max(mh), &options).ok().flatten().filter(|t| { // Only a thumbnail of the same picture: same orientation and aspect within 1 %. let aspect = |w: u32, h: u32| w as f64 / h.max(1) as f64; (aspect(t.width, t.height) / aspect(info.width, info.height) - 1.0).abs() < 0.01 @@ -73,7 +73,7 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { }; let mut decoded = match thumb { Some(t) => t, - None => lightcraft_heif::decode(bytes, &options).map_err(err)?, + None => craft_heif::decode(bytes, &options).map_err(err)?, }; let raw = Raw { width: decoded.width as usize, diff --git a/crates/codecs/tests/it/heif.rs b/crates/codecs/tests/it/heif.rs index 3364aec4d3..5cd2e63d0b 100644 --- a/crates/codecs/tests/it/heif.rs +++ b/crates/codecs/tests/it/heif.rs @@ -1,9 +1,9 @@ //! HEIC/HEIF through the codec API (feature `heif`), on lossless synthetic files from -//! `lightcraft_heif::testdata`: an iPhone-like grid with a Display P3 profile, rotation, EXIF, a +//! `craft_heif::testdata`: an iPhone-like grid with a Display P3 profile, rotation, EXIF, a //! thumbnail and an HDR gain map; `nclx`-only colour; 10-bit; and hostile input. +use craft_heif::testdata::{Prop, Spec, build}; use lightcraft_codecs::*; -use lightcraft_heif::testdata::{Prop, Spec, build}; fn grey(x: u32, y: u32) -> [u16; 3] { [((x * 7 + y * 13) % 220 + 20) as u16, 128, 128] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index ab73adb42e..1486642429 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -66,6 +66,6 @@ lightcraft-testkit = { workspace = true } # HDR JPEG XL tests read the file's colour encoding jxl-oxide = { workspace = true } # Lossless synthetic HEIC files (the import test; decoded when the codecs' `heif` feature is on). -lightcraft-heif = { workspace = true, features = ["testdata"] } +craft-heif = { workspace = true, features = ["testdata"] } libc = { workspace = true } craft-tiff = { workspace = true } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 95be627fc5..4de20ab3ee 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -2820,7 +2820,7 @@ fn a_file_gone_since_the_import_review_is_not_imported() { /// a JPEG. In a build without the codecs' `heif` feature it is reported as failed, saying why. #[test] fn heic_imports_as_a_normal_photo_or_says_why_not() { - use lightcraft_heif::testdata::{Prop, Spec, build}; + use craft_heif::testdata::{Prop, Spec, build}; let src = temp_dir("heic"); let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150]; let p3 = lightcraft_codecs::icc::write_named(lightcraft_codecs::NamedSpace::DisplayP3); @@ -2857,8 +2857,8 @@ fn heic_imports_as_a_normal_photo_or_says_why_not() { /// writes as UTC: an iPhone photo landed five hours late and after 19:00 on the wrong day. #[test] fn a_heic_is_dated_by_its_exif_and_not_by_the_file() { + use craft_heif::testdata::{Spec, build}; use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; - use lightcraft_heif::testdata::{Spec, build}; let src = temp_dir("heic-capture-time"); let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150]; let mut exif = IfdBuilder::new(); diff --git a/crates/heif/Cargo.toml b/crates/heif/Cargo.toml deleted file mode 100644 index 95641fb2fd..0000000000 --- a/crates/heif/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "lightcraft-heif" -description = "Optional HEIF/HEIC still-image decoder for LightCraft (heic-rs for the container and HEVC, libheif-matching colour conversion, panic-guarded)" -version.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -# Pure Rust, no unsafe. Pinned exactly: a young, single-owner crate that parses untrusted files; -# moving the pin is a reviewed change (re-run the heif tests and the codecs corpus tests). -# Mirrors PhotoCraft's photocraft-heif (same team, same decision): heic-rs was chosen over the -# other permissive candidates (heif-oxide's HEVC decoder, rust_h265, follows FFmpeg's (LGPL) -# code structure; gamut-heic has no HEVC decoder of its own). -heic-rs = { version = "=0.1.4", default-features = false, features = ["std"] } - -# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded. -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"] } -rayon = { workspace = true } - -[features] -# `lightcraft_heif::testdata`: lossless synthetic HEIF files, for the tests of the crates above. -testdata = [] - -[lints] -workspace = true diff --git a/crates/heif/README.md b/crates/heif/README.md deleted file mode 100644 index 75db814b0d..0000000000 --- a/crates/heif/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# lightcraft-heif - -The optional HEIF / HEIC decoder of LightCraft: iPhone and Mac photos. [`heic-rs`](https://github.com/tbraun96/heic-rs) -(pure Rust, no `unsafe`, MIT OR Apache-2.0, written from the H.265 / HEIF specifications) reads the -container and reconstructs the HEVC pictures; this crate turns them into 16-bit RGB itself so the -result matches libheif to within one code value: - -- the colour description is the item's `colr nclx` (or its first tile's), else the HEVC VUI - (iPhones: full range), else the H.265 defaults; an unspecified matrix is BT.601. heic-rs alone - assumes BT.709 limited range, about 8 code values off on every iPhone photo; -- chroma is upsampled by nearest neighbour, or centred bilinear when a `clap` starts on an odd - pixel, as libheif does; -- `imir` axis 0 flips top and bottom, as libheif writes and reads it (heic-rs names it the other way); -- a grid's ICC profile may sit on its tiles. - -Single pictures and grid-tiled photos, 4:2:0 and monochrome, 8- to 10-bit, alpha auxiliary images -(other auxiliary images — HDR gain maps, depth — are ignored), the container's rotation/mirror/crop, -ICC, EXIF and XMP, and the file's thumbnail item. 4:2:2 and 4:4:4 (Canon/Sony "HIF") are refused -with `Error::Unsupported`: heic-rs 0.1.1 loses sync on them. Read-only. - -```rust -let info = lightcraft_heif::probe(&bytes)?; // size, depth, alpha: check limits first -let img = lightcraft_heif::decode(&bytes, &lightcraft_heif::Options::default())?; -// img.width, img.height, img.has_alpha, img.bit_depth, img.data (RGB/RGBA u16), img.colour, img.icc, img.exif, img.xmp -let thumb = lightcraft_heif::decode_thumbnail(&bytes, 256, &Default::default())?; // Option -``` - -Errors are `Error::Unsupported` (image sequences, overlays, 4:2:2/4:4:4, …), `Error::Limit` or -`Error::Malformed`. It never panics: every call into heic-rs runs under `catch_unwind`, and a panic -inside it (PhotoCraft's fuzzing found two in 0.1.1) becomes `Error::Malformed`. - -Feature `testdata` exposes `lightcraft_heif::testdata`: lossless synthetic HEIF files (PCM-coded -32 × 32 HEVC pictures, grids, every property above) for the tests of the crates above. - -## Why it is a separate, optional crate - -- **A young decoder.** heic-rs is new and has a single maintainer. It is pinned exactly - (`=0.1.1`); moving the pin is a reviewed change (re-run the crate tests and - `cargo test -p lightcraft-codecs --features heif`). The other permissive candidates were - rejected: heif-oxide's HEVC decoder (rust_h265) follows FFmpeg's (LGPL) code structure, and - gamut-heic has no HEVC decoder of its own. -- **HEVC patents are a distributor's call.** `lightcraft-codecs` uses this crate only behind its - non-default `heif` feature; the apps forward it and the release packages enable it. Without it, - HEIC files are still recognised and opening one is a clear "HEIC/HEIF support isn't included in - this build" error — the same policy as PhotoCraft. - -The crate depends on no other LightCraft crate; `codecs` → `heif` is the only edge between them. diff --git a/crates/heif/src/census.rs b/crates/heif/src/census.rs deleted file mode 100644 index 6dbe035fca..0000000000 --- a/crates/heif/src/census.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Caps on the container's metadata boxes, counted before heic-rs touches the file. -//! -//! heic-rs 0.1.4 (pinned `=0.1.4`) has no aggregate work budget inside its container parsing: -//! every `ipma` association entry rescans the vector of already-seen item ids (quadratic in -//! the number of entries), and an `iloc` extent using construction method 2 reconstructs its -//! source item afresh for every extent that references it, with no shared cache. Legitimate -//! phone-photo metadata never comes near these caps — real corpora keep both well under a few -//! kilobytes — so anything above them is hostile or corrupt and is refused before the -//! countable CPU work happens. -//! -//! [`depth_boxes`] stops silently at structural blips: heic-rs's own parser reports those -//! better than this walk could, and an `ipma` box past the cap is caught wherever it parses. - -use heic_rs::boxes::BoxIter; - -use crate::Error; - -/// The largest `ipma` box (item ↔ property associations) payload accepted, 64 KiB. An entry -/// costs at least 3 bytes, so this bounds heic-rs's per-entry rescan of earlier item ids to -/// ~21 000 entries ≈ 220 million comparisons: long enough to be annoying, never minutes. -const MAX_IPMA_BYTES: usize = 64 << 10; - -/// The largest `iloc` box (item locations) payload accepted, 64 KiB. An extent costs at least -/// 12 bytes, so this bounds both the parse itself and how many extents a -/// construction-method-2 reconstruction chain can visit. -const MAX_ILOC_BYTES: usize = 64 << 10; - -/// Falls through unless the container declares more `ipma` or `iloc` payload than a -/// legitimate phone photo ever does. -pub fn cap(bytes: &[u8]) -> Result<(), Error> { - let mut c = Census::default(); - depth_boxes(&mut c, BoxIter::new(bytes), 0); - if c.ipma > MAX_IPMA_BYTES { - return Err(Error::Limit(format!("the image carries {} bytes of property associations, over the {MAX_IPMA_BYTES}-byte cap", c.ipma))); - } - if c.iloc > MAX_ILOC_BYTES { - return Err(Error::Limit(format!("the image carries {} bytes of item locations, over the {MAX_ILOC_BYTES}-byte cap", c.iloc))); - } - Ok(()) -} - -/// The metadata-box payload sizes seen so far. -#[derive(Default)] -struct Census { - ipma: usize, - iloc: usize, -} - -/// Walks boxes, adding the payload sizes of those named in [`Census`]. -/// -/// Only `meta` and `iprp` (the two nesting boxes the metadata is built from) are descended -/// into, no deeper than that depth, so a nested-box trick can't hide a box from the count. -fn depth_boxes(c: &mut Census, boxes: BoxIter<'_>, depth: u32) { - if depth > 3 { - return; - } - for b in boxes { - // A structural error stops the walk; `heic_rs::probe` reports it properly afterwards. - let Ok(b) = b else { return }; - if b.is(b"ipma") { - c.ipma = c.ipma.saturating_add(b.payload.len()); - } else if b.is(b"iloc") { - c.iloc = c.iloc.saturating_add(b.payload.len()); - } else if b.is(b"meta") { - // `meta` is a FullBox: version and flags sit between its header and its children. - if b.payload.len() >= 4 { - depth_boxes(c, BoxIter::new(&b.payload[4..]), depth + 1); - } - } else if b.is(b"iprp") { - depth_boxes(c, b.children(), depth + 1); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Assembles ftyp + meta(version/flags + iprp(ipco, ipma)) by hand; only the structure - /// the census walks matters, no item is ever defined. - fn file_with(ipma_payload: &[u8]) -> Vec { - let mut out = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic".to_vec(); - let mut iprp = Vec::new(); - iprp.extend(box_of(b"ipco", b"")); - iprp.extend(box_of(b"ipma", ipma_payload)); - let mut meta = vec![0u8, 0, 0, 0]; // version 0, flags 0 - meta.extend(box_of(b"iprp", &iprp)); - out.extend(box_of(b"meta", &meta)); - out - } - - fn box_of(kind: &[u8; 4], body: &[u8]) -> Vec { - let mut out = Vec::with_capacity(8 + body.len()); - let size = u32::try_from(8 + body.len()).expect("test box fits in u32"); - out.extend_from_slice(&size.to_be_bytes()); - out.extend_from_slice(kind); - out.extend_from_slice(body); - out - } - - #[test] - fn an_oversized_ipma_is_refused() { - // 40 000 entries of 6 bytes: 240 KiB of ipma, far over the cap, and quadratic if - // parsed (each entry rescans the earlier item ids in heic-rs 0.1.4). - let mut ipma = Vec::new(); - for _ in 0..40_000u32 { - ipma.extend_from_slice(&[0u8, 0, 0, 0, 0, 0]); - } - let bytes = file_with(&ipma); - let r = crate::probe(&bytes).map(|_| ()); - assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("associations")), "{r:?}"); - } - - #[test] - fn a_undersized_ipma_is_untouched_by_the_caps() { - // The same shape with a normal ipma (two entries): the caps pass, and whatever error - // follows must not come from them. - let bytes = file_with(&[0, 0, 4, 1, 1, 2, 0, 0]); - let r = crate::probe(&bytes); - assert!(!matches!(r, Err(Error::Limit(ref m)) if m.contains("cap")), "{r:?}"); - } -} diff --git a/crates/heif/src/lib.rs b/crates/heif/src/lib.rs deleted file mode 100644 index a0733f6334..0000000000 --- a/crates/heif/src/lib.rs +++ /dev/null @@ -1,605 +0,0 @@ -//! `lightcraft-heif`: the optional HEIF / HEIC (iPhone and Mac photo) decoder. -//! -//! `heic-rs`, a pure-Rust HEIF container and HEVC still-picture decoder, reads the container and -//! reconstructs the coded pictures (bit-exact against libde265 on iPhone photos); this crate turns -//! them into RGB itself ([`ycc`]) so the colours match libheif: it honours the HEVC VUI's range -//! and matrix ([`vui`]) where heic-rs assumes BT.709 limited range, and upsamples chroma like -//! libheif. Single pictures and grid-tiled photos, 8- to 16-bit, monochrome, alpha auxiliary -//! images, ICC, EXIF and XMP. The API is plain data ([`Info`], [`Decoded`], [`Error`]) so the -//! crate knows nothing about the rest of LightCraft; `lightcraft-codecs` adapts it behind its -//! `heif` feature. Shares heic-rs and its regression fixtures with PhotoCraft's `photocraft-heif`. -//! -//! HEIF records orientation in the container (`irot`/`imir`, plus a `clap` crop), not in EXIF. -//! [`Options::apply_transforms`] applies them; with it off, the pixels come back as coded. -//! Auxiliary images other than alpha (HDR gain maps, depth maps) are ignored. -//! -//! Never panics: heic-rs is young, so every call into it runs under `catch_unwind` and a panic -//! inside it becomes [`Error::Malformed`]. - -#![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -mod census; -mod orient; -/// Lossless synthetic HEIF files for tests, here and in the crates above (feature `testdata`). -#[cfg(any(test, feature = "testdata"))] -#[doc(hidden)] -pub mod testdata; -mod vui; -mod ycc; - -use std::borrow::Cow; - -use heic_rs::context::Context; -use heic_rs::hevc::Frame; -use heic_rs::props::ItemProps; -use heic_rs::props::colr::Range; - -/// What a HEIF file declares, read from the container alone (no pixel is decoded). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Info { - /// Size after the container transforms (rotation, mirror, crop): what a viewer shows. - pub width: u32, - pub height: u32, - /// Size as coded, before the transforms. - pub coded_width: u32, - pub coded_height: u32, - /// The primary image has an alpha auxiliary image. - pub has_alpha: bool, - /// Bits per sample as coded (8 for most photos, 10 for HDR-capable ones). - pub bit_depth: u8, -} - -/// Decode settings. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Options { - /// Refuse images with more pixels than this (checked before decoding). - pub max_pixels: u64, - /// Apply the container's rotation, mirror and crop (`irot`/`imir`/`clap`). - pub apply_transforms: bool, -} - -impl Default for Options { - fn default() -> Self { - Options { max_pixels: 1 << 28, apply_transforms: true } - } -} - -/// How the file describes its colour: the code points of ITU-T H.273, from the `colr` `nclx` -/// box, else the HEVC VUI, else the standard defaults (2 = unspecified, limited range). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Colour { - pub primaries: u16, - pub transfer: u16, - pub matrix: u16, - pub full_range: bool, -} - -/// A decoded image: interleaved RGB or RGBA, 16 bits per sample whatever the coded depth, -/// row-major, no padding. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Decoded { - pub width: u32, - pub height: u32, - /// Four channels (RGBA) instead of three (RGB). - pub has_alpha: bool, - /// Bits per sample as coded. - pub bit_depth: u8, - pub data: Vec, - pub colour: Colour, - /// The primary image's ICC profile. - pub icc: Option>, - /// EXIF as a TIFF structure (without HEIF's offset header). Its Orientation tag only mirrors - /// what the container says; it is returned verbatim. - pub exif: Option>, - /// The XMP packet. - pub xmp: Option, -} - -/// Why a file could not be decoded. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Error { - /// A valid file using something this decoder does not handle (image sequences, overlays…). - Unsupported(&'static str), - /// The image is larger than [`Options::max_pixels`] or holds an oversized box. - Limit(String), - /// Broken or truncated data (or a decoder bug, reported the same way). - Malformed(String), -} - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Unsupported(m) => write!(f, "unsupported HEIF: {m}"), - Error::Limit(m) => write!(f, "limit exceeded: {m}"), - Error::Malformed(m) => write!(f, "malformed HEIF: {m}"), - } - } -} - -impl std::error::Error for Error {} - -const SEQUENCE: &str = "this file holds an image sequence; only HEIF still images can be opened"; - -/// heic-rs 0.1.1 reconstructs 4:2:0 and monochrome pictures exactly but fails on the 4:2:2 and -/// 4:4:4 ones some cameras write (Canon and Sony "HIF"); those failures are reported as this. -const CHROMA_422_444: &str = "4:2:2 and 4:4:4 HEIF images (as some Canon and Sony cameras write) can't be decoded yet"; - -pub(crate) fn err(e: heic_rs::Error) -> Error { - match e { - heic_rs::Error::Unsupported(what) => Error::Unsupported(what), - // The primary item is neither an HEVC picture nor a grid of them. - heic_rs::Error::MissingBox("hvcC") => Error::Unsupported("the image is an overlay, an identity derivation or not HEVC-coded"), - heic_rs::Error::PixelLimit { .. } | heic_rs::Error::BoxTooLarge { .. } => Error::Limit(e.to_string()), - e => Error::Malformed(e.to_string()), - } -} - -/// Runs `f`, turning a heic-rs panic into an error. Fuzzing in the sibling app found two -/// out-of-range slices in heic-rs 0.1.1 on malformed files: in its box parser (`boxes.rs:130`) -/// and during reconstruction (`hevc/decode/recon.rs:70`). -fn guarded(f: impl FnOnce() -> Result) -> Result { - std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(Error::Malformed("the HEIF decoder failed on this file".into()))) -} - -/// Reads the container's declared size, depth and alpha without decoding pixels, so callers can -/// check their limits first. Also refuses a file cut short: every coded picture of the primary -/// image must lie within `bytes`. -pub fn probe(bytes: &[u8]) -> Result { - guarded(|| probe_unguarded(bytes)) -} - -fn probe_unguarded(bytes: &[u8]) -> Result { - census::cap(bytes)?; - // No `meta` box: no still image, only a `moov` image sequence (a video track). - let open_error = |e| match e { - heic_rs::Error::MissingBox("meta") => Error::Unsupported(SEQUENCE), - e => err(e), - }; - let ctx = Context::open(bytes).map_err(open_error)?; - let id = ctx.meta.primary; - // heic-rs 0.1.4 caps the size of what it assembles, not the work: an item built from other - // items (`iloc` construction method 2) is rebuilt once per extent, so a chain of such items - // multiplies at every level while each result stays small. Count those visits from the - // `iloc` table before reconstructing anything: the primary item first (`heic_rs::probe` and - // `Context::grid` both rebuild its descriptor), then its alpha plane and, when that is a grid, - // its tiles, then every tile reference, repeats included. - let mut visits = 0_usize; - item_visits(&ctx, id, 0, &mut visits)?; - // `heic_rs::probe` reads an item without `ispe` from its parameter sets - check_item_parameter_sets(&ctx.props(id).map_err(err)?)?; - let info = heic_rs::probe(bytes).map_err(open_error)?; - let alpha = ctx.alpha_item(id).map_err(err)?; - if let Some(alpha) = alpha { - item_visits(&ctx, alpha, 0, &mut visits)?; - // an alpha plane may be a grid too: its tiles are rebuilt when it is decoded - if let Some((_, tiles)) = ctx.grid(alpha).map_err(err)? { - for &tile in tiles.iter().filter(|&&tile| tile != alpha) { - item_visits(&ctx, tile, 0, &mut visits)?; - } - } - } - let mut coded = match ctx.grid(id).map_err(err)? { - Some((_, tiles)) => tiles, - None => vec![id], - }; - for &item in coded.iter().filter(|&&item| item != id) { - item_visits(&ctx, item, 0, &mut visits)?; - } - // A `dimg` listing may name the same tile more than once, and reconstructable items are - // moreover rebuilt for every extent that references them in heic-rs 0.1.4. For the size - // check each unique item counts once: the total reconstruction (all of it assembled from - // `bytes` by heic-rs) is held below one copy of the file, above which a repeat or chain - // wants more bytes than exist. Order doesn't matter here: this only checks that every - // tile's bytes lie in the file. - coded.sort_unstable(); - coded.dedup(); - let mut reconstructed = 0_usize; - for item in coded { - reconstructed = reconstructed.saturating_add(ctx.item_data(item).map_err(err)?.len()); - if reconstructed > bytes.len() { - return Err(Error::Limit(format!( - "the container holds {reconstructed} bytes of item data, over the {} bytes of the file itself", - bytes.len() - ))); - } - } - Ok(Info { - width: info.width, - height: info.height, - coded_width: info.coded_width, - coded_height: info.coded_height, - has_alpha: info.has_alpha, - bit_depth: info.bit_depth, - }) -} - -/// Most extent visits heic-rs may spend reconstructing the primary image's coded items; real -/// files need one per tile (plus a few for the rare derived item). -const MAX_ITEM_VISITS: usize = 4096; -/// Deepest chain of items built from items we follow (heic-rs refuses beyond eight itself). -const MAX_ITEM_CHAIN: u32 = 8; - -/// Adds to `visits` the extents heic-rs would read to reconstruct `id`, following items built -/// from other items, and fails once that passes [`MAX_ITEM_VISITS`] or the chain is too deep. -fn item_visits(ctx: &Context<'_>, id: u32, depth: u32, visits: &mut usize) -> Result<(), Error> { - use heic_rs::meta::iloc::Construction; - if depth > MAX_ITEM_CHAIN { - return Err(Error::Limit(format!("items built from items nest deeper than {MAX_ITEM_CHAIN} levels"))); - } - let Some(loc) = ctx.meta.location(id) else { return Ok(()) }; - *visits = visits.saturating_add(loc.extents.len().max(1)); - if *visits > MAX_ITEM_VISITS { - return Err(Error::Limit(format!("reconstructing the image takes over {MAX_ITEM_VISITS} item extent reads"))); - } - if loc.construction == Construction::Item { - for e in &loc.extents { - if let Ok(source) = u32::try_from(e.index) - && source != id - { - item_visits(ctx, source, depth + 1, visits)?; - } - } - } - Ok(()) -} - -/// Decodes the primary image, with its metadata. -pub fn decode(bytes: &[u8], options: &Options) -> Result { - guarded(|| decode_unguarded(bytes, options)) -} - -/// Decodes the smallest thumbnail image the file carries whose long edge is at least -/// `min_edge`, if any (iPhones store one of about 320 × 240). Transforms are applied as for the -/// primary image; the metadata (and, when the thumbnail has no profile of its own, the ICC -/// profile) are the primary image's. -pub fn decode_thumbnail(bytes: &[u8], min_edge: u32, options: &Options) -> Result, Error> { - guarded(|| { - let ctx = Context::open(bytes).map_err(err)?; - let primary = ctx.meta.primary; - let mut best: Option<(u32, u32)> = None; - // A thumbnail whose own reconstruction would cost too much is not a candidate; the visits - // of all the candidates share one budget. - let mut candidate_visits = 0_usize; - for r in ctx.meta.refs.iter().filter(|r| r.kind == heic_rs::meta::iref::RefKind::Thmb && r.to.contains(&primary)) { - if item_visits(&ctx, r.from, 0, &mut candidate_visits).is_err() { - continue; - } - let Ok(p) = ctx.props(r.from) else { continue }; - if check_item_parameter_sets(&p).is_err() { - continue; - } - // A grid whose tile would fail the same check must not win and then fail in - // `decode_item`, with no fallback to a larger valid thumbnail. - let grid = match ctx.grid(r.from) { - Ok(grid) => grid, - // an unreadable grid fails in `decode_item` too: not a candidate - Err(_) => continue, - }; - if let Some((_, tiles)) = grid { - let mut seen = std::collections::HashSet::new(); - let tiles_ok = tiles.iter().filter(|t| seen.insert(**t)).all(|&t| { - item_visits(&ctx, t, 0, &mut candidate_visits).is_ok() && ctx.props(t).is_ok_and(|tp| check_item_parameter_sets(&tp).is_ok()) - }); - if !tiles_ok { - continue; - } - } - let Ok((w, h)) = ctx.coded_size(r.from, &p) else { continue }; - let edge = w.max(h); - if edge >= min_edge && best.is_none_or(|(_, e)| edge < e) { - best = Some((r.from, edge)); - } - } - let Some((id, _)) = best else { return Ok(None) }; - // The same pre-scan as `probe`: the thumbnail's own descriptor and every tile reference - // are counted before heic-rs rebuilds any of them. - let mut visits = 0_usize; - item_visits(&ctx, id, 0, &mut visits)?; - if let Some((_, tiles)) = ctx.grid(id).map_err(err)? { - for &tile in &tiles { - item_visits(&ctx, tile, 0, &mut visits)?; - } - } - let mut decoded = decode_item(&ctx, id, options, false)?; - if decoded.icc.is_none() { - decoded.icc = item_icc(&ctx, primary); - } - (decoded.exif, decoded.xmp) = metadata(&ctx); - Ok(Some(decoded)) - }) -} - -/// An item's ICC profile; a grid whose own properties carry none takes its first tile's (as on -/// some iPhones). -fn item_icc(ctx: &Context<'_>, id: u32) -> Option> { - let p = ctx.props(id).ok()?; - let icc = p.icc.or_else(|| { - let (_, tiles) = ctx.grid(id).ok()??; - ctx.props(*tiles.first()?).ok()?.icc - }); - icc.map(<[u8]>::to_vec) -} - -fn decode_unguarded(bytes: &[u8], options: &Options) -> Result { - // Refuses sequences with a clear message before anything else is read. - probe_unguarded(bytes)?; - let ctx = Context::open(bytes).map_err(err)?; - let mut decoded = decode_item(&ctx, ctx.meta.primary, options, true)?; - let (exif, xmp) = metadata(&ctx); - decoded.exif = exif; - decoded.xmp = xmp; - Ok(decoded) -} - -/// Decodes one image item (a coded picture or a grid of them) to RGB(A), alpha included when -/// `with_alpha` and the item has an alpha auxiliary image. -fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool) -> Result { - let p = ctx.props(id).map_err(err)?; - // heic-rs 0.1.4 keeps every associated transform and its [`orient::apply`] allocates the - // full picture again for each: a file could chain the repetition and multiply decode CPU - // without changing any checked size. Real files carry at most one `clap`, `irot` and - // `imir`, so refuse anything approaching [`MAX_TRANSFORMS`] (CodeRabbit #44). - if p.transforms.len() > MAX_TRANSFORMS { - return Err(Error::Limit(format!("the image carries {} transform properties, over the {MAX_TRANSFORMS}-property cap", p.transforms.len()))); - } - let limit = options.max_pixels; - // The declared sizes are refused before anything is decoded or allocated (an item without - // `ispe` takes its size from its parameter sets, checked first). - check_item_parameter_sets(&p)?; - let (cw, ch) = ctx.coded_size(id, &p).map_err(err)?; - heic_rs::image::check_pixels(cw, ch, limit).map_err(err)?; - let (tw, th) = heic_rs::transform::transformed_size(cw, ch, &p.transforms).map_err(err)?; - heic_rs::image::check_pixels(tw, th, limit).map_err(err)?; - - let coded = Coded::decode(ctx, id, &p, limit)?; - let planes = coded.planes()?; - let colour = colour(&p, &coded.first_props); - let signal = ycc::Signal { matrix: colour.matrix, full_range: colour.full_range }; - let alpha_id = if with_alpha { ctx.alpha_item(id).map_err(err)? } else { None }; - let (w, h) = planes.size(); - // A grid's canvas dimensions come from its payload, not the checked `ispe` (CodeRabbit - // #48): check the real one, before [`ycc::to_rgb16`] allocates for it. - match (u32::try_from(w), u32::try_from(h)) { - (Ok(wu), Ok(hu)) => { - heic_rs::image::check_pixels(wu, hu, limit).map_err(err)?; - } - _ => return Err(Error::Limit(format!("the image canvas is {w}x{h}, beyond the {limit}-pixel limit"))), - } - let mode = if options.apply_transforms && orient::odd_crop(w, h, &p.transforms)? { ycc::Upsampling::Bilinear } else { ycc::Upsampling::Nearest }; - let mut data = ycc::to_rgb16(&planes, signal, alpha_id.is_some(), mode) - .ok_or_else(|| Error::Malformed("the decoded pictures don't cover the image".into()))?; - if let Some(aux) = alpha_id { - let ap = ctx.props(aux).map_err(err)?; - let alpha = Coded::decode(ctx, aux, &ap, limit)?; - let alpha_planes = alpha.planes()?; - if alpha_planes.size() != (w, h) { - return Err(Error::Unsupported("an alpha image of a different size than the picture")); - } - ycc::put_alpha(&alpha_planes, &mut data).ok_or_else(|| Error::Malformed("the alpha image is incomplete".into()))?; - } - let bit_depth = planes.bit_depth(); - let has_alpha = alpha_id.is_some(); - let mut img = orient::Pixels { width: w, height: h, ch: if has_alpha { 4 } else { 3 }, data }; - if options.apply_transforms { - img = orient::apply(img, &p.transforms)?; - } - Ok(Decoded { - width: u32::try_from(img.width).map_err(|_| Error::Limit("image too wide".into()))?, - height: u32::try_from(img.height).map_err(|_| Error::Limit("image too tall".into()))?, - has_alpha, - bit_depth, - data: img.data, - colour, - // A grid whose own properties carry no profile takes its tiles' (as on some iPhones). - icc: p.icc.or(coded.first_props.icc).map(<[u8]>::to_vec), - exif: None, - xmp: None, - }) -} - -/// How many times `max_pixels` the coded pictures of one item may hold together: a grid's tiles -/// cover its canvas rounded up to whole tiles, so legitimate grids sit near 1. -const GRID_BUDGET: u64 = 2; - -/// The most transform properties (`clap`/`irot`/`imir`) one item may carry. Real files have at -/// most one of each, so anything approaching this is a reordered or hostile association list. -const MAX_TRANSFORMS: usize = 12; - -/// The most parameter sets one `hvcC` may carry: one per id H.265 allows (16 VPS, 16 SPS, 64 PPS). -/// heic-rs 0.1.4 replaces a repeated id by scanning every set kept so far, so more sets (repeats, -/// or ids past the standard's range) only make that collection quadratic. -const MAX_PARAMETER_SETS: usize = 16 + 16 + 64; -/// Highest `pps_pic_parameter_set_id` H.265 allows (7.4.3.3.1). -const MAX_PPS_ID: u32 = 63; -/// Most tile columns and rows a picture may have: H.265's level limits (Table A.8, levels 6 to -/// 6.2). heic-rs 0.1.4 builds its tile tables by walking the tile boundaries for every coding tree -/// block, so its work grows with blocks × tiles; these keep that a small multiple of the blocks. -const MAX_TILE_COLS: u32 = 20; -const MAX_TILE_ROWS: u32 = 22; - -/// Refuses parameter sets that would make heic-rs's set collection or tile tables cost far more -/// than the picture: too many sets, a PPS id out of range, or more tiles than any level allows. -fn check_parameter_sets(sets: &[&[u8]]) -> Result<(), Error> { - if sets.len() > MAX_PARAMETER_SETS { - return Err(Error::Limit(format!("the hvcC record carries {} parameter sets, over the {MAX_PARAMETER_SETS}-set cap", sets.len()))); - } - let layouts = vui::pps_layouts(sets).ok_or_else(|| Error::Malformed("unreadable picture parameter set".into()))?; - for p in layouts { - if p.id > MAX_PPS_ID { - return Err(Error::Malformed(format!("picture parameter set id {} is out of range", p.id))); - } - if p.tile_cols > MAX_TILE_COLS || p.tile_rows > MAX_TILE_ROWS { - return Err(Error::Limit(format!( - "a picture of {} × {} tiles, over the {MAX_TILE_COLS} × {MAX_TILE_ROWS} H.265 allows", - p.tile_cols, p.tile_rows - ))); - } - } - Ok(()) -} - -/// [`check_parameter_sets`] of a coded item's `hvcC`, if it has one. -fn check_item_parameter_sets(p: &ItemProps<'_>) -> Result<(), Error> { - p.hvcc.as_ref().map_or(Ok(()), |h| check_parameter_sets(&h.parameter_sets())) -} - -/// The decoded pictures of an item: one, or a grid's tiles in `dimg` order. -struct Coded<'a> { - frames: Vec, - grid: Option, - /// The properties of the first coded picture (the item itself, or the first tile): where the - /// HEVC configuration and its VUI live. - first_props: ItemProps<'a>, - /// A failed 4:2:2 / 4:4:4 picture, for the error message. - chroma_format: u8, -} - -impl<'a> Coded<'a> { - fn decode(ctx: &Context<'a>, id: u32, p: &ItemProps<'a>, limit: u64) -> Result, Error> { - let (grid, ids) = match ctx.grid(id).map_err(err)? { - Some((g, tiles)) => (Some(g), tiles), - None => (None, vec![id]), - }; - let first = *ids.first().ok_or_else(|| Error::Malformed("grid lists no tiles".into()))?; - let first_props = if first == id { p.clone() } else { ctx.props(first).map_err(err)? }; - let chroma_format = first_props.hvcc.as_ref().map_or(1, |c| c.chroma_format); - // #1518: the decoder allocates each picture at its SPS's uncropped size, which a - // conformance window (or a slice picking another SPS) can make far larger than the - // declared one, and a grid holds all its tiles at once. Both are refused before decoding. - let mut total = 0u64; - // A grid may list one tile thousands of times: each distinct tile is read and checked - // once, so the work follows the file's items, not the grid's cell count. - let mut largest_of: std::collections::HashMap = std::collections::HashMap::new(); - for t in &ids { - if let Some(largest) = largest_of.get(t) { - total = total.saturating_add(*largest); - continue; - } - let tp = ctx.props(*t).map_err(err)?; - let hvcc = tp.hvcc.as_ref().ok_or(heic_rs::Error::MissingBox("hvcC")).map_err(err)?; - check_parameter_sets(&hvcc.parameter_sets())?; - let sizes = vui::coded_sizes(&hvcc.parameter_sets()).ok_or_else(|| Error::Malformed("unreadable sequence parameter set".into()))?; - let mut largest = 0u64; - for (w, h) in sizes { - heic_rs::image::check_pixels(w, h, limit).map_err(err)?; - largest = largest.max(u64::from(w) * u64::from(h)); - } - largest_of.insert(*t, largest); - total = total.saturating_add(largest); - } - if total > limit.saturating_mul(GRID_BUDGET) { - return Err(Error::Limit(format!("the coded pictures hold {total} pixels, over the {limit}-pixel limit"))); - } - let decode_one = |t: &u32| -> Result { - let tp = ctx.props(*t).map_err(err)?; - let hvcc = tp.hvcc.as_ref().ok_or(heic_rs::Error::MissingBox("hvcC")).map_err(err)?; - let data = ctx.item_data(*t).map_err(err)?; - let nals = hvcc.split_nals(&data).map_err(err)?; - let params = hvcc.parameter_sets(); - if params.is_empty() { - return Err(Error::Malformed("hvcC carries no parameter sets".into())); - } - let frame = heic_rs::hevc::decode_still(¶ms, &nals).map_err(err)?; - frame.validate().map_err(err)?; - heic_rs::image::check_pixels(frame.width, frame.height, limit).map_err(err)?; - Ok(frame) - }; - #[cfg(not(target_arch = "wasm32"))] - let frames: Result, Error> = { - use rayon::prelude::*; - ids.par_iter().map(decode_one).collect() - }; - #[cfg(target_arch = "wasm32")] - let frames: Result, Error> = ids.iter().map(decode_one).collect(); - let frames = frames.map_err(|e| match e { - Error::Malformed(_) if chroma_format >= 2 => Error::Unsupported(CHROMA_422_444), - e => e, - })?; - Ok(Coded { frames, grid, first_props, chroma_format }) - } - - fn planes(&self) -> Result, Error> { - match (&self.grid, self.frames.as_slice()) { - (Some(g), tiles) => heic_rs::grid::Mosaic::new(g, tiles).map(ycc::Planes::Grid).map_err(err), - (None, [frame]) => Ok(ycc::Planes::Picture(frame)), - (None, _) => Err(Error::Malformed(format!("expected one coded picture (chroma format {})", self.chroma_format))), - } - } -} - -/// The colour description in force: `nclx` on the item (or, for a grid without one, on its -/// first tile), else the VUI of its (first) coded picture, else the H.265 defaults. -fn colour(p: &ItemProps<'_>, coded: &ItemProps<'_>) -> Colour { - if let Some(n) = p.nclx.or(coded.nclx) { - return Colour { primaries: n.primaries, transfer: n.transfer, matrix: n.matrix_code, full_range: n.range == Range::Full }; - } - let s = coded.hvcc.as_ref().and_then(|c| vui::signal(&c.parameter_sets())).unwrap_or_default(); - Colour { primaries: s.primaries.into(), transfer: s.transfer.into(), matrix: s.matrix.into(), full_range: s.full_range } -} - -/// The primary image's EXIF (TIFF structure) and XMP packet. Metadata is a courtesy: a broken -/// metadata item never fails a decode whose pixels came out fine. -fn metadata(ctx: &Context<'_>) -> (Option>, Option) { - let id = ctx.meta.primary; - // Metadata is best effort, so an item that would cost too much to rebuild is skipped, not an error. - let mut visits = 0_usize; - let cheap = |item: Option, visits: &mut usize| item.is_none_or(|item| item_visits(ctx, item, 0, visits).is_ok()); - let exif = if cheap(ctx.exif_item(id), &mut visits) { ctx.exif(id).ok().flatten().map(<[u8]>::to_vec) } else { None }; - let xmp_item = ctx.xmp_item(id).filter(|&x| cheap(Some(x), &mut visits)); - let xmp = xmp_item.and_then(|x| ctx.item_data(x).ok()).and_then(|d| match d { - Cow::Borrowed(b) => String::from_utf8(b.to_vec()).ok(), - Cow::Owned(b) => String::from_utf8(b).ok(), - }); - (exif, xmp.map(|x| x.trim_end_matches('\0').to_string())) -} - -#[cfg(test)] -mod tests_synthetic; - -#[cfg(test)] -mod tests { - use super::*; - - /// Found by PhotoCraft's `decode_heif` fuzz target: a malformed box makes heic-rs 0.1.1 slice - /// out of range (`boxes.rs:130`). It must be an error, not a crash. - const HEIC_RS_BOX_PANIC: [u8; 72] = [ - 0x00, 0x00, 0x00, 0x24, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x69, 0x66, 0x31, 0x4d, 0x69, 0x50, - 0x72, 0x6d, 0x69, 0x61, 0x66, 0x4d, 0x69, 0x48, 0x42, 0x72, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x65, 0x74, 0x61, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x75, 0x75, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x03, 0x08, 0x08, 0x08, 0x00, 0x03, 0x01, 0x03, 0x70, - 0x00, 0xa8, 0x00, - ]; - - #[test] - fn a_heic_rs_panic_is_a_malformed_error() { - for apply_transforms in [true, false] { - let r = decode(&HEIC_RS_BOX_PANIC, &Options { apply_transforms, ..Default::default() }); - assert!(matches!(r, Err(Error::Malformed(_))), "{r:?}"); - } - } - - #[test] - fn image_sequence_is_unsupported_with_a_clear_message() { - // An ftyp and nothing else: a HEIF image sequence would have a moov here instead of a meta. - let bytes = b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc"; - for r in [probe(bytes).map(|_| ()), decode(bytes, &Options::default()).map(|_| ())] { - assert!(matches!(&r, Err(Error::Unsupported(m)) if m.contains("sequence")), "{r:?}"); - } - } - - #[test] - fn garbage_is_an_error() { - for bytes in [&b""[..], b"\0\0\0\x18ftypheic\0\0\0\0mif1heic", &[0xFF; 64]] { - assert!(probe(bytes).is_err()); - assert!(decode(bytes, &Options::default()).is_err()); - assert!(decode_thumbnail(bytes, 1, &Options::default()).is_err()); - } - } - - #[test] - fn errors_display_their_kind() { - assert!(Error::Unsupported("x").to_string().contains("unsupported")); - assert!(Error::Limit("x".into()).to_string().contains("limit")); - assert!(Error::Malformed("x".into()).to_string().contains("malformed")); - } -} diff --git a/crates/heif/src/orient.rs b/crates/heif/src/orient.rs deleted file mode 100644 index 487eb7e220..0000000000 --- a/crates/heif/src/orient.rs +++ /dev/null @@ -1,178 +0,0 @@ -//! The container's transformative properties (`clap` crop, `irot` rotation, `imir` mirror), -//! applied to interleaved 16-bit pixels in the order the file associates them. -//! -//! `imir` follows libheif, which writes and reads `axis = 0` as a flip about the horizontal axis -//! (top and bottom exchanged) and `axis = 1` as a left-right flip. heic-rs 0.1.1 names the coded -//! values the other way round (`Mirror::LeftRight` is `axis = 0`), so they are swapped here. - -use heic_rs::props::Transform; -use heic_rs::props::simple::{Clap, Mirror, Rotation}; - -use crate::Error; - -/// Interleaved samples, `ch` per pixel, row-major. -pub struct Pixels { - pub width: usize, - pub height: usize, - pub ch: usize, - pub data: Vec, -} - -impl Pixels { - fn remap(&self, width: usize, height: usize, src: impl Fn(usize, usize) -> (usize, usize)) -> Pixels { - let ch = self.ch; - let mut data = vec![0u16; width * height * ch]; - for (y, row) in data.chunks_exact_mut(width * ch).enumerate() { - for (x, px) in row.chunks_exact_mut(ch).enumerate() { - let (sx, sy) = src(x, y); - let i = (sy * self.width + sx) * ch; - if let Some(s) = self.data.get(i..i + ch) { - px.copy_from_slice(s); - } - } - } - Pixels { width, height, ch, data } - } -} - -/// The rectangle `(left, top, width, height)` a `clap` selects from a `w` × `h` image. Its centre -/// is `((w - 1) / 2 + horizOff, (h - 1) / 2 + vertOff)`; a corner that falls between two pixels -/// is rounded as libheif does: left down, top up. -pub fn crop_rect(w: usize, h: usize, c: Clap) -> Result<(usize, usize, usize, usize), Error> { - let bad = || Error::Malformed("clap selects an impossible rectangle".into()); - let size = |(n, d): (u32, u32)| (d != 0).then(|| n / d).ok_or_else(bad); - let (cw, ch) = (size(c.width)? as usize, size(c.height)? as usize); - if cw == 0 || ch == 0 || cw > w || ch > h { - return Err(bad()); - } - // Twice the corner, so the half pixels of odd sizes stay exact. - let twice = |full: usize, cropped: usize, (n, d): (i32, u32)| -> Result { - if d == 0 { - return Err(bad()); - } - Ok((full - cropped) as i64 + (2 * i64::from(n)).div_euclid(i64::from(d))) - }; - let left = twice(w, cw, c.horiz_off)?.div_euclid(2); - let top = (twice(h, ch, c.vert_off)? + 1).div_euclid(2); - let left = usize::try_from(left).map_err(|_| bad())?; - let top = usize::try_from(top).map_err(|_| bad())?; - if left + cw > w || top + ch > h { - return Err(bad()); - } - Ok((left, top, cw, ch)) -} - -/// Whether a `clap` among `transforms` (applied to a `w` × `h` image) starts at an odd column -/// or row. libheif crops such images after upsampling their chroma bilinearly instead of with -/// its default nearest neighbour; [`crate::ycc`] follows it so the pixels match. -pub fn odd_crop(mut w: usize, mut h: usize, transforms: &[Transform]) -> Result { - for t in transforms { - match *t { - Transform::Crop(c) => { - let (left, top, cw, ch) = crop_rect(w, h, c)?; - if left % 2 == 1 || top % 2 == 1 { - return Ok(true); - } - (w, h) = (cw, ch); - } - Transform::Rotate(Rotation::Ccw90 | Rotation::Ccw270) => (w, h) = (h, w), - _ => {} - } - } - Ok(false) -} - -pub fn apply(mut img: Pixels, transforms: &[Transform]) -> Result { - for t in transforms { - let (w, h) = (img.width, img.height); - img = match *t { - Transform::Crop(c) => { - let (left, top, cw, ch) = crop_rect(w, h, c)?; - img.remap(cw, ch, |x, y| (x + left, y + top)) - } - // Counter-clockwise: the right column becomes the top row. - Transform::Rotate(Rotation::Ccw90) => img.remap(h, w, |x, y| (w - 1 - y, x)), - Transform::Rotate(Rotation::Ccw180) => img.remap(w, h, |x, y| (w - 1 - x, h - 1 - y)), - Transform::Rotate(Rotation::Ccw270) => img.remap(h, w, |x, y| (y, h - 1 - x)), - Transform::Rotate(Rotation::None) => img, - // `axis = 0` (heic-rs's `LeftRight`): top and bottom exchanged, as libheif reads it. - Transform::Mirror(Mirror::LeftRight) => img.remap(w, h, |x, y| (x, h - 1 - y)), - // `axis = 1`: left and right exchanged. - Transform::Mirror(Mirror::TopBottom) => img.remap(w, h, |x, y| (w - 1 - x, y)), - }; - } - Ok(img) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// 3×2, one channel: 1 2 3 / 4 5 6. - fn img() -> Pixels { - Pixels { width: 3, height: 2, ch: 1, data: vec![1, 2, 3, 4, 5, 6] } - } - - fn run(t: Transform) -> (usize, usize, Vec) { - let p = apply(img(), &[t]).unwrap(); - (p.width, p.height, p.data) - } - - #[test] - fn rotations_are_counter_clockwise() { - assert_eq!(run(Transform::Rotate(Rotation::Ccw90)), (2, 3, vec![3, 6, 2, 5, 1, 4])); - assert_eq!(run(Transform::Rotate(Rotation::Ccw180)), (3, 2, vec![6, 5, 4, 3, 2, 1])); - assert_eq!(run(Transform::Rotate(Rotation::Ccw270)), (2, 3, vec![4, 1, 5, 2, 6, 3])); - assert_eq!(run(Transform::Rotate(Rotation::None)), (3, 2, vec![1, 2, 3, 4, 5, 6])); - } - - #[test] - fn mirrors_follow_libheif() { - // axis 0 (heic-rs `LeftRight`) exchanges top and bottom; axis 1 left and right. - assert_eq!(run(Transform::Mirror(Mirror::LeftRight)), (3, 2, vec![4, 5, 6, 1, 2, 3])); - assert_eq!(run(Transform::Mirror(Mirror::TopBottom)), (3, 2, vec![3, 2, 1, 6, 5, 4])); - } - - fn clap(w: u32, h: u32, ho: i32, vo: i32) -> Clap { - Clap { width: (w, 1), height: (h, 1), horiz_off: (ho, 1), vert_off: (vo, 1) } - } - - #[test] - fn clap_corners_round_like_libheif() { - // Measured against libheif 1.23 on a 512 × 512 picture. - assert_eq!(crop_rect(512, 512, clap(301, 201, 0, 0)).unwrap(), (105, 156, 301, 201)); - assert_eq!(crop_rect(512, 512, clap(300, 200, 0, 0)).unwrap(), (106, 156, 300, 200)); - assert_eq!(crop_rect(512, 512, clap(301, 201, 37, -21)).unwrap(), (142, 135, 301, 201)); - assert_eq!(crop_rect(512, 512, clap(301, 201, -3, 5)).unwrap(), (102, 161, 301, 201)); - assert_eq!(crop_rect(512, 512, clap(300, 201, 0, 0)).unwrap(), (106, 156, 300, 201)); - assert_eq!(crop_rect(1500, 1000, clap(1001, 701, 37, -21)).unwrap(), (286, 129, 1001, 701)); - let p = apply(img(), &[Transform::Crop(clap(2, 1, 1, 0))]).unwrap(); - // The half-pixel top rounds down a row. - assert_eq!((p.width, p.height, p.data), (2, 1, vec![5, 6])); - } - - #[test] - fn impossible_claps_are_errors() { - for c in [ - clap(0, 1, 0, 0), - clap(4, 1, 0, 0), - clap(3, 2, 1, 0), - clap(3, 2, 0, -1), - Clap { width: (1, 0), ..clap(1, 1, 0, 0) }, - Clap { horiz_off: (0, 0), ..clap(1, 1, 0, 0) }, - ] { - assert!(crop_rect(3, 2, c).is_err(), "{c:?}"); - } - assert!(apply(img(), &[Transform::Crop(clap(9, 9, 0, 0))]).is_err()); - } - - #[test] - fn odd_crops_are_detected_through_rotations() { - assert!(!odd_crop(512, 512, &[Transform::Crop(clap(300, 200, 0, 0))]).unwrap()); - assert!(odd_crop(512, 512, &[Transform::Crop(clap(301, 200, 0, 0))]).unwrap()); - // After a quarter turn the crop applies to a 200 × 300 image. - let t = [Transform::Crop(clap(300, 200, 0, 0)), Transform::Rotate(Rotation::Ccw90), Transform::Crop(clap(197, 300, 0, 0))]; - assert!(odd_crop(512, 512, &t).unwrap()); - assert!(!odd_crop(512, 512, &[Transform::Rotate(Rotation::Ccw90)]).unwrap()); - } -} diff --git a/crates/heif/src/testdata.rs b/crates/heif/src/testdata.rs deleted file mode 100644 index bd8945cabd..0000000000 --- a/crates/heif/src/testdata.rs +++ /dev/null @@ -1,569 +0,0 @@ -//! Synthetic HEIF files for tests (feature `testdata`): lossless, so every decoded sample is known. -//! -//! Each coded picture is one 32 × 32 coding tree unit stored as PCM samples (H.265 7.3.8.7): -//! the bitstream carries the YCbCr values verbatim, so the decoder's HEVC stage reproduces them -//! exactly and a test checks everything after it (grid composition, colour, transforms, -//! metadata) against values it chose. The few CABAC bins around the PCM data are written with a -//! minimal arithmetic encoder (9.3.4.4). Larger images are grids of such pictures, which is how -//! iPhones store photos too (with 512 × 512 tiles). -//! -//! Not a general HEIF or HEVC writer: 4:2:0 or monochrome, 8 or 10 bits, a CTU per picture. - -/// Side of every coded picture. -pub const TILE: u32 = 32; - -/// YCbCr samples at a luma position (chroma is taken at even positions, 4:2:0). -pub type Sampler<'a> = &'a dyn Fn(u32, u32) -> [u16; 3]; - -/// A property of the primary image. -#[derive(Debug, Clone, PartialEq)] -pub enum Prop { - /// `colr` of type `prof`. - Icc(Vec), - /// `colr` of type `nclx`: primaries, transfer, matrix, full range. - Nclx(u16, u16, u16, bool), - /// `irot`: quarter turns counter-clockwise. - Irot(u8), - /// `imir` with this axis. - Imir(u8), - /// `clap`: width, height, horizontal and vertical offset (whole pixels). - Clap(u32, u32, i32, i32), -} - -/// What [`build`] writes. -pub struct Spec<'a> { - /// Displayed (grid output) size, before transforms. - pub width: u32, - pub height: u32, - pub bit_depth: u8, - pub sample: Sampler<'a>, - /// Properties of the primary image, in association order. - pub props: Vec, - /// EXIF as a TIFF structure (written with HEIF's 4-byte offset header). - pub exif: Option>, - /// An alpha auxiliary image (monochrome, full range). - pub alpha: Option<&'a dyn Fn(u32, u32) -> u16>, - /// A thumbnail item of half the size with these samples (in its own coordinates). - pub thumbnail: Option>, - /// Auxiliary images of these types the decoder must ignore (HDR gain map, depth…). - pub ignored_aux: Vec<&'static str>, - /// When nonzero, the alpha image is instead a grid of `n` × `n` references to one alpha tile - /// (a hostile file: the same stored picture rebuilt for every reference). - pub alpha_tile_repeats: u8, -} - -impl<'a> Spec<'a> { - pub fn new(width: u32, height: u32, sample: Sampler<'a>) -> Spec<'a> { - Spec { - width, - height, - bit_depth: 8, - sample, - props: Vec::new(), - exif: None, - alpha: None, - thumbnail: None, - ignored_aux: Vec::new(), - alpha_tile_repeats: 0, - } - } -} - -#[derive(Default)] -struct Bits { - bytes: Vec, - n: usize, -} - -impl Bits { - fn put(&mut self, v: u32, len: u32) { - for i in (0..len).rev() { - if self.n.is_multiple_of(8) { - self.bytes.push(0); - } - if (v >> i) & 1 == 1 - && let Some(b) = self.bytes.last_mut() - { - *b |= 0x80 >> (self.n % 8); - } - self.n += 1; - } - } - - fn ue(&mut self, v: u32) { - let x = u64::from(v) + 1; - let len = 64 - x.leading_zeros(); - self.put(0, len - 1); - self.put((x & 0xffff_ffff) as u32, len); - } - - fn align_zero(&mut self) { - while !self.n.is_multiple_of(8) { - self.put(0, 1); - } - } - - fn trailing(&mut self) { - self.put(1, 1); - self.align_zero(); - } -} - -/// The CABAC arithmetic encoder of H.265 9.3.4.4, for the bins these pictures need. -struct Cabac { - low: u32, - range: u32, - first: bool, - outstanding: u32, -} - -impl Cabac { - fn new() -> Cabac { - Cabac { low: 0, range: 510, first: true, outstanding: 0 } - } - - fn put_bit(&mut self, out: &mut Bits, b: u32) { - if self.first { - self.first = false; - } else { - out.put(b, 1); - } - while self.outstanding > 0 { - out.put(1 - b, 1); - self.outstanding -= 1; - } - } - - fn renorm(&mut self, out: &mut Bits) { - while self.range < 256 { - if self.low < 256 { - self.put_bit(out, 0); - } else if self.low >= 512 { - self.low -= 512; - self.put_bit(out, 1); - } else { - self.low -= 256; - self.outstanding += 1; - } - self.range <<= 1; - self.low <<= 1; - } - } - - /// `part_mode` = PART_2Nx2N: the most probable symbol of a fresh context (initValue 184 at - /// QP 26 gives pStateIdx 0, valMps 1), so the LPS range is `rangeTabLps[0][3]` = 240. - fn part_mode_2nx2n(&mut self, out: &mut Bits) { - let lps = [128, 176, 208, 240][((self.range >> 6) & 3) as usize]; - self.range -= lps; - self.renorm(out); - } - - /// A terminating bin equal to 1 (`pcm_flag`, `end_of_slice_segment_flag`), with the flush. - fn terminate_one(&mut self, out: &mut Bits) { - self.range -= 2; - self.low += self.range; - self.range = 2; - self.renorm(out); - self.put_bit(out, (self.low >> 9) & 1); - out.put(((self.low >> 7) & 3) | 1, 2); - } -} - -fn nal(kind: u8, rbsp: &[u8]) -> Vec { - let mut out = vec![kind << 1, 1]; - let mut zeros = 0; - for &b in rbsp { - if zeros >= 2 && b <= 3 { - out.push(3); - zeros = 0; - } - zeros = if b == 0 { zeros + 1 } else { 0 }; - out.push(b); - } - out -} - -fn profile_idc(bit_depth: u8, mono: bool) -> u32 { - match (bit_depth, mono) { - (_, true) => 4, // range extensions - (8, false) => 1, - _ => 2, - } -} - -fn ptl(w: &mut Bits, idc: u32) { - w.put(0, 2); - w.put(0, 1); - w.put(idc, 5); - w.put(1 << (31 - idc), 32); // compatible with itself - w.put(0b1001, 4); // progressive, frame only - w.put(0, 22); - w.put(0, 21); - w.put(0, 1); - w.put(93, 8); // level 3.1 -} - -fn parameter_sets(bit_depth: u8, mono: bool) -> [Vec; 3] { - let idc = profile_idc(bit_depth, mono); - let bd = u32::from(bit_depth); - let mut v = Bits::default(); - v.put(0, 4); - v.put(3, 2); - v.put(0, 6); - v.put(0, 3); - v.put(1, 1); - v.put(0xffff, 16); - ptl(&mut v, idc); - v.put(0, 1); // vps_sub_layer_ordering_info_present_flag - v.ue(0); - v.ue(0); - v.ue(0); - v.put(0, 6); // vps_max_layer_id - v.ue(0); // vps_num_layer_sets_minus1 - v.put(0, 1); // vps_timing_info_present_flag - v.put(0, 1); // vps_extension_flag - v.trailing(); - - let mut s = Bits::default(); - s.put(0, 4); - s.put(0, 3); - s.put(1, 1); - ptl(&mut s, idc); - s.ue(0); - s.ue(if mono { 0 } else { 1 }); - s.ue(TILE); - s.ue(TILE); - s.put(0, 1); // conformance_window_flag - s.ue(bd - 8); - s.ue(bd - 8); - s.ue(4); - s.put(1, 1); - s.ue(0); - s.ue(0); - s.ue(0); - s.ue(2); // log2_min_luma_coding_block_size_minus3: 32 - s.ue(0); // log2_diff_max_min_luma_coding_block_size: CTB 32 - s.ue(0); // log2_min_luma_transform_block_size_minus2: 4 - s.ue(3); // log2_diff_max_min_luma_transform_block_size: 32 - s.ue(0); - s.ue(0); - s.put(0, 1); // scaling_list_enabled_flag - s.put(0, 1); // amp_enabled_flag - s.put(0, 1); // sample_adaptive_offset_enabled_flag - s.put(1, 1); // pcm_enabled_flag - s.put(bd - 1, 4); // pcm_sample_bit_depth_luma_minus1 - s.put(bd - 1, 4); // pcm_sample_bit_depth_chroma_minus1 - s.ue(2); // log2_min_pcm_luma_coding_block_size_minus3: 32 - s.ue(0); // log2_diff_max_min_pcm_luma_coding_block_size - s.put(1, 1); // pcm_loop_filter_disabled_flag - s.ue(0); // num_short_term_ref_pic_sets - s.put(0, 1); // long_term_ref_pics_present_flag - s.put(0, 1); // sps_temporal_mvp_enabled_flag - s.put(0, 1); // strong_intra_smoothing_enabled_flag - s.put(0, 1); // vui_parameters_present_flag - s.put(0, 1); // sps_extension_present_flag - s.trailing(); - - let mut p = Bits::default(); - p.ue(0); - p.ue(0); - p.put(0, 6); // dependent slices, output flag, 3 extra header bits, sign hiding - p.put(0, 1); // cabac_init_present_flag - p.ue(0); - p.ue(0); - p.ue(0); // init_qp_minus26 (se(0) is the same bits) - p.put(0, 3); // constrained intra, transform skip, cu_qp_delta - p.ue(0); - p.ue(0); - p.put(0, 1); - p.put(0, 2); - p.put(0, 1); // transquant_bypass_enabled_flag - p.put(0, 1); // tiles_enabled_flag - p.put(0, 1); // entropy_coding_sync_enabled_flag - p.put(0, 1); // pps_loop_filter_across_slices_enabled_flag - p.put(1, 1); // deblocking_filter_control_present_flag - p.put(0, 1); // deblocking_filter_override_enabled_flag - p.put(1, 1); // pps_deblocking_filter_disabled_flag - p.put(0, 1); - p.put(0, 1); - p.ue(0); - p.put(0, 1); - p.put(0, 1); - p.trailing(); - [nal(32, &v.bytes), nal(33, &s.bytes), nal(34, &p.bytes)] -} - -/// One coded 32 × 32 picture: the `hvcC` payload and the item data (length-prefixed NAL). -struct Coded { - hvcc: Vec, - data: Vec, -} - -fn picture(bit_depth: u8, mono: bool, sample: &dyn Fn(u32, u32) -> [u16; 3]) -> Coded { - let bd = u32::from(bit_depth); - let mut w = Bits::default(); - w.put(1, 1); // first_slice_segment_in_pic_flag - w.put(0, 1); // no_output_of_prior_pics_flag - w.ue(0); - w.ue(2); // I slice - w.ue(0); // slice_qp_delta, se(0) - w.trailing(); // byte_alignment() - let mut c = Cabac::new(); - c.part_mode_2nx2n(&mut w); - c.terminate_one(&mut w); // pcm_flag - w.align_zero(); // pcm_alignment_zero_bit - for y in 0..TILE { - for x in 0..TILE { - w.put(u32::from(sample(x, y)[0]), bd); - } - } - if !mono { - for k in 1..3 { - for y in 0..TILE / 2 { - for x in 0..TILE / 2 { - w.put(u32::from(sample(2 * x, 2 * y)[k]), bd); - } - } - } - } - let mut c = Cabac::new(); - c.terminate_one(&mut w); // end_of_slice_segment_flag (its flush ends in the stop bit) - w.align_zero(); - let slice = nal(19, &w.bytes); - - let sets = parameter_sets(bit_depth, mono); - let mut h = vec![1u8, profile_idc(bit_depth, mono) as u8]; - h.extend_from_slice(&(1u32 << (31 - profile_idc(bit_depth, mono))).to_be_bytes()); - h.extend_from_slice(&[ - 0x90, - 0, - 0, - 0, - 0, - 0, - 93, - 0xf0, - 0, - 0xfc, - 0xfc | u8::from(!mono), - 0xf8 | (bit_depth - 8), - 0xf8 | (bit_depth - 8), - 0, - 0, - 0x0f, - 3, - ]); - for (kind, set) in [32u8, 33, 34].into_iter().zip(&sets) { - h.push(0x80 | kind); - h.extend_from_slice(&1u16.to_be_bytes()); - h.extend_from_slice(&(set.len() as u16).to_be_bytes()); - h.extend_from_slice(set); - } - let mut data = (slice.len() as u32).to_be_bytes().to_vec(); - data.extend_from_slice(&slice); - Coded { hvcc: h, data } -} - -fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { - let mut v = ((payload.len() + 8) as u32).to_be_bytes().to_vec(); - v.extend_from_slice(kind); - v.extend_from_slice(payload); - v -} - -fn full_box(kind: &[u8; 4], version: u8, payload: &[u8]) -> Vec { - let mut p = vec![version, 0, 0, 0]; - p.extend_from_slice(payload); - bx(kind, &p) -} - -struct Item { - id: u16, - kind: &'static [u8; 4], - data: Vec, - /// Indices (1-based) into the property list, with the essential flag. - props: Vec<(u8, bool)>, - /// Not an image of its own (a grid tile). - hidden: bool, -} - -#[derive(Default)] -struct File { - items: Vec, - props: Vec>, - refs: Vec<(&'static [u8; 4], u16, Vec)>, -} - -impl File { - fn prop(&mut self, b: Vec) -> u8 { - self.props.push(b); - self.props.len() as u8 - } - - fn add(&mut self, kind: &'static [u8; 4], data: Vec, props: Vec<(u8, bool)>) -> u16 { - let id = self.items.len() as u16 + 1; - self.items.push(Item { id, kind, data, props, hidden: false }); - id - } - - /// A coded image of `w` × `h` (a grid when larger than a tile); returns its item id. - fn image(&mut self, w: u32, h: u32, bit_depth: u8, mono: bool, sample: &dyn Fn(u32, u32) -> [u16; 3]) -> u16 { - let (cols, rows) = (w.div_ceil(TILE), h.div_ceil(TILE)); - let ispe = |w: u32, h: u32| { - let mut p = w.to_be_bytes().to_vec(); - p.extend_from_slice(&h.to_be_bytes()); - full_box(b"ispe", 0, &p) - }; - let mut hvcc_prop = None; - let tile_ispe = self.prop(ispe(TILE, TILE)); - let mut tiles = Vec::new(); - for r in 0..rows { - for c in 0..cols { - let coded = picture(bit_depth, mono, &|x, y| sample((c * TILE + x).min(w - 1), (r * TILE + y).min(h - 1))); - let hv = *hvcc_prop.get_or_insert_with(|| self.prop(bx(b"hvcC", &coded.hvcc))); - tiles.push(self.add(b"hvc1", coded.data, vec![(hv, true), (tile_ispe, false)])); - } - } - if let ([only], true) = (tiles.as_slice(), w == TILE && h == TILE) { - return *only; - } - for it in self.items.iter_mut().filter(|i| tiles.contains(&i.id)) { - it.hidden = true; - } - let mut g = vec![0u8, 0, (rows - 1) as u8, (cols - 1) as u8]; - g.extend_from_slice(&(w as u16).to_be_bytes()); - g.extend_from_slice(&(h as u16).to_be_bytes()); - let grid_ispe = self.prop(ispe(w, h)); - let id = self.add(b"grid", g, vec![(grid_ispe, false)]); - self.refs.push((b"dimg", id, tiles)); - id - } - - fn write(self, primary: u16) -> Vec { - let ftyp = bx(b"ftyp", b"heic\0\0\0\0mif1heic"); - let mut hdlr = vec![0u8; 4]; - hdlr.extend_from_slice(b"pict"); - hdlr.extend_from_slice(&[0; 13]); - let hdlr = full_box(b"hdlr", 0, &hdlr); - let pitm = full_box(b"pitm", 0, &primary.to_be_bytes()); - let mut iinf = (self.items.len() as u16).to_be_bytes().to_vec(); - for it in &self.items { - let mut e = vec![2, 0, 0, u8::from(it.hidden)]; // version 2, flags - e.extend_from_slice(&it.id.to_be_bytes()); - e.extend_from_slice(&[0, 0]); - e.extend_from_slice(it.kind); - e.push(0); - iinf.extend_from_slice(&bx(b"infe", &e)); - } - let iinf = full_box(b"iinf", 0, &iinf); - let mut iref = Vec::new(); - for (kind, from, to) in &self.refs { - let mut r = from.to_be_bytes().to_vec(); - r.extend_from_slice(&(to.len() as u16).to_be_bytes()); - for t in to { - r.extend_from_slice(&t.to_be_bytes()); - } - iref.extend_from_slice(&bx(kind, &r)); - } - let iref = full_box(b"iref", 0, &iref); - let ipco = bx(b"ipco", &self.props.concat()); - let mut ipma = (self.items.iter().filter(|i| !i.props.is_empty()).count() as u32).to_be_bytes().to_vec(); - for it in self.items.iter().filter(|i| !i.props.is_empty()) { - ipma.extend_from_slice(&it.id.to_be_bytes()); - ipma.push(it.props.len() as u8); - ipma.extend(it.props.iter().map(|&(i, essential)| i | if essential { 0x80 } else { 0 })); - } - let iprp = bx(b"iprp", &[ipco, full_box(b"ipma", 0, &ipma)].concat()); - let iloc = |base: u32| { - let mut l = vec![0x44, 0x00]; - l.extend_from_slice(&(self.items.len() as u16).to_be_bytes()); - let mut offset = base; - for it in &self.items { - l.extend_from_slice(&it.id.to_be_bytes()); - l.extend_from_slice(&[0, 0, 0, 0, 0, 1]); // construction method 0, data ref 0, one extent - l.extend_from_slice(&offset.to_be_bytes()); - l.extend_from_slice(&(it.data.len() as u32).to_be_bytes()); - offset += it.data.len() as u32; - } - full_box(b"iloc", 1, &l) - }; - let meta = |base| full_box(b"meta", 0, &[hdlr.clone(), pitm.clone(), iloc(base), iinf.clone(), iref.clone(), iprp.clone()].concat()); - let start = (ftyp.len() + meta(0).len() + 8) as u32; - let mdat = bx(b"mdat", &self.items.iter().flat_map(|i| i.data.iter().copied()).collect::>()); - [ftyp, meta(start), mdat].concat() - } -} - -/// Writes the HEIF file `spec` describes. -pub fn build(spec: &Spec<'_>) -> Vec { - let mut f = File::default(); - let primary = f.image(spec.width, spec.height, spec.bit_depth, false, spec.sample); - let mut assoc = Vec::new(); - for p in &spec.props { - let b = match p { - Prop::Icc(icc) => bx(b"colr", &[b"prof".as_slice(), icc].concat()), - Prop::Nclx(pr, tc, mc, full) => { - let mut c = b"nclx".to_vec(); - for v in [pr, tc, mc] { - c.extend_from_slice(&v.to_be_bytes()); - } - c.push(if *full { 0x80 } else { 0 }); - bx(b"colr", &c) - } - Prop::Irot(a) => bx(b"irot", &[a & 3]), - Prop::Imir(a) => bx(b"imir", &[a & 1]), - Prop::Clap(w, h, ho, vo) => { - let mut c = Vec::new(); - for v in [*w as i32, 1, *h as i32, 1, *ho, 1, *vo, 1] { - c.extend_from_slice(&v.to_be_bytes()); - } - bx(b"clap", &c) - } - }; - assoc.push((f.prop(b), true, matches!(p, Prop::Clap(..)))); - } - if let Some(it) = f.items.iter_mut().find(|i| i.id == primary) { - it.props.extend(assoc.iter().map(|&(i, e, _)| (i, e))); - } - if let Some(exif) = &spec.exif { - let id = f.add(b"Exif", [&[0u8, 0, 0, 0][..], exif].concat(), Vec::new()); - f.refs.push((b"cdsc", id, vec![primary])); - } - let bd = spec.bit_depth; - let aux = |f: &mut File, urn: &str, sample: &dyn Fn(u32, u32) -> [u16; 3]| { - let id = f.image(spec.width, spec.height, bd, true, sample); - let auxc = f.prop(full_box(b"auxC", 0, &[urn.as_bytes(), &[0]].concat())); - if let Some(it) = f.items.iter_mut().find(|i| i.id == id) { - it.props.push((auxc, true)); - } - f.refs.push((b"auxl", id, vec![primary])); - }; - if let (Some(alpha), n @ 1..) = (spec.alpha, spec.alpha_tile_repeats) { - let tile = f.image(TILE, TILE, bd, true, &|x, y| [alpha(x, y), 0, 0]); - if let Some(it) = f.items.iter_mut().find(|i| i.id == tile) { - it.hidden = true; - } - let side = u32::from(n) * TILE; - let mut g = vec![0u8, 0, n - 1, n - 1]; - g.extend_from_slice(&(side as u16).to_be_bytes()); - g.extend_from_slice(&(side as u16).to_be_bytes()); - let auxc = f.prop(full_box(b"auxC", 0, b"urn:mpeg:hevc:2015:auxid:1\0")); - let id = f.add(b"grid", g, vec![(auxc, true)]); - f.refs.push((b"dimg", id, vec![tile; usize::from(n) * usize::from(n)])); - f.refs.push((b"auxl", id, vec![primary])); - } else if let Some(alpha) = spec.alpha { - aux(&mut f, "urn:mpeg:hevc:2015:auxid:1", &|x, y| [alpha(x, y), 0, 0]); - } - for urn in &spec.ignored_aux { - aux(&mut f, urn, &|x, y| [((x + y) % 256) as u16, 0, 0]); - } - if let Some(sample) = spec.thumbnail { - // Half the size, with the primary image's colour and orientation (not its crop). - let id = f.image(spec.width / 2, spec.height / 2, spec.bit_depth, false, sample); - if let Some(it) = f.items.iter_mut().find(|i| i.id == id) { - it.props.extend(assoc.iter().filter(|a| !a.2).map(|&(i, e, _)| (i, e))); - } - f.refs.push((b"thmb", id, vec![primary])); - } - f.write(primary) -} diff --git a/crates/heif/src/tests_synthetic.rs b/crates/heif/src/tests_synthetic.rs deleted file mode 100644 index d08b6d1fb4..0000000000 --- a/crates/heif/src/tests_synthetic.rs +++ /dev/null @@ -1,214 +0,0 @@ -//! Decoding lossless synthetic HEIF files ([`crate::testdata`]): every expected sample is known. - -use crate::testdata::{Prop, Spec, build}; -use crate::{Error, Options, decode, decode_thumbnail, probe}; - -/// A luma value unique enough to identify its position; chroma neutral. -fn luma(x: u32, y: u32) -> u16 { - ((x * 7 + y * 13) % 220 + 20) as u16 -} - -fn grey(x: u32, y: u32) -> [u16; 3] { - [luma(x, y), 128, 128] -} - -const FULL_601: Prop = Prop::Nclx(1, 13, 6, true); - -/// Decoded red channel at `(x, y)`, back in 8-bit code values. -fn at(d: &crate::Decoded, x: u32, y: u32) -> u16 { - let ch = if d.has_alpha { 4 } else { 3 }; - d.data[((y * d.width + x) as usize) * ch] / 257 -} - -fn decoded(spec: &Spec) -> crate::Decoded { - decode(&build(spec), &Options::default()).unwrap() -} - -#[test] -fn a_grid_reassembles_exactly() { - // 4 × 3 tiles of 32, cropped by the grid to 100 × 70. - let d = decoded(&Spec { props: vec![FULL_601], ..Spec::new(100, 70, &grey) }); - assert_eq!((d.width, d.height, d.bit_depth, d.has_alpha), (100, 70, 8, false)); - for y in 0..70 { - for x in 0..100 { - let px = &d.data[((y * 100 + x) * 3) as usize..][..3]; - assert_eq!(px, [luma(x, y) * 257; 3], "({x}, {y})"); - } - } - let info = probe(&build(&Spec::new(100, 70, &grey))).unwrap(); - assert_eq!((info.width, info.height, info.coded_width, info.coded_height, info.bit_depth), (100, 70, 100, 70, 8)); -} - -#[test] -fn colour_follows_the_matrix_and_range() { - // BT.601 full range, a saturated orange: within one code value of the exact conversion. - let (y, cb, cr) = (150.0f32, 80.0, 190.0); - let s = |_: u32, _: u32| [y as u16, cb as u16, cr as u16]; - let d = decoded(&Spec { props: vec![FULL_601], ..Spec::new(32, 32, &s) }); - let (u, v) = (cb - 128.0, cr - 128.0); - let expected = [y + 1.402 * v, y - 0.344_136 * u - 0.714_136 * v, y + 1.772 * u].map(|c| c.clamp(0.0, 255.0)); - for (got, want) in d.data[..3].iter().zip(expected) { - assert!((f32::from(*got) / 257.0 - want).abs() <= 1.0, "{:?} vs {expected:?}", &d.data[..3]); - } - assert_eq!(d.colour, crate::Colour { primaries: 1, transfer: 13, matrix: 6, full_range: true }); - - // No nclx and no VUI: the H.265 defaults, limited range (16 → black, 235 → white). - let ends = |x: u32, _: u32| [if x < 16 { 16 } else { 235 }, 128, 128]; - let d = decoded(&Spec::new(32, 32, &ends)); - assert!(!d.colour.full_range); - assert_eq!((d.data[0], d.data[20 * 3]), (0, 65535)); -} - -#[test] -fn ten_bit_samples_keep_their_precision() { - let s = |x: u32, y: u32| [(x * 31 + y) as u16 % 1024, 512, 512]; - let d = decoded(&Spec { bit_depth: 10, props: vec![FULL_601], ..Spec::new(64, 32, &s) }); - assert_eq!(d.bit_depth, 10); - for x in [0, 1, 5, 33, 63] { - let want = ((x * 31) % 1024) as f64 / 1023.0 * 65535.0; - assert!((f64::from(d.data[(x * 3) as usize]) - want).abs() <= 1.0, "x {x}"); - } -} - -#[test] -fn container_transforms_are_applied_like_libheif() { - let (w, h) = (70u32, 40u32); - let spec = |props: Vec| Spec { props: [vec![FULL_601], props].concat(), ..Spec::new(w, h, &grey) }; - // irot: counter-clockwise quarter turns. - let d = decoded(&spec(vec![Prop::Irot(1)])); - assert_eq!((d.width, d.height), (h, w)); - assert_eq!(at(&d, 0, 0), luma(w - 1, 0)); // the right column becomes the top row - assert_eq!(at(&d, h - 1, w - 1), luma(0, h - 1)); - let d = decoded(&spec(vec![Prop::Irot(2)])); - assert_eq!(at(&d, 0, 0), luma(w - 1, h - 1)); - let d = decoded(&spec(vec![Prop::Irot(3)])); - assert_eq!(at(&d, 0, 0), luma(0, h - 1)); - // imir: axis 0 exchanges top and bottom, axis 1 left and right (libheif's reading). - let d = decoded(&spec(vec![Prop::Imir(0)])); - assert_eq!((at(&d, 0, 0), at(&d, 5, 0)), (luma(0, h - 1), luma(5, h - 1))); - let d = decoded(&spec(vec![Prop::Imir(1)])); - assert_eq!((at(&d, 0, 0), at(&d, 0, 5)), (luma(w - 1, 0), luma(w - 1, 5))); - // clap: centred crop moved by its offsets; a half-pixel corner goes left and down. - let d = decoded(&spec(vec![Prop::Clap(31, 21, 3, -2)])); - assert_eq!((d.width, d.height), (31, 21)); - // left = (70 - 31 + 6) / 2 = 22.5 → 22, top = (40 - 21 - 4) / 2 = 7.5 → 8 - assert_eq!(at(&d, 0, 0), luma(22, 8)); - // In association order: crop, then turn, then mirror. - let d = decoded(&spec(vec![Prop::Clap(30, 20, 0, 0), Prop::Irot(1), Prop::Imir(1)])); - assert_eq!((d.width, d.height), (20, 30)); - // The crop is (20, 10) to (49, 29); the turn brings its bottom-right corner to the top-right, - // the left-right mirror to the top-left. - assert_eq!(at(&d, 0, 0), luma(49, 29)); - let info = probe(&build(&spec(vec![Prop::Irot(1)]))).unwrap(); - assert_eq!((info.width, info.height, info.coded_width, info.coded_height), (h, w, w, h)); - // Transforms off: as coded. - let d = decode(&build(&spec(vec![Prop::Irot(1)])), &Options { apply_transforms: false, ..Default::default() }).unwrap(); - assert_eq!((d.width, d.height, at(&d, 3, 2)), (w, h, luma(3, 2))); -} - -#[test] -fn metadata_aux_images_and_thumbnails() { - let icc = b"not parsed here: carried verbatim".to_vec(); - let exif = b"MM\0\x2a\0\0\0\x08\0\0".to_vec(); - let spec = Spec { - props: vec![Prop::Icc(icc.clone()), FULL_601], - exif: Some(exif.clone()), - thumbnail: Some(&|_, _| [77, 128, 128]), - ignored_aux: vec!["urn:com:apple:photo:2020:aux:hdrgainmap", "urn:mpeg:hevc:2015:auxid:2"], - ..Spec::new(64, 64, &grey) - }; - let bytes = build(&spec); - let d = decode(&bytes, &Options::default()).unwrap(); - assert_eq!((d.width, d.height, d.has_alpha), (64, 64, false)); - assert_eq!(d.icc.as_deref(), Some(icc.as_slice())); - assert_eq!(d.exif.as_deref(), Some(exif.as_slice())); - let t = decode_thumbnail(&bytes, 32, &Options::default()).unwrap().unwrap(); - assert_eq!((t.width, t.height, t.data[0]), (32, 32, 77 * 257)); - assert_eq!(t.exif.as_deref(), Some(exif.as_slice())); - assert_eq!(t.icc.as_deref(), Some(icc.as_slice())); - assert!(decode_thumbnail(&bytes, 33, &Options::default()).unwrap().is_none()); -} - -#[test] -fn alpha_comes_from_its_auxiliary_image() { - let alpha = |x: u32, _: u32| (x * 4) as u16; - let d = decoded(&Spec { props: vec![FULL_601], alpha: Some(&alpha), ..Spec::new(64, 32, &grey) }); - assert!(d.has_alpha); - assert_eq!(d.data.len(), 64 * 32 * 4); - assert_eq!((d.data[3], d.data[10 * 4 + 3]), (0, 40 * 257)); - assert_eq!(d.data[..3], [luma(0, 0) * 257; 3]); -} - -#[test] -fn an_alpha_grid_decodes_and_its_tile_references_share_the_visit_budget() { - let alpha = |x: u32, _: u32| (x * 4) as u16; - // a 2 × 2 alpha grid naming one tile four times: a valid file - let d = decoded(&Spec { alpha: Some(&alpha), alpha_tile_repeats: 2, ..Spec::new(64, 64, &grey) }); - assert!(d.has_alpha); - assert_eq!((d.data[10 * 4 + 3], d.data[42 * 4 + 3]), (40 * 257, 40 * 257)); - // 70 × 70 references to that tile: each would be rebuilt and decoded, so it is refused first - let bytes = build(&Spec { alpha: Some(&alpha), alpha_tile_repeats: 70, ..Spec::new(32, 32, &grey) }); - for r in [probe(&bytes).map(|_| ()), decode(&bytes, &Options::default()).map(|_| ())] { - assert!(matches!(&r, Err(Error::Limit(m)) if m.contains("extent reads")), "{r:?}"); - } -} - -#[test] -fn limits_are_checked_before_decoding() { - let bytes = build(&Spec::new(96, 64, &grey)); - let r = decode(&bytes, &Options { max_pixels: 96 * 64 - 1, ..Default::default() }); - assert!(matches!(r, Err(Error::Limit(_))), "{r:?}"); -} - -/// #1518: a grid's tiles together are held to the pixel budget before any is decoded. A -/// 33 × 33 canvas fits 1089 pixels, but its four 32 × 32 tiles hold 4096: over twice the limit. -#[test] -fn grid_tiles_are_held_to_the_pixel_budget_together() { - let bytes = build(&Spec::new(33, 33, &grey)); - let r = decode(&bytes, &Options { max_pixels: 33 * 33, ..Default::default() }); - assert!(matches!(r, Err(Error::Limit(_))), "{r:?}"); - let d = decode(&bytes, &Options { max_pixels: 2 * 32 * 32, ..Default::default() }).unwrap(); - assert_eq!((d.width, d.height), (33, 33)); -} - -#[test] -fn truncated_and_corrupted_files_are_errors_not_panics() { - let bytes = build(&Spec { props: vec![FULL_601, Prop::Irot(1)], thumbnail: Some(&grey), ..Spec::new(64, 64, &grey) }); - let full = decode(&bytes, &Options::default()).unwrap(); - for cut in (0..bytes.len()).step_by(7) { - let b = &bytes[..cut]; - // Cut inside the photo: an error. Cut in the trailing thumbnail: the whole photo. - if let (Ok(_), Ok(d)) = (probe(b), decode(b, &Options::default())) { - assert_eq!(d.data, full.data, "cut at {cut} of {}", bytes.len()); - } - let _ = decode_thumbnail(b, 1, &Options::default()); - } - // Flip bits all over the file: any outcome but a panic. - let mut state = 0x2545_f491_u32; - for _ in 0..400 { - let mut b = bytes.clone(); - for _ in 0..3 { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - let i = state as usize % b.len(); - b[i] ^= 1 << (state % 8); - } - let _ = probe(&b); - let _ = decode(&b, &Options::default()); - let _ = decode_thumbnail(&b, 1, &Options::default()); - } -} - -/// CodeRabbit #44: heic-rs keeps every associated transform and each one re-allocates the -/// whole picture, so 13 of them are over the [`crate::MAX_TRANSFORMS`] cap and refused. -#[test] -fn too_many_transform_properties_are_refused() { - let bytes = build(&Spec { props: std::iter::repeat_n(Prop::Irot(0), 13).collect(), ..Spec::new(32, 32, &grey) }); - let r = decode(&bytes, &Options::default()); - assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("transform")), "{r:?}"); - // At the cap they're not: 12 identity rotations decode normally. - let bytes = build(&Spec { props: std::iter::repeat_n(Prop::Irot(0), 12).collect(), ..Spec::new(32, 32, &grey) }); - let d = decode(&bytes, &Options::default()).unwrap(); - assert_eq!((d.width, d.height), (32, 32)); -} diff --git a/crates/heif/src/vui.rs b/crates/heif/src/vui.rs deleted file mode 100644 index bfe10fa097..0000000000 --- a/crates/heif/src/vui.rs +++ /dev/null @@ -1,567 +0,0 @@ -//! The colour description in an HEVC sequence parameter set's VUI (Rec. ITU-T H.265, 7.3.2.2 and -//! Annex E): the fallback a HEIF reader uses when the item carries no `colr` box of type `nclx`. -//! iPhone photos are the common case: they label their colour with an ICC profile only and say in -//! the VUI that their YCbCr is full range. -//! -//! Only the syntax up to `matrix_coeffs` is read. Anything this parser can't follow returns `None` -//! and the caller falls back to the H.265 defaults; it never fails a decode. - -/// What the VUI's `video_signal_type` says (H.265 E.3.1). Absent fields keep the defaults the -/// standard infers: limited range, every code point 2 ("unspecified"). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Signal { - pub full_range: bool, - pub primaries: u8, - pub transfer: u8, - pub matrix: u8, -} - -impl Default for Signal { - fn default() -> Self { - Signal { full_range: false, primaries: 2, transfer: 2, matrix: 2 } - } -} - -/// NAL unit type of a sequence parameter set. -const SPS_NUT: u8 = 33; - -/// Reads the signal description from the SPS among `parameter_sets` (NAL units with their -/// two-byte header, as an `hvcC` record stores them). `None`: no SPS, or one this reader can't -/// follow; `Some(Signal::default())`: an SPS without VUI colour fields. -pub fn signal(parameter_sets: &[&[u8]]) -> Option { - let sps = parameter_sets.iter().find(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == SPS_NUT))?; - parse_sps(&unescape(sps.get(2..)?)) -} - -/// The uncropped picture size (`pic_width/height_in_luma_samples`) of every SPS among -/// `parameter_sets`: what the decoder allocates before it applies the conformance window, so the -/// pixel budget is checked against it (heic-rs reports only the first SPS, cropped). `None`: an -/// SPS this reader can't follow. -pub fn coded_sizes(parameter_sets: &[&[u8]]) -> Option> { - parameter_sets - .iter() - .filter(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == SPS_NUT)) - .map(|sps| { - let rbsp = unescape(sps.get(2..)?); - let r = &mut Bits { data: &rbsp, pos: 0 }; - sps_size(r).map(|(w, h, _)| (w, h)) - }) - .collect() -} - -/// NAL unit type of a picture parameter set. -const PPS_NUT: u8 = 34; - -/// What [`pps_layouts`] reads of a picture parameter set. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct PpsLayout { - /// `pps_pic_parameter_set_id`. - pub id: u32, - /// `num_tile_columns_minus1 + 1` (1 without tiles). - pub tile_cols: u32, - /// `num_tile_rows_minus1 + 1` (1 without tiles). - pub tile_rows: u32, -} - -/// The id and tile layout of every PPS among `parameter_sets`, read up to the tile counts -/// (H.265 7.3.2.3.1). `None`: a PPS this reader can't follow. -pub fn pps_layouts(parameter_sets: &[&[u8]]) -> Option> { - parameter_sets - .iter() - .filter(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == PPS_NUT)) - .map(|pps| { - let rbsp = unescape(pps.get(2..)?); - pps_layout(&mut Bits { data: &rbsp, pos: 0 }) - }) - .collect() -} - -fn pps_layout(r: &mut Bits) -> Option { - let id = r.ue()?; // pps_pic_parameter_set_id - r.ue()?; // pps_seq_parameter_set_id - // dependent slices, output flag, 3 extra slice header bits, sign hiding, cabac_init_present - r.skip(7)?; - r.ue()?; // num_ref_idx_l0_default_active_minus1 - r.ue()?; // num_ref_idx_l1_default_active_minus1 - r.se()?; // init_qp_minus26 - r.skip(2)?; // constrained_intra_pred_flag, transform_skip_enabled_flag - if r.flag()? { - r.ue()?; // diff_cu_qp_delta_depth - } - r.se()?; // pps_cb_qp_offset - r.se()?; // pps_cr_qp_offset - // slice chroma qp offsets present, weighted pred, weighted bipred, transquant bypass - r.skip(4)?; - let tiles = r.flag()?; // tiles_enabled_flag - r.skip(1)?; // entropy_coding_sync_enabled_flag - let (tile_cols, tile_rows) = if tiles { (r.ue()?.checked_add(1)?, r.ue()?.checked_add(1)?) } else { (1, 1) }; - Some(PpsLayout { id, tile_cols, tile_rows }) -} - -/// Reads an SPS up to and including the picture size, leaving `r` after it: width, height and -/// `sps_max_sub_layers_minus1`. -fn sps_size(r: &mut Bits) -> Option<(u32, u32, u32)> { - r.skip(4)?; // sps_video_parameter_set_id - let max_sub_layers_minus1 = r.u(3)?; - if max_sub_layers_minus1 > 6 { - return None; - } - r.skip(1)?; // sps_temporal_id_nesting_flag - profile_tier_level(r, max_sub_layers_minus1)?; - r.ue()?; // sps_seq_parameter_set_id - if r.ue()? == 3 { - r.skip(1)?; // separate_colour_plane_flag - } - let width = r.ue()?; // pic_width_in_luma_samples - let height = r.ue()?; // pic_height_in_luma_samples - Some((width, height, max_sub_layers_minus1)) -} - -/// Removes emulation prevention bytes (`00 00 03` → `00 00`). -fn unescape(nal: &[u8]) -> Vec { - let mut out = Vec::with_capacity(nal.len()); - let mut zeros = 0usize; - for &b in nal { - if zeros >= 2 && b == 3 { - zeros = 0; - continue; - } - zeros = if b == 0 { zeros + 1 } else { 0 }; - out.push(b); - } - out -} - -struct Bits<'a> { - data: &'a [u8], - pos: usize, -} - -impl Bits<'_> { - fn u(&mut self, n: u32) -> Option { - let mut v = 0u32; - for _ in 0..n { - let byte = *self.data.get(self.pos / 8)?; - v = (v << 1) | u32::from((byte >> (7 - self.pos % 8)) & 1); - self.pos += 1; - } - Some(v) - } - - fn flag(&mut self) -> Option { - self.u(1).map(|b| b == 1) - } - - fn skip(&mut self, n: usize) -> Option<()> { - self.pos = self.pos.checked_add(n)?; - (self.pos <= self.data.len().saturating_mul(8)).then_some(()) - } - - /// `ue(v)`; values past 32 bits are refused (no valid field here needs them). - fn ue(&mut self) -> Option { - let mut zeros = 0u32; - while !self.flag()? { - zeros += 1; - if zeros > 31 { - return None; - } - } - let rest = self.u(zeros)?; - ((1u64 << zeros) - 1 + u64::from(rest)).try_into().ok() - } - - fn se(&mut self) -> Option<()> { - self.ue().map(|_| ()) - } -} - -/// `profile_tier_level(1, max_sub_layers_minus1)` (7.3.3): only skipped. -fn profile_tier_level(r: &mut Bits, max_sub_layers_minus1: u32) -> Option<()> { - r.skip(88)?; // general profile space .. general_inbld/reserved flag - r.skip(8)?; // general_level_idc - let mut present = [(false, false); 8]; - for p in present.iter_mut().take(max_sub_layers_minus1 as usize) { - *p = (r.flag()?, r.flag()?); - } - if max_sub_layers_minus1 > 0 { - r.skip(2 * (8 - max_sub_layers_minus1 as usize))?; // reserved_zero_2bits - } - for &(profile, level) in present.iter().take(max_sub_layers_minus1 as usize) { - if profile { - r.skip(88)?; - } - if level { - r.skip(8)?; - } - } - Some(()) -} - -/// `scaling_list_data()` (7.3.4): only skipped. -fn scaling_list_data(r: &mut Bits) -> Option<()> { - for size_id in 0..4u32 { - let step = if size_id == 3 { 3 } else { 1 }; - for _ in (0..6).step_by(step) { - if !r.flag()? { - r.ue()?; // scaling_list_pred_matrix_id_delta - } else { - let coefs = 64.min(1 << (4 + (size_id << 1))); - if size_id > 1 { - r.se()?; // scaling_list_dc_coef_minus8 - } - for _ in 0..coefs { - r.se()?; // scaling_list_delta_coef - } - } - } - } - Some(()) -} - -/// `st_ref_pic_set(idx)` (7.3.7) as it appears in an SPS; returns `NumDeltaPocs[idx]`. -fn st_ref_pic_set(r: &mut Bits, idx: usize, num_delta_pocs: &[u32]) -> Option { - if idx != 0 && r.flag()? { - // inter_ref_pic_set_prediction_flag: predicted from the previous set (in an SPS, - // delta_idx_minus1 is absent and RefRpsIdx = idx - 1). - r.skip(1)?; // delta_rps_sign - r.ue()?; // abs_delta_rps_minus1 - let reference = *num_delta_pocs.get(idx - 1)?; - let mut count = 0u32; - for _ in 0..=reference { - let used = r.flag()?; - let kept = used || r.flag()?; // use_delta_flag when not used_by_curr_pic_flag - count += u32::from(kept); - } - return Some(count); - } - let negative = r.ue()?; - let positive = r.ue()?; - let total = negative.checked_add(positive)?; - if total > 32 { - return None; // at most 16 + 16 for any level - } - for _ in 0..total { - r.ue()?; // delta_poc_s*_minus1 - r.skip(1)?; // used_by_curr_pic_s*_flag - } - Some(total) -} - -fn parse_sps(rbsp: &[u8]) -> Option { - let r = &mut Bits { data: rbsp, pos: 0 }; - let (_, _, max_sub_layers_minus1) = sps_size(r)?; - parse_sps_parameters(r, max_sub_layers_minus1)?; - parse_vui(r) -} - -fn parse_sps_parameters(r: &mut Bits<'_>, max_sub_layers_minus1: u32) -> Option<()> { - if r.flag()? { - for _ in 0..4 { - r.ue()?; // conf_win_*_offset - } - } - r.ue()?; // bit_depth_luma_minus8 - r.ue()?; // bit_depth_chroma_minus8 - let log2_max_poc_lsb = r.ue()?.checked_add(4)?; - if log2_max_poc_lsb > 16 { - return None; - } - let first = if r.flag()? { 0 } else { max_sub_layers_minus1 }; - for _ in first..=max_sub_layers_minus1 { - r.ue()?; // sps_max_dec_pic_buffering_minus1 - r.ue()?; // sps_max_num_reorder_pics - r.ue()?; // sps_max_latency_increase_plus1 - } - for _ in 0..6 { - r.ue()?; // coding/transform block sizes, transform hierarchy depths - } - if r.flag()? && r.flag()? { - // scaling_list_enabled_flag, sps_scaling_list_data_present_flag - scaling_list_data(r)?; - } - r.skip(2)?; // amp_enabled_flag, sample_adaptive_offset_enabled_flag - if r.flag()? { - // pcm_enabled_flag - r.skip(8)?; // pcm sample bit depths - r.ue()?; - r.ue()?; - r.skip(1)?; // pcm_loop_filter_disabled_flag - } - let sets = r.ue()? as usize; - if sets > 64 { - return None; - } - let mut num_delta_pocs = Vec::with_capacity(sets); - for idx in 0..sets { - let n = st_ref_pic_set(r, idx, &num_delta_pocs)?; - num_delta_pocs.push(n); - } - if r.flag()? { - // long_term_ref_pics_present_flag - let n = r.ue()?; - if n > 32 { - return None; - } - for _ in 0..n { - r.skip(log2_max_poc_lsb as usize + 1)?; // lt_ref_pic_poc_lsb_sps, used_by_curr_pic_lt_sps_flag - } - } - r.skip(2)?; // sps_temporal_mvp_enabled_flag, strong_intra_smoothing_enabled_flag - Some(()) -} - -fn parse_vui(r: &mut Bits<'_>) -> Option { - let mut signal = Signal::default(); - if !r.flag()? { - return Some(signal); // no VUI - } - if r.flag()? && r.u(8)? == 255 { - // aspect_ratio_info_present_flag, aspect_ratio_idc == EXTENDED_SAR - r.skip(32)?; - } - if r.flag()? { - r.skip(1)?; // overscan_appropriate_flag - } - if r.flag()? { - // video_signal_type_present_flag - r.skip(3)?; // video_format - signal.full_range = r.flag()?; - if r.flag()? { - signal.primaries = r.u(8)? as u8; - signal.transfer = r.u(8)? as u8; - signal.matrix = r.u(8)? as u8; - } - } - Some(signal) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A bit writer for building parameter sets in tests. - #[derive(Default)] - pub(crate) struct Writer { - pub bits: Vec, - } - - impl Writer { - pub fn u(&mut self, v: u32, n: u32) { - for i in (0..n).rev() { - self.bits.push(i < 32 && (v >> i) & 1 == 1); - } - } - pub fn ue(&mut self, v: u32) { - let x = u64::from(v) + 1; - let len = 64 - x.leading_zeros(); - self.u(0, len - 1); - for i in (0..len).rev() { - self.bits.push((x >> i) & 1 == 1); - } - } - pub fn bytes(mut self) -> Vec { - self.bits.push(true); // rbsp_stop_one_bit - while !self.bits.len().is_multiple_of(8) { - self.bits.push(false); - } - self.bits.chunks(8).map(|c| c.iter().fold(0u8, |a, &b| (a << 1) | u8::from(b))).collect() - } - } - - fn sps(vui: impl FnOnce(&mut Writer), st_sets: impl FnOnce(&mut Writer)) -> Vec { - let mut w = Writer::default(); - w.u(0, 4); - w.u(1, 3); // one sub-layer above the base - w.u(1, 1); - w.u(0, 88); - w.u(93, 8); - w.u(0b11, 2); // sub-layer profile and level present - w.u(0, 2 * 7); - w.u(0, 88); - w.u(0, 8); - w.ue(0); - w.ue(1); // 4:2:0 - w.ue(4032); - w.ue(3024); - w.u(1, 1); // conformance window - for _ in 0..4 { - w.ue(3); - } - w.ue(0); - w.ue(0); - w.ue(4); - w.u(1, 1); - for _ in 0..2 { - w.ue(1); - w.ue(0); - w.ue(0); - } - for v in [0, 3, 0, 3, 0, 0] { - w.ue(v); - } - w.u(1, 1); // scaling lists, with data - w.u(1, 1); - for size_id in 0..4u32 { - for _ in (0..6).step_by(if size_id == 3 { 3 } else { 1 }) { - w.u(1, 1); - if size_id > 1 { - w.ue(0); - } - for _ in 0..64.min(1 << (4 + (size_id << 1))) { - w.ue(0); - } - } - } - w.u(0, 2); - w.u(1, 1); // pcm - w.u(0x77, 8); - w.ue(0); - w.ue(1); - w.u(1, 1); - st_sets(&mut w); - w.u(1, 1); // long-term pictures - w.ue(1); - w.u(0, 8 + 1); - w.u(0, 2); - vui(&mut w); - let mut nal = vec![SPS_NUT << 1, 1]; - // escape like a real NAL so `signal` has to unescape - let mut zeros = 0; - for b in w.bytes() { - if zeros >= 2 && b <= 3 { - nal.push(3); - zeros = 0; - } - zeros = if b == 0 { zeros + 1 } else { 0 }; - nal.push(b); - } - nal - } - - fn two_rps(w: &mut Writer) { - w.ue(2); - w.ue(1); // set 0: one negative picture - w.ue(0); - w.ue(0); - w.u(1, 1); - w.u(1, 1); // set 1: predicted from set 0 - w.u(0, 1); - w.ue(0); - w.u(0, 1); // not used ... - w.u(1, 1); // ... but kept - w.u(1, 1); - } - - #[test] - fn reads_full_range_and_matrix_from_the_vui() { - let nal = sps( - |w| { - w.u(1, 1); // vui present - w.u(1, 1); - w.u(255, 8); - w.u(0x0001_0001, 32); - w.u(1, 1); - w.u(0, 1); - w.u(1, 1); // video_signal_type_present_flag - w.u(5, 3); - w.u(1, 1); // full range - w.u(1, 1); - w.u(12, 8); - w.u(13, 8); - w.u(6, 8); - }, - two_rps, - ); - let s = signal(&[&[0x40, 1, 0xc], &nal, &[0x44, 1]]); - assert_eq!(s, Some(Signal { full_range: true, primaries: 12, transfer: 13, matrix: 6 })); - } - - #[test] - fn absent_fields_take_the_standard_defaults() { - let no_vui = sps(|w| w.u(0, 1), |w| w.ue(0)); - assert_eq!(signal(&[&no_vui]), Some(Signal::default())); - let range_only = sps( - |w| { - w.u(1, 1); - w.u(0, 2); - w.u(1, 1); - w.u(5, 3); - w.u(1, 1); - w.u(0, 1); // no colour description - }, - |w| w.ue(0), - ); - assert_eq!(signal(&[&range_only]), Some(Signal { full_range: true, ..Signal::default() })); - } - - #[test] - fn missing_or_truncated_sps_is_none() { - assert_eq!(signal(&[]), None); - assert_eq!(signal(&[&[0x40, 1, 2, 3]]), None); - let nal = sps(|w| w.u(0, 1), |w| w.ue(0)); - for cut in 2..nal.len() - 2 { - // never panics; most cuts are None - let _ = signal(&[nal.get(..cut).unwrap_or_default()]); - } - assert_eq!(signal(&[&[SPS_NUT << 1, 1, 0xff, 0xff, 0xff]]), None); - } - - /// A PPS NAL as encoders write it, with `tiles` (columns, rows) when tiles are enabled. - fn pps(id: u32, cu_qp_delta: bool, tiles: Option<(u32, u32)>) -> Vec { - let mut w = Writer::default(); - w.ue(id); - w.ue(0); // sps id - w.u(0, 7); - w.ue(0); - w.ue(0); - w.ue(3); // init_qp_minus26 = -2 - w.u(0, 2); - w.u(u32::from(cu_qp_delta), 1); - if cu_qp_delta { - w.ue(1); - } - w.ue(1); // cb offset +1 - w.ue(2); // cr offset -1 - w.u(0, 4); - w.u(u32::from(tiles.is_some()), 1); - w.u(0, 1); - if let Some((c, r)) = tiles { - w.ue(c - 1); - w.ue(r - 1); - w.u(1, 1); // uniform spacing - w.u(1, 1); - } - w.u(0, 3); - [vec![PPS_NUT << 1, 1], w.bytes()].concat() - } - - #[test] - fn reads_pps_ids_and_tile_counts() { - let plain = pps(5, true, None); - let tiled = pps(63, false, Some((4, 3))); - let sps_nal = sps(|w| w.u(0, 1), |w| w.ue(0)); - assert_eq!( - pps_layouts(&[&sps_nal, &plain, &tiled]), - Some(vec![PpsLayout { id: 5, tile_cols: 1, tile_rows: 1 }, PpsLayout { id: 63, tile_cols: 4, tile_rows: 3 }]) - ); - assert_eq!(pps_layouts(&[&[PPS_NUT << 1, 1]]), None); - assert!(crate::check_parameter_sets(&[&sps_nal, &plain, &tiled]).is_ok()); - assert!(crate::check_parameter_sets(&[&pps(0, false, Some((20, 22)))]).is_ok()); - } - - #[test] - fn refuses_parameter_sets_that_multiply_decoder_work() { - // a PPS id past 63: heic-rs would keep every distinct one and rescan them all for each - let r = crate::check_parameter_sets(&[&pps(64, false, None)]); - assert!(matches!(r, Err(crate::Error::Malformed(_))), "{r:?}"); - // thousands of PPS records (even with valid, repeated ids): quadratic collection - let one = pps(1, false, None); - let many: Vec<&[u8]> = vec![&one; 5000]; - assert!(matches!(crate::check_parameter_sets(&many), Err(crate::Error::Limit(_)))); - // more tiles than any H.265 level allows: tile tables cost blocks × tiles - for (c, r) in [(21, 1), (1, 23), (1024, 1024)] { - let r = crate::check_parameter_sets(&[&pps(0, false, Some((c, r)))]); - assert!(matches!(r, Err(crate::Error::Limit(_))), "{r:?}"); - } - } -} diff --git a/crates/heif/src/ycc.rs b/crates/heif/src/ycc.rs deleted file mode 100644 index 384d25f2ae..0000000000 --- a/crates/heif/src/ycc.rs +++ /dev/null @@ -1,352 +0,0 @@ -//! YCbCr → RGB for decoded HEVC pictures, done here rather than in heic-rs so the result matches -//! libheif (the reference every HEIF tool is checked against) to within one code value: -//! -//! - **Which matrix and range.** The item's `colr` `nclx` box when there is one; otherwise the -//! HEVC VUI ([`crate::vui`]); otherwise the H.265 defaults (limited range). An unspecified matrix -//! is BT.601, as libheif reads it. heic-rs 0.1.1 ignores the VUI and assumes BT.709 limited -//! range for every file without `nclx`, which shifts every iPhone photo (full range, ICC only) -//! by about 8 code values. -//! - **Chroma upsampling.** Nearest neighbour (each chroma sample covers its 2×2 or 2×1 luma -//! block), as libheif does by default. libheif switches to a centred bilinear filter (weights -//! 9/3/3/1 sixteenths, in integers) when a `clap` crop starts at an odd column or row; so does -//! [`Upsampling::Bilinear`]. -//! -//! The arithmetic is floating point and the result 16-bit, whatever the coded depth, so the -//! develop pipeline gets every bit the conversion produces. - -use heic_rs::grid::Mosaic; -use heic_rs::hevc::{ChromaFormat, Frame}; - -/// The coded pictures one image is made of. -pub enum Planes<'a> { - Picture(&'a Frame), - Grid(Mosaic<'a>), -} - -impl Planes<'_> { - pub fn size(&self) -> (usize, usize) { - match self { - Planes::Picture(f) => (f.width as usize, f.height as usize), - Planes::Grid(m) => (m.width() as usize, m.height() as usize), - } - } - - pub fn bit_depth(&self) -> u8 { - match self { - Planes::Picture(f) => f.bit_depth, - Planes::Grid(m) => m.bit_depth(), - } - } - - pub fn chroma(&self) -> ChromaFormat { - match self { - Planes::Picture(f) => f.chroma, - Planes::Grid(m) => m.chroma(), - } - } - - fn chroma_width(&self) -> usize { - let (w, h) = self.size(); - self.chroma().chroma_size(w as u32, h as u32).0 as usize - } - - fn luma_row(&self, y: usize, dst: &mut [u16]) -> Option<()> { - match self { - Planes::Picture(f) => copy_row(&f.y, f.y_stride as usize, y, dst), - Planes::Grid(m) => m.luma_row(y, dst), - } - } - - fn chroma_row(&self, cr: bool, r: usize, dst: &mut [u16]) -> Option<()> { - match self { - Planes::Picture(f) => copy_row(if cr { &f.cr } else { &f.cb }, f.c_stride as usize, r, dst), - Planes::Grid(m) => m.chroma_row(cr, r, dst), - } - } -} - -fn copy_row(plane: &[u16], stride: usize, y: usize, dst: &mut [u16]) -> Option<()> { - let start = y.checked_mul(stride)?; - dst.copy_from_slice(plane.get(start..start.checked_add(dst.len())?)?); - Some(()) -} - -/// How the three coded channels map to R, G, B (H.273 `MatrixCoefficients`). -#[derive(Debug, Clone, Copy, PartialEq)] -enum Matrix { - /// 0: the channels are G, B, R. - Identity, - /// 8: YCgCo. - YCgCo, - /// Every Kr/Kb matrix: R = Y + `cr_r`·Cr, G = Y − `cb_g`·Cb − `cr_g`·Cr, B = Y + `cb_b`·Cb. - Kr { cr_r: f32, cb_g: f32, cr_g: f32, cb_b: f32 }, -} - -impl Matrix { - /// Unknown, reserved and unspecified codes are BT.601, like libheif. - fn from_code(code: u16) -> Matrix { - let (kr, kb) = match code { - 0 => return Matrix::Identity, - 8 => return Matrix::YCgCo, - 1 => (0.2126, 0.0722), - 4 => (0.30, 0.11), - 7 => (0.212, 0.087), - // 10 (BT.2020 constant luminance) is approximated by its non-constant matrix. - 9 | 10 => (0.2627, 0.0593), - _ => (0.299, 0.114), - }; - let kg = 1.0 - kr - kb; - Matrix::Kr { cr_r: 2.0 * (1.0 - kr), cb_g: 2.0 * kb * (1.0 - kb) / kg, cr_g: 2.0 * kr * (1.0 - kr) / kg, cb_b: 2.0 * (1.0 - kb) } - } -} - -/// How the samples are to be read: the matrix and the range. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Signal { - pub matrix: u16, - pub full_range: bool, -} - -/// How subsampled chroma is brought to the luma resolution. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Upsampling { - Nearest, - /// Centred bilinear: chroma sits between its two luma columns (and rows for 4:2:0). - Bilinear, -} - -/// One chroma row brought to the full width `w` of luma row `y`. -fn chroma_at(planes: &Planes<'_>, cr: bool, y: usize, w: usize, mode: Upsampling, buf: &mut [u16], next: &mut [u16]) -> Option> { - let chroma = planes.chroma(); - let (xs, ys) = (chroma.x_shift(), chroma.y_shift()); - let (wf, hf) = planes.size(); - let rows = chroma.chroma_size(wf as u32, hf as u32).1 as usize; - let cy = y >> ys; - planes.chroma_row(cr, cy, buf)?; - let last = buf.len().checked_sub(1)?; - if mode == Upsampling::Nearest || xs == 0 { - return (0..w).map(|x| buf.get(x >> xs).copied()).collect(); - } - // The nearer neighbour on each axis takes a quarter of the weight. - let ny = if ys == 0 { - cy - } else if y.is_multiple_of(2) { - cy.saturating_sub(1) - } else { - (cy + 1).min(rows.checked_sub(1)?) - }; - planes.chroma_row(cr, ny, next)?; - (0..w) - .map(|x| { - let cx = x >> 1; - let nx = if x % 2 == 0 { cx.saturating_sub(1) } else { (cx + 1).min(last) }; - let (a, an) = (u32::from(*buf.get(cx)?), u32::from(*buf.get(nx)?)); - let v = if ys == 0 { - (3 * a + an + 2) >> 2 - } else { - let (b, bn) = (u32::from(*next.get(cx)?), u32::from(*next.get(nx)?)); - (9 * a + 3 * b + 3 * an + bn + 8) >> 4 - }; - u16::try_from(v).ok() - }) - .collect() -} - -/// Converts `planes` to interleaved 16-bit RGB, or RGBA with room left for alpha (filled with -/// 65535 here). `None` when the planes can't supply a row they promised (a malformed grid). -pub fn to_rgb16(planes: &Planes<'_>, signal: Signal, alpha: bool, mode: Upsampling) -> Option> { - let (w, h) = planes.size(); - let ch = if alpha { 4 } else { 3 }; - let bd = u32::from(planes.bit_depth()); - if !(8..=16).contains(&bd) || w == 0 || h == 0 { - return None; - } - // The default caller limit is 2²8 pixels, at most four channels per pixel, so the largest - // legitimate `w·h·ch` is 2²30 samples. Anything more is a malformed or hostile canvas the - // decode path would have refused before calling here (CodeRabbit #48): refuse rather than - // ask for a multi-gigabuffer (or worse, over usize). - if w.checked_mul(h)?.checked_mul(ch)? > 1 << 30 { - return None; - } - let max = ((1u32 << bd) - 1) as f32; - let half = (1u32 << (bd - 1)) as f32; - let scale = (1u32 << (bd - 8)) as f32; - // Normalised Y = (v − y_off)·y_mul, Cb/Cr = (v − half)·c_mul. - let (y_off, y_mul, c_mul) = - if signal.full_range { (0.0, 1.0 / max, 1.0 / max) } else { (16.0 * scale, 1.0 / (219.0 * scale), 1.0 / (224.0 * scale)) }; - let matrix = Matrix::from_code(signal.matrix); - let mono = planes.chroma() == ChromaFormat::Monochrome; - let cw = planes.chroma_width(); - - let mut out = vec![0u16; w.checked_mul(h)?.checked_mul(ch)?]; - let row = |y: usize, dst: &mut [u16]| -> Option<()> { - let mut luma = vec![0u16; w]; - planes.luma_row(y, &mut luma)?; - let (cb, cr) = if mono { - (Vec::new(), Vec::new()) - } else { - let (mut buf, mut next) = (vec![0u16; cw], vec![0u16; cw]); - (chroma_at(planes, false, y, w, mode, &mut buf, &mut next)?, chroma_at(planes, true, y, w, mode, &mut buf, &mut next)?) - }; - for (x, (px, &yv)) in dst.chunks_exact_mut(ch).zip(&luma).enumerate() { - let rgb = if mono { - let v = (f32::from(yv) - y_off) * y_mul; - [v, v, v] - } else { - let (u, v) = (f32::from(*cb.get(x)?), f32::from(*cr.get(x)?)); - match matrix { - // G, B, R all read like luma. - Matrix::Identity => [(v - y_off) * y_mul, (f32::from(yv) - y_off) * y_mul, (u - y_off) * y_mul], - Matrix::YCgCo => { - let (yn, cg, co) = ((f32::from(yv) - y_off) * y_mul, (u - half) * c_mul, (v - half) * c_mul); - let t = yn - cg; - [t + co, yn + cg, t - co] - } - Matrix::Kr { cr_r, cb_g, cr_g, cb_b } => { - let (yn, u, v) = ((f32::from(yv) - y_off) * y_mul, (u - half) * c_mul, (v - half) * c_mul); - [yn + cr_r * v, yn - cb_g * u - cr_g * v, yn + cb_b * u] - } - } - }; - for (o, c) in px.iter_mut().zip(rgb) { - *o = (c.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; - } - if alpha && let Some(a) = px.get_mut(3) { - *a = u16::MAX; - } - } - Some(()) - }; - let row_len = w * ch; - #[cfg(not(target_arch = "wasm32"))] - let ok = { - use rayon::prelude::*; - out.par_chunks_mut(row_len).enumerate().all(|(y, dst)| row(y, dst).is_some()) - }; - #[cfg(target_arch = "wasm32")] - let ok = out.chunks_mut(row_len).enumerate().all(|(y, dst)| row(y, dst).is_some()); - ok.then_some(out) -} - -/// Writes an alpha picture's luma, full range, into channel 3 of `rgba`. -pub fn put_alpha(planes: &Planes<'_>, rgba: &mut [u16]) -> Option<()> { - let (w, h) = planes.size(); - let max = ((1u32 << u32::from(planes.bit_depth()).clamp(1, 16)) - 1) as f32; - let mut luma = vec![0u16; w]; - for (y, row) in rgba.chunks_exact_mut(w * 4).enumerate().take(h) { - planes.luma_row(y, &mut luma)?; - for (px, &a) in row.as_chunks_mut::<4>().0.iter_mut().zip(&luma) { - let v = (f32::from(a) / max).clamp(0.0, 1.0); - px[3] = (v * 65535.0 + 0.5) as u16; - } - } - Some(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn frame(w: u32, h: u32, bd: u8, chroma: ChromaFormat, y: u16, cb: u16, cr: u16) -> Frame { - let (cw, chh) = chroma.chroma_size(w, h); - let n = (cw * chh) as usize; - Frame { - width: w, - height: h, - bit_depth: bd, - chroma, - y: vec![y; (w * h) as usize], - cb: vec![cb; n], - cr: vec![cr; n], - y_stride: w, - c_stride: cw, - } - } - - fn rgb(f: &Frame, matrix: u16, full_range: bool) -> [u16; 3] { - let v = to_rgb16(&Planes::Picture(f), Signal { matrix, full_range }, false, Upsampling::Nearest).unwrap(); - [v[0], v[1], v[2]] - } - - #[test] - fn neutral_and_primaries_convert_exactly() { - // Full-range grey stays grey; limited-range black and white reach the ends. - assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128), 6, true), [128 * 257; 3]); - assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 16, 128, 128), 1, false), [0; 3]); - assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 235, 128, 128), 1, false), [65535; 3]); - assert_eq!(rgb(&frame(4, 4, 10, ChromaFormat::Yuv420, 940, 512, 512), 9, false), [65535; 3]); - // BT.601 full-range pure red: Y = 76.245, Cb = 84.97, Cr = 255.5 → (255, 0, 0) within rounding. - let red = rgb(&frame(2, 2, 8, ChromaFormat::Yuv444, 76, 85, 255), 6, true); - assert!(red[0] > 65000 && red[1] < 300 && red[2] < 300, "{red:?}"); - // Identity: the channels are G, B, R. - assert_eq!(rgb(&frame(2, 2, 8, ChromaFormat::Yuv444, 10, 20, 30), 0, true), [30 * 257, 10 * 257, 20 * 257]); - // Monochrome. - assert_eq!(rgb(&frame(2, 2, 8, ChromaFormat::Monochrome, 51, 0, 0), 6, true), [51 * 257; 3]); - } - - #[test] - fn chroma_is_nearest_neighbour() { - // 4:2:0, 4×2 luma, chroma 2×1: the left chroma sample covers columns 0–1 only. - let mut f = frame(4, 2, 8, ChromaFormat::Yuv420, 128, 128, 128); - f.cr = vec![200, 128]; - let v = to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, false, Upsampling::Nearest).unwrap(); - let red: Vec = v.chunks(3).map(|p| p[0]).collect(); - assert!(red[0] == red[1] && red[1] == red[4] && red[0] > red[2] && red[2] == 128 * 257, "{red:?}"); - } - - #[test] - fn bilinear_chroma_is_centred_9_3_3_1() { - // 4:2:0, 4×4 luma, chroma 2×2 with one bright corner sample. - let mut f = frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128); - f.cr = vec![200, 128, 128, 128]; - let p = Planes::Picture(&f); - let (mut buf, mut next) = (vec![0; 2], vec![0; 2]); - let rows: Vec> = (0..4).map(|y| chroma_at(&p, true, y, 4, Upsampling::Bilinear, &mut buf, &mut next).unwrap()).collect(); - // Row 0 sits nearest chroma row 0 (and clamps upward); row 1 blends a quarter of row 1. - assert_eq!(rows[0], [200, 182, 146, 128]); - assert_eq!(rows[1], [182, 169, 142, 128]); - assert_eq!(rows[2], [146, 142, 133, 128]); - assert_eq!(rows[3], [128; 4]); - assert_eq!(chroma_at(&p, true, 1, 4, Upsampling::Nearest, &mut buf, &mut next).unwrap(), [200, 200, 128, 128]); - } - - #[test] - fn alpha_and_bad_planes() { - let f = frame(2, 2, 8, ChromaFormat::Yuv420, 128, 128, 128); - let mut v = to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, true, Upsampling::Nearest).unwrap(); - assert_eq!(v[3], 65535); - put_alpha(&Planes::Picture(&frame(2, 2, 8, ChromaFormat::Monochrome, 51, 0, 0)), &mut v).unwrap(); - assert_eq!(v[3], 51 * 257); - let mut short = frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128); - short.y.truncate(5); - assert!(to_rgb16(&Planes::Picture(&short), Signal { matrix: 6, full_range: true }, false, Upsampling::Bilinear).is_none()); - assert!( - to_rgb16( - &Planes::Picture(&frame(2, 2, 7, ChromaFormat::Yuv420, 0, 0, 0)), - Signal { matrix: 6, full_range: true }, - false, - Upsampling::Nearest - ) - .is_none() - ); - } - - /// CodeRabbit #48: a plane claiming 500 000 × 500 000 pixels must be refused without ever - /// allocating for it (before the cap this vec was never built; upper-bounding allocation - /// would have been a 7.5-gibabuffer or a panic instead of an error). - #[test] - fn an_oversized_canvas_is_refused_without_allocation() { - let f = Frame { - width: 500_000, - height: 500_000, - bit_depth: 8, - chroma: ChromaFormat::Yuv420, - y: vec![128], - cb: vec![128; 4], - cr: vec![128; 4], - y_stride: 0, - c_stride: 0, - }; - assert!(to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, false, Upsampling::Nearest).is_none()); - } -} diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index e570fe21de..1b146c99da 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -17,6 +17,6 @@ chrono = { workspace = true } [dev-dependencies] # Lossless synthetic HEIC files: the HEIF item reader is proved against a real container writer. -lightcraft-heif = { workspace = true, features = ["testdata"] } +craft-heif = { workspace = true, features = ["testdata"] } proptest = { workspace = true } serde_json = { workspace = true } diff --git a/crates/meta/src/heif.rs b/crates/meta/src/heif.rs index ce3a133831..3aae1e284a 100644 --- a/crates/meta/src/heif.rs +++ b/crates/meta/src/heif.rs @@ -2,7 +2,7 @@ //! (box structure from ISO/IEC 14496-12, item model from ISO/IEC 23008-12). //! //! HEIC is what iPhones and Macs write. Its pixels need an HEVC decoder (the optional -//! `lightcraft-heif` crate), its metadata does not, so this reader is in every build: a HEIC +//! `craft-heif` crate), its metadata does not, so this reader is in every build: a HEIC //! imports with its capture time, camera and lens whether or not the build can show the picture. //! //! The `meta` box holds an item information box (`iinf`, one `infe` per item) naming each item's @@ -390,14 +390,14 @@ mod tests { assert!(embedded(&lying).exif.is_none()); } - /// The real container writer of `lightcraft-heif`, so the reader is proved against the layout + /// The real container writer of `craft-heif`, so the reader is proved against the layout /// a HEIF encoder produces and not only against this module's own test builder. #[test] fn a_synthetic_heif_file_carries_its_exif() { let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); - let mut spec = lightcraft_heif::testdata::Spec::new(64, 64, &|x, _| [x as u16 * 4, 0, 0]); + let mut spec = craft_heif::testdata::Spec::new(64, 64, &|x, _| [x as u16 * 4, 0, 0]); spec.exif = Some(tiff.clone()); - let file = lightcraft_heif::testdata::build(&spec); + let file = craft_heif::testdata::build(&spec); assert!(is_heif(&file)); assert_eq!(embedded(&file).exif.as_deref(), Some(tiff.as_slice())); assert_eq!(crate::extract(&file).capture_time.map(|d| d.to_iso()).as_deref(), Some("2026-10-18T13:00:00-05:00")); diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index c396651ae5..9d6b0ca1e6 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -51,8 +51,11 @@ pub fn check_image(data: &[u8], info: &ImageInfo) -> Result { let (across, down) = info.grid(); let planes = if info.planar == 2 { cpp } else { 1 }; let expected = (across as usize).saturating_mul(down as usize).saturating_mul(planes); - if chunks.len() < expected { - return Err(RawError::Corrupt(format!("{} image data chunks, expected {expected}", chunks.len()))); + // the offsets table says how many chunks the image declares: craft-tiff builds at most one + // descriptor per byte of file (craft-libs#827), so `chunks` may be shorter on a grid of tiles + // sharing one payload, and the bytes behind it are what the bounds below count. + if info.offsets.len() < expected { + return Err(RawError::Corrupt(format!("{} image data chunks, expected {expected}", info.offsets.len()))); } // Tile sizes don't depend on the image size, and every tile is decoded at its nominal size and held until the copy: // a grid of tiles no larger than the image covers less than twice its width and height, so more than four times diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6c5f74ae22..7f82adf2e9 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -19,7 +19,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/ | TIFF | ✅ 8/16/32-bit | ✅ 8/16-bit, LZW/ZIP | ✅ 1–64-bit integer, 16–64-bit float, bilevel, CCITT fax, WhiteIsZero | ✅ 8/16-bit, 32-bit float linear, none / LZW / ZIP | `crates/tiff`, `crates/codecs/src/tiff_codec.rs` | | PNG | ✅ | ✅ | ✅ | ✅ | | | PSD / PSB | ✅ (maximized-compatibility composite) | ✅ (Classic: PSD export, edit-in round trip) | ✅ merged composite | ⬜ (external-editor round trip writes 16-bit TIFF) | `crates/codecs/src/psd.rs` | -| HEIC / HEIF | ✅ | ⬜ (Classic) / HDR only | ✅ in every release build (`crates/heif`, heic-rs) | ⬜ | `heif` feature on by packaging scripts | +| HEIC / HEIF | ✅ | ⬜ (Classic) / HDR only | ✅ in every release build (`craft-heif` from craft-libs, heic-rs) | ⬜ | `heif` feature on by packaging scripts | | AVIF | ✅ | ✅ (HDR) | ⬜ recognised, not decoded (no permissive pure-Rust AV1 decoder) | ✅ 8/10-bit, PQ HDR | | | JPEG XL | ✅ | ✅ | ✅ (`jxl-oxide`) incl. DNG 1.7 JXL tiles | ✅ lossy / lossless, 8/16-bit, PQ HDR (`jixel`, native only; ⬜ web) | `crates/engine/src/tests/export.rs` | | WebP | not in its document types | ⬜ | ✅ | ✅ | beyond target | @@ -27,7 +27,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/ | DNG (from raw) | ✅ | ✅ incl. lossy, embedded original | ✅ | ✅ uncompressed, LJ92, Deflate or lossy (JPEG tiles, optional long edge); ⬜ embedded original | `crates/raw/src/dngwrite.rs` | | Render to DNG (15.5) | — | ✅ | — | 🟡 export format "Rendered DNG" (linear float DNG, edit baked in); not yet added to the catalog | `crates/raw/src/dngwrite.rs` (`write_rendered_dng`) | | Original + sidecar | — | ✅ | — | ✅ | | -| HDR gain map JPEG (ISO 21496-1) | ✅ | ✅ | ✅ (gain map read) | ✅ | `crates/codecs/src/gainmap.rs` | +| HDR gain map JPEG (ISO 21496-1) | ✅ | ✅ | ✅ (gain map read) | ✅ | `crates/codecs/src/gainmap.rs` (JPEG layout), `craft-gainmap` (metadata, compute, apply) | | PQ / HLG HDR | ✅ | ✅ AVIF, JXL, TIFF | — | 🟡 PQ AVIF, PQ JPEG XL, float TIFF; no HLG | | | Contact sheet / print PDF | — | ✅ (Print module: PDF / JPEG / printer) | — | 🟡 paginated contact-sheet PDF (A4 / Letter, 150 dpi, sRGB) | `crates/engine/src/contact_sheet.rs` | | Video (MP4, MOV, AVCHD…) | ✅ playback, trim, edit | ✅ export | 🟡 catalogued (kind, duration) | ⬜ | see video gap | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 2b9d779822..b9f5fa44e4 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -81,7 +81,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`), `crates/engine/src/import.rs` (`browse_queue`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); the folder's photos join the view batch by batch while they are read, first screen first (`browse_queue`: newest file first for the default sort), so a 2,933-raw wedding folder shows its first photos in 0.9 s instead of after every file was read (30.6 s; the whole folder still takes ~30 s); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `craft-heif` from craft-libs, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | | LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Canon CRW verified pixel-exact on 6 bodies (D30, D60, 10D, 300D, G1, G6; 10 CC0 files in the corpus, `crates/raw/tests/it/corpus.rs`, plus 18 maintainer D60 files via the digest-pinned sample test of craft-crw in craft-libs (crates/crw/tests/samples.rs there); `craft-libs crates/crw/clean-room/03-verification.md`). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 556ea01b12..f5aa147a2d 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -286,10 +286,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { let mut c = cargo(); c.args(["clippy", "-p", "lightcraft-codecs", "--features", "heif", "--all-targets", "--", "-D", "warnings"]); run(c, "cargo clippy -p lightcraft-codecs --features heif --all-targets -- -D warnings")?; - test( - tests(&with_test_targets(&["-p", "lightcraft-codecs", "-p", "lightcraft-heif", "--features", "lightcraft-codecs/heif"])), - "heif", - )?; + test(tests(&with_test_targets(&["-p", "lightcraft-codecs", "--features", "lightcraft-codecs/heif"])), "heif")?; // the engine's HEIC import test, with the decoder (the workspace run checks the error) test(tests(&["-p", "lightcraft-engine", "--lib", "--features", "lightcraft-codecs/heif", "heic"]), "heif") }), diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index a9078ce8bf..fcfe4d9d64 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -7,7 +7,7 @@ //! - fmt, layers, assets, roots: always (seconds); //! - clippy on the whole workspace (check builds only; catches callers broken by an API change); //! - the tests of the changed packages only (not their dependents); -//! - heif when `lightcraft-codecs` / `lightcraft-heif` changed; +//! - heif when `lightcraft-codecs` changed (or the workspace files, which pin craft-heif); //! - parity when the tracker docs, a command/control crate, or a file's path changed (renames and //! deletions: the tracker cites paths); //! - the wasm check of the changed packages that must build for wasm32. @@ -28,7 +28,7 @@ const WORKSPACE_WIDE_DIRS: &[&str] = &[".cargo/"]; /// Packages whose ids or paths the parity tracker cites (commands, develop controls, UI menus). const PARITY_PACKAGES: &[&str] = &["lightcraft-engine", "lightcraft-develop", "lightcraft-ui-egui", "lightcraft-cli"]; const PARITY_DOCS: &[&str] = &["docs/parity-checklist.md", "docs/gaps.md"]; -const HEIF_PACKAGES: &[&str] = &["lightcraft-codecs", "lightcraft-heif"]; +const HEIF_PACKAGES: &[&str] = &["lightcraft-codecs"]; /// Files outside a package's directory that it compiles in (`include_str!` / `include_bytes!`, /// a build script's `rerun-if-changed`): a change to one counts as a change to those packages. /// An entry ending in `/` covers the directory. `embedded_files_are_mapped` keeps this complete. diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index db515980bc..f1e3ff6e9b 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -42,7 +42,6 @@ pub const TABLE: &[(&str, Class)] = &[ ("fetch", Class::Layer(0)), ("denoise-core", Class::Layer(1)), ("denoise", Class::Layer(1)), - ("heif", Class::Layer(0)), ("raw", Class::Layer(1)), ("codecs", Class::Layer(1)), ("meta", Class::Layer(1)),